From 20305494f8189994a6dc39cd450837a8f9e58dee Mon Sep 17 00:00:00 2001 From: Dundar Göc Date: Sat, 27 Aug 2022 14:26:12 +0200 Subject: refactor: remove redundant casts --- src/nvim/decoration.c | 4 +- src/nvim/ex_docmd.c | 2 +- src/nvim/extmark.c | 4 +- src/nvim/highlight.c | 4 +- src/nvim/keycodes.c | 144 +++++++++++++++++++++++++------------------------- src/nvim/mouse.c | 4 +- 6 files changed, 81 insertions(+), 81 deletions(-) diff --git a/src/nvim/decoration.c b/src/nvim/decoration.c index a93fb599c4..9f3e5a8638 100644 --- a/src/nvim/decoration.c +++ b/src/nvim/decoration.c @@ -547,7 +547,7 @@ int decor_virt_lines(win_T *wp, linenr_T lnum, VirtLines *lines) } int virt_lines = 0; - int row = (int)MAX(lnum - 2, 0); + int row = MAX(lnum - 2, 0); int end_row = (int)lnum; MarkTreeIter itr[1] = { 0 }; marktree_itr_get(buf->b_marktree, row, 0, itr); @@ -558,7 +558,7 @@ int decor_virt_lines(win_T *wp, linenr_T lnum, VirtLines *lines) } else if (marktree_decor_level(mark) < kDecorLevelVirtLine) { goto next_mark; } - bool above = mark.pos.row > (int)(lnum - 2); + bool above = mark.pos.row > (lnum - 2); Decoration *decor = mark.decor_full; if (decor && decor->virt_lines_above == above) { virt_lines += (int)kv_size(decor->virt_lines); diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index eadde7a725..0d74ff6574 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -3088,7 +3088,7 @@ cmdidx_T excmd_get_cmdidx(const char *cmd, size_t len) { cmdidx_T idx; - for (idx = (cmdidx_T)0; (int)idx < (int)CMD_SIZE; idx = (cmdidx_T)((int)idx + 1)) { + for (idx = (cmdidx_T)0; (int)idx < CMD_SIZE; idx = (cmdidx_T)((int)idx + 1)) { if (strncmp(cmdnames[(int)idx].cmd_name, cmd, len) == 0) { break; } diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index 1639f72990..8e780f4aaa 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -510,11 +510,11 @@ void extmark_adjust(buf_T *buf, linenr_T line1, linenr_T line2, linenr_T amount, bcount_t old_byte = 0, new_byte = 0; int old_row, new_row; if (amount == MAXLNUM) { - old_row = (int)(line2 - line1 + 1); + old_row = line2 - line1 + 1; // TODO(bfredl): ej kasta? old_byte = (bcount_t)buf->deleted_bytes2; - new_row = (int)(amount_after + old_row); + new_row = amount_after + old_row; } else { // A region is either deleted (amount == MAXLNUM) or // added (line2 == MAXLNUM). The only other case is :move diff --git a/src/nvim/highlight.c b/src/nvim/highlight.c index c5a84c731d..4848668351 100644 --- a/src/nvim/highlight.c +++ b/src/nvim/highlight.c @@ -223,7 +223,7 @@ int ns_get_hl(NS *ns_hl, int hl_id, bool link, bool nodefault) } } - it.attr_id = fallback ? -1 : hl_get_syn_attr((int)ns_id, hl_id, attrs); + it.attr_id = fallback ? -1 : hl_get_syn_attr(ns_id, hl_id, attrs); it.version = p->hl_valid - tmp; it.is_default = attrs.rgb_ae_attr & HL_DEFAULT; it.link_global = attrs.rgb_ae_attr & HL_GLOBAL; @@ -406,7 +406,7 @@ void update_ns_hl(int ns_id) } int *hl_attrs = **alloc; - for (int hlf = 0; hlf < (int)HLF_COUNT; hlf++) { + for (int hlf = 0; hlf < HLF_COUNT; hlf++) { int id = syn_check_group(hlf_names[hlf], STRLEN(hlf_names[hlf])); bool optional = (hlf == HLF_INACTIVE || hlf == HLF_NFLOAT); hl_attrs[hlf] = hl_get_ui_attr(ns_id, hlf, id, optional); diff --git a/src/nvim/keycodes.c b/src/nvim/keycodes.c index 5a5257efb2..2b00d371f0 100644 --- a/src/nvim/keycodes.c +++ b/src/nvim/keycodes.c @@ -57,15 +57,15 @@ static char_u modifier_keys_table[] = MOD_MASK_SHIFT, '*', '4', 'k', 'D', // delete char MOD_MASK_SHIFT, '*', '5', 'k', 'L', // delete line MOD_MASK_SHIFT, '*', '7', '@', '7', // end - MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', // end + MOD_MASK_CTRL, KS_EXTRA, KE_C_END, '@', '7', // end MOD_MASK_SHIFT, '*', '9', '@', '9', // exit MOD_MASK_SHIFT, '*', '0', '@', '0', // find MOD_MASK_SHIFT, '#', '1', '%', '1', // help MOD_MASK_SHIFT, '#', '2', 'k', 'h', // home - MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', // home + MOD_MASK_CTRL, KS_EXTRA, KE_C_HOME, 'k', 'h', // home MOD_MASK_SHIFT, '#', '3', 'k', 'I', // insert MOD_MASK_SHIFT, '#', '4', 'k', 'l', // left arrow - MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', // left arrow + MOD_MASK_CTRL, KS_EXTRA, KE_C_LEFT, 'k', 'l', // left arrow MOD_MASK_SHIFT, '%', 'a', '%', '3', // message MOD_MASK_SHIFT, '%', 'b', '%', '4', // move MOD_MASK_SHIFT, '%', 'c', '%', '5', // next @@ -75,63 +75,63 @@ static char_u modifier_keys_table[] = MOD_MASK_SHIFT, '%', 'g', '%', '0', // redo MOD_MASK_SHIFT, '%', 'h', '&', '3', // replace MOD_MASK_SHIFT, '%', 'i', 'k', 'r', // right arr. - MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', // right arr. + MOD_MASK_CTRL, KS_EXTRA, KE_C_RIGHT, 'k', 'r', // right arr. MOD_MASK_SHIFT, '%', 'j', '&', '5', // resume MOD_MASK_SHIFT, '!', '1', '&', '6', // save MOD_MASK_SHIFT, '!', '2', '&', '7', // suspend MOD_MASK_SHIFT, '!', '3', '&', '8', // undo - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', // up arrow - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', // down arrow + MOD_MASK_SHIFT, KS_EXTRA, KE_S_UP, 'k', 'u', // up arrow + MOD_MASK_SHIFT, KS_EXTRA, KE_S_DOWN, 'k', 'd', // down arrow // vt100 F1 - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1, - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2, - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3, - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4, - - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', // F1 - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', // F10 - - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A', - - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K', - - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q', - MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF1, KS_EXTRA, KE_XF1, + MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF2, KS_EXTRA, KE_XF2, + MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF3, KS_EXTRA, KE_XF3, + MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF4, KS_EXTRA, KE_XF4, + + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F1, 'k', '1', // F1 + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F2, 'k', '2', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F3, 'k', '3', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F4, 'k', '4', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F5, 'k', '5', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F6, 'k', '6', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F7, 'k', '7', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F8, 'k', '8', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F9, 'k', '9', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F10, 'k', ';', // F10 + + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F11, 'F', '1', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F12, 'F', '2', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F13, 'F', '3', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F14, 'F', '4', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F15, 'F', '5', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F16, 'F', '6', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F17, 'F', '7', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F18, 'F', '8', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F19, 'F', '9', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F20, 'F', 'A', + + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F21, 'F', 'B', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F22, 'F', 'C', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F23, 'F', 'D', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F24, 'F', 'E', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F25, 'F', 'F', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F26, 'F', 'G', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F27, 'F', 'H', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F28, 'F', 'I', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F29, 'F', 'J', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F30, 'F', 'K', + + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F31, 'F', 'L', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F32, 'F', 'M', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F33, 'F', 'N', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F34, 'F', 'O', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F35, 'F', 'P', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F36, 'F', 'Q', + MOD_MASK_SHIFT, KS_EXTRA, KE_S_F37, 'F', 'R', // TAB pseudo code - MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB, + MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, KE_TAB, NUL }; @@ -349,26 +349,26 @@ static struct mousetable { bool is_drag; // Is it a mouse drag event? } mouse_table[] = { - { (int)KE_LEFTMOUSE, MOUSE_LEFT, true, false }, - { (int)KE_LEFTDRAG, MOUSE_LEFT, false, true }, - { (int)KE_LEFTRELEASE, MOUSE_LEFT, false, false }, - { (int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, true, false }, - { (int)KE_MIDDLEDRAG, MOUSE_MIDDLE, false, true }, - { (int)KE_MIDDLERELEASE, MOUSE_MIDDLE, false, false }, - { (int)KE_RIGHTMOUSE, MOUSE_RIGHT, true, false }, - { (int)KE_RIGHTDRAG, MOUSE_RIGHT, false, true }, - { (int)KE_RIGHTRELEASE, MOUSE_RIGHT, false, false }, - { (int)KE_X1MOUSE, MOUSE_X1, true, false }, - { (int)KE_X1DRAG, MOUSE_X1, false, true }, - { (int)KE_X1RELEASE, MOUSE_X1, false, false }, - { (int)KE_X2MOUSE, MOUSE_X2, true, false }, - { (int)KE_X2DRAG, MOUSE_X2, false, true }, - { (int)KE_X2RELEASE, MOUSE_X2, false, false }, + { KE_LEFTMOUSE, MOUSE_LEFT, true, false }, + { KE_LEFTDRAG, MOUSE_LEFT, false, true }, + { KE_LEFTRELEASE, MOUSE_LEFT, false, false }, + { KE_MIDDLEMOUSE, MOUSE_MIDDLE, true, false }, + { KE_MIDDLEDRAG, MOUSE_MIDDLE, false, true }, + { KE_MIDDLERELEASE, MOUSE_MIDDLE, false, false }, + { KE_RIGHTMOUSE, MOUSE_RIGHT, true, false }, + { KE_RIGHTDRAG, MOUSE_RIGHT, false, true }, + { KE_RIGHTRELEASE, MOUSE_RIGHT, false, false }, + { KE_X1MOUSE, MOUSE_X1, true, false }, + { KE_X1DRAG, MOUSE_X1, false, true }, + { KE_X1RELEASE, MOUSE_X1, false, false }, + { KE_X2MOUSE, MOUSE_X2, true, false }, + { KE_X2DRAG, MOUSE_X2, false, true }, + { KE_X2RELEASE, MOUSE_X2, false, false }, // DRAG without CLICK - { (int)KE_MOUSEMOVE, MOUSE_RELEASE, false, true }, + { KE_MOUSEMOVE, MOUSE_RELEASE, false, true }, // RELEASE without CLICK - { (int)KE_IGNORE, MOUSE_RELEASE, false, false }, - { 0, 0, 0, 0 }, + { KE_IGNORE, MOUSE_RELEASE, false, false }, + { 0, 0, 0, 0 }, }; /// Return the modifier mask bit (#MOD_MASK_*) corresponding to mod name @@ -926,8 +926,8 @@ char *replace_termcodes(const char *const from, const size_t from_len, char **co } else { src += 5; result[dlen++] = K_SPECIAL; - result[dlen++] = (int)KS_EXTRA; - result[dlen++] = (int)KE_SNR; + result[dlen++] = KS_EXTRA; + result[dlen++] = KE_SNR; snprintf((char *)result + dlen, buf_len - dlen, "%" PRId64, (int64_t)current_sctx.sc_sid); dlen += STRLEN(result + dlen); diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index 3dfbeec048..cc833dc3c0 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -702,8 +702,8 @@ static linenr_T find_longest_lnum(void) max = len; ret = lnum; } else if (len == (colnr_T)max - && abs((int)(lnum - curwin->w_cursor.lnum)) - < abs((int)(ret - curwin->w_cursor.lnum))) { + && abs(lnum - curwin->w_cursor.lnum) + < abs(ret - curwin->w_cursor.lnum)) { ret = lnum; } } -- cgit From 691f4715c0cf4bc11ea2280db8777e6dd174a8ac Mon Sep 17 00:00:00 2001 From: Dundar Göc Date: Fri, 26 Aug 2022 23:11:25 +0200 Subject: refactor: replace char_u with char Work on https://github.com/neovim/neovim/issues/459 --- src/nvim/buffer.c | 2 +- src/nvim/charset.c | 2 +- src/nvim/cmdexpand.c | 2 +- src/nvim/debugger.c | 2 +- src/nvim/diff.c | 2 +- src/nvim/edit.c | 6 +- src/nvim/eval/funcs.c | 6 +- src/nvim/ex_cmds.c | 4 +- src/nvim/ex_docmd.c | 16 +-- src/nvim/ex_getln.c | 2 +- src/nvim/file_search.c | 12 +-- src/nvim/fileio.c | 12 +-- src/nvim/garray.h | 2 +- src/nvim/getchar.c | 4 +- src/nvim/globals.h | 16 +-- src/nvim/help.c | 2 +- src/nvim/highlight.c | 2 +- src/nvim/indent.c | 13 +-- src/nvim/insexpand.c | 29 +++--- src/nvim/lua/stdlib.c | 4 +- src/nvim/main.c | 2 +- src/nvim/mark.c | 4 +- src/nvim/mbyte.c | 22 ++--- src/nvim/memfile.c | 10 +- src/nvim/memline.c | 20 ++-- src/nvim/message.c | 2 +- src/nvim/normal.c | 4 +- src/nvim/normal.h | 4 +- src/nvim/ops.c | 12 +-- src/nvim/option.c | 264 +++++++++++++++++++++++-------------------------- src/nvim/option_defs.h | 86 ++++++++-------- src/nvim/optionstr.c | 230 +++++++++++++++++++++--------------------- src/nvim/quickfix.c | 8 +- src/nvim/runtime.c | 2 +- src/nvim/screen.c | 30 +++--- src/nvim/shada.c | 2 +- src/nvim/spell.c | 12 +-- src/nvim/spellfile.c | 42 ++++---- src/nvim/statusline.c | 4 +- src/nvim/syntax.c | 65 ++++++------ src/nvim/tag.c | 52 +++++----- 41 files changed, 497 insertions(+), 520 deletions(-) diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index 514be4c56b..5dc7083a01 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -2701,7 +2701,7 @@ void buflist_list(exarg_T *eap) home_replace(buf, buf->b_fname, (char *)NameBuff, MAXPATHL, true); } - if (message_filtered(NameBuff)) { + if (message_filtered((char_u *)NameBuff)) { continue; } diff --git a/src/nvim/charset.c b/src/nvim/charset.c index dc62b85716..df951854e0 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -246,7 +246,7 @@ int buf_init_chartab(buf_T *buf, int global) } c = *p; - p = skip_to_option_part(p); + p = (char_u *)skip_to_option_part((char *)p); if ((c == ',') && (*p == NUL)) { // Trailing comma is not allowed. diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index b55e885235..7f9a8b2a5c 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -705,7 +705,7 @@ int showmatches(expand_T *xp, int wildmenu) p = (char_u *)L_SHOWFILE(k); } else { home_replace(NULL, files_found[k], (char *)NameBuff, MAXPATHL, true); - p = NameBuff; + p = (char_u *)NameBuff; } } else { j = false; diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c index d2f4910e14..9aee023f0c 100644 --- a/src/nvim/debugger.c +++ b/src/nvim/debugger.c @@ -703,7 +703,7 @@ void ex_breaklist(exarg_T *eap) smsg(_("%3d %s %s line %" PRId64), bp->dbg_nr, bp->dbg_type == DBG_FUNC ? "func" : "file", - bp->dbg_type == DBG_FUNC ? bp->dbg_name : NameBuff, + bp->dbg_type == DBG_FUNC ? bp->dbg_name : (char_u *)NameBuff, (int64_t)bp->dbg_lnum); } else { smsg(_("%3d expr %s"), bp->dbg_nr, bp->dbg_name); diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 8107b64c83..23fdc728f3 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -1148,7 +1148,7 @@ static int diff_file(diffio_T *dio) (diff_flags & DIFF_IBLANK) ? "-B " : "", (diff_flags & DIFF_ICASE) ? "-i " : "", tmp_orig, tmp_new); - append_redir(cmd, len, (char *)p_srr, tmp_diff); + append_redir(cmd, len, p_srr, tmp_diff); block_autocmds(); // Avoid ShellCmdPost stuff (void)call_shell((char_u *)cmd, kShellOptFilter | kShellOptSilent | kShellOptDoOut, diff --git a/src/nvim/edit.c b/src/nvim/edit.c index ed625e1d6e..adcf9cd075 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -3282,10 +3282,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } } - /* - * Skip over ", ". - */ - look = skip_to_option_part(look); + // Skip over ", ". + look = (char_u *)skip_to_option_part((char *)look); } return false; } diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 581f187140..22447b933a 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -3895,9 +3895,11 @@ static void f_iconv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) const char *const str = tv_get_string(&argvars[0]); char buf1[NUMBUFLEN]; - char_u *const from = enc_canonize(enc_skip((char_u *)tv_get_string_buf(&argvars[1], buf1))); + char_u *const from = + (char_u *)enc_canonize((char *)enc_skip((char_u *)tv_get_string_buf(&argvars[1], buf1))); char buf2[NUMBUFLEN]; - char_u *const to = enc_canonize(enc_skip((char_u *)tv_get_string_buf(&argvars[2], buf2))); + char_u *const to = + (char_u *)enc_canonize((char *)enc_skip((char_u *)tv_get_string_buf(&argvars[2], buf2))); vimconv.vc_type = CONV_NONE; convert_setup(&vimconv, from, to); diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index a72cddc0a9..4a1cdb0fc5 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -743,7 +743,7 @@ void ex_retab(exarg_T *eap) curwin->w_p_list = 0; // don't want list mode here new_ts_str = eap->arg; - if (!tabstop_set((char_u *)eap->arg, &new_vts_array)) { + if (!tabstop_set(eap->arg, &new_vts_array)) { return; } while (ascii_isdigit(*(eap->arg)) || *(eap->arg) == ',') { @@ -1656,7 +1656,7 @@ char *make_filter_cmd(char *cmd, char *itmp, char *otmp) } #endif if (otmp != NULL) { - append_redir(buf, len, (char *)p_srr, otmp); + append_redir(buf, len, p_srr, otmp); } return buf; } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index eadde7a725..8ecc1e266b 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -531,7 +531,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) if (flags & DOCMD_KEEPLINE) { xfree(repeat_cmdline); if (count == 0) { - repeat_cmdline = vim_strsave((char_u *)next_cmdline); + repeat_cmdline = (char *)vim_strsave((char_u *)next_cmdline); } else { repeat_cmdline = NULL; } @@ -3788,8 +3788,8 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp) // if there are still wildcards present. if (vim_strchr(eap->arg, '$') != NULL || vim_strchr(eap->arg, '~') != NULL) { - expand_env_esc((char_u *)eap->arg, NameBuff, MAXPATHL, true, true, NULL); - has_wildcards = path_has_wildcard(NameBuff); + expand_env_esc((char_u *)eap->arg, (char_u *)NameBuff, MAXPATHL, true, true, NULL); + has_wildcards = path_has_wildcard((char_u *)NameBuff); p = (char *)NameBuff; } else { p = NULL; @@ -4058,7 +4058,7 @@ static int getargopt(exarg_T *eap) *arg = NUL; if (pp == &eap->force_ff) { - if (check_ff_value((char_u *)eap->cmd + eap->force_ff) == FAIL) { + if (check_ff_value(eap->cmd + eap->force_ff) == FAIL) { return FAIL; } eap->force_ff = (char_u)eap->cmd[eap->force_ff]; @@ -5482,8 +5482,8 @@ bool changedir_func(char *new_dir, CdScope scope) new_dir = pdir; } - if (os_dirname(NameBuff, MAXPATHL) == OK) { - pdir = (char *)vim_strsave(NameBuff); + if (os_dirname((char_u *)NameBuff, MAXPATHL) == OK) { + pdir = xstrdup(NameBuff); } else { pdir = NULL; } @@ -5496,7 +5496,7 @@ bool changedir_func(char *new_dir, CdScope scope) if (*new_dir == NUL && p_cdh) { #endif // Use NameBuff for home directory name. - expand_env((char_u *)"$HOME", NameBuff, MAXPATHL); + expand_env((char_u *)"$HOME", (char_u *)NameBuff, MAXPATHL); new_dir = (char *)NameBuff; } @@ -5565,7 +5565,7 @@ void ex_cd(exarg_T *eap) /// ":pwd". static void ex_pwd(exarg_T *eap) { - if (os_dirname(NameBuff, MAXPATHL) == OK) { + if (os_dirname((char_u *)NameBuff, MAXPATHL) == OK) { #ifdef BACKSLASH_IN_FILENAME slash_adjust(NameBuff); #endif diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 081aa80778..c509205a6c 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -854,7 +854,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init s->histype == HIST_SEARCH ? s->firstc : NUL); if (s->firstc == ':') { xfree(new_last_cmdline); - new_last_cmdline = vim_strsave(ccline.cmdbuff); + new_last_cmdline = (char *)vim_strsave(ccline.cmdbuff); } } diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index 273fe12d31..a990043017 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -1409,11 +1409,11 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first // copy file name into NameBuff, expanding environment variables save_char = ptr[len]; ptr[len] = NUL; - expand_env_esc(ptr, NameBuff, MAXPATHL, false, true, NULL); + expand_env_esc(ptr, (char_u *)NameBuff, MAXPATHL, false, true, NULL); ptr[len] = save_char; xfree(ff_file_to_find); - ff_file_to_find = vim_strsave(NameBuff); + ff_file_to_find = vim_strsave((char_u *)NameBuff); if (options & FNAME_UNESC) { // Change all "\ " to " ". for (ptr = ff_file_to_find; *ptr != NUL; ptr++) { @@ -1473,11 +1473,11 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first buf = (char *)suffixes; for (;;) { if ( - (os_path_exists(NameBuff) + (os_path_exists((char_u *)NameBuff) && (find_what == FINDFILE_BOTH || ((find_what == FINDFILE_DIR) - == os_isdir(NameBuff))))) { - file_name = vim_strsave(NameBuff); + == os_isdir((char_u *)NameBuff))))) { + file_name = vim_strsave((char_u *)NameBuff); goto theend; } if (*buf == NUL) { @@ -1641,7 +1641,7 @@ int vim_chdirfile(char *fname, CdCause cause) STRLCPY(dir, fname, MAXPATHL); *path_tail_with_sep(dir) = NUL; - if (os_dirname(NameBuff, sizeof(NameBuff)) != OK) { + if (os_dirname((char_u *)NameBuff, sizeof(NameBuff)) != OK) { NameBuff[0] = NUL; } diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 39b4eb4376..b873388473 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -699,7 +699,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, * Decide which 'encoding' to use or use first. */ if (eap != NULL && eap->force_enc != 0) { - fenc = (char *)enc_canonize((char_u *)eap->cmd + eap->force_enc); + fenc = enc_canonize(eap->cmd + eap->force_enc); fenc_alloced = true; keep_dest_enc = true; } else if (curbuf->b_p_bin) { @@ -2056,8 +2056,8 @@ void set_file_options(int set_options, exarg_T *eap) void set_forced_fenc(exarg_T *eap) { if (eap->force_enc != 0) { - char_u *fenc = enc_canonize((char_u *)eap->cmd + eap->force_enc); - set_string_option_direct("fenc", -1, (char *)fenc, OPT_FREE|OPT_LOCAL, 0); + char *fenc = enc_canonize(eap->cmd + eap->force_enc); + set_string_option_direct("fenc", -1, fenc, OPT_FREE|OPT_LOCAL, 0); xfree(fenc); } } @@ -2081,12 +2081,12 @@ static char_u *next_fenc(char **pp, bool *alloced) } p = (char_u *)vim_strchr((*pp), ','); if (p == NULL) { - r = enc_canonize((char_u *)(*pp)); + r = (char_u *)enc_canonize(*pp); *pp += STRLEN(*pp); } else { r = vim_strnsave((char_u *)(*pp), (size_t)(p - (char_u *)(*pp))); *pp = (char *)p + 1; - p = enc_canonize(r); + p = (char_u *)enc_canonize((char *)r); xfree(r); r = p; } @@ -3055,7 +3055,7 @@ nobackup: // Check for forced 'fileencoding' from "++opt=val" argument. if (eap != NULL && eap->force_enc != 0) { fenc = eap->cmd + eap->force_enc; - fenc = (char *)enc_canonize((char_u *)fenc); + fenc = enc_canonize(fenc); fenc_tofree = fenc; } else { fenc = buf->b_p_fenc; diff --git a/src/nvim/garray.h b/src/nvim/garray.h index 56bd5c9130..0281678925 100644 --- a/src/nvim/garray.h +++ b/src/nvim/garray.h @@ -4,7 +4,7 @@ #include // for size_t #include "nvim/log.h" -#include "nvim/types.h" // for char_u +#include "nvim/types.h" /// Structure used for growing arrays. /// This is used to store information that only grows, is deleted all at diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index c1c5680cb0..ebea4b7a9b 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -1302,7 +1302,7 @@ void openscript(char_u *name, bool directly) curscript++; } // use NameBuff for expanded name - expand_env(name, NameBuff, MAXPATHL); + expand_env(name, (char_u *)NameBuff, MAXPATHL); int error; if ((scriptin[curscript] = file_open_new(&error, (char *)NameBuff, kFileReadOnly, 0)) == NULL) { @@ -2120,7 +2120,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth) // Check for match with 'pastetoggle' if (*p_pt != NUL && mp == NULL && (State & (MODE_INSERT | MODE_NORMAL))) { - bool match = typebuf_match_len(p_pt, &mlen); + bool match = typebuf_match_len((char_u *)p_pt, &mlen); if (match) { // write chars to script file(s) if (mlen > typebuf.tb_maplen) { diff --git a/src/nvim/globals.h b/src/nvim/globals.h index 7b93fbc852..8d62674a22 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -159,10 +159,10 @@ EXTERN colnr_T dollar_vcol INIT(= -1); // Variables for Insert mode completion. -EXTERN char_u *edit_submode INIT(= NULL); // msg for CTRL-X submode -EXTERN char_u *edit_submode_pre INIT(= NULL); // prepended to edit_submode -EXTERN char_u *edit_submode_extra INIT(= NULL); // appended to edit_submode -EXTERN hlf_T edit_submode_highl; // highl. method for extra info +EXTERN char *edit_submode INIT(= NULL); // msg for CTRL-X submode +EXTERN char *edit_submode_pre INIT(= NULL); // prepended to edit_submode +EXTERN char *edit_submode_extra INIT(= NULL); // appended to edit_submode +EXTERN hlf_T edit_submode_highl; // highl. method for extra info // state for putting characters in the message area EXTERN int cmdmsg_rl INIT(= false); // cmdline is drawn right to left @@ -667,7 +667,7 @@ EXTERN int swap_exists_action INIT(= SEA_NONE); ///< For dialog when swap file EXTERN bool swap_exists_did_quit INIT(= false); ///< Selected "quit" at the dialog. EXTERN char_u IObuff[IOSIZE]; ///< Buffer for sprintf, I/O, etc. -EXTERN char_u NameBuff[MAXPATHL]; ///< Buffer for expanding file names +EXTERN char NameBuff[MAXPATHL]; ///< Buffer for expanding file names EXTERN char msg_buf[MSG_BUF_LEN]; ///< Small buffer for messages EXTERN char os_buf[ ///< Buffer for the os/ layer #if MAXPATHL > IOSIZE @@ -731,9 +731,9 @@ EXTERN bool need_start_insertmode INIT(= false); ///< start insert mode soon // including the terminating NUL EXTERN char last_mode[MODE_MAX_LENGTH] INIT(= "n"); -EXTERN char_u *last_cmdline INIT(= NULL); // last command line (for ":) -EXTERN char_u *repeat_cmdline INIT(= NULL); // command line for "." -EXTERN char_u *new_last_cmdline INIT(= NULL); // new value for last_cmdline +EXTERN char *last_cmdline INIT(= NULL); // last command line (for ":) +EXTERN char *repeat_cmdline INIT(= NULL); // command line for "." +EXTERN char *new_last_cmdline INIT(= NULL); // new value for last_cmdline EXTERN char *autocmd_fname INIT(= NULL); // fname for on cmdline EXTERN int autocmd_bufnr INIT(= 0); // fnum for on cmdline EXTERN char *autocmd_match INIT(= NULL); // name for on cmdline diff --git a/src/nvim/help.c b/src/nvim/help.c index 19bf67c890..4b2b113437 100644 --- a/src/nvim/help.c +++ b/src/nvim/help.c @@ -537,7 +537,7 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep if (keep_lang) { flags |= TAG_KEEP_LANG; } - if (find_tags(IObuff, num_matches, matches, flags, MAXCOL, NULL) == OK + if (find_tags((char *)IObuff, num_matches, matches, flags, MAXCOL, NULL) == OK && *num_matches > 0) { // Sort the matches found on the heuristic number that is after the // tag name. diff --git a/src/nvim/highlight.c b/src/nvim/highlight.c index c5a84c731d..3e3d03fa9c 100644 --- a/src/nvim/highlight.c +++ b/src/nvim/highlight.c @@ -729,7 +729,7 @@ static int hl_cterm2rgb_color(int nr) 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76, 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE }; - static char_u ansi_table[16][4] = { + static uint8_t ansi_table[16][4] = { // R G B idx { 0, 0, 0, 1 }, // black { 224, 0, 0, 2 }, // dark red diff --git a/src/nvim/indent.c b/src/nvim/indent.c index c4805283c2..7c5f291837 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -34,12 +34,13 @@ /// Set the integer values corresponding to the string setting of 'vartabstop'. /// "array" will be set, caller must free it if needed. -/// Return false for an error. -bool tabstop_set(char_u *var, long **array) +/// +/// @return false for an error. +bool tabstop_set(char *var, long **array) { long valcount = 1; int t; - char_u *cp; + char *cp; if (var[0] == NUL || (var[0] == '0' && var[1] == NUL)) { *array = NULL; @@ -50,8 +51,8 @@ bool tabstop_set(char_u *var, long **array) if (cp == var || cp[-1] == ',') { char *end; - if (strtol((char *)cp, &end, 10) <= 0) { - if (cp != (char_u *)end) { + if (strtol(cp, &end, 10) <= 0) { + if (cp != end) { emsg(_(e_positive)); } else { semsg(_(e_invarg2), cp); @@ -76,7 +77,7 @@ bool tabstop_set(char_u *var, long **array) t = 1; for (cp = var; *cp != NUL;) { - int n = atoi((char *)cp); + int n = atoi(cp); // Catch negative values, overflow and ridiculous big values. if (n <= 0 || n > TABSTOP_MAX) { diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index e6c13f315e..981a8d42a6 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -268,7 +268,7 @@ void ins_ctrl_x(void) } // We're not sure which CTRL-X mode it will be yet ctrl_x_mode = CTRL_X_NOT_DEFINED_YET; - edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); + edit_submode = _(CTRL_X_MSG(ctrl_x_mode)); edit_submode_pre = NULL; showmode(); } else { @@ -1830,9 +1830,9 @@ static bool set_ctrl_x_mode(const int c) // scroll the window one line up or down ctrl_x_mode = CTRL_X_SCROLL; if (!(State & REPLACE_FLAG)) { - edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)"); + edit_submode = _(" (insert) Scroll (^E/^Y)"); } else { - edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)"); + edit_submode = _(" (replace) Scroll (^E/^Y)"); } edit_submode_pre = NULL; showmode(); @@ -2845,10 +2845,10 @@ static void get_next_tag_completion(void) g_tag_at_cursor = true; char **matches; int num_matches; - if (find_tags((char_u *)compl_pattern, &num_matches, &matches, + if (find_tags(compl_pattern, &num_matches, &matches, TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0), - TAG_MANY, (char_u *)curbuf->b_ffname) == OK && num_matches > 0) { + TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0) { ins_compl_add_matches(num_matches, matches, p_ic); } g_tag_at_cursor = false; @@ -4078,7 +4078,7 @@ static int ins_compl_start(void) } if (compl_status_adding()) { - edit_submode_pre = (char_u *)_(" Adding"); + edit_submode_pre = _(" Adding"); if (ctrl_x_mode_line_or_eval()) { // Insert a new line, keep indentation but ignore 'comments'. char *old = curbuf->b_p_com; @@ -4097,9 +4097,9 @@ static int ins_compl_start(void) } if (compl_cont_status & CONT_LOCAL) { - edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]); + edit_submode = _(ctrl_x_msgs[CTRL_X_LOCAL_MSG]); } else { - edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); + edit_submode = _(CTRL_X_MSG(ctrl_x_mode)); } // If any of the original typed text has been changed we need to fix @@ -4123,7 +4123,7 @@ static int ins_compl_start(void) // showmode might reset the internal line pointers, so it must // be called before line = ml_get(), or when this address is no // longer needed. -- Acevedo. - edit_submode_extra = (char_u *)_("-- Searching..."); + edit_submode_extra = _("-- Searching..."); edit_submode_highl = HLF_COUNT; showmode(); edit_submode_extra = NULL; @@ -4137,20 +4137,19 @@ static void ins_compl_show_statusmsg(void) { // we found no match if the list has only the "compl_orig_text"-entry if (is_first_match(compl_first_match->cp_next)) { - edit_submode_extra = compl_status_adding() && compl_length > 1 - ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf); + edit_submode_extra = compl_status_adding() && compl_length > 1 ? _(e_hitend) : _(e_patnotf); edit_submode_highl = HLF_E; } if (edit_submode_extra == NULL) { if (match_at_original_text(compl_curr_match)) { - edit_submode_extra = (char_u *)_("Back at original"); + edit_submode_extra = _("Back at original"); edit_submode_highl = HLF_W; } else if (compl_cont_status & CONT_S_IPOS) { - edit_submode_extra = (char_u *)_("Word from other line"); + edit_submode_extra = _("Word from other line"); edit_submode_highl = HLF_COUNT; } else if (compl_curr_match->cp_next == compl_curr_match->cp_prev) { - edit_submode_extra = (char_u *)_("The only match"); + edit_submode_extra = _("The only match"); edit_submode_highl = HLF_COUNT; compl_curr_match->cp_number = 1; } else { @@ -4175,7 +4174,7 @@ static void ins_compl_show_statusmsg(void) _("match %d"), compl_curr_match->cp_number); } - edit_submode_extra = match_ref; + edit_submode_extra = (char *)match_ref; edit_submode_highl = HLF_R; if (dollar_vcol >= 0) { curs_columns(curwin, false); diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 64e9abe0c9..0d08817285 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -494,8 +494,8 @@ static int nlua_iconv(lua_State *lstate) size_t str_len = 0; const char *str = lua_tolstring(lstate, 1, &str_len); - char_u *from = enc_canonize(enc_skip((char_u *)lua_tolstring(lstate, 2, NULL))); - char_u *to = enc_canonize(enc_skip((char_u *)lua_tolstring(lstate, 3, NULL))); + char_u *from = (char_u *)enc_canonize((char *)enc_skip((char_u *)lua_tolstring(lstate, 2, NULL))); + char_u *to = (char_u *)enc_canonize((char *)enc_skip((char_u *)lua_tolstring(lstate, 3, NULL))); vimconv_T vimconv; vimconv.vc_type = CONV_NONE; diff --git a/src/nvim/main.c b/src/nvim/main.c index e2e150a892..09a387262c 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1490,7 +1490,7 @@ static void handle_quickfix(mparm_T *paramp) set_string_option_direct("ef", -1, paramp->use_ef, OPT_FREE, SID_CARG); } vim_snprintf((char *)IObuff, IOSIZE, "cfile %s", p_ef); - if (qf_init(NULL, (char *)p_ef, p_efm, true, (char *)IObuff, (char *)p_menc) < 0) { + if (qf_init(NULL, (char *)p_ef, p_efm, true, (char *)IObuff, p_menc) < 0) { msg_putchar('\n'); os_exit(3); } diff --git a/src/nvim/mark.c b/src/nvim/mark.c index c4b30ae600..883371c5fb 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -674,7 +674,7 @@ static void fname2fnum(xfmark_T *fm) )) { int len; - expand_env((char_u *)"~/", NameBuff, MAXPATHL); + expand_env((char_u *)"~/", (char_u *)NameBuff, MAXPATHL); len = (int)STRLEN(NameBuff); STRLCPY(NameBuff + len, fm->fname + 2, MAXPATHL - len); } else { @@ -683,7 +683,7 @@ static void fname2fnum(xfmark_T *fm) // Try to shorten the file name. os_dirname(IObuff, IOSIZE); - p = path_shorten_fname(NameBuff, IObuff); + p = path_shorten_fname((char_u *)NameBuff, IObuff); // buflist_new() will call fmarks_check_names() (void)buflist_new((char *)NameBuff, (char *)p, (linenr_T)1, 0); diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index 9213457608..dab6c8fbd3 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -2160,27 +2160,27 @@ char_u *enc_skip(char_u *p) return p; } -/* - * Find the canonical name for encoding "enc". - * When the name isn't recognized, returns "enc" itself, but with all lower - * case characters and '_' replaced with '-'. - * Returns an allocated string. - */ -char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET +/// Find the canonical name for encoding "enc". +/// When the name isn't recognized, returns "enc" itself, but with all lower +/// case characters and '_' replaced with '-'. +/// +/// @return an allocated string. +char *enc_canonize(char *enc) + FUNC_ATTR_NONNULL_RET { char_u *p, *s; int i; if (STRCMP(enc, "default") == 0) { // Use the default encoding as found by set_init_1(). - return vim_strsave(fenc_default); + return (char *)vim_strsave(fenc_default); } // copy "enc" to allocated memory, with room for two '-' char_u *r = xmalloc(STRLEN(enc) + 3); // Make it all lower case and replace '_' with '-'. p = r; - for (s = enc; *s != NUL; s++) { + for (s = (char_u *)enc; *s != NUL; s++) { if (*s == '_') { *p++ = '-'; } else { @@ -2224,7 +2224,7 @@ char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET xfree(r); r = vim_strsave((char_u *)enc_canon_table[i].name); } - return r; + return (char *)r; } /// Search for an encoding alias of "name". @@ -2309,7 +2309,7 @@ enc_locale_copy_enc: buf[i] = NUL; } - return enc_canonize((char_u *)buf); + return (char_u *)enc_canonize(buf); } #if defined(HAVE_ICONV) diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c index 216ee26620..9446aaee4f 100644 --- a/src/nvim/memfile.c +++ b/src/nvim/memfile.c @@ -77,7 +77,7 @@ /// /// @return - The open memory file, on success. /// - NULL, on failure (e.g. file does not exist). -memfile_T *mf_open(char_u *fname, int flags) +memfile_T *mf_open(char *fname, int flags) { memfile_T *mfp = xmalloc(sizeof(memfile_T)); @@ -148,7 +148,7 @@ memfile_T *mf_open(char_u *fname, int flags) /// /// @return OK On success. /// FAIL If file could not be opened. -int mf_open_file(memfile_T *mfp, char_u *fname) +int mf_open_file(memfile_T *mfp, char *fname) { if (mf_do_open(mfp, fname, O_RDWR | O_CREAT | O_EXCL)) { mfp->mf_dirty = true; @@ -749,9 +749,9 @@ void mf_free_fnames(memfile_T *mfp) /// /// Only called when creating or renaming the swapfile. Either way it's a new /// name so we must work out the full path name. -void mf_set_fnames(memfile_T *mfp, char_u *fname) +void mf_set_fnames(memfile_T *mfp, char *fname) { - mfp->mf_fname = fname; + mfp->mf_fname = (char_u *)fname; mfp->mf_ffname = (char_u *)FullName_save((char *)mfp->mf_fname, false); } @@ -779,7 +779,7 @@ bool mf_need_trans(memfile_T *mfp) /// /// @param flags Flags for open(). /// @return A bool indicating success of the `open` call. -static bool mf_do_open(memfile_T *mfp, char_u *fname, int flags) +static bool mf_do_open(memfile_T *mfp, char *fname, int flags) { // fname cannot be NameBuff, because it must have been allocated. mf_set_fnames(mfp, fname); diff --git a/src/nvim/memline.c b/src/nvim/memline.c index 2913d0d271..ee90ae6b15 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -430,7 +430,7 @@ void ml_setname(buf_T *buf) if (vim_rename(mfp->mf_fname, fname) == 0) { success = true; mf_free_fnames(mfp); - mf_set_fnames(mfp, fname); + mf_set_fnames(mfp, (char *)fname); ml_upd_block0(buf, UB_SAME_DIR); break; } @@ -483,7 +483,7 @@ void ml_open_file(buf_T *buf) if (buf->b_spell) { fname = vim_tempname(); if (fname != NULL) { - (void)mf_open_file(mfp, fname); // consumes fname! + (void)mf_open_file(mfp, (char *)fname); // consumes fname! } buf->b_may_swap = false; return; @@ -506,7 +506,7 @@ void ml_open_file(buf_T *buf) if (fname == NULL) { continue; } - if (mf_open_file(mfp, fname) == OK) { // consumes fname! + if (mf_open_file(mfp, (char *)fname) == OK) { // consumes fname! ml_upd_block0(buf, UB_SAME_DIR); // Flush block zero, so others can read it @@ -835,7 +835,7 @@ void ml_recover(bool checkext) */ p = vim_strsave(fname_used); // save "fname_used" for the message: // mf_open() will consume "fname_used"! - mfp = mf_open(fname_used, O_RDONLY); + mfp = mf_open((char *)fname_used, O_RDONLY); fname_used = p; if (mfp == NULL || mfp->mf_fd < 0) { semsg(_("E306: Cannot open %s"), fname_used); @@ -926,7 +926,7 @@ void ml_recover(bool checkext) * If .swp file name given directly, use name from swap file for buffer. */ if (directly) { - expand_env(b0p->b0_fname, NameBuff, MAXPATHL); + expand_env(b0p->b0_fname, (char_u *)NameBuff, MAXPATHL); if (setfname(curbuf, (char *)NameBuff, NULL, true) == FAIL) { goto theend; } @@ -1873,7 +1873,7 @@ errorret: // when the GUI redraws part of the text. recursive++; get_trans_bufname(buf); - shorten_dir(NameBuff); + shorten_dir((char_u *)NameBuff); siemsg(_("E316: ml_get: cannot find line %" PRId64 " in buffer %d %s"), (int64_t)lnum, buf->b_fnum, NameBuff); recursive--; @@ -3472,8 +3472,8 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ // Symlinks may point to the same file even // when the name differs, need to check the // inode too. - expand_env(b0.b0_fname, NameBuff, MAXPATHL); - if (fnamecmp_ino((char_u *)buf->b_ffname, NameBuff, + expand_env(b0.b0_fname, (char_u *)NameBuff, MAXPATHL); + if (fnamecmp_ino((char_u *)buf->b_ffname, (char_u *)NameBuff, char_to_long(b0.b0_ino))) { differ = true; } @@ -3481,8 +3481,8 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ } else { // The name in the swap file may be // "~user/path/file". Expand it first. - expand_env(b0.b0_fname, NameBuff, MAXPATHL); - if (fnamecmp_ino((char_u *)buf->b_ffname, NameBuff, + expand_env(b0.b0_fname, (char_u *)NameBuff, MAXPATHL); + if (fnamecmp_ino((char_u *)buf->b_ffname, (char_u *)NameBuff, char_to_long(b0.b0_ino))) { differ = true; } diff --git a/src/nvim/message.c b/src/nvim/message.c index 40de8a2bc6..fbf9c9b603 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -3426,7 +3426,7 @@ int verbose_open(void) // Only give the error message once. verbose_did_open = true; - verbose_fd = os_fopen((char *)p_vfile, "a"); + verbose_fd = os_fopen(p_vfile, "a"); if (verbose_fd == NULL) { semsg(_(e_notopen), p_vfile); return FAIL; diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 31646f686d..5dd6742e2f 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -4807,14 +4807,14 @@ static void nv_search(cmdarg_T *cap) // When using 'incsearch' the cursor may be moved to set a different search // start position. - cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0, true); + cap->searchbuf = (char *)getcmdline(cap->cmdchar, cap->count1, 0, true); if (cap->searchbuf == NULL) { clearop(oap); return; } - (void)normal_search(cap, cap->cmdchar, cap->searchbuf, + (void)normal_search(cap, cap->cmdchar, (char_u *)cap->searchbuf, (cap->arg || !equalpos(save_cursor, curwin->w_cursor)) ? 0 : SEARCH_MARK, NULL); } diff --git a/src/nvim/normal.h b/src/nvim/normal.h index 9bda70eacd..13ea233658 100644 --- a/src/nvim/normal.h +++ b/src/nvim/normal.h @@ -57,7 +57,7 @@ typedef struct oparg_S { * Arguments for Normal mode commands. */ typedef struct cmdarg_S { - oparg_T *oap; // Operator arguments + oparg_T *oap; // Operator arguments int prechar; // prefix character (optional, always 'g') int cmdchar; // command character int nchar; // next command character (optional) @@ -69,7 +69,7 @@ typedef struct cmdarg_S { long count1; // count before command, default 1 int arg; // extra argument from nv_cmds[] int retval; // return: CA_* values - char_u *searchbuf; // return: pointer to search pattern or NULL + char *searchbuf; // return: pointer to search pattern or NULL } cmdarg_T; // values for retval: diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 0fc15b9382..1bf4c00633 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -1111,7 +1111,7 @@ int do_execreg(int regname, int colon, int addcr, int silent) // don't keep the cmdline containing @: XFREE_CLEAR(new_last_cmdline); // Escape all control characters with a CTRL-V - p = vim_strsave_escaped_ext(last_cmdline, + p = vim_strsave_escaped_ext((char_u *)last_cmdline, (char_u *)"\001\002\003\004\005\006\007" "\010\011\012\013\014\015\016\017" "\020\021\022\023\024\025\026\027" @@ -1346,7 +1346,7 @@ bool get_spec_reg(int regname, char **argp, bool *allocated, bool errmsg) if (last_cmdline == NULL && errmsg) { emsg(_(e_nolastcmd)); } - *argp = (char *)last_cmdline; + *argp = last_cmdline; return true; case '/': // last search-pattern @@ -3854,9 +3854,9 @@ void ex_display(exarg_T *eap) // display last command line if (last_cmdline != NULL && (arg == NULL || vim_strchr((char *)arg, ':') != NULL) - && !got_int && !message_filtered(last_cmdline)) { + && !got_int && !message_filtered((char_u *)last_cmdline)) { msg_puts("\n c \": "); - dis_msg(last_cmdline, false); + dis_msg((char_u *)last_cmdline, false); } // display current file name @@ -5799,7 +5799,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) // If 'cpoptions' does not contain 'r', insert the search // pattern to really repeat the same command. if (vim_strchr(p_cpo, CPO_REDO) == NULL) { - AppendToRedobuffLit((char *)cap->searchbuf, -1); + AppendToRedobuffLit(cap->searchbuf, -1); } AppendToRedobuff(NL_STR); } else if (cap->cmdchar == ':' || cap->cmdchar == K_COMMAND) { @@ -5809,7 +5809,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) if (repeat_cmdline == NULL) { ResetRedobuff(); } else { - AppendToRedobuffLit((char *)repeat_cmdline, -1); + AppendToRedobuffLit(repeat_cmdline, -1); AppendToRedobuff(NL_STR); XFREE_CLEAR(repeat_cmdline); } diff --git a/src/nvim/option.c b/src/nvim/option.c index 4bf978d2f6..c3f803e543 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -149,7 +149,7 @@ static int p_et_nopaste; static long p_sts_nopaste; static long p_tw_nopaste; static long p_wm_nopaste; -static char_u *p_vsts_nopaste; +static char *p_vsts_nopaste; typedef struct vimoption { char *fullname; // full option name @@ -455,7 +455,7 @@ static void set_option_default(int opt_idx, int opt_flags) char_u *varp; // pointer to variable for current option int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; - varp = get_varp_scope(&(options[opt_idx]), both ? OPT_LOCAL : opt_flags); + varp = (char_u *)get_varp_scope(&(options[opt_idx]), both ? OPT_LOCAL : opt_flags); uint32_t flags = options[opt_idx].flags; if (varp != NULL) { // skip hidden option, nothing to do for it if (flags & P_STRING) { @@ -675,12 +675,12 @@ void set_init_3(void) if (FNAMECMP(p, "csh") == 0 || FNAMECMP(p, "tcsh") == 0) { if (do_sp) { - p_sp = (char_u *)"|& tee"; - options[idx_sp].def_val = p_sp; + p_sp = "|& tee"; + options[idx_sp].def_val = (char_u *)p_sp; } if (do_srr) { - p_srr = (char_u *)">&"; - options[idx_srr].def_val = p_srr; + p_srr = ">&"; + options[idx_srr].def_val = (char_u *)p_srr; } } else if (FNAMECMP(p, "sh") == 0 || FNAMECMP(p, "ksh") == 0 @@ -694,12 +694,12 @@ void set_init_3(void) || FNAMECMP(p, "dash") == 0) { // Always use POSIX shell style redirection if we reach this if (do_sp) { - p_sp = (char_u *)"2>&1| tee"; - options[idx_sp].def_val = p_sp; + p_sp = "2>&1| tee"; + options[idx_sp].def_val = (char_u *)p_sp; } if (do_srr) { - p_srr = (char_u *)">%s 2>&1"; - options[idx_srr].def_val = p_srr; + p_srr = ">%s 2>&1"; + options[idx_srr].def_val = (char_u *)p_srr; } } xfree(p); @@ -810,7 +810,7 @@ int do_set(char *arg, int opt_flags) int opt_idx; char *errmsg; char errbuf[80]; - char_u *startarg; + char *startarg; int prefix; // 1: nothing, 0: "no", 2: "inv" in front of name char_u nextchar; // next non-white char after option name int afterchar; // character just after option name @@ -833,7 +833,7 @@ int do_set(char *arg, int opt_flags) while (*arg != NUL) { // loop to process all options errmsg = NULL; - startarg = (char_u *)arg; // remember for error message + startarg = arg; // remember for error message if (STRNCMP(arg, "all", 3) == 0 && !isalpha(arg[3]) && !(opt_flags & OPT_MODELINE)) { @@ -947,7 +947,7 @@ int do_set(char *arg, int opt_flags) } flags = options[opt_idx].flags; - varp = (char *)get_varp_scope(&(options[opt_idx]), opt_flags); + varp = get_varp_scope(&(options[opt_idx]), opt_flags); } else { flags = P_STRING; } @@ -1543,12 +1543,12 @@ skip: if (errmsg != NULL) { STRLCPY(IObuff, _(errmsg), IOSIZE); i = (int)STRLEN(IObuff) + 2; - if (i + ((char_u *)arg - startarg) < IOSIZE) { + if (i + (arg - startarg) < IOSIZE) { // append the argument with the error STRCAT(IObuff, ": "); - assert((char_u *)arg >= startarg); - memmove(IObuff + i, startarg, (size_t)((char_u *)arg - startarg)); - IObuff[i + ((char_u *)arg - startarg)] = NUL; + assert(arg >= startarg); + memmove(IObuff + i, startarg, (size_t)(arg - startarg)); + IObuff[i + (arg - startarg)] = NUL; } // make sure all characters are printable trans_characters((char *)IObuff, IOSIZE); @@ -1741,7 +1741,7 @@ static char_u *option_expand(int opt_idx, char_u *val) * names. * For 'spellsuggest' expand after "file:". */ - expand_env_esc(val, NameBuff, MAXPATHL, + expand_env_esc(val, (char_u *)NameBuff, MAXPATHL, (char_u **)options[opt_idx].var == &p_tags, false, (char_u **)options[opt_idx].var == (char_u **)&p_sps ? (char_u *)"file:" : NULL); @@ -1749,7 +1749,7 @@ static char_u *option_expand(int opt_idx, char_u *val) return NULL; } - return NameBuff; + return (char_u *)NameBuff; } /// After setting various option values: recompute variables that depend on @@ -1779,17 +1779,17 @@ static void didset_options2(void) highlight_changed(); // Parse default for 'fillchars'. - (void)set_chars_option(curwin, (char_u **)&curwin->w_p_fcs, true); + (void)set_chars_option(curwin, &curwin->w_p_fcs, true); // Parse default for 'listchars'. - (void)set_chars_option(curwin, (char_u **)&curwin->w_p_lcs, true); + (void)set_chars_option(curwin, &curwin->w_p_lcs, true); // Parse default for 'wildmode'. check_opt_wim(); xfree(curbuf->b_p_vsts_array); - (void)tabstop_set((char_u *)curbuf->b_p_vsts, &curbuf->b_p_vsts_array); + (void)tabstop_set(curbuf->b_p_vsts, &curbuf->b_p_vsts_array); xfree(curbuf->b_p_vts_array); - (void)tabstop_set((char_u *)curbuf->b_p_vts, &curbuf->b_p_vts_array); + (void)tabstop_set(curbuf->b_p_vts, &curbuf->b_p_vts_array); } /// Check for string options that are NULL (normally only termcap options). @@ -1858,10 +1858,10 @@ void redraw_titles(void) /// Return true if "val" is a valid name: only consists of alphanumeric ASCII /// characters or characters in "allowed". -bool valid_name(const char_u *val, const char *allowed) +bool valid_name(const char *val, const char *allowed) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { - for (const char_u *s = val; *s != NUL; s++) { + for (const char_u *s = (char_u *)val; *s != NUL; s++) { if (!ASCII_ISALNUM(*s) && vim_strchr(allowed, *s) == NULL) { return false; @@ -2930,14 +2930,14 @@ getoption_T get_option_value(const char *name, long *numval, char **stringval, i return gov_unknown; } - char_u *varp = get_varp_scope(&(options[opt_idx]), opt_flags); + char_u *varp = (char_u *)get_varp_scope(&(options[opt_idx]), opt_flags); if (options[opt_idx].flags & P_STRING) { if (varp == NULL) { // hidden option return gov_hidden_string; } if (stringval != NULL) { - if ((char_u **)varp == &p_pt) { // 'pastetoggle' + if ((char **)varp == &p_pt) { // 'pastetoggle' *stringval = str2special_save(*(char **)(varp), false, false); } else { *stringval = xstrdup(*(char **)(varp)); @@ -3056,7 +3056,7 @@ int get_option_value_strict(char *name, int64_t *numval, char **stringval, int o // only getting a pointer, no need to use aucmd_prepbuf() curbuf = (buf_T *)from; curwin->w_buffer = curbuf; - varp = get_varp_scope(p, OPT_LOCAL); + varp = (char_u *)get_varp_scope(p, OPT_LOCAL); curbuf = save_curbuf; curwin->w_buffer = curbuf; } @@ -3064,7 +3064,7 @@ int get_option_value_strict(char *name, int64_t *numval, char **stringval, int o win_T *save_curwin = curwin; curwin = (win_T *)from; curbuf = curwin->w_buffer; - varp = get_varp_scope(p, OPT_LOCAL); + varp = (char_u *)get_varp_scope(p, OPT_LOCAL); curwin = save_curwin; curbuf = curwin->w_buffer; } @@ -3170,7 +3170,7 @@ char *set_option_value(const char *const name, const long number, const char *co return set_string_option(opt_idx, s, opt_flags); } - varp = get_varp_scope(&(options[opt_idx]), opt_flags); + varp = (char_u *)get_varp_scope(&(options[opt_idx]), opt_flags); if (varp != NULL) { // hidden option is not changed if (number == 0 && string != NULL) { int idx; @@ -3306,7 +3306,7 @@ static void showoptions(int all, int opt_flags) varp = NULL; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) != 0) { if (p->indir != PV_NONE) { - varp = get_varp_scope(p, opt_flags); + varp = (char_u *)get_varp_scope(p, opt_flags); } } else { varp = get_varp(p); @@ -3410,13 +3410,12 @@ void ui_refresh_options(void) /// @param opt_flags OPT_LOCAL or OPT_GLOBAL static void showoneopt(vimoption_T *p, int opt_flags) { - char_u *varp; int save_silent = silent_mode; silent_mode = false; info_message = true; // use mch_msg(), not mch_errmsg() - varp = get_varp_scope(p, opt_flags); + char_u *varp = (char_u *)get_varp_scope(p, opt_flags); // for 'modified' we also need to check if 'ff' or 'fenc' changed. if ((p->flags & P_BOOL) && ((int *)varp == &curbuf->b_changed @@ -3462,7 +3461,7 @@ static void showoneopt(vimoption_T *p, int opt_flags) int makeset(FILE *fd, int opt_flags, int local_only) { vimoption_T *p; - char_u *varp; // currently used value + char *varp; // currently used value char_u *varp_fresh; // local value char_u *varp_local = NULL; // fresh value char *cmd; @@ -3499,7 +3498,7 @@ int makeset(FILE *fd, int opt_flags, int local_only) continue; } // Global values are only written when not at the default value. - if ((opt_flags & OPT_GLOBAL) && optval_default(p, varp)) { + if ((opt_flags & OPT_GLOBAL) && optval_default(p, (char_u *)varp)) { continue; } @@ -3518,11 +3517,11 @@ int makeset(FILE *fd, int opt_flags, int local_only) // When fresh value of window-local option is not at the // default, need to write it too. if (!(opt_flags & OPT_GLOBAL) && !local_only) { - varp_fresh = get_varp_scope(p, OPT_GLOBAL); + varp_fresh = (char_u *)get_varp_scope(p, OPT_GLOBAL); if (!optval_default(p, varp_fresh)) { round = 1; - varp_local = varp; - varp = varp_fresh; + varp_local = (char_u *)varp; + varp = (char *)varp_fresh; } } } @@ -3530,7 +3529,7 @@ int makeset(FILE *fd, int opt_flags, int local_only) // Round 1: fresh value for window-local options. // Round 2: other values - for (; round <= 2; varp = varp_local, round++) { + for (; round <= 2; varp = (char *)varp_local, round++) { if (round == 1 || (opt_flags & OPT_GLOBAL)) { cmd = "set"; } else { @@ -3558,8 +3557,7 @@ int makeset(FILE *fd, int opt_flags, int local_only) } do_endif = true; } - if (put_setstring(fd, cmd, p->fullname, (char_u **)varp, - p->flags) == FAIL) { + if (put_setstring(fd, cmd, p->fullname, (char **)varp, p->flags) == FAIL) { return FAIL; } if (do_endif) { @@ -3579,25 +3577,21 @@ int makeset(FILE *fd, int opt_flags, int local_only) /// 'sessionoptions' or 'viewoptions' contains "folds" but not "options". int makefoldset(FILE *fd) { - if (put_setstring(fd, "setlocal", "fdm", (char_u **)&curwin->w_p_fdm, 0) == FAIL - || put_setstring(fd, "setlocal", "fde", (char_u **)&curwin->w_p_fde, 0) - == FAIL - || put_setstring(fd, "setlocal", "fmr", (char_u **)&curwin->w_p_fmr, 0) - == FAIL - || put_setstring(fd, "setlocal", "fdi", (char_u **)&curwin->w_p_fdi, 0) - == FAIL + if (put_setstring(fd, "setlocal", "fdm", &curwin->w_p_fdm, 0) == FAIL + || put_setstring(fd, "setlocal", "fde", &curwin->w_p_fde, 0) == FAIL + || put_setstring(fd, "setlocal", "fmr", &curwin->w_p_fmr, 0) == FAIL + || put_setstring(fd, "setlocal", "fdi", &curwin->w_p_fdi, 0) == FAIL || put_setnum(fd, "setlocal", "fdl", &curwin->w_p_fdl) == FAIL || put_setnum(fd, "setlocal", "fml", &curwin->w_p_fml) == FAIL || put_setnum(fd, "setlocal", "fdn", &curwin->w_p_fdn) == FAIL - || put_setbool(fd, "setlocal", "fen", - curwin->w_p_fen) == FAIL) { + || put_setbool(fd, "setlocal", "fen", curwin->w_p_fen) == FAIL) { return FAIL; } return OK; } -static int put_setstring(FILE *fd, char *cmd, char *name, char_u **valuep, uint64_t flags) +static int put_setstring(FILE *fd, char *cmd, char *name, char **valuep, uint64_t flags) { char_u *s; char_u *buf = NULL; @@ -3612,7 +3606,7 @@ static int put_setstring(FILE *fd, char *cmd, char *name, char_u **valuep, uint6 // options some characters have to be escaped with // CTRL-V or backslash if (valuep == &p_pt) { - s = *valuep; + s = (char_u *)(*valuep); while (*s != NUL) { if (put_escstr(fd, (char_u *)str2special((const char **)&s, false, false), 2) @@ -3625,13 +3619,13 @@ static int put_setstring(FILE *fd, char *cmd, char *name, char_u **valuep, uint6 // replace home directory in the whole option value into "buf" buf = xmalloc(size); - home_replace(NULL, (char *)(*valuep), (char *)buf, size, false); + home_replace(NULL, *valuep, (char *)buf, size, false); // If the option value is longer than MAXPATHL, we need to append // each comma separated part of the option separately, so that it // can be expanded when read back. if (size >= MAXPATHL && (flags & P_COMMA) != 0 - && vim_strchr((char *)(*valuep), ',') != NULL) { + && vim_strchr(*valuep, ',') != NULL) { part = xmalloc(size); // write line break to clear the option, e.g. ':set rtp=' @@ -3659,7 +3653,7 @@ static int put_setstring(FILE *fd, char *cmd, char *name, char_u **valuep, uint6 return FAIL; } xfree(buf); - } else if (put_escstr(fd, *valuep, 2) == FAIL) { + } else if (put_escstr(fd, (char_u *)(*valuep), 2) == FAIL) { return FAIL; } } @@ -3798,12 +3792,12 @@ void unset_global_local_option(char *name, void *from) break; case PV_LCS: clear_string_option(&((win_T *)from)->w_p_lcs); - set_chars_option((win_T *)from, (char_u **)&((win_T *)from)->w_p_lcs, true); + set_chars_option((win_T *)from, &((win_T *)from)->w_p_lcs, true); redraw_later((win_T *)from, UPD_NOT_VALID); break; case PV_FCS: clear_string_option(&((win_T *)from)->w_p_fcs); - set_chars_option((win_T *)from, (char_u **)&((win_T *)from)->w_p_fcs, true); + set_chars_option((win_T *)from, &((win_T *)from)->w_p_fcs, true); redraw_later((win_T *)from, UPD_NOT_VALID); break; case PV_VE: @@ -3814,81 +3808,81 @@ void unset_global_local_option(char *name, void *from) } /// Get pointer to option variable, depending on local or global scope. -static char_u *get_varp_scope(vimoption_T *p, int opt_flags) +static char *get_varp_scope(vimoption_T *p, int opt_flags) { if ((opt_flags & OPT_GLOBAL) && p->indir != PV_NONE) { if (p->var == VAR_WIN) { - return (char_u *)GLOBAL_WO(get_varp(p)); + return GLOBAL_WO(get_varp(p)); } - return p->var; + return (char *)p->var; } if ((opt_flags & OPT_LOCAL) && ((int)p->indir & PV_BOTH)) { switch ((int)p->indir) { case PV_FP: - return (char_u *)&(curbuf->b_p_fp); + return (char *)&(curbuf->b_p_fp); case PV_EFM: - return (char_u *)&(curbuf->b_p_efm); + return (char *)&(curbuf->b_p_efm); case PV_GP: - return (char_u *)&(curbuf->b_p_gp); + return (char *)&(curbuf->b_p_gp); case PV_MP: - return (char_u *)&(curbuf->b_p_mp); + return (char *)&(curbuf->b_p_mp); case PV_EP: - return (char_u *)&(curbuf->b_p_ep); + return (char *)&(curbuf->b_p_ep); case PV_KP: - return (char_u *)&(curbuf->b_p_kp); + return (char *)&(curbuf->b_p_kp); case PV_PATH: - return (char_u *)&(curbuf->b_p_path); + return (char *)&(curbuf->b_p_path); case PV_AR: - return (char_u *)&(curbuf->b_p_ar); + return (char *)&(curbuf->b_p_ar); case PV_TAGS: - return (char_u *)&(curbuf->b_p_tags); + return (char *)&(curbuf->b_p_tags); case PV_TC: - return (char_u *)&(curbuf->b_p_tc); + return (char *)&(curbuf->b_p_tc); case PV_SISO: - return (char_u *)&(curwin->w_p_siso); + return (char *)&(curwin->w_p_siso); case PV_SO: - return (char_u *)&(curwin->w_p_so); + return (char *)&(curwin->w_p_so); case PV_DEF: - return (char_u *)&(curbuf->b_p_def); + return (char *)&(curbuf->b_p_def); case PV_INC: - return (char_u *)&(curbuf->b_p_inc); + return (char *)&(curbuf->b_p_inc); case PV_DICT: - return (char_u *)&(curbuf->b_p_dict); + return (char *)&(curbuf->b_p_dict); case PV_TSR: - return (char_u *)&(curbuf->b_p_tsr); + return (char *)&(curbuf->b_p_tsr); case PV_TSRFU: - return (char_u *)&(curbuf->b_p_tsrfu); + return (char *)&(curbuf->b_p_tsrfu); case PV_TFU: - return (char_u *)&(curbuf->b_p_tfu); + return (char *)&(curbuf->b_p_tfu); case PV_SBR: - return (char_u *)&(curwin->w_p_sbr); + return (char *)&(curwin->w_p_sbr); case PV_STL: - return (char_u *)&(curwin->w_p_stl); + return (char *)&(curwin->w_p_stl); case PV_WBR: - return (char_u *)&(curwin->w_p_wbr); + return (char *)&(curwin->w_p_wbr); case PV_UL: - return (char_u *)&(curbuf->b_p_ul); + return (char *)&(curbuf->b_p_ul); case PV_LW: - return (char_u *)&(curbuf->b_p_lw); + return (char *)&(curbuf->b_p_lw); case PV_BKC: - return (char_u *)&(curbuf->b_p_bkc); + return (char *)&(curbuf->b_p_bkc); case PV_MENC: - return (char_u *)&(curbuf->b_p_menc); + return (char *)&(curbuf->b_p_menc); case PV_FCS: - return (char_u *)&(curwin->w_p_fcs); + return (char *)&(curwin->w_p_fcs); case PV_LCS: - return (char_u *)&(curwin->w_p_lcs); + return (char *)&(curwin->w_p_lcs); case PV_VE: - return (char_u *)&(curwin->w_p_ve); + return (char *)&(curwin->w_p_ve); } return NULL; // "cannot happen" } - return get_varp(p); + return (char *)get_varp(p); } /// Get pointer to option variable at 'opt_idx', depending on local or global /// scope. -char_u *get_option_varp_scope(int opt_idx, int opt_flags) +char *get_option_varp_scope(int opt_idx, int opt_flags) { return get_varp_scope(&(options[opt_idx]), opt_flags); } @@ -4365,8 +4359,8 @@ void didset_window_options(win_T *wp, bool valid_cursor) check_colorcolumn(wp); briopt_check(wp); fill_culopt_flags(NULL, wp); - set_chars_option(wp, (char_u **)&wp->w_p_fcs, true); - set_chars_option(wp, (char_u **)&wp->w_p_lcs, true); + set_chars_option(wp, &wp->w_p_fcs, true); + set_chars_option(wp, &wp->w_p_lcs, true); parse_winhl_opt(wp); // sets w_hl_needs_update also for w_p_winbl check_blending(wp); set_winbar_win(wp, false, valid_cursor); @@ -4504,7 +4498,7 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_p_swf = p_swf; COPY_OPT_SCTX(buf, BV_SWF); } - buf->b_p_cpt = (char *)vim_strsave(p_cpt); + buf->b_p_cpt = xstrdup(p_cpt); COPY_OPT_SCTX(buf, BV_CPT); #ifdef BACKSLASH_IN_FILENAME buf->b_p_csl = vim_strsave(p_csl); @@ -4514,32 +4508,30 @@ void buf_copy_options(buf_T *buf, int flags) COPY_OPT_SCTX(buf, BV_CFU); buf->b_p_ofu = xstrdup(p_ofu); COPY_OPT_SCTX(buf, BV_OFU); - buf->b_p_tfu = (char *)vim_strsave(p_tfu); + buf->b_p_tfu = xstrdup(p_tfu); COPY_OPT_SCTX(buf, BV_TFU); buf->b_p_sts = p_sts; COPY_OPT_SCTX(buf, BV_STS); buf->b_p_sts_nopaste = p_sts_nopaste; - buf->b_p_vsts = (char *)vim_strsave(p_vsts); + buf->b_p_vsts = xstrdup(p_vsts); COPY_OPT_SCTX(buf, BV_VSTS); - if (p_vsts && p_vsts != (char_u *)empty_option) { + if (p_vsts && p_vsts != empty_option) { (void)tabstop_set(p_vsts, &buf->b_p_vsts_array); } else { buf->b_p_vsts_array = NULL; } - buf->b_p_vsts_nopaste = p_vsts_nopaste - ? (char *)vim_strsave(p_vsts_nopaste) - : NULL; + buf->b_p_vsts_nopaste = p_vsts_nopaste ? xstrdup(p_vsts_nopaste) : NULL; buf->b_p_com = xstrdup(p_com); COPY_OPT_SCTX(buf, BV_COM); - buf->b_p_cms = (char *)vim_strsave(p_cms); + buf->b_p_cms = xstrdup(p_cms); COPY_OPT_SCTX(buf, BV_CMS); - buf->b_p_fo = (char *)vim_strsave(p_fo); + buf->b_p_fo = xstrdup(p_fo); COPY_OPT_SCTX(buf, BV_FO); - buf->b_p_flp = (char *)vim_strsave(p_flp); + buf->b_p_flp = xstrdup(p_flp); COPY_OPT_SCTX(buf, BV_FLP); - buf->b_p_nf = (char *)vim_strsave(p_nf); + buf->b_p_nf = xstrdup(p_nf); COPY_OPT_SCTX(buf, BV_NF); - buf->b_p_mps = (char *)vim_strsave(p_mps); + buf->b_p_mps = xstrdup(p_mps); COPY_OPT_SCTX(buf, BV_MPS); buf->b_p_si = p_si; COPY_OPT_SCTX(buf, BV_SI); @@ -4569,25 +4561,25 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_p_smc = p_smc; COPY_OPT_SCTX(buf, BV_SMC); buf->b_s.b_syn_isk = empty_option; - buf->b_s.b_p_spc = (char *)vim_strsave(p_spc); + buf->b_s.b_p_spc = xstrdup(p_spc); COPY_OPT_SCTX(buf, BV_SPC); (void)compile_cap_prog(&buf->b_s); - buf->b_s.b_p_spf = (char *)vim_strsave(p_spf); + buf->b_s.b_p_spf = xstrdup(p_spf); COPY_OPT_SCTX(buf, BV_SPF); - buf->b_s.b_p_spl = (char *)vim_strsave(p_spl); + buf->b_s.b_p_spl = xstrdup(p_spl); COPY_OPT_SCTX(buf, BV_SPL); - buf->b_s.b_p_spo = (char *)vim_strsave(p_spo); + buf->b_s.b_p_spo = xstrdup(p_spo); COPY_OPT_SCTX(buf, BV_SPO); - buf->b_p_inde = (char *)vim_strsave(p_inde); + buf->b_p_inde = xstrdup(p_inde); COPY_OPT_SCTX(buf, BV_INDE); - buf->b_p_indk = (char *)vim_strsave(p_indk); + buf->b_p_indk = xstrdup(p_indk); COPY_OPT_SCTX(buf, BV_INDK); buf->b_p_fp = empty_option; - buf->b_p_fex = (char *)vim_strsave(p_fex); + buf->b_p_fex = xstrdup(p_fex); COPY_OPT_SCTX(buf, BV_FEX); buf->b_p_sua = xstrdup(p_sua); COPY_OPT_SCTX(buf, BV_SUA); - buf->b_p_keymap = (char *)vim_strsave(p_keymap); + buf->b_p_keymap = xstrdup(p_keymap); COPY_OPT_SCTX(buf, BV_KMAP); buf->b_kmap_state |= KEYMAP_INIT; // This isn't really an option, but copying the langmap and IME @@ -4614,12 +4606,12 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_tc_flags = 0; buf->b_p_def = empty_option; buf->b_p_inc = empty_option; - buf->b_p_inex = (char *)vim_strsave(p_inex); + buf->b_p_inex = xstrdup(p_inex); COPY_OPT_SCTX(buf, BV_INEX); buf->b_p_dict = empty_option; buf->b_p_tsr = empty_option; buf->b_p_tsrfu = empty_option; - buf->b_p_qe = (char *)vim_strsave(p_qe); + buf->b_p_qe = xstrdup(p_qe); COPY_OPT_SCTX(buf, BV_QE); buf->b_p_udf = p_udf; COPY_OPT_SCTX(buf, BV_UDF); @@ -4634,7 +4626,7 @@ void buf_copy_options(buf_T *buf, int flags) */ if (dont_do_help) { buf->b_p_isk = (char *)save_p_isk; - if (p_vts && p_vts != (char_u *)empty_option && !buf->b_p_vts_array) { + if (p_vts && p_vts != empty_option && !buf->b_p_vts_array) { (void)tabstop_set(p_vts, &buf->b_p_vts_array); } else { buf->b_p_vts_array = NULL; @@ -4645,9 +4637,9 @@ void buf_copy_options(buf_T *buf, int flags) did_isk = true; buf->b_p_ts = p_ts; COPY_OPT_SCTX(buf, BV_TS); - buf->b_p_vts = (char *)vim_strsave(p_vts); + buf->b_p_vts = xstrdup(p_vts); COPY_OPT_SCTX(buf, BV_VTS); - if (p_vts && p_vts != (char_u *)empty_option && !buf->b_p_vts_array) { + if (p_vts && p_vts != empty_option && !buf->b_p_vts_array) { (void)tabstop_set(p_vts, &buf->b_p_vts_array); } else { buf->b_p_vts_array = NULL; @@ -4966,7 +4958,7 @@ void ExpandOldSetting(int *num_file, char ***file) if (expand_option_idx >= 0) { // Put string of option value in NameBuff. option_value2string(&options[expand_option_idx], expand_option_flags); - var = NameBuff; + var = (char_u *)NameBuff; } else { var = (char_u *)""; } @@ -4999,9 +4991,7 @@ void ExpandOldSetting(int *num_file, char ***file) /// @param opt_flags OPT_GLOBAL and/or OPT_LOCAL static void option_value2string(vimoption_T *opp, int opt_flags) { - char_u *varp; - - varp = get_varp_scope(opp, opt_flags); + char_u *varp = (char_u *)get_varp_scope(opp, opt_flags); if (opp->flags & P_NUM) { long wc = 0; @@ -5023,7 +5013,7 @@ static void option_value2string(vimoption_T *opp, int opt_flags) } else if (opp->flags & P_EXPAND) { home_replace(NULL, (char *)varp, (char *)NameBuff, MAXPATHL, false); // Translate 'pastetoggle' into special key names. - } else if ((char_u **)opp->var == &p_pt) { + } else if ((char **)opp->var == &p_pt) { str2specialbuf((const char *)p_pt, (char *)NameBuff, MAXPATHL); } else { STRLCPY(NameBuff, varp, MAXPATHL); @@ -5052,7 +5042,7 @@ bool shortmess(int x) return (p_shm != NULL && (vim_strchr(p_shm, x) != NULL || (vim_strchr(p_shm, 'a') != NULL - && vim_strchr((char *)SHM_ALL_ABBREVIATIONS, x) != NULL))); + && vim_strchr(SHM_ALL_ABBREVIATIONS, x) != NULL))); } /// paste_option_changed() - Called after p_paste was set or reset. @@ -5101,9 +5091,7 @@ static void paste_option_changed(void) if (p_vsts_nopaste) { xfree(p_vsts_nopaste); } - p_vsts_nopaste = p_vsts && p_vsts != (char_u *)empty_option - ? vim_strsave(p_vsts) - : NULL; + p_vsts_nopaste = p_vsts && p_vsts != empty_option ? xstrdup(p_vsts) : NULL; } // Always set the option values, also when 'paste' is set when it is @@ -5137,9 +5125,9 @@ static void paste_option_changed(void) p_sts = 0; p_ai = 0; if (p_vsts) { - free_string_option((char *)p_vsts); + free_string_option(p_vsts); } - p_vsts = (char_u *)empty_option; + p_vsts = empty_option; } else if (old_p_paste) { // Paste switched from on to off: Restore saved values. @@ -5156,7 +5144,7 @@ static void paste_option_changed(void) buf->b_p_vsts = buf->b_p_vsts_nopaste ? xstrdup(buf->b_p_vsts_nopaste) : empty_option; xfree(buf->b_p_vsts_array); if (buf->b_p_vsts && buf->b_p_vsts != empty_option) { - (void)tabstop_set((char_u *)buf->b_p_vsts, &buf->b_p_vsts_array); + (void)tabstop_set(buf->b_p_vsts, &buf->b_p_vsts_array); } else { buf->b_p_vsts_array = NULL; } @@ -5178,9 +5166,9 @@ static void paste_option_changed(void) p_tw = p_tw_nopaste; p_wm = p_wm_nopaste; if (p_vsts) { - free_string_option((char *)p_vsts); + free_string_option(p_vsts); } - p_vsts = p_vsts_nopaste ? vim_strsave(p_vsts_nopaste) : (char_u *)empty_option; + p_vsts = p_vsts_nopaste ? xstrdup(p_vsts_nopaste) : empty_option; } old_p_paste = p_paste; @@ -5248,20 +5236,20 @@ void fill_breakat_flags(void) } if (p_breakat != NULL) { - for (p = p_breakat; *p; p++) { + for (p = (char_u *)p_breakat; *p; p++) { breakat_flags[*p] = true; } } } /// fill_culopt_flags() -- called when 'culopt' changes value -int fill_culopt_flags(char_u *val, win_T *wp) +int fill_culopt_flags(char *val, win_T *wp) { - char_u *p; + char *p; char_u culopt_flags_new = 0; if (val == NULL) { - p = (char_u *)wp->w_p_culopt; + p = wp->w_p_culopt; } else { p = val; } @@ -5473,7 +5461,7 @@ void set_fileformat(int eol_style, int opt_flags) } /// Skip to next part of an option argument: skip space and comma -char_u *skip_to_option_part(const char_u *p) +char *skip_to_option_part(const char *p) { if (*p == ',') { p++; @@ -5481,7 +5469,7 @@ char_u *skip_to_option_part(const char_u *p) while (*p == ' ') { p++; } - return (char_u *)p; + return (char *)p; } /// Isolate one part of a string option separated by `sep_chars`. @@ -5516,7 +5504,7 @@ size_t copy_option_part(char **option, char *buf, size_t maxlen, char *sep_chars if (*p != NUL && *p != ',') { // skip non-standard separator p++; } - p = (char *)skip_to_option_part((char_u *)p); // p points to next file name + p = skip_to_option_part(p); // p points to next file name *option = p; return len; diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index 59b8485272..6af6b16e86 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -258,7 +258,7 @@ enum { SHM_SEARCHCOUNT = 'S', ///< Search sats: '[1/10]' }; /// Represented by 'a' flag. -#define SHM_ALL_ABBREVIATIONS ((char_u[]) { \ +#define SHM_ALL_ABBREVIATIONS ((char[]) { \ SHM_RO, SHM_MOD, SHM_FILE, SHM_LAST, SHM_TEXT, SHM_LINES, SHM_NEW, SHM_WRI, \ 0, \ }) @@ -440,9 +440,9 @@ EXTERN unsigned bo_flags; #define BO_WILD 0x40000 EXTERN char_u *p_bsk; // 'backupskip' -EXTERN char_u *p_breakat; // 'breakat' -EXTERN char_u *p_bh; ///< 'bufhidden' -EXTERN char_u *p_bt; ///< 'buftype' +EXTERN char *p_breakat; // 'breakat' +EXTERN char *p_bh; ///< 'bufhidden' +EXTERN char *p_bt; ///< 'buftype' EXTERN char *p_cmp; // 'casemap' EXTERN unsigned cmp_flags; #define CMP_INTERNAL 0x001 @@ -459,8 +459,8 @@ EXTERN unsigned cb_flags; #define CB_UNNAMEDMASK (CB_UNNAMED | CB_UNNAMEDPLUS) EXTERN long p_cwh; // 'cmdwinheight' EXTERN long p_ch; // 'cmdheight' -EXTERN char_u *p_cms; ///< 'commentstring' -EXTERN char_u *p_cpt; ///< 'complete' +EXTERN char *p_cms; ///< 'commentstring' +EXTERN char *p_cpt; ///< 'complete' EXTERN long p_columns; // 'columns' EXTERN int p_confirm; // 'confirm' EXTERN char *p_cot; // 'completeopt' @@ -533,9 +533,9 @@ EXTERN unsigned fdo_flags; #define FDO_INSERT 0x100 #define FDO_UNDO 0x200 #define FDO_JUMP 0x400 -EXTERN char_u *p_fex; ///< 'formatexpr' -EXTERN char_u *p_flp; ///< 'formatlistpat' -EXTERN char_u *p_fo; ///< 'formatoptions' +EXTERN char *p_fex; ///< 'formatexpr' +EXTERN char *p_flp; ///< 'formatlistpat' +EXTERN char *p_fo; ///< 'formatoptions' EXTERN char_u *p_fp; // 'formatprg' EXTERN int p_fs; // 'fsync' EXTERN int p_gd; // 'gdefault' @@ -566,10 +566,10 @@ EXTERN int p_ic; // 'ignorecase' EXTERN long p_iminsert; ///< 'iminsert' EXTERN long p_imsearch; ///< 'imsearch' EXTERN int p_inf; ///< 'infercase' -EXTERN char_u *p_inex; ///< 'includeexpr' +EXTERN char *p_inex; ///< 'includeexpr' EXTERN int p_is; // 'incsearch' -EXTERN char_u *p_inde; ///< 'indentexpr' -EXTERN char_u *p_indk; ///< 'indentkeys' +EXTERN char *p_inde; ///< 'indentexpr' +EXTERN char *p_indk; ///< 'indentkeys' EXTERN char *p_icm; // 'inccommand' EXTERN char *p_isf; // 'isfname' EXTERN char *p_isi; // 'isident' @@ -580,7 +580,7 @@ EXTERN char *p_jop; // 'jumpooptions' EXTERN unsigned jop_flags; #define JOP_STACK 0x01 #define JOP_VIEW 0x02 -EXTERN char_u *p_keymap; ///< 'keymap' +EXTERN char *p_keymap; ///< 'keymap' EXTERN char_u *p_kp; // 'keywordprg' EXTERN char *p_km; // 'keymodel' EXTERN char *p_langmap; // 'langmap' @@ -598,11 +598,11 @@ EXTERN char *p_lcs; // 'listchars' EXTERN int p_lz; // 'lazyredraw' EXTERN int p_lpl; // 'loadplugins' EXTERN int p_magic; // 'magic' -EXTERN char_u *p_menc; // 'makeencoding' -EXTERN char *p_mef; // 'makeef' -EXTERN char_u *p_mp; // 'makeprg' -EXTERN char_u *p_mps; ///< 'matchpairs' -EXTERN char_u *p_cc; // 'colorcolumn' +EXTERN char *p_menc; // 'makeencoding' +EXTERN char *p_mef; // 'makeef' +EXTERN char_u *p_mp; // 'makeprg' +EXTERN char *p_mps; ///< 'matchpairs' +EXTERN char_u *p_cc; // 'colorcolumn' EXTERN int p_cc_cols[256]; // array for 'colorcolumn' columns EXTERN long p_mat; // 'matchtime' EXTERN long p_mco; // 'maxcombine' @@ -624,18 +624,18 @@ EXTERN long p_mousescroll_vert INIT(= MOUSESCROLL_VERT_DFLT); EXTERN long p_mousescroll_hor INIT(= MOUSESCROLL_HOR_DFLT); EXTERN long p_mouset; // 'mousetime' EXTERN int p_more; // 'more' -EXTERN char_u *p_nf; ///< 'nrformats' +EXTERN char *p_nf; ///< 'nrformats' EXTERN char *p_opfunc; // 'operatorfunc' -EXTERN char_u *p_para; // 'paragraphs' +EXTERN char_u *p_para; // 'paragraphs' EXTERN int p_paste; // 'paste' -EXTERN char_u *p_pt; // 'pastetoggle' -EXTERN char_u *p_pex; // 'patchexpr' -EXTERN char *p_pm; // 'patchmode' -EXTERN char_u *p_path; // 'path' -EXTERN char_u *p_cdpath; // 'cdpath' +EXTERN char *p_pt; // 'pastetoggle' +EXTERN char_u *p_pex; // 'patchexpr' +EXTERN char *p_pm; // 'patchmode' +EXTERN char_u *p_path; // 'path' +EXTERN char_u *p_cdpath; // 'cdpath' EXTERN int p_pi; ///< 'preserveindent' EXTERN long p_pyx; // 'pyxversion' -EXTERN char_u *p_qe; ///< 'quoteescape' +EXTERN char *p_qe; ///< 'quoteescape' EXTERN int p_ro; ///< 'readonly' EXTERN char *p_rdb; // 'redrawdebug' EXTERN unsigned rdb_flags; @@ -685,13 +685,13 @@ EXTERN unsigned ssop_flags; #define SSOP_TERMINAL 0x10000 #define SSOP_SKIP_RTP 0x20000 -EXTERN char_u *p_sh; // 'shell' -EXTERN char_u *p_shcf; // 'shellcmdflag' -EXTERN char_u *p_sp; // 'shellpipe' -EXTERN char_u *p_shq; // 'shellquote' -EXTERN char_u *p_sxq; // 'shellxquote' -EXTERN char_u *p_sxe; // 'shellxescape' -EXTERN char_u *p_srr; // 'shellredir' +EXTERN char_u *p_sh; // 'shell' +EXTERN char_u *p_shcf; // 'shellcmdflag' +EXTERN char *p_sp; // 'shellpipe' +EXTERN char_u *p_shq; // 'shellquote' +EXTERN char_u *p_sxq; // 'shellxquote' +EXTERN char_u *p_sxe; // 'shellxescape' +EXTERN char *p_srr; // 'shellredir' EXTERN int p_stmp; // 'shelltemp' #ifdef BACKSLASH_IN_FILENAME EXTERN int p_ssl; // 'shellslash' @@ -727,11 +727,11 @@ EXTERN unsigned int tpf_flags; ///< flags from 'termpastefilter' #define TPF_DEL 0x010 #define TPF_C0 0x020 #define TPF_C1 0x040 -EXTERN char_u *p_tfu; ///< 'tagfunc' -EXTERN char_u *p_spc; ///< 'spellcapcheck' -EXTERN char_u *p_spf; ///< 'spellfile' -EXTERN char_u *p_spl; ///< 'spelllang' -EXTERN char_u *p_spo; // 'spelloptions' +EXTERN char *p_tfu; ///< 'tagfunc' +EXTERN char *p_spc; ///< 'spellcapcheck' +EXTERN char *p_spf; ///< 'spellfile' +EXTERN char *p_spl; ///< 'spelllang' +EXTERN char *p_spo; // 'spelloptions' EXTERN char *p_sps; // 'spellsuggest' EXTERN int p_spr; // 'splitright' EXTERN int p_sol; // 'startofline' @@ -745,7 +745,7 @@ EXTERN unsigned swb_flags; #define SWB_NEWTAB 0x008 #define SWB_VSPLIT 0x010 #define SWB_USELAST 0x020 -EXTERN char_u *p_syn; ///< 'syntax' +EXTERN char *p_syn; ///< 'syntax' EXTERN long p_ts; ///< 'tabstop' EXTERN int p_tbs; ///< 'tagbsearch' EXTERN char *p_tc; ///< 'tagcase' @@ -780,13 +780,13 @@ EXTERN long p_uc; ///< 'updatecount' EXTERN long p_ut; ///< 'updatetime' EXTERN char *p_shada; ///< 'shada' EXTERN char *p_shadafile; ///< 'shadafile' -EXTERN char_u *p_vsts; ///< 'varsofttabstop' -EXTERN char_u *p_vts; ///< 'vartabstop' +EXTERN char *p_vsts; ///< 'varsofttabstop' +EXTERN char *p_vts; ///< 'vartabstop' EXTERN char_u *p_vdir; ///< 'viewdir' EXTERN char *p_vop; ///< 'viewoptions' EXTERN unsigned vop_flags; ///< uses SSOP_ flags EXTERN int p_vb; ///< 'visualbell' -EXTERN char_u *p_ve; ///< 'virtualedit' +EXTERN char *p_ve; ///< 'virtualedit' EXTERN unsigned ve_flags; #define VE_BLOCK 5U // includes "all" #define VE_INSERT 6U // includes "all" @@ -798,7 +798,7 @@ EXTERN long p_verbose; // 'verbose' #ifdef IN_OPTION_C char_u *p_vfile = (char_u *)""; // used before options are initialized #else -extern char_u *p_vfile; // 'verbosefile' +extern char *p_vfile; // 'verbosefile' #endif EXTERN int p_warn; // 'warn' EXTERN char *p_wop; // 'wildoptions' diff --git a/src/nvim/optionstr.c b/src/nvim/optionstr.c index 808a70c8cb..1bdfcbecb9 100644 --- a/src/nvim/optionstr.c +++ b/src/nvim/optionstr.c @@ -113,30 +113,30 @@ static char *(p_tpf_values[]) = { "BS", "HT", "FF", "ESC", "DEL", "C0", "C1", NU static char *(p_rdb_values[]) = { "compositor", "nothrottle", "invalid", "nodelta", NULL }; /// All possible flags for 'shm'. -static char_u SHM_ALL[] = { SHM_RO, SHM_MOD, SHM_FILE, SHM_LAST, SHM_TEXT, SHM_LINES, SHM_NEW, - SHM_WRI, SHM_ABBREVIATIONS, SHM_WRITE, SHM_TRUNC, SHM_TRUNCALL, - SHM_OVER, SHM_OVERALL, SHM_SEARCH, SHM_ATTENTION, SHM_INTRO, - SHM_COMPLETIONMENU, SHM_RECORDING, SHM_FILEINFO, SHM_SEARCHCOUNT, 0, }; +static char SHM_ALL[] = { SHM_RO, SHM_MOD, SHM_FILE, SHM_LAST, SHM_TEXT, SHM_LINES, SHM_NEW, + SHM_WRI, SHM_ABBREVIATIONS, SHM_WRITE, SHM_TRUNC, SHM_TRUNCALL, + SHM_OVER, SHM_OVERALL, SHM_SEARCH, SHM_ATTENTION, SHM_INTRO, + SHM_COMPLETIONMENU, SHM_RECORDING, SHM_FILEINFO, SHM_SEARCHCOUNT, 0, }; /// After setting various option values: recompute variables that depend on /// option values. void didset_string_options(void) { - (void)opt_strings_flags((char_u *)p_cmp, p_cmp_values, &cmp_flags, true); - (void)opt_strings_flags((char_u *)p_bkc, p_bkc_values, &bkc_flags, true); - (void)opt_strings_flags((char_u *)p_bo, p_bo_values, &bo_flags, true); - (void)opt_strings_flags((char_u *)p_ssop, p_ssop_values, &ssop_flags, true); - (void)opt_strings_flags((char_u *)p_vop, p_ssop_values, &vop_flags, true); - (void)opt_strings_flags((char_u *)p_fdo, p_fdo_values, &fdo_flags, true); - (void)opt_strings_flags((char_u *)p_dy, p_dy_values, &dy_flags, true); - (void)opt_strings_flags((char_u *)p_rdb, p_rdb_values, &rdb_flags, true); - (void)opt_strings_flags((char_u *)p_tc, p_tc_values, &tc_flags, false); - (void)opt_strings_flags((char_u *)p_tpf, p_tpf_values, &tpf_flags, true); + (void)opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, true); + (void)opt_strings_flags(p_bkc, p_bkc_values, &bkc_flags, true); + (void)opt_strings_flags(p_bo, p_bo_values, &bo_flags, true); + (void)opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, true); + (void)opt_strings_flags(p_vop, p_ssop_values, &vop_flags, true); + (void)opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true); + (void)opt_strings_flags(p_dy, p_dy_values, &dy_flags, true); + (void)opt_strings_flags(p_rdb, p_rdb_values, &rdb_flags, true); + (void)opt_strings_flags(p_tc, p_tc_values, &tc_flags, false); + (void)opt_strings_flags(p_tpf, p_tpf_values, &tpf_flags, true); (void)opt_strings_flags(p_ve, p_ve_values, &ve_flags, true); - (void)opt_strings_flags((char_u *)p_swb, p_swb_values, &swb_flags, true); - (void)opt_strings_flags((char_u *)p_wop, p_wop_values, &wop_flags, true); - (void)opt_strings_flags((char_u *)p_jop, p_jop_values, &jop_flags, true); - (void)opt_strings_flags((char_u *)p_cb, p_cb_values, &cb_flags, true); + (void)opt_strings_flags(p_swb, p_swb_values, &swb_flags, true); + (void)opt_strings_flags(p_wop, p_wop_values, &wop_flags, true); + (void)opt_strings_flags(p_jop, p_jop_values, &jop_flags, true); + (void)opt_strings_flags(p_cb, p_cb_values, &cb_flags, true); } /// Trigger the OptionSet autocommand. @@ -448,7 +448,7 @@ char *set_string_option(const int opt_idx, const char *const value, const int op /// Return true if "val" is a valid 'filetype' name. /// Also used for 'syntax' and 'keymap'. -static bool valid_filetype(const char_u *val) +static bool valid_filetype(const char *val) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { return valid_name(val, ".-_"); @@ -520,7 +520,7 @@ static char *check_mousescroll(char *string) /// Handle setting 'signcolumn' for value 'val' /// /// @return OK when the value is valid, FAIL otherwise -static int check_signcolumn(char_u *val) +static int check_signcolumn(char *val) { if (*val == NUL) { return FAIL; @@ -637,13 +637,12 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf char *errmsg = NULL; char *s, *p; int did_chartab = false; - char_u **gvarp; bool free_oldval = (get_option_flags(opt_idx) & P_ALLOCED); bool value_changed = false; // Get the global option to compare with, otherwise we would have to check // two values for all local options. - gvarp = (char_u **)get_option_varp_scope(opt_idx, OPT_GLOBAL); + char **gvarp = (char **)get_option_varp_scope(opt_idx, OPT_GLOBAL); // Disallow changing some options from secure mode if ((secure || sandbox != 0) @@ -657,7 +656,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf // path separator (slash and/or backslash), wildcards and characters that // are often illegal in a file name. Be more permissive if "secure" is off. errmsg = e_invarg; - } else if (gvarp == (char_u **)&p_bkc) { // 'backupcopy' + } else if (gvarp == &p_bkc) { // 'backupcopy' char *bkc = p_bkc; unsigned int *flags = &bkc_flags; @@ -670,7 +669,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf // make the local value empty: use the global value *flags = 0; } else { - if (opt_strings_flags((char_u *)bkc, p_bkc_values, flags, true) != OK) { + if (opt_strings_flags(bkc, p_bkc_values, flags, true) != OK) { errmsg = e_invarg; } @@ -678,7 +677,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf + ((*flags & BKC_YES) != 0) + ((*flags & BKC_NO) != 0) != 1) { // Must have exactly one of "auto", "yes" and "no". - (void)opt_strings_flags((char_u *)oldval, p_bkc_values, flags, true); + (void)opt_strings_flags(oldval, p_bkc_values, flags, true); errmsg = e_invarg; } } @@ -713,8 +712,8 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } else if (varp == &p_rtp || varp == &p_pp) { // 'runtimepath' 'packpath' runtime_search_path_invalidate(); } else if (varp == &curwin->w_p_culopt - || gvarp == (char_u **)&curwin->w_allbuf_opt.wo_culopt) { // 'cursorlineopt' - if (**varp == NUL || fill_culopt_flags((char_u *)(*varp), curwin) != OK) { + || gvarp == &curwin->w_allbuf_opt.wo_culopt) { // 'cursorlineopt' + if (**varp == NUL || fill_culopt_flags(*varp, curwin) != OK) { errmsg = e_invarg; } } else if (varp == &curwin->w_p_cc) { // 'colorcolumn' @@ -735,42 +734,42 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf errmsg = e_unsupportedoption; } } else if (varp == &p_jop) { // 'jumpoptions' - if (opt_strings_flags((char_u *)p_jop, p_jop_values, &jop_flags, true) != OK) { + if (opt_strings_flags(p_jop, p_jop_values, &jop_flags, true) != OK) { errmsg = e_invarg; } } else if (gvarp == &p_nf) { // 'nrformats' - if (check_opt_strings((char_u *)(*varp), p_nf_values, true) != OK) { + if (check_opt_strings(*varp, p_nf_values, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_ssop) { // 'sessionoptions' - if (opt_strings_flags((char_u *)p_ssop, p_ssop_values, &ssop_flags, true) != OK) { + if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, true) != OK) { errmsg = e_invarg; } if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR)) { // Don't allow both "sesdir" and "curdir". - (void)opt_strings_flags((char_u *)oldval, p_ssop_values, &ssop_flags, true); + (void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, true); errmsg = e_invarg; } } else if (varp == &p_vop) { // 'viewoptions' - if (opt_strings_flags((char_u *)p_vop, p_ssop_values, &vop_flags, true) != OK) { + if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_rdb) { // 'redrawdebug' - if (opt_strings_flags((char_u *)p_rdb, p_rdb_values, &rdb_flags, true) != OK) { + if (opt_strings_flags(p_rdb, p_rdb_values, &rdb_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_sbo) { // 'scrollopt' - if (check_opt_strings((char_u *)p_sbo, p_scbopt_values, true) != OK) { + if (check_opt_strings(p_sbo, p_scbopt_values, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_ambw || (int *)varp == &p_emoji) { // 'ambiwidth' - if (check_opt_strings((char_u *)p_ambw, p_ambw_values, false) != OK) { + if (check_opt_strings(p_ambw, p_ambw_values, false) != OK) { errmsg = e_invarg; } else { errmsg = check_chars_options(); } } else if (varp == &p_bg) { // 'background' - if (check_opt_strings((char_u *)p_bg, p_bg_values, false) == OK) { + if (check_opt_strings(p_bg, p_bg_values, false) == OK) { int dark = (*p_bg == 'd'); init_highlight(false, false); @@ -793,21 +792,21 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf errmsg = e_invarg; } } else if (varp == &p_wop) { // 'wildoptions' - if (opt_strings_flags((char_u *)p_wop, p_wop_values, &wop_flags, true) != OK) { + if (opt_strings_flags(p_wop, p_wop_values, &wop_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_wak) { // 'winaltkeys' if (*p_wak == NUL - || check_opt_strings((char_u *)p_wak, p_wak_values, false) != OK) { + || check_opt_strings(p_wak, p_wak_values, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_ei) { // 'eventignore' if (check_ei() == FAIL) { errmsg = e_invarg; } - } else if (varp == &p_enc || gvarp == (char_u **)&p_fenc || gvarp == &p_menc) { + } else if (varp == &p_enc || gvarp == &p_fenc || gvarp == &p_menc) { // 'encoding', 'fileencoding' and 'makeencoding' - if (gvarp == (char_u **)&p_fenc) { + if (gvarp == &p_fenc) { if (!MODIFIABLE(curbuf) && opt_flags != OPT_GLOBAL) { errmsg = e_modifiable; } else if (vim_strchr(*varp, ',') != NULL) { @@ -824,7 +823,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf if (errmsg == NULL) { // canonize the value, so that STRCMP() can be used on it - p = (char *)enc_canonize((char_u *)(*varp)); + p = enc_canonize(*varp); xfree(*varp); *varp = p; if (varp == &p_enc) { @@ -838,11 +837,11 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } else if (varp == &p_penc) { // Canonize printencoding if VIM standard one - p = (char *)enc_canonize((char_u *)p_penc); + p = enc_canonize(p_penc); xfree(p_penc); p_penc = p; } else if (varp == &curbuf->b_p_keymap) { - if (!valid_filetype((char_u *)(*varp))) { + if (!valid_filetype(*varp)) { errmsg = e_invarg; } else { int secure_save = secure; @@ -883,10 +882,10 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } status_redraw_curbuf(); } - } else if (gvarp == (char_u **)&p_ff) { // 'fileformat' + } else if (gvarp == &p_ff) { // 'fileformat' if (!MODIFIABLE(curbuf) && !(opt_flags & OPT_GLOBAL)) { errmsg = e_modifiable; - } else if (check_opt_strings((char_u *)(*varp), p_ff_values, false) != OK) { + } else if (check_opt_strings(*varp, p_ff_values, false) != OK) { errmsg = e_invarg; } else { redraw_titles(); @@ -899,7 +898,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } } else if (varp == &p_ffs) { // 'fileformats' - if (check_opt_strings((char_u *)p_ffs, p_ff_values, true) != OK) { + if (check_opt_strings(p_ffs, p_ff_values, true) != OK) { errmsg = e_invarg; } } else if (gvarp == &p_mps) { // 'matchpairs' @@ -923,7 +922,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf break; } } - } else if (gvarp == (char_u **)&p_com) { // 'comments' + } else if (gvarp == &p_com) { // 'comments' for (s = *varp; *s;) { while (*s && *s != ':') { if (vim_strchr(COM_ALL, *s) == NULL @@ -947,13 +946,13 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } s++; } - s = (char *)skip_to_option_part((char_u *)s); + s = skip_to_option_part(s); } } else if (varp == &p_lcs || varp == &p_fcs) { // global 'listchars' or 'fillchars' char **local_ptr = varp == &p_lcs ? &curwin->w_p_lcs : &curwin->w_p_fcs; // only apply the global value to "curwin" when it does not have a local value errmsg = - set_chars_option(curwin, (char_u **)varp, **local_ptr == NUL || !(opt_flags & OPT_GLOBAL)); + set_chars_option(curwin, varp, **local_ptr == NUL || !(opt_flags & OPT_GLOBAL)); if (errmsg == NULL) { // If the current window is set to use the global // 'listchars'/'fillchars' value, clear the window-local value. @@ -967,18 +966,18 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf // here, so ignore the return value. local_ptr = varp == &p_lcs ? &wp->w_p_lcs : &wp->w_p_fcs; if (**local_ptr == NUL) { - (void)set_chars_option(wp, (char_u **)local_ptr, true); + (void)set_chars_option(wp, local_ptr, true); } } redraw_all_later(UPD_NOT_VALID); } } else if (varp == &curwin->w_p_lcs) { // local 'listchars' - errmsg = set_chars_option(curwin, (char_u **)varp, true); + errmsg = set_chars_option(curwin, varp, true); } else if (varp == &curwin->w_p_fcs) { // local 'fillchars' - errmsg = set_chars_option(curwin, (char_u **)varp, true); + errmsg = set_chars_option(curwin, varp, true); } else if (varp == &p_cedit) { // 'cedit' errmsg = check_cedit(); - } else if (varp == (char **)&p_vfile) { // 'verbosefile' + } else if (varp == &p_vfile) { // 'verbosefile' verbose_stop(); if (*p_vfile != NUL && verbose_open() == FAIL) { errmsg = e_invarg; @@ -1037,7 +1036,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf if (*p_shada && errmsg == NULL && get_shada_parameter('\'') < 0) { errmsg = N_("E528: Must specify a ' value"); } - } else if (gvarp == (char_u **)&p_sbr) { // 'showbreak' + } else if (gvarp == &p_sbr) { // 'showbreak' for (s = *varp; *s;) { if (ptr2cells(s) != 1) { errmsg = e_showbreak_contains_unprintable_or_wide_character; @@ -1052,7 +1051,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf errmsg = parse_printmbfont(); } else if (varp == &p_langmap) { // 'langmap' langmap_set(); - } else if (varp == (char **)&p_breakat) { // 'breakat' + } else if (varp == &p_breakat) { // 'breakat' fill_breakat_flags(); } else if (varp == &p_titlestring || varp == &p_iconstring) { // 'titlestring' and 'iconstring' @@ -1067,47 +1066,47 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf did_set_title(); } else if (varp == &p_sel) { // 'selection' if (*p_sel == NUL - || check_opt_strings((char_u *)p_sel, p_sel_values, false) != OK) { + || check_opt_strings(p_sel, p_sel_values, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_slm) { // 'selectmode' - if (check_opt_strings((char_u *)p_slm, p_slm_values, true) != OK) { + if (check_opt_strings(p_slm, p_slm_values, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_km) { // 'keymodel' - if (check_opt_strings((char_u *)p_km, p_km_values, true) != OK) { + if (check_opt_strings(p_km, p_km_values, true) != OK) { errmsg = e_invarg; } else { km_stopsel = (vim_strchr(p_km, 'o') != NULL); km_startsel = (vim_strchr(p_km, 'a') != NULL); } } else if (varp == &p_mousem) { // 'mousemodel' - if (check_opt_strings((char_u *)p_mousem, p_mousem_values, false) != OK) { + if (check_opt_strings(p_mousem, p_mousem_values, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_mousescroll) { // 'mousescroll' errmsg = check_mousescroll(p_mousescroll); } else if (varp == &p_swb) { // 'switchbuf' - if (opt_strings_flags((char_u *)p_swb, p_swb_values, &swb_flags, true) != OK) { + if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_debug) { // 'debug' - if (check_opt_strings((char_u *)p_debug, p_debug_values, true) != OK) { + if (check_opt_strings(p_debug, p_debug_values, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_dy) { // 'display' - if (opt_strings_flags((char_u *)p_dy, p_dy_values, &dy_flags, true) != OK) { + if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, true) != OK) { errmsg = e_invarg; } else { (void)init_chartab(); msg_grid_validate(); } } else if (varp == &p_ead) { // 'eadirection' - if (check_opt_strings((char_u *)p_ead, p_ead_values, false) != OK) { + if (check_opt_strings(p_ead, p_ead_values, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_cb) { // 'clipboard' - if (opt_strings_flags((char_u *)p_cb, p_cb_values, &cb_flags, true) != OK) { + if (opt_strings_flags(p_cb, p_cb_values, &cb_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &(curwin->w_s->b_p_spl) // 'spell' @@ -1116,8 +1115,8 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf // buffer in which 'spell' is set load the wordlists. const bool is_spellfile = varp == &(curwin->w_s->b_p_spf); - if ((is_spellfile && !valid_spellfile((char_u *)(*varp))) - || (!is_spellfile && !valid_spelllang((char_u *)(*varp)))) { + if ((is_spellfile && !valid_spellfile(*varp)) + || (!is_spellfile && !valid_spelllang(*varp))) { errmsg = e_invarg; } else { errmsg = did_set_spell_option(is_spellfile); @@ -1139,14 +1138,14 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } else if (gvarp == &p_bh) { // When 'bufhidden' is set, check for valid value. - if (check_opt_strings((char_u *)curbuf->b_p_bh, p_bufhidden_values, false) != OK) { + if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, false) != OK) { errmsg = e_invarg; } } else if (gvarp == &p_bt) { // When 'buftype' is set, check for valid value. if ((curbuf->terminal && curbuf->b_p_bt[0] != 't') || (!curbuf->terminal && curbuf->b_p_bt[0] == 't') - || check_opt_strings((char_u *)curbuf->b_p_bt, p_buftype_values, false) != OK) { + || check_opt_strings(curbuf->b_p_bt, p_buftype_values, false) != OK) { errmsg = e_invarg; } else { if (curwin->w_status_height || global_stl_height()) { @@ -1156,7 +1155,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf curbuf->b_help = (curbuf->b_p_bt[0] == 'h'); redraw_titles(); } - } else if (gvarp == (char_u **)&p_stl || gvarp == (char_u **)&p_wbr || varp == &p_tal + } else if (gvarp == &p_stl || gvarp == &p_wbr || varp == &p_tal || varp == &p_ruf) { // 'statusline', 'winbar', 'tabline' or 'rulerformat' int wid; @@ -1184,7 +1183,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf comp_col(); } // add / remove window bars for 'winbar' - if (gvarp == (char_u **)&p_wbr) { + if (gvarp == &p_wbr) { set_winbar(true); } } else if (gvarp == &p_cpt) { @@ -1223,7 +1222,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } } else if (varp == &p_cot) { // 'completeopt' - if (check_opt_strings((char_u *)p_cot, p_cot_values, true) != OK) { + if (check_opt_strings(p_cot, p_cot_values, true) != OK) { errmsg = e_invarg; } else { completeopt_was_set(); @@ -1236,7 +1235,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } #endif } else if (varp == &curwin->w_p_scl) { // 'signcolumn' - if (check_signcolumn((char_u *)(*varp)) != OK) { + if (check_signcolumn(*varp) != OK) { errmsg = e_invarg; } // When changing the 'signcolumn' to or from 'number', recompute the @@ -1249,20 +1248,20 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } else if (varp == &curwin->w_p_fdc || varp == &curwin->w_allbuf_opt.wo_fdc) { // 'foldcolumn' - if (**varp == NUL || check_opt_strings((char_u *)(*varp), p_fdc_values, false) != OK) { + if (**varp == NUL || check_opt_strings(*varp, p_fdc_values, false) != OK) { errmsg = e_invarg; } - } else if (varp == (char **)&p_pt) { + } else if (varp == &p_pt) { // 'pastetoggle': translate key codes like in a mapping if (*p_pt) { p = NULL; - (void)replace_termcodes((char *)p_pt, + (void)replace_termcodes(p_pt, STRLEN(p_pt), &p, REPTERM_FROM_PART | REPTERM_DO_LT, NULL, CPO_TO_CPO_FLAGS); if (p != NULL) { - free_string_option((char *)p_pt); - p_pt = (char_u *)p; + free_string_option(p_pt); + p_pt = p; } } } else if (varp == &p_bs) { // 'backspace' @@ -1270,14 +1269,14 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf if (*p_bs > '3' || p_bs[1] != NUL) { errmsg = e_invarg; } - } else if (check_opt_strings((char_u *)p_bs, p_bs_values, true) != OK) { + } else if (check_opt_strings(p_bs, p_bs_values, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_bo) { - if (opt_strings_flags((char_u *)p_bo, p_bo_values, &bo_flags, true) != OK) { + if (opt_strings_flags(p_bo, p_bo_values, &bo_flags, true) != OK) { errmsg = e_invarg; } - } else if (gvarp == (char_u **)&p_tc) { // 'tagcase' + } else if (gvarp == &p_tc) { // 'tagcase' unsigned int *flags; if (opt_flags & OPT_LOCAL) { @@ -1292,19 +1291,19 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf // make the local value empty: use the global value *flags = 0; } else if (*p == NUL - || opt_strings_flags((char_u *)p, p_tc_values, flags, false) != OK) { + || opt_strings_flags(p, p_tc_values, flags, false) != OK) { errmsg = e_invarg; } } else if (varp == &p_cmp) { // 'casemap' - if (opt_strings_flags((char_u *)p_cmp, p_cmp_values, &cmp_flags, true) != OK) { + if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_dip) { // 'diffopt' if (diffopt_changed() == FAIL) { errmsg = e_invarg; } - } else if (gvarp == (char_u **)&curwin->w_allbuf_opt.wo_fdm) { // 'foldmethod' - if (check_opt_strings((char_u *)(*varp), p_fdm_values, false) != OK + } else if (gvarp == &curwin->w_allbuf_opt.wo_fdm) { // 'foldmethod' + if (check_opt_strings(*varp, p_fdm_values, false) != OK || *curwin->w_p_fdm == NUL) { errmsg = e_invarg; } else { @@ -1317,7 +1316,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf if (foldmethodIsExpr(curwin)) { foldUpdateAll(curwin); } - } else if (gvarp == (char_u **)&curwin->w_allbuf_opt.wo_fmr) { // 'foldmarker' + } else if (gvarp == &curwin->w_allbuf_opt.wo_fmr) { // 'foldmarker' p = vim_strchr(*varp, ','); if (p == NULL) { errmsg = N_("E536: comma required"); @@ -1331,23 +1330,23 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf errmsg = N_("E537: 'commentstring' must be empty or contain %s"); } } else if (varp == &p_fdo) { // 'foldopen' - if (opt_strings_flags((char_u *)p_fdo, p_fdo_values, &fdo_flags, true) != OK) { + if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &p_fcl) { // 'foldclose' - if (check_opt_strings((char_u *)p_fcl, p_fcl_values, true) != OK) { + if (check_opt_strings(p_fcl, p_fcl_values, true) != OK) { errmsg = e_invarg; } - } else if (gvarp == (char_u **)&curwin->w_allbuf_opt.wo_fdi) { // 'foldignore' + } else if (gvarp == &curwin->w_allbuf_opt.wo_fdi) { // 'foldignore' if (foldmethodIsIndent(curwin)) { foldUpdateAll(curwin); } } else if (gvarp == &p_ve) { // 'virtualedit' - char_u *ve = p_ve; + char *ve = p_ve; unsigned int *flags = &ve_flags; if (opt_flags & OPT_LOCAL) { - ve = (char_u *)curwin->w_p_ve; + ve = curwin->w_p_ve; flags = &curwin->w_ve_flags; } @@ -1381,15 +1380,15 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } } - } else if (gvarp == (char_u **)&p_cino) { // 'cinoptions' + } else if (gvarp == &p_cino) { // 'cinoptions' // TODO(vim): recognize errors parse_cino(curbuf); } else if (varp == &p_icm) { // 'inccommand' - if (check_opt_strings((char_u *)p_icm, p_icm_values, false) != OK) { + if (check_opt_strings(p_icm, p_icm_values, false) != OK) { errmsg = e_invarg; } - } else if (gvarp == (char_u **)&p_ft) { - if (!valid_filetype((char_u *)(*varp))) { + } else if (gvarp == &p_ft) { + if (!valid_filetype(*varp)) { errmsg = e_invarg; } else { value_changed = STRCMP(oldval, *varp) != 0; @@ -1399,7 +1398,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf *value_checked = true; } } else if (gvarp == &p_syn) { - if (!valid_filetype((char_u *)(*varp))) { + if (!valid_filetype(*varp)) { errmsg = e_invarg; } else { value_changed = STRCMP(oldval, *varp) != 0; @@ -1413,20 +1412,20 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf errmsg = e_invarg; } } else if (varp == &p_tpf) { - if (opt_strings_flags((char_u *)p_tpf, p_tpf_values, &tpf_flags, true) != OK) { + if (opt_strings_flags(p_tpf, p_tpf_values, &tpf_flags, true) != OK) { errmsg = e_invarg; } } else if (varp == &(curbuf->b_p_vsts)) { // 'varsofttabstop' - char_u *cp; + char *cp; if (!(*varp)[0] || ((*varp)[0] == '0' && !(*varp)[1])) { XFREE_CLEAR(curbuf->b_p_vsts_array); } else { - for (cp = (char_u *)(*varp); *cp; cp++) { + for (cp = *varp; *cp; cp++) { if (ascii_isdigit(*cp)) { continue; } - if (*cp == ',' && cp > (char_u *)(*varp) && *(cp - 1) != ',') { + if (*cp == ',' && cp > *varp && *(cp - 1) != ',') { continue; } errmsg = e_invarg; @@ -1434,7 +1433,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } if (errmsg == NULL) { long *oldarray = curbuf->b_p_vsts_array; - if (tabstop_set((char_u *)(*varp), &(curbuf->b_p_vsts_array))) { + if (tabstop_set(*varp, &(curbuf->b_p_vsts_array))) { xfree(oldarray); } else { errmsg = e_invarg; @@ -1442,16 +1441,16 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } } else if (varp == &(curbuf->b_p_vts)) { // 'vartabstop' - char_u *cp; + char *cp; if (!(*varp)[0] || ((*varp)[0] == '0' && !(*varp)[1])) { XFREE_CLEAR(curbuf->b_p_vts_array); } else { - for (cp = (char_u *)(*varp); *cp; cp++) { + for (cp = *varp; *cp; cp++) { if (ascii_isdigit(*cp)) { continue; } - if (*cp == ',' && cp > (char_u *)(*varp) && *(cp - 1) != ',') { + if (*cp == ',' && cp > *varp && *(cp - 1) != ',') { continue; } errmsg = e_invarg; @@ -1459,7 +1458,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } if (errmsg == NULL) { long *oldarray = curbuf->b_p_vts_array; - if (tabstop_set((char_u *)(*varp), &(curbuf->b_p_vts_array))) { + if (tabstop_set(*varp, &(curbuf->b_p_vts_array))) { xfree(oldarray); if (foldmethodIsIndent(curwin)) { foldUpdateAll(curwin); @@ -1484,7 +1483,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf p = WW_ALL; } if (varp == &p_shm) { // 'shortmess' - p = (char *)SHM_ALL; + p = SHM_ALL; } else if (varp == &(p_cpo)) { // 'cpoptions' p = CPO_VI; } else if (varp == &(curbuf->b_p_fo)) { // 'formatoptions' @@ -1527,7 +1526,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf && is_global_local_option(opt_idx)) { // global option with local value set to use global value; free // the local value and make it empty - p = (char *)get_option_varp_scope(opt_idx, OPT_LOCAL); + p = get_option_varp_scope(opt_idx, OPT_LOCAL); free_string_option(*(char **)p); *(char **)p = empty_option; } else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL) { @@ -1574,8 +1573,8 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } } if (varp == &(curwin->w_s->b_p_spl)) { - char_u fname[200]; - char_u *q = (char_u *)curwin->w_s->b_p_spl; + char fname[200]; + char *q = curwin->w_s->b_p_spl; // Skip the first name if it is "cjk". if (STRNCMP(q, "cjk,", 4) == 0) { @@ -1586,15 +1585,14 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf // They could set 'spellcapcheck' depending on the language. // Use the first name in 'spelllang' up to '_region' or // '.encoding'. - for (p = (char *)q; *p != NUL; p++) { + for (p = q; *p != NUL; p++) { if (!ASCII_ISALNUM(*p) && *p != '-') { break; } } - if (p > (char *)q) { - vim_snprintf((char *)fname, sizeof(fname), "spell/%.*s.vim", - (int)(p - (char *)q), q); - source_runtime((char *)fname, DIP_ALL); + if (p > q) { + vim_snprintf(fname, sizeof(fname), "spell/%.*s.vim", (int)(p - q), q); + source_runtime(fname, DIP_ALL); } } } @@ -1618,7 +1616,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf /// @param list when true: accept a list of values /// /// @return OK for correct value, FAIL otherwise. Empty is always OK. -static int check_opt_strings(char_u *val, char **values, int list) +static int check_opt_strings(char *val, char **values, int list) { return opt_strings_flags(val, values, NULL, list); } @@ -1631,7 +1629,7 @@ static int check_opt_strings(char_u *val, char **values, int list) /// @param list when true: accept a list of values /// /// @return OK for correct value, FAIL otherwise. Empty is always OK. -static int opt_strings_flags(char_u *val, char **values, unsigned *flagp, bool list) +static int opt_strings_flags(char *val, char **values, unsigned *flagp, bool list) { unsigned int new_flags = 0; @@ -1659,7 +1657,7 @@ static int opt_strings_flags(char_u *val, char **values, unsigned *flagp, bool l } /// @return OK if "p" is a valid fileformat name, FAIL otherwise. -int check_ff_value(char_u *p) +int check_ff_value(char *p) { return check_opt_strings(p, p_ff_values, false); } diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index f528bc651b..1b548e1f1b 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -607,7 +607,7 @@ static efm_T *parse_efm_option(char *efm) goto parse_efm_error; } // Advance to next part - efm = (char *)skip_to_option_part((char_u *)efm + len); // skip comma and spaces + efm = skip_to_option_part(efm + len); // skip comma and spaces } if (fmt_first == NULL) { // nothing found @@ -4222,7 +4222,7 @@ static char *make_get_fullcmd(const char *makecmd, const char *fname) // If 'shellpipe' empty: don't redirect to 'errorfile'. if (*p_sp != NUL) { - append_redir(cmd, len, (char *)p_sp, (char *)fname); + append_redir(cmd, len, p_sp, (char *)fname); } // Display the fully formed command. Output a newline if there's something @@ -4241,7 +4241,7 @@ static char *make_get_fullcmd(const char *makecmd, const char *fname) // Used for ":make", ":lmake", ":grep", ":lgrep", ":grepadd", and ":lgrepadd" void ex_make(exarg_T *eap) { - char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : (char *)p_menc; + char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : p_menc; // Redirect ":grep" to ":vimgrep" if 'grepprg' is "internal". if (grep_internal(eap->cmdidx)) { @@ -4981,7 +4981,7 @@ void ex_cfile(exarg_T *eap) set_string_option_direct("ef", -1, eap->arg, OPT_FREE, 0); } - char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : (char *)p_menc; + char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : p_menc; if (is_loclist_cmd(eap->cmdidx)) { wp = curwin; diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index 23606fdc77..25f85b6193 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -2432,7 +2432,7 @@ void ex_scriptencoding(exarg_T *eap) } if (*eap->arg != NUL) { - name = (char *)enc_canonize((char_u *)eap->arg); + name = enc_canonize(eap->arg); } else { name = eap->arg; } diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 9c1064d608..3258dc11d6 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -734,13 +734,13 @@ int showmode(void) length = (Rows - msg_row) * Columns - 3; } if (edit_submode_extra != NULL) { - length -= vim_strsize((char *)edit_submode_extra); + length -= vim_strsize(edit_submode_extra); } if (length > 0) { if (edit_submode_pre != NULL) { - length -= vim_strsize((char *)edit_submode_pre); + length -= vim_strsize(edit_submode_pre); } - if (length - vim_strsize((char *)edit_submode) > 0) { + if (length - vim_strsize(edit_submode) > 0) { if (edit_submode_pre != NULL) { msg_puts_attr((const char *)edit_submode_pre, attr); } @@ -1026,7 +1026,7 @@ void draw_tabline(void) if (col + len >= Columns - 3) { break; } - grid_puts_len(&default_grid, NameBuff, len, 0, col, + grid_puts_len(&default_grid, (char_u *)NameBuff, len, 0, col, hl_combine_attr(attr, win_hl_attr(cwp, HLF_T))); col += len; } @@ -1040,9 +1040,9 @@ void draw_tabline(void) if (room > 0) { // Get buffer name in NameBuff[] get_trans_bufname(cwp->w_buffer); - shorten_dir(NameBuff); + shorten_dir((char_u *)NameBuff); len = vim_strsize((char *)NameBuff); - p = NameBuff; + p = (char_u *)NameBuff; while (len > room) { len -= ptr2cells((char *)p); MB_PTR_ADV(p); @@ -1295,13 +1295,13 @@ static int get_encoded_char_adv(const char_u **p) /// @param varp either the global or the window-local value. /// @param apply if false, do not store the flags, only check for errors. /// @return error message, NULL if it's OK. -char *set_chars_option(win_T *wp, char_u **varp, bool apply) +char *set_chars_option(win_T *wp, char **varp, bool apply) { const char_u *last_multispace = NULL; // Last occurrence of "multispace:" const char_u *last_lmultispace = NULL; // Last occurrence of "leadmultispace:" int multispace_len = 0; // Length of lcs-multispace string int lead_multispace_len = 0; // Length of lcs-leadmultispace string - const bool is_listchars = (varp == (char_u **)&p_lcs || varp == (char_u **)&wp->w_p_lcs); + const bool is_listchars = (varp == &p_lcs || varp == &wp->w_p_lcs); struct chars_tab { int *cp; ///< char value @@ -1344,17 +1344,17 @@ char *set_chars_option(win_T *wp, char_u **varp, bool apply) struct chars_tab *tab; int entries; - const char_u *value = *varp; + const char_u *value = (char_u *)(*varp); if (is_listchars) { tab = lcs_tab; entries = ARRAY_SIZE(lcs_tab); - if (varp == (char_u **)&wp->w_p_lcs && wp->w_p_lcs[0] == NUL) { + if (varp == &wp->w_p_lcs && wp->w_p_lcs[0] == NUL) { value = (char_u *)p_lcs; // local value is empty, use the global value } } else { tab = fcs_tab; entries = ARRAY_SIZE(fcs_tab); - if (varp == (char_u **)&wp->w_p_fcs && wp->w_p_fcs[0] == NUL) { + if (varp == &wp->w_p_fcs && wp->w_p_fcs[0] == NUL) { value = (char_u *)p_fcs; // local value is empty, use the global value } } @@ -1520,17 +1520,17 @@ char *set_chars_option(win_T *wp, char_u **varp, bool apply) /// @return an untranslated error message if any of them is invalid, NULL otherwise. char *check_chars_options(void) { - if (set_chars_option(curwin, (char_u **)&p_lcs, false) != NULL) { + if (set_chars_option(curwin, &p_lcs, false) != NULL) { return e_conflicts_with_value_of_listchars; } - if (set_chars_option(curwin, (char_u **)&p_fcs, false) != NULL) { + if (set_chars_option(curwin, &p_fcs, false) != NULL) { return e_conflicts_with_value_of_fillchars; } FOR_ALL_TAB_WINDOWS(tp, wp) { - if (set_chars_option(wp, (char_u **)&wp->w_p_lcs, true) != NULL) { + if (set_chars_option(wp, &wp->w_p_lcs, true) != NULL) { return e_conflicts_with_value_of_listchars; } - if (set_chars_option(wp, (char_u **)&wp->w_p_fcs, true) != NULL) { + if (set_chars_option(wp, &wp->w_p_fcs, true) != NULL) { return e_conflicts_with_value_of_fillchars; } } diff --git a/src/nvim/shada.c b/src/nvim/shada.c index 3de16b3e69..b45a041d96 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -1477,7 +1477,7 @@ static char *shada_filename(const char *file) // because various expansions must have already be done by the shell. // If shell is not performing them then they should be done in main.c // where arguments are parsed, *not here*. - expand_env((char_u *)file, &(NameBuff[0]), MAXPATHL); + expand_env((char_u *)file, (char_u *)&(NameBuff[0]), MAXPATHL); file = (const char *)&(NameBuff[0]); } } diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 8fcb379bcf..10923829c3 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -1848,7 +1848,7 @@ char *did_set_spelllang(win_T *wp) region = NULL; len = (int)STRLEN(lang); - if (!valid_spelllang(lang)) { + if (!valid_spelllang((char *)lang)) { continue; } @@ -3545,18 +3545,18 @@ int expand_spelling(linenr_T lnum, char_u *pat, char ***matchp) return ga.ga_len; } -/// Return true if "val" is a valid 'spelllang' value. -bool valid_spelllang(const char_u *val) +/// @return true if "val" is a valid 'spelllang' value. +bool valid_spelllang(const char *val) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { return valid_name(val, ".-_,@"); } -/// Return true if "val" is a valid 'spellfile' value. -bool valid_spellfile(const char_u *val) +/// @return true if "val" is a valid 'spellfile' value. +bool valid_spellfile(const char *val) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { - for (const char_u *s = val; *s != NUL; s++) { + for (const char_u *s = (char_u *)val; *s != NUL; s++) { if (!vim_isfilec(*s) && *s != ',' && *s != ' ') { return false; } diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index c68dbd8e53..8d6307f123 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -2121,7 +2121,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) if (itemcnt > 0) { if (is_aff_rule(items, itemcnt, "SET", 2) && aff->af_enc == NULL) { // Setup for conversion from "ENC" to 'encoding'. - aff->af_enc = enc_canonize(items[1]); + aff->af_enc = (char_u *)enc_canonize((char *)items[1]); if (!spin->si_ascii && convert_setup(&spin->si_conv, aff->af_enc, (char_u *)p_enc) == FAIL) { smsg(_("Conversion in %s not supported: from %s to %s"), @@ -2167,9 +2167,8 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) STRCAT(p, " "); STRCAT(p, items[1]); spin->si_info = p; - } else if (is_aff_rule(items, itemcnt, "MIDWORD", 2) - && midword == NULL) { - midword = getroom_save(spin, items[1]); + } else if (is_aff_rule(items, itemcnt, "MIDWORD", 2) && midword == NULL) { + midword = (char_u *)getroom_save(spin, items[1]); } else if (is_aff_rule(items, itemcnt, "TRY", 2)) { // ignored, we look in the tree for what chars may appear } @@ -2307,12 +2306,12 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) } if (i >= gap->ga_len) { ga_grow(gap, 2); - ((char **)(gap->ga_data))[gap->ga_len++] = (char *)getroom_save(spin, items[1]); - ((char **)(gap->ga_data))[gap->ga_len++] = (char *)getroom_save(spin, items[2]); + ((char **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, items[1]); + ((char **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, items[2]); } } else if (is_aff_rule(items, itemcnt, "SYLLABLE", 2) && syllable == NULL) { - syllable = getroom_save(spin, items[1]); + syllable = (char_u *)getroom_save(spin, items[1]); } else if (is_aff_rule(items, itemcnt, "NOBREAK", 1)) { spin->si_nobreak = true; } else if (is_aff_rule(items, itemcnt, "NOSPLITSUGS", 1)) { @@ -2445,10 +2444,10 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) aff_entry = getroom(spin, sizeof(*aff_entry), true); if (STRCMP(items[2], "0") != 0) { - aff_entry->ae_chop = getroom_save(spin, items[2]); + aff_entry->ae_chop = (char_u *)getroom_save(spin, items[2]); } if (STRCMP(items[3], "0") != 0) { - aff_entry->ae_add = getroom_save(spin, items[3]); + aff_entry->ae_add = (char_u *)getroom_save(spin, items[3]); // Recognize flags on the affix: abcd/XYZ aff_entry->ae_flags = (char_u *)vim_strchr((char *)aff_entry->ae_add, '/'); @@ -2468,7 +2467,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) if (STRCMP(items[4], ".") != 0) { char_u buf[MAXLINELEN]; - aff_entry->ae_cond = getroom_save(spin, items[4]); + aff_entry->ae_cond = (char_u *)getroom_save(spin, items[4]); if (*items[0] == 'P') { sprintf((char *)buf, "^%s", items[4]); } else { @@ -2517,7 +2516,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) if (aff_entry->ae_cond != NULL) { char_u buf[MAXLINELEN]; onecap_copy(items[4], buf, true); - aff_entry->ae_cond = getroom_save(spin, buf); + aff_entry->ae_cond = (char_u *)getroom_save(spin, buf); if (aff_entry->ae_cond != NULL) { sprintf((char *)buf, "^%s", aff_entry->ae_cond); @@ -2547,7 +2546,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) idx = spin->si_prefcond.ga_len; pp = GA_APPEND_VIA_PTR(char_u *, &spin->si_prefcond); *pp = (aff_entry->ae_cond == NULL) ? - NULL : getroom_save(spin, aff_entry->ae_cond); + NULL : (char_u *)getroom_save(spin, aff_entry->ae_cond); } // Add the prefix to the prefix tree. @@ -2673,10 +2672,10 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) } } else if (is_aff_rule(items, itemcnt, "SOFOFROM", 2) && sofofrom == NULL) { - sofofrom = getroom_save(spin, items[1]); + sofofrom = (char_u *)getroom_save(spin, items[1]); } else if (is_aff_rule(items, itemcnt, "SOFOTO", 2) && sofoto == NULL) { - sofoto = getroom_save(spin, items[1]); + sofoto = (char_u *)getroom_save(spin, items[1]); } else if (STRCMP(items[0], "COMMON") == 0) { int i; @@ -3042,9 +3041,9 @@ static void add_fromto(spellinfo_T *spin, garray_T *gap, char_u *from, char_u *t fromto_T *ftp = GA_APPEND_VIA_PTR(fromto_T, gap); (void)spell_casefold(curwin, from, (int)STRLEN(from), word, MAXWLEN); - ftp->ft_from = getroom_save(spin, word); + ftp->ft_from = (char_u *)getroom_save(spin, word); (void)spell_casefold(curwin, to, (int)STRLEN(to), word, MAXWLEN); - ftp->ft_to = getroom_save(spin, word); + ftp->ft_to = (char_u *)getroom_save(spin, word); } // Converts a boolean argument in a SAL line to true or false; @@ -3207,7 +3206,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) } // Store the word in the hashtable to be able to find duplicates. - dw = getroom_save(spin, w); + dw = (char_u *)getroom_save(spin, w); if (dw == NULL) { retval = FAIL; xfree(pc); @@ -3728,7 +3727,7 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) // Setup for conversion to 'encoding'. line += 9; - enc = enc_canonize(line); + enc = (char_u *)enc_canonize((char *)line); if (!spin->si_ascii && convert_setup(&spin->si_conv, enc, (char_u *)p_enc) == FAIL) { smsg(_("Conversion in %s not supported: from %s to %s"), @@ -3864,9 +3863,10 @@ static void *getroom(spellinfo_T *spin, size_t len, bool align) return p; } -// Make a copy of a string into memory allocated with getroom(). -// Returns NULL when out of memory. -static char_u *getroom_save(spellinfo_T *spin, char_u *s) +/// Make a copy of a string into memory allocated with getroom(). +/// +/// @return NULL when out of memory. +static char *getroom_save(spellinfo_T *spin, char_u *s) { const size_t s_size = STRLEN(s) + 1; return memcpy(getroom(spin, s_size, false), s, s_size); diff --git a/src/nvim/statusline.c b/src/nvim/statusline.c index 8b56eaadf0..b9cddb7b94 100644 --- a/src/nvim/statusline.c +++ b/src/nvim/statusline.c @@ -77,7 +77,7 @@ void win_redr_status(win_T *wp) width = is_stl_global ? Columns : wp->w_width; get_trans_bufname(wp->w_buffer); - p = NameBuff; + p = (char_u *)NameBuff; len = (int)STRLEN(p); if (bt_help(wp->w_buffer) @@ -138,7 +138,7 @@ void win_redr_status(win_T *wp) if (get_keymap_str(wp, "<%s>", (char *)NameBuff, MAXPATHL) && this_ru_col - len > (int)(STRLEN(NameBuff) + 1)) { - grid_puts(&default_grid, NameBuff, row, + grid_puts(&default_grid, (char_u *)NameBuff, row, (int)((size_t)this_ru_col - STRLEN(NameBuff) - 1), attr); } diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index 20287089f7..187dc4eed4 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -1634,11 +1634,9 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con bool zero_width_next_list = false; garray_T zero_width_next_ga; - /* - * No character, no attributes! Past end of line? - * Do try matching with an empty line (could be the start of a region). - */ - line = syn_getcurline(); + // No character, no attributes! Past end of line? + // Do try matching with an empty line (could be the start of a region). + line = (char_u *)syn_getcurline(); if (line[current_col] == NUL && current_col != 0) { /* * If we found a match after the last column, use it. @@ -1706,12 +1704,10 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con if (syn_block->b_syn_containedin || cur_si == NULL || cur_si->si_cont_list != NULL) { - /* - * 2. Check for keywords, if on a keyword char after a non-keyword - * char. Don't do this when syncing. - */ + // 2. Check for keywords, if on a keyword char after a non-keyword + // char. Don't do this when syncing. if (do_keywords) { - line = syn_getcurline(); + line = (char_u *)syn_getcurline(); const char_u *cur_pos = line + current_col; if (vim_iswordp_buf(cur_pos, syn_buf) && (current_col == 0 @@ -1979,13 +1975,11 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con * Handle searching for nextgroup match. */ if (current_next_list != NULL && !keep_next_list) { - /* - * If a nextgroup was not found, continue looking for one if: - * - this is an empty line and the "skipempty" option was given - * - we are on white space and the "skipwhite" option was given - */ + // If a nextgroup was not found, continue looking for one if: + // - this is an empty line and the "skipempty" option was given + // - we are on white space and the "skipwhite" option was given if (!found_match) { - line = syn_getcurline(); + line = (char_u *)syn_getcurline(); if (((current_next_flags & HL_SKIPWHITE) && ascii_iswhite(line[current_col])) || ((current_next_flags & HL_SKIPEMPTY) @@ -2108,7 +2102,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con // nextgroup ends at end of line, unless "skipnl" or "skipempty" present if (current_next_list != NULL - && (line = syn_getcurline())[current_col] != NUL + && (line = (char_u *)syn_getcurline())[current_col] != NUL && line[current_col + 1] == NUL && !(current_next_flags & (HL_SKIPNL | HL_SKIPEMPTY))) { current_next_list = NULL; @@ -2874,12 +2868,10 @@ static void syn_add_start_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *s result->col = col; } -/* - * Get current line in syntax buffer. - */ -static char_u *syn_getcurline(void) +/// Get current line in syntax buffer. +static char *syn_getcurline(void) { - return ml_get_buf(syn_buf, current_lnum, false); + return (char *)ml_get_buf(syn_buf, current_lnum, false); } /* @@ -4059,7 +4051,7 @@ static char *get_group_name(char *arg, char **name_end) /// /// @return a pointer to the next argument (which isn't an option). /// Return NULL for any error; -static char_u *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, int skip) +static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, int skip) { char_u *gname_start, *gname; int syn_id; @@ -4205,7 +4197,7 @@ static char_u *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, } } - return (char_u *)arg; + return arg; } /* @@ -4347,7 +4339,7 @@ static void syn_cmd_keyword(exarg_T *eap, int syncing) cnt = 0; p = keyword_copy; for (; rest != NULL && !ends_excmd(*rest); rest = skipwhite(rest)) { - rest = (char *)get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); + rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); if (rest == NULL || ends_excmd(*rest)) { break; } @@ -4442,18 +4434,18 @@ static void syn_cmd_match(exarg_T *eap, int syncing) syn_opt_arg.cont_list = NULL; syn_opt_arg.cont_in_list = NULL; syn_opt_arg.next_list = NULL; - rest = (char *)get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); + rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); // get the pattern. init_syn_patterns(); CLEAR_FIELD(item); - rest = (char *)get_syn_pattern((char_u *)rest, &item); + rest = get_syn_pattern((char_u *)rest, &item); if (vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) { syn_opt_arg.flags |= HL_HAS_EOL; } // Get options after the pattern - rest = (char *)get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); + rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); if (rest != NULL) { // all arguments are valid /* @@ -4568,7 +4560,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) // get the options, patterns and matchgroup. while (rest != NULL && !ends_excmd(*rest)) { // Check for option arguments - rest = (char *)get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); + rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); if (rest == NULL || ends_excmd(*rest)) { break; } @@ -4639,7 +4631,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) assert(item == ITEM_SKIP || item == ITEM_END); reg_do_extmatch = REX_USE; } - rest = (char *)get_syn_pattern((char_u *)rest, ppp->pp_synp); + rest = get_syn_pattern((char_u *)rest, ppp->pp_synp); reg_do_extmatch = 0; if (item == ITEM_END && vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) { @@ -5034,12 +5026,11 @@ static void init_syn_patterns(void) ga_set_growsize(&curwin->w_s->b_syn_patterns, 10); } -/* - * Get one pattern for a ":syntax match" or ":syntax region" command. - * Stores the pattern and program in a synpat_T. - * Returns a pointer to the next argument, or NULL in case of an error. - */ -static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) +/// Get one pattern for a ":syntax match" or ":syntax region" command. +/// Stores the pattern and program in a synpat_T. +/// +/// @return a pointer to the next argument, or NULL in case of an error. +static char *get_syn_pattern(char_u *arg, synpat_T *ci) { char *end; int *p; @@ -5128,7 +5119,7 @@ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) semsg(_("E402: Garbage after pattern: %s"), arg); return NULL; } - return (char_u *)skipwhite(end); + return skipwhite(end); } /* diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 2e5ce972d8..50121832ba 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -57,6 +57,7 @@ typedef struct tag_pointers { // filled in by parse_tag_line(): char_u *tagname; // start of tag name (skip "file:") + // char_u *tagname_end; // char after tag name char_u *fname; // first char of file name char_u *fname_end; // char after file name @@ -483,8 +484,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) flags |= TAG_NO_TAGFUNC; } - if (find_tags(name, &new_num_matches, &new_matches, flags, - max_num_matches, buf_ffname) == OK + if (find_tags((char *)name, &new_num_matches, &new_matches, flags, + max_num_matches, (char *)buf_ffname) == OK && new_num_matches < max_num_matches) { max_num_matches = MAXCOL; // If less than max_num_matches // found: all matches found. @@ -1365,8 +1366,8 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl /// @param matchesp return: array of matches found /// @param mincount MAXCOL: find all matches other: minimal number of matches */ /// @param buf_ffname name of buffer for priority -int find_tags(char_u *pat, int *num_matches, char ***matchesp, int flags, int mincount, - char_u *buf_ffname) +int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int mincount, + char *buf_ffname) { FILE *fp; char_u *lbuf; // line buffer @@ -1459,17 +1460,17 @@ int find_tags(char_u *pat, int *num_matches, char ***matchesp, int flags, int mi p_ic = false; break; case TC_FOLLOWSCS: - p_ic = ignorecase(pat); + p_ic = ignorecase((char_u *)pat); break; case TC_SMART: - p_ic = ignorecase_opt(pat, true, true); + p_ic = ignorecase_opt((char_u *)pat, true, true); break; default: abort(); } help_save = curbuf->b_help; - orgpat.pat = pat; + orgpat.pat = (char_u *)pat; orgpat.regmatch.regprog = NULL; vimconv.vc_type = CONV_NONE; @@ -1503,8 +1504,8 @@ int find_tags(char_u *pat, int *num_matches, char ***matchesp, int flags, int mi if (orgpat.len > 3 && pat[orgpat.len - 3] == '@' && ASCII_ISALPHA(pat[orgpat.len - 2]) && ASCII_ISALPHA(pat[orgpat.len - 1])) { - saved_pat = vim_strnsave(pat, (size_t)orgpat.len - 3); - help_lang_find = &pat[orgpat.len - 2]; + saved_pat = vim_strnsave((char_u *)pat, (size_t)orgpat.len - 3); + help_lang_find = (char_u *)&pat[orgpat.len - 2]; orgpat.pat = saved_pat; orgpat.len -= 3; } @@ -1527,8 +1528,8 @@ int find_tags(char_u *pat, int *num_matches, char ***matchesp, int flags, int mi if (*curbuf->b_p_tfu != NUL && use_tfu && !tfu_in_use) { tfu_in_use = true; - retval = find_tagfunc_tags(pat, &ga_match[0], &match_count, - flags, buf_ffname); + retval = find_tagfunc_tags((char_u *)pat, &ga_match[0], &match_count, flags, + (char_u *)buf_ffname); tfu_in_use = false; if (retval != NOTDONE) { goto findtag_end; @@ -2055,7 +2056,7 @@ parse_line: } else { // Decide in which array to store this match. is_current = test_for_current(tagp.fname, tagp.fname_end, tag_fname, - buf_ffname); + (char_u *)buf_ffname); is_static = test_for_static(&tagp); // Decide in which of the sixteen tables to store this match. @@ -3107,13 +3108,13 @@ int expand_tags(int tagnames, char_u *pat, int *num_file, char ***file) extra_flag = 0; } if (pat[0] == '/') { - ret = find_tags(pat + 1, num_file, file, + ret = find_tags((char *)pat + 1, num_file, file, TAG_REGEXP | extra_flag | TAG_VERBOSE | TAG_NO_TAGFUNC, - TAG_MANY, (char_u *)curbuf->b_ffname); + TAG_MANY, curbuf->b_ffname); } else { - ret = find_tags(pat, num_file, file, + ret = find_tags((char *)pat, num_file, file, TAG_REGEXP | extra_flag | TAG_VERBOSE | TAG_NO_TAGFUNC | TAG_NOIC, - TAG_MANY, (char_u *)curbuf->b_ffname); + TAG_MANY, curbuf->b_ffname); } if (ret == OK && !tagnames) { // Reorganize the tags for display and matching as strings of: @@ -3150,8 +3151,7 @@ int expand_tags(int tagnames, char_u *pat, int *num_file, char ***file) /// /// @param start start of the value /// @param end after the value; can be NULL -static int add_tag_field(dict_T *dict, const char *field_name, const char_u *start, - const char_u *end) +static int add_tag_field(dict_T *dict, const char *field_name, const char *start, const char *end) FUNC_ATTR_NONNULL_ARG(1, 2) { int len = 0; @@ -3198,8 +3198,8 @@ int get_tags(list_T *list, char_u *pat, char_u *buf_fname) tagptrs_T tp; bool is_static; - ret = find_tags(pat, &num_matches, &matches, - TAG_REGEXP | TAG_NOIC, MAXCOL, buf_fname); + ret = find_tags((char *)pat, &num_matches, &matches, + TAG_REGEXP | TAG_NOIC, MAXCOL, (char *)buf_fname); if (ret == OK && num_matches > 0) { for (i = 0; i < num_matches; i++) { int parse_result = parse_match((char_u *)matches[i], &tp); @@ -3220,11 +3220,11 @@ int get_tags(list_T *list, char_u *pat, char_u *buf_fname) tv_list_append_dict(list, dict); full_fname = tag_full_fname(&tp); - if (add_tag_field(dict, "name", tp.tagname, tp.tagname_end) == FAIL - || add_tag_field(dict, "filename", full_fname, NULL) == FAIL - || add_tag_field(dict, "cmd", tp.command, tp.command_end) == FAIL - || add_tag_field(dict, "kind", tp.tagkind, - tp.tagkind ? tp.tagkind_end : NULL) == FAIL + if (add_tag_field(dict, "name", (char *)tp.tagname, (char *)tp.tagname_end) == FAIL + || add_tag_field(dict, "filename", (char *)full_fname, NULL) == FAIL + || add_tag_field(dict, "cmd", (char *)tp.command, (char *)tp.command_end) == FAIL + || add_tag_field(dict, "kind", (char *)tp.tagkind, + tp.tagkind ? (char *)tp.tagkind_end : NULL) == FAIL || tv_dict_add_nr(dict, S_LEN("static"), is_static) == FAIL) { ret = FAIL; } @@ -3259,7 +3259,7 @@ int get_tags(list_T *list, char_u *pat, char_u *buf_fname) p++; } n[len] = NUL; - if (add_tag_field(dict, (char *)n, s, p) == FAIL) { + if (add_tag_field(dict, (char *)n, (char *)s, (char *)p) == FAIL) { ret = FAIL; } n[len] = ':'; -- cgit From 88c32b5eba9fa7072bb4a76a8dbb73c6603165be Mon Sep 17 00:00:00 2001 From: Raphael Date: Sun, 28 Aug 2022 17:07:24 +0800 Subject: fix(l10n): improve zh_CN and zh_TW translations (#19969) --- src/nvim/po/zh_CN.UTF-8.po | 52 +++---- src/nvim/po/zh_TW.UTF-8.po | 360 +++++++++++++++++++++++---------------------- 2 files changed, 211 insertions(+), 201 deletions(-) diff --git a/src/nvim/po/zh_CN.UTF-8.po b/src/nvim/po/zh_CN.UTF-8.po index 373833fa80..afa2f29029 100644 --- a/src/nvim/po/zh_CN.UTF-8.po +++ b/src/nvim/po/zh_CN.UTF-8.po @@ -734,9 +734,9 @@ msgid "E120: Using not in a script context: %s" msgstr "E120: 不能在 script 上下文外使用: %s" #: ../eval.c:7391 -#, fuzzy, c-format +#, c-format msgid "E725: Calling dict function without Dictionary: %s" -msgstr "E720: Dictionary 中缺少冒号: %s" +msgstr "E725: 调用字典函数但是没有字典:%s" #: ../eval.c:7453 #, fuzzy @@ -766,19 +766,16 @@ msgid "E737: Key already exists: %s" msgstr "E737: 键已存在: %s" #: ../eval.c:8692 -#, fuzzy msgid "extend() argument" -msgstr "--cmd 参数" +msgstr "extend() 参数" #: ../eval.c:8915 -#, fuzzy msgid "map() argument" -msgstr "-c 参数" +msgstr "map() 参数" #: ../eval.c:8916 -#, fuzzy msgid "filter() argument" -msgstr "-c 参数" +msgstr "filter() 参数" #: ../eval.c:9229 #, c-format @@ -849,9 +846,8 @@ msgid "E702: Sort compare function failed" msgstr "E702: Sort 比较函数失败" #: ../eval.c:13806 -#, fuzzy msgid "E882: Uniq compare function failed" -msgstr "E702: Sort 比较函数失败" +msgstr "E882: Uniq 比较函数失败" #: ../eval.c:14085 msgid "(Invalid)" @@ -864,31 +860,31 @@ msgstr "E677: 写临时文件出错" #: ../eval.c:16159 #, fuzzy msgid "E805: Using a Float as a Number" -msgstr "E745: 将 List 作数字使用" +msgstr "E805: 将浮点数当做数字使用" #: ../eval.c:16162 msgid "E703: Using a Funcref as a Number" -msgstr "E703: 将 Funcref 作数字使用" +msgstr "E703: 将函数当做数字使用" #: ../eval.c:16170 msgid "E745: Using a List as a Number" -msgstr "E745: 将 List 作数字使用" +msgstr "E745: 将列表当做数字使用" #: ../eval.c:16173 msgid "E728: Using a Dictionary as a Number" -msgstr "E728: 将 Dictionary 作数字使用" +msgstr "E728: 将字典当做数字使用" #: ../eval.c:16259 msgid "E729: using Funcref as a String" -msgstr "E729: 将 Funcref 作 String 使用" +msgstr "E729: 将函数当做字符串使用" #: ../eval.c:16262 msgid "E730: using List as a String" -msgstr "E730: 将 List 作 String 使用" +msgstr "E730: 将列表当做字符串使用" #: ../eval.c:16265 msgid "E731: using Dictionary as a String" -msgstr "E731: 将 Dictionary 作 String 使用" +msgstr "E731: 将字典当做字符串使用" #: ../eval.c:16619 #, c-format @@ -3053,11 +3049,11 @@ msgstr "E673: 不兼容的多字节编码和字符集。" #: ../hardcopy.c:2238 msgid "E674: printmbcharset cannot be empty with multi-byte encoding." -msgstr "E674: printmbcharset 在多字节编码下不能为空。" +msgstr "E674: printmbcharset 在多字节编码下不能为空" #: ../hardcopy.c:2254 msgid "E675: No default font specified for multi-byte printing." -msgstr "E675: 没有指定多字节打印的默认字体。" +msgstr "E675: 没有指定多字节打印的默认字体" #: ../hardcopy.c:2426 msgid "E324: Can't open PostScript output file" @@ -4204,9 +4200,8 @@ msgstr "E329: 没有菜单 \"%s\"" #. Only a mnemonic or accelerator is not valid. #: ../menu.c:329 -#, fuzzy msgid "E792: Empty menu name" -msgstr "E749: 空的缓冲区" +msgstr "E792: 空的菜单名称" #: ../menu.c:340 msgid "E330: Menu path must not lead to a sub-menu" @@ -4329,9 +4324,8 @@ msgid "E766: Insufficient arguments for printf()" msgstr "E766: printf() 的参数不足" #: ../message.c:3119 -#, fuzzy msgid "E807: Expected Float argument for printf()" -msgstr "E766: printf() 的参数不足" +msgstr "E807: 期盼浮点数作为printf()参数" #: ../message.c:3873 msgid "E767: Too many arguments to printf()" @@ -5675,9 +5669,9 @@ msgid "E781: .sug file doesn't match .spl file: %s" msgstr "E781: .sug 文件不能匹配 .spl 文件: %s" #: ../spell.c:9305 -#, fuzzy, c-format +#, c-format msgid "E782: error while reading .sug file: %s" -msgstr "E47: 读取错误文件失败" +msgstr "E782: 当读取.sug 文件时错误" #. This should have been checked when generating the .spl #. file. @@ -5867,6 +5861,7 @@ msgstr "E410: 不正确的 :syntax 子命令: %s" msgid "" " TOTAL COUNT MATCH SLOWEST AVERAGE NAME PATTERN" msgstr "" +" 总 计 计 数 匹 配 最 慢 的 平 均 名 字 模 式" #: ../syntax.c:6146 msgid "E679: recursive loop loading syncolor.vim" @@ -6103,14 +6098,13 @@ msgstr "Vim: 读错误,退出中...\n" #. This happens when the FileChangedRO autocommand changes the #. * file in a way it becomes shorter. #: ../undo.c:379 -#, fuzzy msgid "E881: Line count changed unexpectedly" -msgstr "E787: 意外地改变了缓冲区" +msgstr "E881: 行数意外地改变了" #: ../undo.c:627 -#, fuzzy, c-format +#, c-format msgid "E828: Cannot open undo file for writing: %s" -msgstr "E212: 无法打开并写入文件" +msgstr "E828: 无法打开撤销文件去写入" #: ../undo.c:717 #, c-format diff --git a/src/nvim/po/zh_TW.UTF-8.po b/src/nvim/po/zh_TW.UTF-8.po index 5da69dfe69..e95b1e2cad 100644 --- a/src/nvim/po/zh_TW.UTF-8.po +++ b/src/nvim/po/zh_TW.UTF-8.po @@ -59,19 +59,19 @@ msgstr "無法傳送回應訊息" #: ../api/private/helpers.c:204 msgid "internal error: unknown option type" -msgstr "" +msgstr "內部錯誤: 未知的選項類型" #: ../buffer.c:92 msgid "[Location List]" -msgstr "" +msgstr "[Location 列表]" #: ../buffer.c:93 msgid "[Quickfix List]" -msgstr "" +msgstr "[Quickfix 列表]" #: ../buffer.c:94 msgid "E855: Autocommands caused command to abort" -msgstr "" +msgstr "E855: 自動命令導致命令被停止" #: ../buffer.c:135 msgid "E82: Cannot allocate any buffer, exiting..." @@ -349,7 +349,7 @@ msgstr "E103: 緩衝區 \"%s\" 不是在 diff 模式" #: ../diff.c:2193 msgid "E787: Buffer changed unexpectedly" -msgstr "" +msgstr "E787: 意外地改變了緩衝區" #: ../digraph.c:1598 msgid "E104: Escape not allowed in digraph" @@ -365,7 +365,7 @@ msgstr "E105: 使用 :loadkeymap " #: ../digraph.c:1821 msgid "E791: Empty keymap entry" -msgstr "" +msgstr "E791: 空的鍵位映射項" #: ../edit.c:82 msgid " Keyword completion (^N^P)" @@ -434,11 +434,11 @@ msgstr "已到段落結尾" #: ../edit.c:101 msgid "E839: Completion function changed window" -msgstr "" +msgstr "E839: 補全函式更改了窗口" #: ../edit.c:102 msgid "E840: Completion function deleted text" -msgstr "" +msgstr "E840: 補全函式刪除了文本" #: ../edit.c:1847 msgid "'dictionary' option is empty" @@ -556,7 +556,7 @@ msgstr "E118: 函式 %s 的引數過多" #: ../eval.c:148 #, c-format msgid "E716: Key not present in Dictionary: %s" -msgstr "" +msgstr "E716: 鍵在字典中不存在: %s" #: ../eval.c:150 #, c-format @@ -581,7 +581,7 @@ msgstr "E360: 不能用 -f 選項執行 shell" #: ../eval.c:154 #, c-format msgid "E734: Wrong variable type for %s=" -msgstr "" +msgstr "E734: 錯誤的變數類型: %s=" #: ../eval.c:155 #, fuzzy, c-format @@ -595,19 +595,19 @@ msgstr "E461: 不合法的變數名稱: %s" #: ../eval.c:157 msgid "E806: using Float as a String" -msgstr "" +msgstr "E806: 使用浮點數作為字串" #: ../eval.c:1830 msgid "E687: Less targets than List items" -msgstr "" +msgstr "E687: 目標比列表項數少" #: ../eval.c:1834 msgid "E688: More targets than List items" -msgstr "" +msgstr "E688: 目標比列表項數多" #: ../eval.c:1906 msgid "Double ; in list of variables" -msgstr "" +msgstr "變數列表出現兩個 ;" #: ../eval.c:2078 #, fuzzy, c-format @@ -616,23 +616,23 @@ msgstr "E138: 無法寫入 viminfo 檔案 %s !" #: ../eval.c:2391 msgid "E689: Can only index a List or Dictionary" -msgstr "" +msgstr "E689: 只能索引一個列表或者字典" #: ../eval.c:2396 msgid "E708: [:] must come last" -msgstr "" +msgstr "E708: [:] 必須在最後" #: ../eval.c:2439 msgid "E709: [:] requires a List value" -msgstr "" +msgstr "E709: [:] 需要一個列表值" #: ../eval.c:2674 msgid "E710: List value has more items than target" -msgstr "" +msgstr "E710: 列表值的項比目標多" #: ../eval.c:2678 msgid "E711: List value has not enough items" -msgstr "" +msgstr "E711: 列表值沒有足夠多的項" #: ../eval.c:2867 #, fuzzy @@ -651,7 +651,7 @@ msgstr "E108: 無此變數: \"%s\"" #: ../eval.c:3333 msgid "E743: variable nested too deep for (un)lock" -msgstr "" +msgstr "E743: (un)lock 的變數嵌套過深" #: ../eval.c:3630 msgid "E109: Missing ':' after '?'" @@ -659,7 +659,7 @@ msgstr "E109: '?' 後缺少 ':'" #: ../eval.c:3893 msgid "E691: Can only compare List with List" -msgstr "" +msgstr "E691: 只能比較列表和列表" #: ../eval.c:3895 #, fuzzy @@ -668,7 +668,7 @@ msgstr "E449: 收到不正確的運算式" #: ../eval.c:3915 msgid "E735: Can only compare Dictionary with Dictionary" -msgstr "" +msgstr "E735: 只能比較字典和字典" #: ../eval.c:3917 #, fuzzy @@ -677,7 +677,7 @@ msgstr "E116: 函式 %s 的引數不正確" #: ../eval.c:3932 msgid "E693: Can only compare Funcref with Funcref" -msgstr "" +msgstr "E693: 只能比較Funcref 和 Funcref" #: ../eval.c:3934 #, fuzzy @@ -736,7 +736,7 @@ msgstr "E242: 找不到顏色: %s" #: ../eval.c:6499 #, c-format msgid "E721: Duplicate key in Dictionary: \"%s\"" -msgstr "" +msgstr "E721: Dictionary 中出現重複的鍵: \"%s\"" #: ../eval.c:6517 #, fuzzy, c-format @@ -781,7 +781,7 @@ msgstr "E120: 不能在 script 本文外使用: %s" #: ../eval.c:7391 #, c-format msgid "E725: Calling dict function without Dictionary: %s" -msgstr "" +msgstr "E725: 調用字典函式但是沒有字典: %s" #: ../eval.c:7453 #, fuzzy @@ -814,16 +814,15 @@ msgstr "E227: %s 的 mapping 已經存在" #: ../eval.c:8692 msgid "extend() argument" -msgstr "" +msgstr "extend() 參數" #: ../eval.c:8915 -#, fuzzy msgid "map() argument" -msgstr "vim [參數] " +msgstr "map() 參數" #: ../eval.c:8916 msgid "filter() argument" -msgstr "" +msgstr "filter() 參數" #: ../eval.c:9229 #, c-format @@ -857,19 +856,19 @@ msgstr "E596: 不正確的字型" #: ../eval.c:11980 msgid "E726: Stride is zero" -msgstr "" +msgstr "E726: 步長為零" #: ../eval.c:11982 msgid "E727: Start past end" -msgstr "" +msgstr "E727: 起始值在終止值後" #: ../eval.c:12024 ../eval.c:15297 msgid "" -msgstr "" +msgstr "<空>" #: ../eval.c:12282 msgid "remove() argument" -msgstr "" +msgstr "remove() 參數" #: ../eval.c:12466 msgid "E655: Too many symbolic links (cycle?)" @@ -877,11 +876,11 @@ msgstr "E655: 太多層的符號鏈結(symlink) (循環?)" #: ../eval.c:12593 msgid "reverse() argument" -msgstr "" +msgstr "reverse() 參數" #: ../eval.c:13721 msgid "sort() argument" -msgstr "" +msgstr "sort() 參數" #: ../eval.c:13721 #, fuzzy @@ -895,7 +894,7 @@ msgstr "E237: 無法選擇此印表機" #: ../eval.c:13806 msgid "E882: Uniq compare function failed" -msgstr "" +msgstr "E882: Uniq 比較函式失敗" #: ../eval.c:14085 msgid "(Invalid)" @@ -908,32 +907,31 @@ msgstr "E208: 寫入檔案 \"%s\" 錯誤" #: ../eval.c:16159 msgid "E805: Using a Float as a Number" -msgstr "" +msgstr "E805: 將浮點數當做數字使用" #: ../eval.c:16162 msgid "E703: Using a Funcref as a Number" -msgstr "" +msgstr "E703: 將函式當做數字使用" #: ../eval.c:16170 msgid "E745: Using a List as a Number" -msgstr "" +msgstr "E745: 將列表當做數字使用" #: ../eval.c:16173 msgid "E728: Using a Dictionary as a Number" -msgstr "" +msgstr "E728: 將字典當做數字使用" #: ../eval.c:16259 msgid "E729: using Funcref as a String" -msgstr "" +msgstr "E729: 將函式當做字串使用" #: ../eval.c:16262 -#, fuzzy msgid "E730: using List as a String" -msgstr "E374: 格式化字串裡少了 ]" +msgstr "E730: 將列表當做字串使用" #: ../eval.c:16265 msgid "E731: using Dictionary as a String" -msgstr "" +msgstr "E731: 將字典當做字串使用" #: ../eval.c:16619 #, fuzzy, c-format @@ -953,12 +951,12 @@ msgstr "E128: 函式名稱第一個字母必須大寫: %s" #: ../eval.c:16732 #, c-format msgid "E705: Variable name conflicts with existing function: %s" -msgstr "" +msgstr "E705: 變數名與已有函式名衝突: %s" #: ../eval.c:16763 #, c-format msgid "E741: Value is locked: %s" -msgstr "" +msgstr "E741: 值已鎖定: %s" #: ../eval.c:16764 ../eval.c:16769 ../message.c:1839 msgid "Unknown" @@ -971,7 +969,7 @@ msgstr "E284: 不能設定 IC 數值" #: ../eval.c:16838 msgid "E698: variable nested too deep for making a copy" -msgstr "" +msgstr "E698: 變數嵌套過深無法複製" #: ../eval.c:17249 #, c-format @@ -1216,7 +1214,7 @@ msgstr "要覆寫已存在的檔案 \"%.*s\"?" #: ../ex_cmds.c:2317 #, c-format msgid "Swap file \"%s\" exists, overwrite anyway?" -msgstr "" +msgstr "交換文件 \"%s\" 已存在,確實需要覆蓋嗎?" #: ../ex_cmds.c:2326 #, fuzzy, c-format @@ -1456,7 +1454,7 @@ msgstr "%3d %s %s 第 % 行 " #: ../ex_cmds2.c:942 msgid "E750: First use \":profile start {fname}\"" -msgstr "" +msgstr "E750: 請先使用 :profile start " #: ../ex_cmds2.c:1269 #, fuzzy, c-format @@ -1555,7 +1553,7 @@ msgstr "vim [參數] " #: ../ex_cmds2.c:2771 msgid "environment variable" -msgstr "" +msgstr "環境變數" #: ../ex_cmds2.c:2773 #, fuzzy @@ -2047,7 +2045,7 @@ msgstr "E199: 已刪除掉作用中的視窗或暫存區" #: ../file_search.c:203 msgid "E854: path too long for completion" -msgstr "" +msgstr "E854: 補全用的路徑太長了" #: ../file_search.c:446 #, c-format @@ -2099,11 +2097,11 @@ msgstr "[未命名]" #: ../fileio.c:511 msgid "[New DIRECTORY]" -msgstr "" +msgstr "[新目錄]" #: ../fileio.c:529 ../fileio.c:532 msgid "[File too big]" -msgstr "" +msgstr "[文件太大]" #: ../fileio.c:534 msgid "[Permission Denied]" @@ -2265,7 +2263,7 @@ msgstr "E513: 無法寫入 -- 轉換失敗" msgid "" "E513: write error, conversion failed in line % (make 'fenc' empty to " "override)" -msgstr "" +msgstr "E513: 寫入錯誤,轉換失敗 (請將 'fenc' 置空以強制執行)" #: ../fileio.c:3448 msgid "E514: write error (file system full?)" @@ -2720,7 +2718,7 @@ msgstr "E49: 錯誤的捲動大小" #: ../globals.h:1021 msgid "E901: Job table is full" -msgstr "" +msgstr "E901: 任務表已經滿" #: ../globals.h:1024 #, c-format @@ -2877,7 +2875,7 @@ msgstr "E42: 沒有錯誤" #: ../globals.h:1067 msgid "E776: No location list" -msgstr "" +msgstr "E776: 沒有位置列表" #: ../globals.h:1068 msgid "E43: Damaged match string" @@ -2992,7 +2990,7 @@ msgstr "E473: 內部錯誤" #: ../globals.h:1104 msgid "E363: pattern uses more memory than 'maxmempattern'" -msgstr "" +msgstr "E363: 表達式的內存超出 'maxmempattern'" #: ../globals.h:1105 #, fuzzy @@ -3097,15 +3095,15 @@ msgstr "E621: \"%s\" 資源檔版本錯誤" #: ../hardcopy.c:2225 msgid "E673: Incompatible multi-byte encoding and character set." -msgstr "" +msgstr "E673: 不兼容的多字節編碼和字元集" #: ../hardcopy.c:2238 msgid "E674: printmbcharset cannot be empty with multi-byte encoding." -msgstr "" +msgstr "E674: printmbcharset 在多字節編碼下不能為空" #: ../hardcopy.c:2254 msgid "E675: No default font specified for multi-byte printing." -msgstr "" +msgstr "E675: 沒有指定多字節打印的默認字型" #: ../hardcopy.c:2426 msgid "E324: Can't open PostScript output file" @@ -3267,6 +3265,7 @@ msgstr "%-5s: %-30s (用法: %s)" #: ../if_cscope.c:1155 msgid "" "\n" +" a: Find assignments to this symbol\n" " c: Find functions calling this function\n" " d: Find functions called by this function\n" " e: Find this egrep pattern\n" @@ -3276,6 +3275,16 @@ msgid "" " s: Find this C symbol\n" " t: Find this text string\n" msgstr "" +"\n" +" a: 搜索對此符號的賦值\n" +" c: 搜索調用此函式的函式\n" +" d: 搜索此函式調用的函式\n" +" e: 搜索此 egrep 模式\n" +" f: 搜索此文件\n" +" g: 搜索此定義\n" +" i: 搜索包含此文件的文件\n" +" s: 搜索此 C 符号\n" +" t: 搜索此文本字串\n" #: ../if_cscope.c:1226 msgid "E568: duplicate cscope database not added" @@ -3509,7 +3518,7 @@ msgstr "-N\t\t\t'nocompatible' 不完全與傳統 Vi 相容,可使用 Vim 加 #: ../main.c:2215 msgid "-V[N][fname]\t\tBe verbose [level N] [log messages to fname]" -msgstr "" +msgstr "-V[N][fname]\t\t詳細 [level N] [log messages to fname]" #: ../main.c:2216 msgid "-D\t\t\tDebugging mode" @@ -3602,7 +3611,7 @@ msgstr "-W \t對檔案 寫入所有輸入的命令" #: ../main.c:2240 msgid "--startuptime \tWrite startup timing messages to " -msgstr "" +msgstr "--startuptime \t將啟動時間寫入到文件 " #: ../main.c:2242 msgid "-i \t\tUse instead of .viminfo" @@ -3794,7 +3803,7 @@ msgstr "" #: ../memline.c:945 msgid " has been damaged (page size is smaller than minimum value).\n" -msgstr "" +msgstr "已损坏(頁面大小小於最小值)。\n" #: ../memline.c:974 #, c-format @@ -4082,7 +4091,7 @@ msgstr "E317: 指標區塊 id 錯 2" #: ../memline.c:3070 #, c-format msgid "E773: Symlink loop for \"%s\"" -msgstr "" +msgstr "E773: \"%s\" 符號鏈接出現循環" #: ../memline.c:3221 msgid "E325: ATTENTION" @@ -4231,7 +4240,7 @@ msgstr "E329: 沒有那樣的選單" #. Only a mnemonic or accelerator is not valid. #: ../menu.c:329 msgid "E792: Empty menu name" -msgstr "" +msgstr "E792: 空的菜單名稱" #: ../menu.c:340 msgid "E330: Menu path must not lead to a sub-menu" @@ -4312,7 +4321,7 @@ msgstr "-- 尚有 --" #: ../message.c:2398 msgid " SPACE/d/j: screen/page/line down, b/u/k: up, q: quit " -msgstr "" +msgstr " 空格/d/j: 屏幕/頁/行 下翻,b/u/k: 上翻,q: 退出 " #: ../message.c:3021 ../message.c:3031 msgid "Question" @@ -4357,7 +4366,7 @@ msgstr "E116: 函式 %s 的引數不正確" #: ../message.c:3119 msgid "E807: Expected Float argument for printf()" -msgstr "" +msgstr "E807: 期盼浮點數作為printf()參數" #: ../message.c:3873 #, fuzzy @@ -4370,11 +4379,11 @@ msgstr "W10: 注意: 你正在修改一個唯讀檔" #: ../misc1.c:2537 msgid "Type number and or click with mouse (empty cancels): " -msgstr "" +msgstr "請輸入數字並或點擊鼠標(空白取消): " #: ../misc1.c:2539 msgid "Type number and (empty cancels): " -msgstr "" +msgstr "請選擇數字並( 取消): " #: ../misc1.c:2585 msgid "1 more line" @@ -4400,7 +4409,7 @@ msgstr " (已中斷)" #: ../misc1.c:2635 msgid "Beep!" -msgstr "" +msgstr "Beep!" #: ../misc2.c:738 #, c-format @@ -4617,7 +4626,7 @@ msgstr "E520: 不能在 Modeline 裡出現" #: ../option.c:2815 msgid "E846: Key code not set" -msgstr "" +msgstr "E846: 未設置鍵位代碼" #: ../option.c:2924 msgid "E521: Number required after =" @@ -4642,11 +4651,11 @@ msgstr "E589: 'backupext' 跟 'patchmode' 是一樣的" #: ../option.c:3964 msgid "E834: Conflicts with value of 'listchars'" -msgstr "" +msgstr "E834: 與'listchars'中的值發生衝突" #: ../option.c:3966 msgid "E835: Conflicts with value of 'fillchars'" -msgstr "" +msgstr "E835: 與'fillchars'中的值發生衝突" #: ../option.c:4163 msgid "E524: Missing colon" @@ -4884,7 +4893,7 @@ msgstr "E382: 無法寫入,'buftype' 選項已設定" #: ../quickfix.c:2812 msgid "E683: File name missing or invalid pattern" -msgstr "" +msgstr "E683: 缺少文件名或模式無效" #: ../quickfix.c:2911 #, fuzzy, c-format @@ -5022,25 +5031,26 @@ msgid "" "E864: \\%#= can only be followed by 0, 1, or 2. The automatic engine will be " "used " msgstr "" +"E864: \\%#= 後面只能是0,1,或者2。自動引擎將會被使用" #: ../regexp_nfa.c:239 msgid "E865: (NFA) Regexp end encountered prematurely" -msgstr "" +msgstr "E865: (NFA) 過早的遇到了正則表達式的結尾" #: ../regexp_nfa.c:240 #, c-format msgid "E866: (NFA regexp) Misplaced %c" -msgstr "" +msgstr "E866: (NFA regexp) %c 放錯了位置" #: ../regexp_nfa.c:242 #, c-format msgid "E877: (NFA regexp) Invalid character class: %" -msgstr "" +msgstr "E877: (NFA regexp) 不可用的字元類: %" #: ../regexp_nfa.c:1261 #, c-format msgid "E867: (NFA) Unknown operator '\\z%c'" -msgstr "" +msgstr "E867: (NFA) 未知的操作符 '\\z%c'" #: ../regexp_nfa.c:1387 #, c-format @@ -5050,21 +5060,21 @@ msgstr "" #: ../regexp_nfa.c:1802 #, c-format msgid "E869: (NFA) Unknown operator '\\@%c'" -msgstr "" +msgstr "E869: (NFA) 未知的操作符 '\\%%%c'" #: ../regexp_nfa.c:1831 msgid "E870: (NFA regexp) Error reading repetition limits" -msgstr "" +msgstr "E870: (NFA regexp) 读取重复限制时出错" #. Can't have a multi follow a multi. #: ../regexp_nfa.c:1895 msgid "E871: (NFA regexp) Can't have a multi follow a multi !" -msgstr "" +msgstr "E871: (NFA regexp) 不能多个跟多个!" #. Too many `(' #: ../regexp_nfa.c:2037 msgid "E872: (NFA regexp) Too many '('" -msgstr "" +msgstr "E872: (NFA regexp) 太多 '('" #: ../regexp_nfa.c:2042 #, fuzzy @@ -5073,31 +5083,32 @@ msgstr "E50: 太多 \\z(" #: ../regexp_nfa.c:2066 msgid "E873: (NFA regexp) proper termination error" -msgstr "" +msgstr "E873: (NFA regexp) 未適當終止" #: ../regexp_nfa.c:2599 msgid "E874: (NFA) Could not pop the stack !" -msgstr "" +msgstr "E874: (NFA) 無法出棧!" #: ../regexp_nfa.c:3298 msgid "" "E875: (NFA regexp) (While converting from postfix to NFA), too many states " "left on stack" -msgstr "" +msgstr "E875: (NFA regexp) (從後綴轉到 NFA 时),棧上遺留了太多狀態" #: ../regexp_nfa.c:3302 msgid "E876: (NFA regexp) Not enough space to store the whole NFA " -msgstr "" +msgstr "E876: (NFA regexp) 沒有足夠的空間存儲NFA " #: ../regexp_nfa.c:4571 ../regexp_nfa.c:4869 msgid "" "Could not open temporary log file for writing, displaying on stderr ... " msgstr "" +"無法打開臨時日志文件進行寫入,顯示在stderr中..." #: ../regexp_nfa.c:4840 #, c-format msgid "(NFA) COULD NOT OPEN %s !" -msgstr "" +msgstr "(NFA) 不能打开 %s !" #: ../regexp_nfa.c:6049 #, fuzzy @@ -5270,17 +5281,17 @@ msgstr "E297: 暫存檔寫入錯誤" #: ../spell.c:952 msgid "E758: Truncated spell file" -msgstr "" +msgstr "E758: 已截斷的拼寫文件" #: ../spell.c:953 #, c-format msgid "Trailing text in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,多餘的後續文本: %s" #: ../spell.c:954 #, c-format msgid "Affix name too long in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,附加項名字太長: %s" #: ../spell.c:955 #, fuzzy @@ -5289,20 +5300,20 @@ msgstr "E431: Tag 檔 \"%s\" 格式錯誤" #: ../spell.c:957 msgid "E762: Character in FOL, LOW or UPP is out of range" -msgstr "" +msgstr "E762: FOL、LOW 或 UPP 中字元超出範圍" #: ../spell.c:958 msgid "Compressing word tree..." -msgstr "" +msgstr "壓縮單詞樹……" #: ../spell.c:1951 msgid "E756: Spell checking is not enabled" -msgstr "" +msgstr "E756: 拼寫檢查未啟用" #: ../spell.c:2249 #, c-format msgid "Warning: Cannot find word list \"%s.%s.spl\" or \"%s.ascii.spl\"" -msgstr "" +msgstr "警告: 找不到單詞列表 \"%s.%s.spl\" or \"%s.ascii.spl\"" #: ../spell.c:2473 #, fuzzy, c-format @@ -5316,11 +5327,11 @@ msgstr "E307: %s 看起來不像是 Vim 暫存檔" #: ../spell.c:2501 msgid "E771: Old spell file, needs to be updated" -msgstr "" +msgstr "E771: 舊的拼寫文件,需要更新" #: ../spell.c:2504 msgid "E772: Spell file is for newer version of Vim" -msgstr "" +msgstr "E772: 為更高版本的 Vim 所使用的拼寫文件" #: ../spell.c:2602 #, fuzzy @@ -5340,66 +5351,68 @@ msgstr "搜尋 tag 檔案 \"%s\"" #: ../spell.c:4589 ../spell.c:5635 ../spell.c:6140 #, c-format msgid "Conversion failure for word in %s line %d: %s" -msgstr "" +msgstr "單詞 %s 轉換失敗,第 %d 行: %s" #: ../spell.c:4630 ../spell.c:6170 #, c-format msgid "Conversion in %s not supported: from %s to %s" -msgstr "" +msgstr "不支持 %s 中的轉換: 从 %s 到 %s" #: ../spell.c:4642 #, c-format msgid "Invalid value for FLAG in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,FLAG 的值无效: %s" #: ../spell.c:4655 #, c-format msgid "FLAG after using flags in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,在使用標志後出現 FLAG: %s" #: ../spell.c:4723 #, c-format msgid "" "Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line " "%d" -msgstr "" +msgstr "在 PFX 項之後定義 COMPOUNDFORBIDFLAG (%s 第%d行)可能會給出的錯誤結果" +"%d" #: ../spell.c:4731 #, c-format msgid "" "Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line " "%d" -msgstr "" +msgstr "在 PFX 項之後定義 COMPOUNDFORBIDFLAG (%s 第%d行)可能會給出的錯誤結果" +"%d" #: ../spell.c:4747 #, c-format msgid "Wrong COMPOUNDRULES value in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,错误的 COMPOUNDMIN 值: %s" #: ../spell.c:4771 #, c-format msgid "Wrong COMPOUNDWORDMAX value in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,错误的 COMPOUNDWORDMAX 值: %s" #: ../spell.c:4777 #, c-format msgid "Wrong COMPOUNDMIN value in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,错误的 COMPOUNDMIN 值: %s" #: ../spell.c:4783 #, c-format msgid "Wrong COMPOUNDSYLMAX value in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,错误的 COMPOUNDSYLMAX 值: %s" #: ../spell.c:4795 #, c-format msgid "Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,错误的 CHECKCOMPOUNDPATTERN 值: %s" #: ../spell.c:4847 #, c-format msgid "Different combining flag in continued affix block in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,在連續的附加塊種出現不同的組合標誌: %s" #: ../spell.c:4850 #, fuzzy, c-format @@ -5412,45 +5425,47 @@ msgid "" "Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in %s " "line %d: %s" msgstr "" +"%s 第 %d 行,附加項被 BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST 使" +"用: %s" #: ../spell.c:4893 #, c-format msgid "Expected Y or N in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,此處需要 Y 或 N: %s" #: ../spell.c:4968 #, c-format msgid "Broken condition in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,錯誤的條件: %s" #: ../spell.c:5091 #, c-format msgid "Expected REP(SAL) count in %s line %d" -msgstr "" +msgstr "%s 第 %d 行,此處需要 REP(SAL) 計數" #: ../spell.c:5120 #, c-format msgid "Expected MAP count in %s line %d" -msgstr "" +msgstr "%s 第 %d 行,此處需要 MAP 計數" #: ../spell.c:5132 #, c-format msgid "Duplicate character in MAP in %s line %d" -msgstr "" +msgstr "%s 第 %d 行,MAP 中存在重複的字元" #: ../spell.c:5176 #, c-format msgid "Unrecognized or duplicate item in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,無法識別或重複的項: %s" #: ../spell.c:5197 #, c-format msgid "Missing FOL/LOW/UPP line in %s" -msgstr "" +msgstr "%s 中缺少 FOL/LOW/UPP 行" #: ../spell.c:5220 msgid "COMPOUNDSYLMAX used without SYLLABLE" -msgstr "" +msgstr "在没有 SYLLABLE 的情況下使用了 COMPOUNDSYLMAX" #: ../spell.c:5236 #, fuzzy @@ -5464,32 +5479,32 @@ msgstr "太多編輯參數" #: ../spell.c:5240 msgid "Too many postponed prefixes and/or compound flags" -msgstr "" +msgstr "太多延遲前綴和/或組合標誌" #: ../spell.c:5250 #, c-format msgid "Missing SOFO%s line in %s" -msgstr "" +msgstr "%s 中缺少 SOFO%s 行" #: ../spell.c:5253 #, c-format msgid "Both SAL and SOFO lines in %s" -msgstr "" +msgstr "%s 同時出現 SAL 和 SOFO 行" #: ../spell.c:5331 #, c-format msgid "Flag is not a number in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,標誌不是數字: %s" #: ../spell.c:5334 #, c-format msgid "Illegal flag in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,無效的標誌: %s" #: ../spell.c:5493 ../spell.c:5501 #, c-format msgid "%s value differs from what is used in another .aff file" -msgstr "" +msgstr "%s 的值與另一個 .aff 文件中使用的值不相同" #: ../spell.c:5602 #, fuzzy, c-format @@ -5499,12 +5514,12 @@ msgstr "掃瞄字典: %s" #: ../spell.c:5611 #, c-format msgid "E760: No word count in %s" -msgstr "" +msgstr "E760: %s 中没有單詞計數" #: ../spell.c:5669 #, c-format msgid "line %6d, word %6d - %s" -msgstr "" +msgstr "第 %6d 行,第 %6d 个單詞 - %s" #: ../spell.c:5691 #, fuzzy, c-format @@ -5514,17 +5529,17 @@ msgstr "每一行都找不到: %s" #: ../spell.c:5694 #, c-format msgid "First duplicate word in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,首次出現重複的單詞: %s" #: ../spell.c:5746 #, c-format msgid "%d duplicate word(s) in %s" -msgstr "" +msgstr "存在 %d 个重複的單詞,在 %s 中" #: ../spell.c:5748 #, c-format msgid "Ignored %d word(s) with non-ASCII characters in %s" -msgstr "" +msgstr "忽略了含有非 ASCII 字元的 %d 个單詞,在 %s 中" #: ../spell.c:6115 #, fuzzy, c-format @@ -5534,42 +5549,42 @@ msgstr "從標準輸入讀取..." #: ../spell.c:6155 #, c-format msgid "Duplicate /encoding= line ignored in %s line %d: %s" -msgstr "" +msgstr "%s 第 %ld 行,重复的 /encoding= 行已被忽略: %s" #: ../spell.c:6159 #, c-format msgid "/encoding= line after word ignored in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,单词后的 /encoding= 行已被忽略: %s" #: ../spell.c:6180 #, c-format msgid "Duplicate /regions= line ignored in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,重复的 /regions= 行已被忽略: %s" #: ../spell.c:6185 #, c-format msgid "Too many regions in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,太多區域: %s" #: ../spell.c:6198 #, c-format msgid "/ line ignored in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,/ 行已被忽略: %s" #: ../spell.c:6224 #, fuzzy, c-format msgid "Invalid region nr in %s line %d: %s" -msgstr "E573: 不正確的伺服器 id : %s" +msgstr "%s 第 %d 行,無效的區域號: %s" #: ../spell.c:6230 #, c-format msgid "Unrecognized flags in %s line %d: %s" -msgstr "" +msgstr "%s 第 %d 行,不可識別的標誌: %s" #: ../spell.c:6257 #, c-format msgid "Ignored %d words with non-ASCII characters" -msgstr "" +msgstr "忽略了含有非 ASCII 字元的 %d 个單詞" #: ../spell.c:6656 #, c-format @@ -5578,23 +5593,23 @@ msgstr "" #: ../spell.c:7340 msgid "Reading back spell file..." -msgstr "" +msgstr "读取拼寫文件……" #. Go through the trie of good words, soundfold each word and add it to #. the soundfold trie. #: ../spell.c:7357 msgid "Performing soundfolding..." -msgstr "" +msgstr "正在 soundfolding……" #: ../spell.c:7368 #, c-format msgid "Number of words after soundfolding: %" -msgstr "" +msgstr "soundfolding 后的單詞数: %" #: ../spell.c:7476 #, c-format msgid "Total number of words: %d" -msgstr "" +msgstr "單詞总数: %d" #: ../spell.c:7655 #, fuzzy, c-format @@ -5604,11 +5619,11 @@ msgstr "寫入 viminfo 檔案 \"%s\" 中" #: ../spell.c:7707 ../spell.c:7927 #, c-format msgid "Estimated runtime memory use: %d bytes" -msgstr "" +msgstr "估計運行時的內存用量: %d 位元" #: ../spell.c:7820 msgid "E751: Output file name must not have region name" -msgstr "" +msgstr "E751: 輸出文件不能含有區域名" #: ../spell.c:7822 #, fuzzy @@ -5622,7 +5637,7 @@ msgstr "E15: 不正確的運算式: %s" #: ../spell.c:7907 msgid "Warning: both compounding and NOBREAK specified" -msgstr "" +msgstr "警告: 同時指定了 compounding 和 NOBREAK" #: ../spell.c:7920 #, fuzzy, c-format @@ -5631,30 +5646,30 @@ msgstr "寫入 viminfo 檔案 \"%s\" 中" #: ../spell.c:7925 msgid "Done!" -msgstr "" +msgstr "完成!" #: ../spell.c:8034 #, c-format msgid "E765: 'spellfile' does not have % entries" -msgstr "" +msgstr "E765: 'spellfile' 没有 % 項" #: ../spell.c:8074 #, c-format msgid "Word '%.*s' removed from %s" -msgstr "" +msgstr "从 %s 中删除了單詞" #: ../spell.c:8117 #, c-format msgid "Word '%.*s' added to %s" -msgstr "" +msgstr "向 %s 中添加了單詞" #: ../spell.c:8381 msgid "E763: Word characters differ between spell files" -msgstr "" +msgstr "E763: 拼寫文件之間的字元不相同" #: ../spell.c:8684 msgid "Sorry, no suggestions" -msgstr "" +msgstr "抱歉,没有建议" #: ../spell.c:8687 #, fuzzy, c-format @@ -5671,7 +5686,7 @@ msgstr "將變動存儲至 \"%.*s\"?" #: ../spell.c:8737 #, c-format msgid " < \"%.*s\"" -msgstr "" +msgstr " < \"%.*s\"" #: ../spell.c:8882 #, fuzzy @@ -5691,28 +5706,28 @@ msgstr "E307: %s 看起來不像是 Vim 暫存檔" #: ../spell.c:9282 #, c-format msgid "E779: Old .sug file, needs to be updated: %s" -msgstr "" +msgstr "E779: 舊的.sug 文件,需要更新: %s" #: ../spell.c:9286 #, c-format msgid "E780: .sug file is for newer version of Vim: %s" -msgstr "" +msgstr "E780: .sug 文件適用於較新的 Vim 版本: %s" #: ../spell.c:9295 #, c-format msgid "E781: .sug file doesn't match .spl file: %s" -msgstr "" +msgstr "E781: .sug 文件不能匹配 .spl 文件: %s" #: ../spell.c:9305 #, fuzzy, c-format msgid "E782: error while reading .sug file: %s" -msgstr "E47: 讀取錯誤檔案失敗" +msgstr "E782: 當讀取.sug 文件時錯誤" #. This should have been checked when generating the .spl #. file. #: ../spell.c:11575 msgid "E783: duplicate char in MAP entry" -msgstr "" +msgstr "E783: MAP 條目中有重複的字元" #: ../syntax.c:266 msgid "No Syntax items defined for this buffer" @@ -5894,10 +5909,11 @@ msgstr "E410: 不正確的 :syntax 子命令: %s" msgid "" " TOTAL COUNT MATCH SLOWEST AVERAGE NAME PATTERN" msgstr "" +" 總 計 計 數 匹 配 最 慢 的 平 均 名 字 模 式" #: ../syntax.c:6146 msgid "E679: recursive loop loading syncolor.vim" -msgstr "" +msgstr "E679: 加載 syncolor.vim 时出現嵌套循環" #: ../syntax.c:6256 #, c-format @@ -5975,7 +5991,7 @@ msgstr "E5248: 群組名稱中有不正確的字元" #: ../syntax.c:7448 msgid "E849: Too many highlight and syntax groups" -msgstr "" +msgstr "E849: 高亮和語法組過多" #: ../tag.c:104 msgid "E555: at bottom of tag stack" @@ -6083,7 +6099,7 @@ msgstr "E435: 找不到 tag, 用猜的!" #: ../tag.c:2797 #, c-format msgid "Duplicate field name: %s" -msgstr "" +msgstr "重複的字段名: %s" #: ../term.c:1442 msgid "' not known. Available builtin terminals are:" @@ -6131,35 +6147,35 @@ msgstr "Vim: 讀取輸入錯誤,離開中...\n" #. * file in a way it becomes shorter. #: ../undo.c:379 msgid "E881: Line count changed unexpectedly" -msgstr "" +msgstr "E881: 行數意外地改變了" #: ../undo.c:627 -#, fuzzy, c-format +#, c-format msgid "E828: Cannot open undo file for writing: %s" -msgstr "E212: 無法以寫入模式開啟" +msgstr "E828: 無法打開撤銷文件去寫入" #: ../undo.c:717 #, c-format msgid "E825: Corrupted undo file (%s): %s" -msgstr "" +msgstr "E825: 已損壞的撤銷文件 (%s): %s" #: ../undo.c:1039 msgid "Cannot write undo file in any directory in 'undodir'" -msgstr "" +msgstr "不能寫入撤銷文件到 'undodir' 中的任何文件夾" #: ../undo.c:1074 #, c-format msgid "Will not overwrite with undo file, cannot read: %s" -msgstr "" +msgstr "不能寫入撤銷文件,不可讀取: %s" #: ../undo.c:1092 #, c-format msgid "Will not overwrite, this is not an undo file: %s" -msgstr "" +msgstr "不會覆蓋,這不是撤銷文件: %s" #: ../undo.c:1108 msgid "Skipping undo file write, nothing to undo" -msgstr "" +msgstr "跳過撤消文件寫入,沒有可撤消的內容" #: ../undo.c:1121 #, fuzzy, c-format @@ -6174,7 +6190,7 @@ msgstr "E297: 暫存檔寫入錯誤" #: ../undo.c:1280 #, c-format msgid "Not reading undo file, owner differs: %s" -msgstr "" +msgstr "不能讀取撤銷文件,擁有者不同: %s" #: ../undo.c:1292 #, fuzzy, c-format @@ -6198,7 +6214,7 @@ msgstr "E484: 無法開啟檔案 %s" #: ../undo.c:1328 msgid "File contents changed, cannot use undo info" -msgstr "" +msgstr "文件內容已經改變,不能使用撤銷信息" #: ../undo.c:1497 #, fuzzy, c-format @@ -6207,11 +6223,11 @@ msgstr "結束執行 %s" #: ../undo.c:1586 ../undo.c:1812 msgid "Already at oldest change" -msgstr "" +msgstr "已經在最早的改變" #: ../undo.c:1597 ../undo.c:1814 msgid "Already at newest change" -msgstr "" +msgstr "已經在最新的改變" #: ../undo.c:1806 #, fuzzy, c-format @@ -6259,11 +6275,11 @@ msgstr "% 行 %s 過 %d 次" #: ../undo.c:2228 msgid "before" -msgstr "" +msgstr "之前" #: ../undo.c:2228 msgid "after" -msgstr "" +msgstr "之後" #: ../undo.c:2325 #, fuzzy @@ -6272,7 +6288,7 @@ msgstr "沒有這個 mapping 對應" #: ../undo.c:2330 msgid "number changes when saved" -msgstr "" +msgstr " 編號 改變 時間 保存" #: ../undo.c:2360 #, fuzzy, c-format -- cgit From f9641d1ac6bae58a42572ce3bfa34d62d5f22619 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Tue, 23 Aug 2022 21:05:46 +0200 Subject: refactor(lsp): factor out read_loop function --- runtime/lua/vim/lsp/rpc.lua | 57 +++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 0926912066..f96321c845 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -241,6 +241,35 @@ function default_dispatchers.on_error(code, err) local _ = log.error() and log.error('client_error:', client_errors[code], err) end +---@private +local function create_read_loop(handle_body, on_no_chunk, on_error) + local parse_chunk = coroutine.wrap(request_parser_loop) + parse_chunk() + return function(err, chunk) + if err then + on_error(err) + return + end + + if not chunk then + if on_no_chunk then + on_no_chunk() + end + return + end + + while true do + local headers, body = parse_chunk(chunk) + if headers then + handle_body(body) + chunk = '' + else + break + end + end + end +end + --- Starts an LSP server process and create an LSP RPC client object to --- interact with it. Communication with the server is currently limited to stdio. --- @@ -592,31 +621,9 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) local request_parser = coroutine.wrap(request_parser_loop) request_parser() - stdout:read_start(function(err, chunk) - if err then - -- TODO better handling. Can these be intermittent errors? - on_error(client_errors.READ_ERROR, err) - return - end - -- This should signal that we are done reading from the client. - if not chunk then - return - end - -- Flush anything in the parser by looping until we don't get a result - -- anymore. - while true do - local headers, body = request_parser(chunk) - -- If we successfully parsed, then handle the response. - if headers then - handle_body(body) - -- Set chunk to empty so that we can call request_parser to get - -- anything existing in the parser to flush. - chunk = '' - else - break - end - end - end) + stdout:read_start(create_read_loop(handle_body, nil, function(err) + on_error(client_errors.READ_ERROR, err) + end)) return { pid = pid, -- cgit From 7d3e4aee6a11f0bd4c53b0dcb18a496b5fdd32b2 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Tue, 23 Aug 2022 22:39:34 +0200 Subject: refactor(lsp): encapsulate rpc uv handle To prepare for different transports like TCP where the handle won't have a kill method. --- runtime/doc/lsp.txt | 5 +++-- runtime/lua/vim/lsp.lua | 11 +++++------ runtime/lua/vim/lsp/rpc.lua | 12 ++++++++---- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 9235fdef34..9661a43e4c 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -1904,7 +1904,7 @@ notify({method}, {params}) *vim.lsp.rpc.notify()* Parameters: ~ {method} (string) The invoked LSP method - {params} (table): Parameters for the invoked LSP method + {params} (table|nil): Parameters for the invoked LSP method Return: ~ (bool) `true` if notification could be sent, `false` if not @@ -1915,7 +1915,8 @@ request({method}, {params}, {callback}, {notify_reply_callback}) Parameters: ~ {method} (string) The invoked LSP method - {params} (table) Parameters for the invoked LSP method + {params} (table|nil) Parameters for the invoked LSP + method {callback} (function) Callback to invoke {notify_reply_callback} (function|nil) Callback to invoke as soon as a request is no longer pending diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index fd64c1a495..5986f5a5e8 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -1464,14 +1464,13 @@ function lsp.start_client(config) --- you request to stop a client which has previously been requested to --- shutdown, it will automatically escalate and force shutdown. --- - ---@param force (bool, optional) + ---@param force boolean|nil function client.stop(force) - local handle = rpc.handle - if handle:is_closing() then + if rpc.is_closing() then return end if force or not client.initialized or graceful_shutdown_failed then - handle:kill(15) + rpc.terminate() return end -- Sending a signal after a process has exited is acceptable. @@ -1480,7 +1479,7 @@ function lsp.start_client(config) rpc.notify('exit') else -- If there was an error in the shutdown request, then term to be safe. - handle:kill(15) + rpc.terminate() graceful_shutdown_failed = true end end) @@ -1492,7 +1491,7 @@ function lsp.start_client(config) ---@returns (bool) true if client is stopped or in the process of being ---stopped; false otherwise function client.is_stopped() - return rpc.handle:is_closing() + return rpc.is_closing() end ---@private diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index f96321c845..1fbfd3c8e1 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -405,7 +405,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) -- --- Sends a notification to the LSP server. ---@param method (string) The invoked LSP method - ---@param params (table): Parameters for the invoked LSP method + ---@param params (table|nil): Parameters for the invoked LSP method ---@returns (bool) `true` if notification could be sent, `false` if not local function notify(method, params) return encode_and_send({ @@ -432,7 +432,7 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) --- Sends a request to the LSP server and runs {callback} upon response. --- ---@param method (string) The invoked LSP method - ---@param params (table) Parameters for the invoked LSP method + ---@param params (table|nil) Parameters for the invoked LSP method ---@param callback (function) Callback to invoke ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not @@ -626,8 +626,12 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) end)) return { - pid = pid, - handle = handle, + is_closing = function() + return handle:is_closing() + end, + terminate = function() + handle:kill(15) + end, request = request, notify = notify, } -- cgit From 46bb34e26b3bee89fd1d5d9d1bebced00000732d Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Wed, 24 Aug 2022 19:36:37 +0200 Subject: refactor(lsp): extract rpc client from rpc.start Makes the previously inner functions re-usable for a TCP client --- runtime/lua/vim/lsp/rpc.lua | 616 ++++++++++++++++++++++++-------------------- 1 file changed, 335 insertions(+), 281 deletions(-) diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 1fbfd3c8e1..5ac1b91e70 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -270,6 +270,292 @@ local function create_read_loop(handle_body, on_no_chunk, on_error) end end +---@class RpcClient +---@field message_index number +---@field message_callbacks table +---@field notify_reply_callbacks table +---@field transport table +---@field dispatchers table + +---@class RpcClient +local Client = {} + +---@private +function Client:encode_and_send(payload) + local _ = log.debug() and log.debug('rpc.send', payload) + if self.transport.is_closing() then + return false + end + local encoded = vim.json.encode(payload) + self.transport.write(format_message_with_content_length(encoded)) + return true +end + +---@private +--- Sends a notification to the LSP server. +---@param method (string) The invoked LSP method +---@param params (table|nil): Parameters for the invoked LSP method +---@returns (bool) `true` if notification could be sent, `false` if not +function Client:notify(method, params) + return self:encode_and_send({ + jsonrpc = '2.0', + method = method, + params = params, + }) +end + +---@private +--- sends an error object to the remote LSP process. +function Client:send_response(request_id, err, result) + return self:encode_and_send({ + id = request_id, + jsonrpc = '2.0', + error = err, + result = result, + }) +end + +---@private +--- Sends a request to the LSP server and runs {callback} upon response. +--- +---@param method (string) The invoked LSP method +---@param params (table|nil) Parameters for the invoked LSP method +---@param callback (function) Callback to invoke +---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending +---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not +function Client:request(method, params, callback, notify_reply_callback) + validate({ + callback = { callback, 'f' }, + notify_reply_callback = { notify_reply_callback, 'f', true }, + }) + self.message_index = self.message_index + 1 + local message_id = self.message_index + local result = self:encode_and_send({ + id = message_id, + jsonrpc = '2.0', + method = method, + params = params, + }) + local message_callbacks = self.message_callbacks + local notify_reply_callbacks = self.notify_reply_callbacks + if result then + if message_callbacks then + message_callbacks[message_id] = schedule_wrap(callback) + else + return false + end + if notify_reply_callback and notify_reply_callbacks then + notify_reply_callbacks[message_id] = schedule_wrap(notify_reply_callback) + end + return result, message_id + else + return false + end +end + +---@private +function Client:on_error(errkind, ...) + assert(client_errors[errkind]) + -- TODO what to do if this fails? + pcall(self.dispatchers.on_error, errkind, ...) +end + +---@private +function Client:pcall_handler(errkind, status, head, ...) + if not status then + self:on_error(errkind, head, ...) + return status, head + end + return status, head, ... +end + +---@private +function Client:try_call(errkind, fn, ...) + return self:pcall_handler(errkind, pcall(fn, ...)) +end + +-- TODO periodically check message_callbacks for old requests past a certain +-- time and log them. This would require storing the timestamp. I could call +-- them with an error then, perhaps. + +---@private +function Client:handle_body(body) + local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) + if not ok then + self:on_error(client_errors.INVALID_SERVER_JSON, decoded) + return + end + local _ = log.debug() and log.debug('rpc.receive', decoded) + + if type(decoded.method) == 'string' and decoded.id then + local err + -- Schedule here so that the users functions don't trigger an error and + -- we can still use the result. + schedule(function() + local status, result + status, result, err = self:try_call( + client_errors.SERVER_REQUEST_HANDLER_ERROR, + self.dispatchers.server_request, + decoded.method, + decoded.params + ) + local _ = log.debug() + and log.debug( + 'server_request: callback result', + { status = status, result = result, err = err } + ) + if status then + if not (result or err) then + -- TODO this can be a problem if `null` is sent for result. needs vim.NIL + error( + string.format( + 'method %q: either a result or an error must be sent to the server in response', + decoded.method + ) + ) + end + if err then + assert( + type(err) == 'table', + 'err must be a table. Use rpc_response_error to help format errors.' + ) + local code_name = assert( + protocol.ErrorCodes[err.code], + 'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.' + ) + err.message = err.message or code_name + end + else + -- On an exception, result will contain the error message. + err = rpc_response_error(protocol.ErrorCodes.InternalError, result) + result = nil + end + self:send_response(decoded.id, err, result) + end) + -- This works because we are expecting vim.NIL here + elseif decoded.id and (decoded.result ~= vim.NIL or decoded.error ~= vim.NIL) then + -- We sent a number, so we expect a number. + local result_id = assert(tonumber(decoded.id), 'response id must be a number') + + -- Notify the user that a response was received for the request + local notify_reply_callbacks = self.notify_reply_callbacks + local notify_reply_callback = notify_reply_callbacks and notify_reply_callbacks[result_id] + if notify_reply_callback then + validate({ + notify_reply_callback = { notify_reply_callback, 'f' }, + }) + notify_reply_callback(result_id) + notify_reply_callbacks[result_id] = nil + end + + local message_callbacks = self.message_callbacks + + -- Do not surface RequestCancelled to users, it is RPC-internal. + if decoded.error then + local mute_error = false + if decoded.error.code == protocol.ErrorCodes.RequestCancelled then + local _ = log.debug() and log.debug('Received cancellation ack', decoded) + mute_error = true + end + + if mute_error then + -- Clear any callback since this is cancelled now. + -- This is safe to do assuming that these conditions hold: + -- - The server will not send a result callback after this cancellation. + -- - If the server sent this cancellation ACK after sending the result, the user of this RPC + -- client will ignore the result themselves. + if result_id and message_callbacks then + message_callbacks[result_id] = nil + end + return + end + end + + local callback = message_callbacks and message_callbacks[result_id] + if callback then + message_callbacks[result_id] = nil + validate({ + callback = { callback, 'f' }, + }) + if decoded.error then + decoded.error = setmetatable(decoded.error, { + __tostring = format_rpc_error, + }) + end + self:try_call( + client_errors.SERVER_RESULT_CALLBACK_ERROR, + callback, + decoded.error, + decoded.result + ) + else + self:on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) + local _ = log.error() and log.error('No callback found for server response id ' .. result_id) + end + elseif type(decoded.method) == 'string' then + -- Notification + self:try_call( + client_errors.NOTIFICATION_HANDLER_ERROR, + self.dispatchers.notification, + decoded.method, + decoded.params + ) + else + -- Invalid server message + self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) + end +end + +---@private +---@return RpcClient +local function new_client(dispatchers, transport) + local state = { + message_index = 0, + message_callbacks = {}, + notify_reply_callbacks = {}, + transport = transport, + dispatchers = dispatchers, + } + return setmetatable(state, { __index = Client }) +end + +---@private +---@param client RpcClient +local function public_client(client) + local result = {} + + ---@private + function result.is_closing() + return client.transport.is_closing() + end + + ---@private + function result.terminate() + client.transport.terminate() + end + + --- Sends a request to the LSP server and runs {callback} upon response. + --- + ---@param method (string) The invoked LSP method + ---@param params (table|nil) Parameters for the invoked LSP method + ---@param callback (function) Callback to invoke + ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending + ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not + function result.request(method, params, callback, notify_reply_callback) + return client:request(method, params, callback, notify_reply_callback) + end + + --- Sends a notification to the LSP server. + ---@param method (string) The invoked LSP method + ---@param params (table|nil): Parameters for the invoked LSP method + ---@returns (bool) `true` if notification could be sent, `false` if not + function result.notify(method, params) + return client:notify(method, params) + end + + return result +end + --- Starts an LSP server process and create an LSP RPC client object to --- interact with it. Communication with the server is currently limited to stdio. --- @@ -334,134 +620,59 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) local stdin = uv.new_pipe(false) local stdout = uv.new_pipe(false) local stderr = uv.new_pipe(false) - - local message_index = 0 - local message_callbacks = {} - local notify_reply_callbacks = {} - local handle, pid - do - ---@private - --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. - ---@param code (number) Exit code - ---@param signal (number) Signal that was used to terminate (if any) - local function onexit(code, signal) - stdin:close() - stdout:close() - stderr:close() - handle:close() - -- Make sure that message_callbacks/notify_reply_callbacks can be gc'd. - message_callbacks = nil - notify_reply_callbacks = nil - dispatchers.on_exit(code, signal) - end - local spawn_params = { - args = cmd_args, - stdio = { stdin, stdout, stderr }, - detached = not is_win, - } - if extra_spawn_params then - spawn_params.cwd = extra_spawn_params.cwd - spawn_params.env = env_merge(extra_spawn_params.env) - if extra_spawn_params.detached ~= nil then - spawn_params.detached = extra_spawn_params.detached - end - end - handle, pid = uv.spawn(cmd, spawn_params, onexit) - if handle == nil then - stdin:close() - stdout:close() - stderr:close() - local msg = string.format('Spawning language server with cmd: `%s` failed', cmd) - if string.match(pid, 'ENOENT') then - msg = msg - .. '. The language server is either not installed, missing from PATH, or not executable.' - else - msg = msg .. string.format(' with error message: %s', pid) + + local client = new_client(dispatchers, { + write = function(msg) + stdin:write(msg) + end, + is_closing = function() + return handle == nil or handle:is_closing() + end, + terminate = function() + if handle then + handle:kill(15) end - vim.notify(msg, vim.log.levels.WARN) - return - end - end + end, + }) ---@private - --- Encodes {payload} into a JSON-RPC message and sends it to the remote - --- process. - --- - ---@param payload table - ---@returns true if the payload could be scheduled, false if the main event-loop is in the process of closing. - local function encode_and_send(payload) - local _ = log.debug() and log.debug('rpc.send', payload) - if handle == nil or handle:is_closing() then - return false - end - local encoded = vim.json.encode(payload) - stdin:write(format_message_with_content_length(encoded)) - return true - end - - -- FIXME: DOC: Should be placed on the RPC client object returned by - -- `start()` - -- - --- Sends a notification to the LSP server. - ---@param method (string) The invoked LSP method - ---@param params (table|nil): Parameters for the invoked LSP method - ---@returns (bool) `true` if notification could be sent, `false` if not - local function notify(method, params) - return encode_and_send({ - jsonrpc = '2.0', - method = method, - params = params, - }) + --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. + ---@param code (number) Exit code + ---@param signal (number) Signal that was used to terminate (if any) + local function onexit(code, signal) + stdin:close() + stdout:close() + stderr:close() + handle:close() + dispatchers.on_exit(code, signal) end - - ---@private - --- sends an error object to the remote LSP process. - local function send_response(request_id, err, result) - return encode_and_send({ - id = request_id, - jsonrpc = '2.0', - error = err, - result = result, - }) + local spawn_params = { + args = cmd_args, + stdio = { stdin, stdout, stderr }, + detached = not is_win, + } + if extra_spawn_params then + spawn_params.cwd = extra_spawn_params.cwd + spawn_params.env = env_merge(extra_spawn_params.env) + if extra_spawn_params.detached ~= nil then + spawn_params.detached = extra_spawn_params.detached + end end - - -- FIXME: DOC: Should be placed on the RPC client object returned by - -- `start()` - -- - --- Sends a request to the LSP server and runs {callback} upon response. - --- - ---@param method (string) The invoked LSP method - ---@param params (table|nil) Parameters for the invoked LSP method - ---@param callback (function) Callback to invoke - ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending - ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not - local function request(method, params, callback, notify_reply_callback) - validate({ - callback = { callback, 'f' }, - notify_reply_callback = { notify_reply_callback, 'f', true }, - }) - message_index = message_index + 1 - local message_id = message_index - local result = encode_and_send({ - id = message_id, - jsonrpc = '2.0', - method = method, - params = params, - }) - if result then - if message_callbacks then - message_callbacks[message_id] = schedule_wrap(callback) - else - return false - end - if notify_reply_callback and notify_reply_callbacks then - notify_reply_callbacks[message_id] = schedule_wrap(notify_reply_callback) - end - return result, message_id + handle, pid = uv.spawn(cmd, spawn_params, onexit) + if handle == nil then + stdin:close() + stdout:close() + stderr:close() + local msg = string.format('Spawning language server with cmd: `%s` failed', cmd) + if string.match(pid, 'ENOENT') then + msg = msg + .. '. The language server is either not installed, missing from PATH, or not executable.' else - return false + msg = msg .. string.format(' with error message: %s', pid) end + vim.notify(msg, vim.log.levels.WARN) + return end stderr:read_start(function(_, chunk) @@ -470,171 +681,14 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) end end) - ---@private - local function on_error(errkind, ...) - assert(client_errors[errkind]) - -- TODO what to do if this fails? - pcall(dispatchers.on_error, errkind, ...) - end - ---@private - local function pcall_handler(errkind, status, head, ...) - if not status then - on_error(errkind, head, ...) - return status, head - end - return status, head, ... - end - ---@private - local function try_call(errkind, fn, ...) - return pcall_handler(errkind, pcall(fn, ...)) - end - - -- TODO periodically check message_callbacks for old requests past a certain - -- time and log them. This would require storing the timestamp. I could call - -- them with an error then, perhaps. - - ---@private - local function handle_body(body) - local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) - if not ok then - on_error(client_errors.INVALID_SERVER_JSON, decoded) - return - end - local _ = log.debug() and log.debug('rpc.receive', decoded) - - if type(decoded.method) == 'string' and decoded.id then - local err - -- Schedule here so that the users functions don't trigger an error and - -- we can still use the result. - schedule(function() - local status, result - status, result, err = try_call( - client_errors.SERVER_REQUEST_HANDLER_ERROR, - dispatchers.server_request, - decoded.method, - decoded.params - ) - local _ = log.debug() - and log.debug( - 'server_request: callback result', - { status = status, result = result, err = err } - ) - if status then - if not (result or err) then - -- TODO this can be a problem if `null` is sent for result. needs vim.NIL - error( - string.format( - 'method %q: either a result or an error must be sent to the server in response', - decoded.method - ) - ) - end - if err then - assert( - type(err) == 'table', - 'err must be a table. Use rpc_response_error to help format errors.' - ) - local code_name = assert( - protocol.ErrorCodes[err.code], - 'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.' - ) - err.message = err.message or code_name - end - else - -- On an exception, result will contain the error message. - err = rpc_response_error(protocol.ErrorCodes.InternalError, result) - result = nil - end - send_response(decoded.id, err, result) - end) - -- This works because we are expecting vim.NIL here - elseif decoded.id and (decoded.result ~= vim.NIL or decoded.error ~= vim.NIL) then - -- We sent a number, so we expect a number. - local result_id = assert(tonumber(decoded.id), 'response id must be a number') - - -- Notify the user that a response was received for the request - local notify_reply_callback = notify_reply_callbacks and notify_reply_callbacks[result_id] - if notify_reply_callback then - validate({ - notify_reply_callback = { notify_reply_callback, 'f' }, - }) - notify_reply_callback(result_id) - notify_reply_callbacks[result_id] = nil - end - - -- Do not surface RequestCancelled to users, it is RPC-internal. - if decoded.error then - local mute_error = false - if decoded.error.code == protocol.ErrorCodes.RequestCancelled then - local _ = log.debug() and log.debug('Received cancellation ack', decoded) - mute_error = true - end - - if mute_error then - -- Clear any callback since this is cancelled now. - -- This is safe to do assuming that these conditions hold: - -- - The server will not send a result callback after this cancellation. - -- - If the server sent this cancellation ACK after sending the result, the user of this RPC - -- client will ignore the result themselves. - if result_id and message_callbacks then - message_callbacks[result_id] = nil - end - return - end - end - - local callback = message_callbacks and message_callbacks[result_id] - if callback then - message_callbacks[result_id] = nil - validate({ - callback = { callback, 'f' }, - }) - if decoded.error then - decoded.error = setmetatable(decoded.error, { - __tostring = format_rpc_error, - }) - end - try_call( - client_errors.SERVER_RESULT_CALLBACK_ERROR, - callback, - decoded.error, - decoded.result - ) - else - on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) - local _ = log.error() - and log.error('No callback found for server response id ' .. result_id) - end - elseif type(decoded.method) == 'string' then - -- Notification - try_call( - client_errors.NOTIFICATION_HANDLER_ERROR, - dispatchers.notification, - decoded.method, - decoded.params - ) - else - -- Invalid server message - on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) - end + local handle_body = function(body) + client:handle_body(body) end - - local request_parser = coroutine.wrap(request_parser_loop) - request_parser() stdout:read_start(create_read_loop(handle_body, nil, function(err) - on_error(client_errors.READ_ERROR, err) + client:on_error(client_errors.READ_ERROR, err) end)) - return { - is_closing = function() - return handle:is_closing() - end, - terminate = function() - handle:kill(15) - end, - request = request, - notify = notify, - } + return public_client(client) end return { -- cgit From 60ec6e34d585a7f633d49aab790066c1740885e1 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Wed, 24 Aug 2022 20:25:34 +0200 Subject: feat(lsp): add tcp support --- runtime/doc/lsp.txt | 26 +++++++-- runtime/lua/vim/lsp.lua | 38 +++++++++---- runtime/lua/vim/lsp/rpc.lua | 104 ++++++++++++++++++++++++++++-------- test/functional/plugin/lsp_spec.lua | 28 ++++++++++ 4 files changed, 159 insertions(+), 37 deletions(-) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 9661a43e4c..82d94afdc8 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -825,7 +825,7 @@ start({config}, {opts}) *vim.lsp.start()* re-uses a client if name and root_dir matches. Return: ~ - (number) client_id + (number|nil) client_id start_client({config}) *vim.lsp.start_client()* Starts and initializes a client with the given configuration. @@ -835,9 +835,16 @@ start_client({config}) *vim.lsp.start_client()* The following parameters describe fields in the {config} table. Parameters: ~ - {cmd} (required, string or list treated like - |jobstart()|) Base command that initiates the LSP - client. + {cmd} (table|string|fun(dispatchers: table):table) + command string or list treated like |jobstart|. + The command must launch the language server + process. `cmd` can also be a function that + creates an RPC client. The function receives a + dispatchers table and must return a table with + the functions `request`, `notify`, `is_closing` + and `terminate` See |vim.lsp.rpc.request| and + |vim.lsp.rpc.notify| For TCP there is a built-in + rpc client factory: |vim.lsp.rpc.connect| {cmd_cwd} (string, default=|getcwd()|) Directory to launch the `cmd` process. Not related to `root_dir`. {cmd_env} (table) Environment flags to pass to the LSP on @@ -1890,6 +1897,17 @@ should_log({level}) *vim.lsp.log.should_log()* ============================================================================== Lua module: vim.lsp.rpc *lsp-rpc* +connect({host}, {port}) *vim.lsp.rpc.connect()* + Create a LSP RPC client factory that connects via TCP to the given host + and port + + Parameters: ~ + {host} (string) + {port} (number) + + Return: ~ + (function) + format_rpc_error({err}) *vim.lsp.rpc.format_rpc_error()* Constructs an error message from an LSP error object. diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 5986f5a5e8..1dc1a045fd 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -289,7 +289,12 @@ local function validate_client_config(config) 'flags.debounce_text_changes must be a number with the debounce time in milliseconds' ) - local cmd, cmd_args = lsp._cmd_parts(config.cmd) + local cmd, cmd_args + if type(config.cmd) == 'function' then + cmd = config.cmd + else + cmd, cmd_args = lsp._cmd_parts(config.cmd) + end local offset_encoding = valid_encodings.UTF16 if config.offset_encoding then offset_encoding = validate_encoding(config.offset_encoding) @@ -855,14 +860,17 @@ end --- Used on all running clients. --- The default implementation re-uses a client if name --- and root_dir matches. ----@return number client_id +---@return number|nil client_id function lsp.start(config, opts) opts = opts or {} local reuse_client = opts.reuse_client or function(client, conf) return client.config.root_dir == conf.root_dir and client.name == conf.name end - config.name = config.name or (config.cmd[1] and vim.fs.basename(config.cmd[1])) or nil + config.name = config.name + if not config.name and type(config.cmd) == 'table' then + config.name = config.cmd[1] and vim.fs.basename(config.cmd[1]) or nil + end local bufnr = api.nvim_get_current_buf() for _, clients in ipairs({ uninitialized_clients, lsp.get_active_clients() }) do for _, client in pairs(clients) do @@ -893,8 +901,13 @@ end --- The following parameters describe fields in the {config} table. --- --- ----@param cmd: (required, string or list treated like |jobstart()|) Base command ---- that initiates the LSP client. +---@param cmd: (table|string|fun(dispatchers: table):table) command string or +--- list treated like |jobstart|. The command must launch the language server +--- process. `cmd` can also be a function that creates an RPC client. +--- The function receives a dispatchers table and must return a table with the +--- functions `request`, `notify`, `is_closing` and `terminate` +--- See |vim.lsp.rpc.request| and |vim.lsp.rpc.notify| +--- For TCP there is a built-in rpc client factory: |vim.lsp.rpc.connect| --- ---@param cmd_cwd: (string, default=|getcwd()|) Directory to launch --- the `cmd` process. Not related to `root_dir`. @@ -1164,11 +1177,16 @@ function lsp.start_client(config) end -- Start the RPC client. - local rpc = lsp_rpc.start(cmd, cmd_args, dispatch, { - cwd = config.cmd_cwd, - env = config.cmd_env, - detached = config.detached, - }) + local rpc + if type(cmd) == 'function' then + rpc = cmd(dispatch) + else + rpc = lsp_rpc.start(cmd, cmd_args, dispatch, { + cwd = config.cmd_cwd, + env = config.cmd_env, + detached = config.detached, + }) + end -- Return nil if client fails to start if not rpc then diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 5ac1b91e70..238c6c0570 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -556,6 +556,84 @@ local function public_client(client) return result end +---@private +local function merge_dispatchers(dispatchers) + if dispatchers then + local user_dispatchers = dispatchers + dispatchers = {} + for dispatch_name, default_dispatch in pairs(default_dispatchers) do + local user_dispatcher = user_dispatchers[dispatch_name] + if user_dispatcher then + if type(user_dispatcher) ~= 'function' then + error(string.format('dispatcher.%s must be a function', dispatch_name)) + end + -- server_request is wrapped elsewhere. + if + not (dispatch_name == 'server_request' or dispatch_name == 'on_exit') -- TODO this blocks the loop exiting for some reason. + then + user_dispatcher = schedule_wrap(user_dispatcher) + end + dispatchers[dispatch_name] = user_dispatcher + else + dispatchers[dispatch_name] = default_dispatch + end + end + else + dispatchers = default_dispatchers + end + return dispatchers +end + +--- Create a LSP RPC client factory that connects via TCP to the given host +--- and port +--- +---@param host string +---@param port number +---@return function +local function connect(host, port) + return function(dispatchers) + dispatchers = merge_dispatchers(dispatchers) + local tcp = uv.new_tcp() + local closing = false + local transport = { + write = function(msg) + tcp:write(msg) + end, + is_closing = function() + return closing + end, + terminate = function() + if not closing then + closing = true + tcp:shutdown() + tcp:close() + dispatchers.on_exit(0, 0) + end + end, + } + local client = new_client(dispatchers, transport) + tcp:connect(host, port, function(err) + if err then + vim.schedule(function() + vim.notify( + string.format('Could not connect to %s:%s, reason: %s', host, port, vim.inspect(err)), + vim.log.levels.WARN + ) + end) + return + end + local handle_body = function(body) + client:handle_body(body) + end + tcp:read_start(create_read_loop(handle_body, transport.terminate, function(read_err) + client:on_error(client_errors.READ_ERROR, read_err) + end)) + end) + + return public_client(client) + end +end + --- Starts an LSP server process and create an LSP RPC client object to --- interact with it. Communication with the server is currently limited to stdio. --- @@ -593,30 +671,8 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params) if extra_spawn_params and extra_spawn_params.cwd then assert(is_dir(extra_spawn_params.cwd), 'cwd must be a directory') end - if dispatchers then - local user_dispatchers = dispatchers - dispatchers = {} - for dispatch_name, default_dispatch in pairs(default_dispatchers) do - local user_dispatcher = user_dispatchers[dispatch_name] - if user_dispatcher then - if type(user_dispatcher) ~= 'function' then - error(string.format('dispatcher.%s must be a function', dispatch_name)) - end - -- server_request is wrapped elsewhere. - if - not (dispatch_name == 'server_request' or dispatch_name == 'on_exit') -- TODO this blocks the loop exiting for some reason. - then - user_dispatcher = schedule_wrap(user_dispatcher) - end - dispatchers[dispatch_name] = user_dispatcher - else - dispatchers[dispatch_name] = default_dispatch - end - end - else - dispatchers = default_dispatchers - end + dispatchers = merge_dispatchers(dispatchers) local stdin = uv.new_pipe(false) local stdout = uv.new_pipe(false) local stderr = uv.new_pipe(false) @@ -693,8 +749,10 @@ end return { start = start, + connect = connect, rpc_response_error = rpc_response_error, format_rpc_error = format_rpc_error, client_errors = client_errors, + create_read_loop = create_read_loop, } -- vim:sw=2 ts=2 et diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index cd7415de90..fa731f6faf 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -3181,4 +3181,32 @@ describe('LSP', function() } end) end) + + describe('cmd', function() + it('can connect to lsp server via rpc.connect', function() + local result = exec_lua [[ + local uv = vim.loop + local server = uv.new_tcp() + local init = nil + server:bind('127.0.0.1', 0) + server:listen(127, function(err) + assert(not err, err) + local socket = uv.new_tcp() + server:accept(socket) + socket:read_start(require('vim.lsp.rpc').create_read_loop(function(body) + init = body + socket:close() + end)) + end) + local port = server:getsockname().port + vim.lsp.start({ name = 'dummy', cmd = vim.lsp.rpc.connect('127.0.0.1', port) }) + vim.wait(1000, function() return init ~= nil end) + assert(init, "server must receive `initialize` request") + server:close() + server:shutdown() + return vim.json.decode(init) + ]] + eq(result.method, "initialize") + end) + end) end) -- cgit From b21980bd607e952fe52957aec3214367bd48527b Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 29 Aug 2022 05:58:32 +0800 Subject: fix(keywordprg): default to :help if set to empty string (#19983) --- src/nvim/normal.c | 5 ++--- test/functional/editor/K_spec.lua | 11 +++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 31646f686d..cab380003d 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -4278,13 +4278,12 @@ static void nv_ident(cmdarg_T *cap) // double the length of the word. p_kp / curbuf->b_p_kp could be added // and some numbers. char_u *kp = *curbuf->b_p_kp == NUL ? p_kp : (char_u *)curbuf->b_p_kp; // 'keywordprg' - assert(*kp != NUL); // option.c:do_set() should default to ":help" if empty. - bool kp_ex = (*kp == ':'); // 'keywordprg' is an ex command - bool kp_help = (STRCMP(kp, ":he") == 0 || STRCMP(kp, ":help") == 0); + bool kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0 || STRCMP(kp, ":help") == 0); if (kp_help && *skipwhite(ptr) == NUL) { emsg(_(e_noident)); // found white space only return; } + bool kp_ex = (*kp == ':'); // 'keywordprg' is an ex command size_t buf_size = n * 2 + 30 + STRLEN(kp); char *buf = xmalloc(buf_size); buf[0] = NUL; diff --git a/test/functional/editor/K_spec.lua b/test/functional/editor/K_spec.lua index 8ad81ac3d6..3b5580540f 100644 --- a/test/functional/editor/K_spec.lua +++ b/test/functional/editor/K_spec.lua @@ -1,6 +1,6 @@ local helpers = require('test.functional.helpers')(after_each) -local eq, clear, eval, feed, retry = - helpers.eq, helpers.clear, helpers.eval, helpers.feed, helpers.retry +local eq, clear, eval, feed, meths, retry = + helpers.eq, helpers.clear, helpers.eval, helpers.feed, helpers.meths, helpers.retry describe('K', function() local test_file = 'K_spec_out' @@ -58,4 +58,11 @@ describe('K', function() helpers.neq(bufnr, eval('bufnr()')) end) + it('empty string falls back to :help #19298', function() + meths.set_option('keywordprg', '') + meths.buf_set_lines(0, 0, -1, true, {'doesnotexist'}) + feed('K') + eq('E149: Sorry, no help for doesnotexist', meths.get_vvar('errmsg')) + end) + end) -- cgit From 1dcaa75a6564b8a90e74a96e242803c6aa3f59cf Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 29 Aug 2022 06:16:20 +0800 Subject: fix(events): triggered WinScrolled when only skipcol changed (#19972) fix(events): trigger WinScrolled when only skipcol changed vim-patch:9.0.0304: WinScrolled is not triggered when only skipcol changes Problem: WinScrolled is not triggered when only skipcol changes. Solution: Add w_last_skipcol and use it. (closes vim/vim#10998) https://github.com/vim/vim/commit/670ab0334b536e12d84810de88e73b7bcb01346d --- src/nvim/autocmd.c | 1 + src/nvim/buffer_defs.h | 3 ++- src/nvim/testdir/test_autocmd.vim | 33 ++++++++++++++++++++++++++++ src/nvim/window.c | 2 ++ test/functional/autocmd/winscrolled_spec.lua | 14 ++++++++++++ 5 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 2fe9df2206..1c1de214cd 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -1119,6 +1119,7 @@ int autocmd_register(int64_t id, event_T event, char *pat, int patlen, int group if (event == EVENT_WINSCROLLED && !has_event(EVENT_WINSCROLLED)) { curwin->w_last_topline = curwin->w_topline; curwin->w_last_leftcol = curwin->w_leftcol; + curwin->w_last_skipcol = curwin->w_skipcol; curwin->w_last_width = curwin->w_width; curwin->w_last_height = curwin->w_height; } diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index 58bdd2c0a8..319c2addba 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -1240,9 +1240,10 @@ struct window_S { colnr_T w_skipcol; // starting column when a single line // doesn't fit in the window - // four fields that are only used when there is a WinScrolled autocommand + // five fields that are only used when there is a WinScrolled autocommand linenr_T w_last_topline; ///< last known value for w_topline colnr_T w_last_leftcol; ///< last known value for w_leftcol + colnr_T w_last_skipcol; ///< last known value for w_skipcol int w_last_width; ///< last known value for w_width int w_last_height; ///< last known value for w_height diff --git a/src/nvim/testdir/test_autocmd.vim b/src/nvim/testdir/test_autocmd.vim index a249c2bf50..27bc6303cf 100644 --- a/src/nvim/testdir/test_autocmd.vim +++ b/src/nvim/testdir/test_autocmd.vim @@ -341,6 +341,39 @@ func Test_WinScrolled_close_curwin() call delete('Xtestout') endfunc +func Test_WinScrolled_long_wrapped() + CheckRunVimInTerminal + + let lines =<< trim END + set scrolloff=0 + let height = winheight(0) + let width = winwidth(0) + let g:scrolled = 0 + au WinScrolled * let g:scrolled += 1 + call setline(1, repeat('foo', height * width)) + call cursor(1, height * width) + END + call writefile(lines, 'Xtest_winscrolled_long_wrapped') + let buf = RunVimInTerminal('-S Xtest_winscrolled_long_wrapped', {'rows': 6}) + + call term_sendkeys(buf, ":echo g:scrolled\") + call WaitForAssert({-> assert_match('^0 ', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, 'gj') + call term_sendkeys(buf, ":echo g:scrolled\") + call WaitForAssert({-> assert_match('^1 ', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, '0') + call term_sendkeys(buf, ":echo g:scrolled\") + call WaitForAssert({-> assert_match('^2 ', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, '$') + call term_sendkeys(buf, ":echo g:scrolled\") + call WaitForAssert({-> assert_match('^3 ', term_getline(buf, 6))}, 1000) + + call delete('Xtest_winscrolled_long_wrapped') +endfunc + func Test_WinClosed() " Test that the pattern is matched against the closed window's ID, and both " and are set to it. diff --git a/src/nvim/window.c b/src/nvim/window.c index ffbb0fa27f..5b8a69f6eb 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -5362,6 +5362,7 @@ void may_trigger_winscrolled(void) win_T *wp = curwin; if (wp->w_last_topline != wp->w_topline || wp->w_last_leftcol != wp->w_leftcol + || wp->w_last_skipcol != wp->w_skipcol || wp->w_last_width != wp->w_width || wp->w_last_height != wp->w_height) { char winid[NUMBUFLEN]; @@ -5375,6 +5376,7 @@ void may_trigger_winscrolled(void) if (win_valid_any_tab(wp)) { wp->w_last_topline = wp->w_topline; wp->w_last_leftcol = wp->w_leftcol; + wp->w_last_skipcol = wp->w_skipcol; wp->w_last_width = wp->w_width; wp->w_last_height = wp->w_height; } diff --git a/test/functional/autocmd/winscrolled_spec.lua b/test/functional/autocmd/winscrolled_spec.lua index 5c1b758961..12b8e7c42d 100644 --- a/test/functional/autocmd/winscrolled_spec.lua +++ b/test/functional/autocmd/winscrolled_spec.lua @@ -61,6 +61,20 @@ describe('WinScrolled', function() eq(3, eval('g:scrolled')) end) + it('is triggered by scrolling on a long wrapped line #19968', function() + local height = meths.win_get_height(0) + local width = meths.win_get_width(0) + meths.buf_set_lines(0, 0, -1, true, {('foo'):rep(height * width)}) + meths.win_set_cursor(0, {1, height * width - 1}) + eq(0, eval('g:scrolled')) + feed('gj') + eq(1, eval('g:scrolled')) + feed('0') + eq(2, eval('g:scrolled')) + feed('$') + eq(3, eval('g:scrolled')) + end) + it('is triggered when the window scrolls in Insert mode', function() local height = meths.win_get_height(0) local lines = {} -- cgit From 253f0ffd8d4784b7fca03f8f6c2455b9ee83ff9b Mon Sep 17 00:00:00 2001 From: Shougo Date: Mon, 29 Aug 2022 14:11:52 +0900 Subject: vim-patch:9.0.0285: it is not easy to change the command line from a plugin (#19979) vim-patch:9.0.0285: it is not easy to change the command line from a plugin Problem: It is not easy to change the command line from a plugin. Solution: Add setcmdline(). (Shougo Matsushita, closes vim/vim#10869) https://github.com/vim/vim/commit/07ea5f1509fe8dafe3262ed2702b4d0fc99e288b --- runtime/doc/builtin.txt | 27 ++++++++++++++++++++------ runtime/doc/usr_41.txt | 1 + src/nvim/eval.lua | 1 + src/nvim/eval/funcs.c | 25 ++++++++++++++++++++++++ src/nvim/ex_getln.c | 38 ++++++++++++++++++++++++++++++++++--- src/nvim/testdir/test_cmdline.vim | 40 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 123 insertions(+), 9 deletions(-) diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 8cb9149529..a2e15142e7 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -400,6 +400,7 @@ setbufvar({buf}, {varname}, {val}) set {varname} in buffer {buf} to {val} setcellwidths({list}) none set character cell width overrides setcharpos({expr}, {list}) Number set the {expr} position to {list} setcharsearch({dict}) Dict set character search from {dict} +setcmdline({str} [, {pos}]) Number set command-line setcmdpos({pos}) Number set cursor position in command-line setcursorcharpos({list}) Number move cursor to position in {list} setenv({name}, {val}) none set environment variable @@ -2880,7 +2881,8 @@ getcmdcompltype() *getcmdcompltype()* Only works when the command line is being edited, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=|. See |:command-completion| for the return string. - Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|. + Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. Returns an empty string when completion is not defined. getcmdline() *getcmdline()* @@ -2889,7 +2891,8 @@ getcmdline() *getcmdline()* |c_CTRL-R_=|. Example: > :cmap eescape(getcmdline(), ' \') -< Also see |getcmdtype()|, |getcmdpos()| and |setcmdpos()|. +< Also see |getcmdtype()|, |getcmdpos()|, |setcmdpos()| and + |setcmdline()|. Returns an empty string when entering a password or using |inputsecret()|. @@ -2899,7 +2902,8 @@ getcmdpos() *getcmdpos()* Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. Returns 0 otherwise. - Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|. + Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. getcmdscreenpos() *getcmdscreenpos()* Return the screen position of the cursor in the command line @@ -2908,7 +2912,8 @@ getcmdscreenpos() *getcmdscreenpos()* Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. Returns 0 otherwise. - Also see |getcmdpos()|, |setcmdpos()|. + Also see |getcmdpos()|, |setcmdpos()|, |getcmdline()| and + |setcmdline()|. getcmdtype() *getcmdtype()* Return the current command-line type. Possible return values @@ -6912,6 +6917,16 @@ setcharsearch({dict}) *setcharsearch()* Can also be used as a |method|: > SavedSearch()->setcharsearch() +setcmdline({str} [, {pos}]) *setcmdline()* + Set the command line to {str} and set the cursor position to + {pos}. + If {pos} is omitted, the cursor is positioned after the text. + Returns 0 when successful, 1 when not editing the command + line. + + Can also be used as a |method|: > + GetText()->setcmdline() + setcmdpos({pos}) *setcmdpos()* Set the cursor position in the command line to byte position {pos}. The first position is 1. @@ -6924,8 +6939,8 @@ setcmdpos({pos}) *setcmdpos()* before inserting the resulting text. When the number is too big the cursor is put at the end of the line. A number smaller than one has undefined results. - Returns FALSE when successful, TRUE when not editing the - command line. + Returns 0 when successful, 1 when not editing the command + line. Can also be used as a |method|: > GetPos()->setcmdpos() diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 0c907bfb68..76c2f8454f 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -872,6 +872,7 @@ Command line: *command-line-functions* getcmdpos() get position of the cursor in the command line getcmdscreenpos() get screen position of the cursor in the command line + setcmdline() set the current command line setcmdpos() set position of the cursor in the command line getcmdtype() return the current command-line type getcmdwintype() return the current command-line window type diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 4863d8013d..3e89489459 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -332,6 +332,7 @@ return { setcharpos={args=2, base=2}, setcharsearch={args=1, base=1}, setcmdpos={args=1, base=1}, + setcmdline={args={1, 2}, base=1}, setcursorcharpos={args={1, 3}, base=1}, setenv={args=2, base=2}, setfperm={args=2, base=1}, diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 581f187140..2ed9ed34f4 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -7619,6 +7619,31 @@ static void f_setcharsearch(typval_T *argvars, typval_T *rettv, EvalFuncData fpt } } +/// "setcmdline()" function +static void f_setcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) +{ + if (argvars[0].v_type != VAR_STRING || argvars[0].vval.v_string == NULL) { + emsg(_(e_stringreq)); + return; + } + + int pos = -1; + if (argvars[1].v_type != VAR_UNKNOWN) { + bool error = false; + + pos = (int)tv_get_number_chk(&argvars[1], &error) - 1; + if (error) { + return; + } + if (pos < 0) { + emsg(_(e_positive)); + return; + } + } + + rettv->vval.v_number = set_cmdline_str(argvars[0].vval.v_string, pos); +} + /// "setcmdpos()" function static void f_setcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 081aa80778..84eacf3997 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -2373,9 +2373,9 @@ end: return cmdpreview_type != 0; } -static int command_line_changed(CommandLineState *s) +/// Trigger CmdlineChanged autocommands. +static void do_autocmd_cmdlinechanged(int firstc) { - // Trigger CmdlineChanged autocommands. if (has_event(EVENT_CMDLINECHANGED)) { TryState tstate; Error err = ERROR_INIT; @@ -2383,7 +2383,7 @@ static int command_line_changed(CommandLineState *s) dict_T *dict = get_v_event(&save_v_event); char firstcbuf[2]; - firstcbuf[0] = (char)(s->firstc > 0 ? s->firstc : '-'); + firstcbuf[0] = (char)firstc; firstcbuf[1] = 0; // set v:event to a dictionary with information about the commandline @@ -2403,6 +2403,12 @@ static int command_line_changed(CommandLineState *s) redrawcmd(); } } +} + +static int command_line_changed(CommandLineState *s) +{ + // Trigger CmdlineChanged autocommands. + do_autocmd_cmdlinechanged(s->firstc > 0 ? s->firstc : '-'); if (s->firstc == ':' && current_sctx.sc_sid == 0 // only if interactive @@ -3991,6 +3997,32 @@ int get_cmdline_screen_pos(void) return p->cmdspos; } +/// Set the command line str to "str". +/// @return 1 when failed, 0 when OK. +int set_cmdline_str(const char *str, int pos) +{ + CmdlineInfo *p = get_ccline_ptr(); + + if (p == NULL) { + return 1; + } + + int len = (int)STRLEN(str); + realloc_cmdbuff(len + 1); + p->cmdlen = len; + STRCPY(p->cmdbuff, str); + + p->cmdpos = pos < 0 || pos > p->cmdlen ? p->cmdlen : pos; + new_cmdpos = p->cmdpos; + + redrawcmd(); + + // Trigger CmdlineChanged autocommands. + do_autocmd_cmdlinechanged(ccline.cmdfirstc == NUL ? '-' : ccline.cmdfirstc); + + return 0; +} + /* * Set the command line byte position to "pos". Zero is the first position. * Only works when the command line is being edited. diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index 517509004a..a5a30b7953 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -2185,4 +2185,44 @@ func Test_wildmenu_pum_disable_while_shown() set wildoptions& wildmenu& endfunc +func Test_setcmdline() + func SetText(text, pos) + call assert_equal(0, setcmdline(a:text)) + call assert_equal(a:text, getcmdline()) + call assert_equal(len(a:text) + 1, getcmdpos()) + + call assert_equal(0, setcmdline(a:text, a:pos)) + call assert_equal(a:text, getcmdline()) + call assert_equal(a:pos, getcmdpos()) + + call assert_fails('call setcmdline("' .. a:text .. '", -1)', 'E487:') + call assert_fails('call setcmdline({}, 0)', 'E928:') + call assert_fails('call setcmdline("' .. a:text .. '", {})', 'E728:') + + return '' + endfunc + + call feedkeys(":\=SetText('set rtp?', 2)\\", 'xt') + call assert_equal('set rtp?', @:) + + " setcmdline() returns 1 when not editing the command line. + call assert_equal(1, 'foo'->setcmdline()) + + " Called in custom function + func CustomComplete(A, L, P) + call assert_equal(0, setcmdline("DoCmd ")) + return "January\nFebruary\nMars\n" + endfunc + + com! -nargs=* -complete=custom,CustomComplete DoCmd : + call feedkeys(":DoCmd \\\"\", 'tx') + call assert_equal('"DoCmd January February Mars', @:) + + " Called in + cnoremap a setcmdline('let foo=') + call feedkeys(":a\", 'tx') + call assert_equal('let foo=0', @:) + cunmap a +endfunc + " vim: shiftwidth=2 sts=2 expandtab -- cgit From ea4e9c71ccaf406fe7aa6b47d461cdab2d6c01e9 Mon Sep 17 00:00:00 2001 From: bfredl Date: Sat, 27 Aug 2022 11:28:11 +0200 Subject: refactor(plines): use a struct for chartabsize state This is a refactor extracted from vim-patch 9.0.0067: cannot show virtual text The logic for inline virtual text is going to be different in nvim than text property based text in vim, but this refactor is still useful, as calculation of displayed linesize is going to be stateful in a similar way. --- src/nvim/change.c | 4 +- src/nvim/charset.c | 24 +++++-- src/nvim/cursor.c | 16 +++-- src/nvim/drawline.c | 28 +++++--- src/nvim/edit.c | 80 +++++++++++++--------- src/nvim/eval/funcs.c | 6 +- src/nvim/ex_cmds.c | 2 +- src/nvim/getchar.c | 19 ++++-- src/nvim/indent.c | 52 +++++++++------ src/nvim/mouse.c | 26 ++++---- src/nvim/ops.c | 101 +++++++++++++++++++--------- src/nvim/plines.c | 182 ++++++++++++++++++++++++++++++-------------------- src/nvim/plines.h | 14 ++++ src/nvim/regexp.c | 2 +- src/nvim/regexp_bt.c | 1 + src/nvim/regexp_nfa.c | 2 +- 16 files changed, 354 insertions(+), 205 deletions(-) diff --git a/src/nvim/change.c b/src/nvim/change.c index 04dfb20a1b..074700f4df 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -653,9 +653,9 @@ void ins_char_bytes(char_u *buf, size_t charlen) // cells. May result in adding spaces to fill a gap. colnr_T vcol; getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL); - colnr_T new_vcol = vcol + win_chartabsize(curwin, buf, vcol); + colnr_T new_vcol = vcol + win_chartabsize(curwin, (char *)buf, vcol); while (oldp[col + oldlen] != NUL && vcol < new_vcol) { - vcol += win_chartabsize(curwin, oldp + col + oldlen, vcol); + vcol += win_chartabsize(curwin, (char *)oldp + col + oldlen, vcol); // Don't need to remove a TAB that takes us to the right // position. if (vcol > new_vcol && oldp[col + oldlen] == TAB) { diff --git a/src/nvim/charset.c b/src/nvim/charset.c index dc62b85716..3632c3d70b 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -930,14 +930,18 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en posptr -= utf_head_off(line, posptr); } + chartabsize_T cts; + init_chartabsize_arg(&cts, wp, pos->lnum, 0, line, line); + // This function is used very often, do some speed optimizations. // When 'list', 'linebreak', 'showbreak' and 'breakindent' are not set - // use a simple loop. + // and there are no virtual text use a simple loop. // Also use this when 'list' is set but tabs take their normal size. if ((!wp->w_p_list || (wp->w_p_lcs_chars.tab1 != NUL)) && !wp->w_p_lbr && *get_showbreak_value(wp) == NUL - && !wp->w_p_bri) { + && !wp->w_p_bri + && !cts.cts_has_virt_text) { for (;;) { head = 0; int c = *ptr; @@ -984,25 +988,29 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en } else { for (;;) { // A tab gets expanded, depending on the current column + // Other things also take up space. head = 0; - incr = win_lbr_chartabsize(wp, line, ptr, vcol, &head); + incr = win_lbr_chartabsize(&cts, &head); // make sure we don't go past the end of the line - if (*ptr == NUL) { + if (*cts.cts_ptr == NUL) { // NUL at end of line only takes one column incr = 1; break; } - if ((posptr != NULL) && (ptr >= posptr)) { + if ((posptr != NULL) && ((char_u *)cts.cts_ptr >= posptr)) { // character at pos->col break; } - vcol += incr; - MB_PTR_ADV(ptr); + cts.cts_vcol += incr; + MB_PTR_ADV(cts.cts_ptr); } + vcol = cts.cts_vcol; + ptr = (char_u *)cts.cts_ptr; } + clear_chartabsize_arg(&cts); if (start != NULL) { *start = vcol + head; @@ -1013,6 +1021,8 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en } if (cursor != NULL) { + // cursor is after inserted text + vcol += cts.cts_cur_text_width; if ((*ptr == TAB) && (State & MODE_NORMAL) && !wp->w_p_list diff --git a/src/nvim/cursor.c b/src/nvim/cursor.c index 14ebc11cbf..ed0488cf76 100644 --- a/src/nvim/cursor.c +++ b/src/nvim/cursor.c @@ -137,14 +137,18 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a } } - char_u *ptr = line; - while (col <= wcol && *ptr != NUL) { + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, pos->lnum, 0, line, line); + while (cts.cts_vcol <= wcol && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) - csize = win_lbr_chartabsize(curwin, line, ptr, col, &head); - MB_PTR_ADV(ptr); - col += csize; + csize = win_lbr_chartabsize(&cts, &head); + MB_PTR_ADV(cts.cts_ptr); + cts.cts_vcol += csize; } - idx = (int)(ptr - line); + col = cts.cts_vcol; + idx = (int)(cts.cts_ptr - (char *)line); + clear_chartabsize_arg(&cts); + // Handle all the special cases. The virtual_active() check // is needed to ensure that a virtual position off the end of // a line has the correct indexing. The one_more comparison diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index 9132d6666e..4b5f6c6c06 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -940,12 +940,19 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, } if (v > 0 && !number_only) { char_u *prev_ptr = ptr; - while (vcol < v && *ptr != NUL) { - c = win_lbr_chartabsize(wp, line, ptr, (colnr_T)vcol, NULL); - vcol += c; - prev_ptr = ptr; - MB_PTR_ADV(ptr); + chartabsize_T cts; + int charsize; + + init_chartabsize_arg(&cts, wp, lnum, (colnr_T)vcol, line, ptr); + while (cts.cts_vcol < v && *cts.cts_ptr != NUL) { + charsize = win_lbr_chartabsize(&cts, NULL); + cts.cts_vcol += charsize; + prev_ptr = (char_u *)cts.cts_ptr; + MB_PTR_ADV(cts.cts_ptr); } + vcol = cts.cts_vcol; + ptr = (char_u *)cts.cts_ptr; + clear_chartabsize_arg(&cts); // When: // - 'cuc' is set, or @@ -963,11 +970,11 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // Handle a character that's not completely on the screen: Put ptr at // that character but skip the first few screen characters. if (vcol > v) { - vcol -= c; + vcol -= charsize; ptr = prev_ptr; // If the character fits on the screen, don't need to skip it. // Except for a TAB. - if (utf_ptr2cells((char *)ptr) >= c || *ptr == TAB) { + if (utf_ptr2cells((char *)ptr) >= charsize || *ptr == TAB) { n_skip = (int)(v - vcol); } } @@ -1798,8 +1805,10 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, && !vim_isbreak((int)(*ptr))) { int mb_off = utf_head_off(line, ptr - 1); char_u *p = ptr - (mb_off + 1); - // TODO(neovim): is passing p for start of the line OK? - n_extra = win_lbr_chartabsize(wp, line, p, (colnr_T)vcol, NULL) - 1; + chartabsize_T cts; + + init_chartabsize_arg(&cts, wp, lnum, (colnr_T)vcol, line, p); + n_extra = win_lbr_chartabsize(&cts, NULL) - 1; // We have just drawn the showbreak value, no need to add // space for it again. @@ -1825,6 +1834,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, c = ' '; } } + clear_chartabsize_arg(&cts); } in_multispace = c == ' ' && ((ptr > line + 1 && ptr[-2] == ' ') || *ptr == ' '); diff --git a/src/nvim/edit.c b/src/nvim/edit.c index ed625e1d6e..e785a46dae 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1665,28 +1665,28 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang } else if (!(State & MODE_INSERT)) { new_cursor_col = curwin->w_cursor.col; } else { - /* - * Compute the screen column where the cursor should be. - */ + // Compute the screen column where the cursor should be. vcol = get_indent() - vcol; curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol); - /* - * Advance the cursor until we reach the right screen column. - */ - vcol = last_vcol = 0; - new_cursor_col = -1; + // Advance the cursor until we reach the right screen column. + last_vcol = 0; ptr = get_cursor_line_ptr(); - while (vcol <= (int)curwin->w_virtcol) { - last_vcol = vcol; - if (new_cursor_col >= 0) { - new_cursor_col += utfc_ptr2len((char *)ptr + new_cursor_col); - } else { - new_cursor_col++; + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, 0, 0, ptr, ptr); + while (cts.cts_vcol <= (int)curwin->w_virtcol) { + last_vcol = cts.cts_vcol; + if (cts.cts_vcol > 0) { + MB_PTR_ADV(cts.cts_ptr); + } + if (*cts.cts_ptr == NUL) { + break; } - vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol); + cts.cts_vcol += lbr_chartabsize(&cts); } vcol = last_vcol; + new_cursor_col = (int)(cts.cts_ptr - cts.cts_line); + clear_chartabsize_arg(&cts); /* * May need to insert spaces to be able to position the cursor on @@ -2991,7 +2991,7 @@ static void replace_do_bs(int limit_col) // Get the number of screen cells used by the character we are // going to delete. getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL); - orig_vcols = win_chartabsize(curwin, get_cursor_pos_ptr(), start_vcol); + orig_vcols = win_chartabsize(curwin, (char *)get_cursor_pos_ptr(), start_vcol); } (void)del_char_after_col(limit_col); if (l_State & VREPLACE_FLAG) { @@ -3006,7 +3006,7 @@ static void replace_do_bs(int limit_col) ins_len = (int)STRLEN(p) - orig_len; vcol = start_vcol; for (i = 0; i < ins_len; i++) { - vcol += win_chartabsize(curwin, p + i, vcol); + vcol += win_chartabsize(curwin, (char *)p + i, vcol); i += utfc_ptr2len((char *)p) - 1; } vcol -= start_vcol; @@ -4644,11 +4644,15 @@ static bool ins_tab(void) getvcol(curwin, &fpos, &vcol, NULL, NULL); getvcol(curwin, cursor, &want_vcol, NULL, NULL); + char_u *tab = (char_u *)"\t"; + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, 0, vcol, tab, tab); + // Use as many TABs as possible. Beware of 'breakindent', 'showbreak' // and 'linebreak' adding extra virtual columns. while (ascii_iswhite(*ptr)) { - i = lbr_chartabsize(NULL, (char_u *)"\t", vcol); - if (vcol + i > want_vcol) { + i = lbr_chartabsize(&cts); + if (cts.cts_vcol + i > want_vcol) { break; } if (*ptr != TAB) { @@ -4663,19 +4667,24 @@ static bool ins_tab(void) } fpos.col++; ptr++; - vcol += i; + cts.cts_vcol += i; } + vcol = cts.cts_vcol; + clear_chartabsize_arg(&cts); if (change_col >= 0) { int repl_off = 0; - char_u *line = ptr; - // Skip over the spaces we need. - while (vcol < want_vcol && *ptr == ' ') { - vcol += lbr_chartabsize(line, ptr, vcol); - ptr++; + init_chartabsize_arg(&cts, curwin, 0, vcol, ptr, ptr); + while (cts.cts_vcol < want_vcol && *cts.cts_ptr == ' ') { + cts.cts_vcol += lbr_chartabsize(&cts); + cts.cts_ptr++; repl_off++; } + ptr = (char_u *)cts.cts_ptr; + vcol = cts.cts_vcol; + clear_chartabsize_arg(&cts); + if (vcol > want_vcol) { // Must have a char with 'showbreak' just before it. ptr--; @@ -4855,7 +4864,6 @@ static int ins_digraph(void) int ins_copychar(linenr_T lnum) { int c; - int temp; char_u *ptr, *prev_ptr; char_u *line; @@ -4865,17 +4873,23 @@ int ins_copychar(linenr_T lnum) } // try to advance to the cursor column - temp = 0; - line = ptr = ml_get(lnum); - prev_ptr = ptr; + line = ml_get(lnum); + prev_ptr = line; validate_virtcol(); - while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL) { - prev_ptr = ptr; - temp += lbr_chartabsize_adv(line, &ptr, (colnr_T)temp); + + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, lnum, 0, line, line); + while (cts.cts_vcol < curwin->w_virtcol && *cts.cts_ptr != NUL) { + prev_ptr = (char_u *)cts.cts_ptr; + cts.cts_vcol += lbr_chartabsize_adv(&cts); } - if ((colnr_T)temp > curwin->w_virtcol) { + + if (cts.cts_vcol > curwin->w_virtcol) { ptr = prev_ptr; + } else { + ptr = (char_u *)cts.cts_ptr; } + clear_chartabsize_arg(&cts); c = utf_ptr2char((char *)ptr); if (c == NUL) { diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 581f187140..f3a00ffeb2 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -849,11 +849,11 @@ static void get_col(typval_T *argvars, typval_T *rettv, bool charcol) // col(".") when the cursor is on the NUL at the end of the line // because of "coladd" can be seen as an extra column. if (virtual_active() && fp == &curwin->w_cursor) { - char_u *p = get_cursor_pos_ptr(); + char *p = (char *)get_cursor_pos_ptr(); if (curwin->w_cursor.coladd >= (colnr_T)win_chartabsize(curwin, p, curwin->w_virtcol - curwin->w_cursor.coladd)) { int l; - if (*p != NUL && p[(l = utfc_ptr2len((char *)p))] == NUL) { + if (*p != NUL && p[(l = utfc_ptr2len(p))] == NUL) { col += l; } } @@ -8512,7 +8512,7 @@ static void f_strdisplaywidth(typval_T *argvars, typval_T *rettv, EvalFuncData f col = (int)tv_get_number(&argvars[1]); } - rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, (char_u *)s) - col); + rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, (char *)s) - col); } /// "strwidth()" function diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index a72cddc0a9..3bb900b57f 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -841,7 +841,7 @@ void ex_retab(exarg_T *eap) if (ptr[col] == NUL) { break; } - vcol += win_chartabsize(curwin, (char_u *)ptr + col, (colnr_T)vcol); + vcol += win_chartabsize(curwin, ptr + col, (colnr_T)vcol); if (vcol >= MAXCOL) { emsg(_(e_resulting_text_too_long)); break; diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index c1c5680cb0..f875fda13d 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -2547,7 +2547,7 @@ static int vgetorpeek(bool advance) && (State & MODE_INSERT) && (p_timeout || (keylen == KEYLEN_PART_KEY && p_ttimeout)) && (c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len, 3, 25L)) == 0) { - colnr_T col = 0, vcol; + colnr_T col = 0; char_u *ptr; if (mode_displayed) { @@ -2565,15 +2565,20 @@ static int vgetorpeek(bool advance) // We are expecting to truncate the trailing // white-space, so find the last non-white // character -- webb - col = vcol = curwin->w_wcol = 0; + curwin->w_wcol = 0; ptr = get_cursor_line_ptr(); - while (col < curwin->w_cursor.col) { - if (!ascii_iswhite(ptr[col])) { - curwin->w_wcol = vcol; + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, + curwin->w_cursor.lnum, 0, ptr, ptr); + while ((char_u *)cts.cts_ptr < ptr + curwin->w_cursor.col) { + if (!ascii_iswhite(*cts.cts_ptr)) { + curwin->w_wcol = cts.cts_vcol; } - vcol += lbr_chartabsize(ptr, ptr + col, vcol); - col += utfc_ptr2len((char *)ptr + col); + cts.cts_vcol += lbr_chartabsize(&cts); + cts.cts_ptr += utfc_ptr2len(cts.cts_ptr); } + clear_chartabsize_arg(&cts); + curwin->w_wrow = curwin->w_cline_row + curwin->w_wcol / curwin->w_width_inner; curwin->w_wcol %= curwin->w_width_inner; diff --git a/src/nvim/indent.c b/src/nvim/indent.c index c4805283c2..8aa8492dae 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -1034,13 +1034,15 @@ int get_lisp_indent(void) amount = 2; } else { char_u *line = that; - - amount = 0; - - while (*that && col) { - amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount); + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, pos->lnum, 0, line, line); + while (*cts.cts_ptr != NUL && col > 0) { + cts.cts_vcol += lbr_chartabsize_adv(&cts); col--; } + amount = cts.cts_vcol; + that = (char_u *)cts.cts_ptr; + clear_chartabsize_arg(&cts); // Some keywords require "body" indenting rules (the // non-standard-lisp ones are Scheme special forms): @@ -1056,10 +1058,15 @@ int get_lisp_indent(void) } firsttry = amount; - while (ascii_iswhite(*that)) { - amount += lbr_chartabsize(line, that, (colnr_T)amount); - that++; + init_chartabsize_arg(&cts, curwin, (colnr_T)(that - line), + amount, line, that); + while (ascii_iswhite(*cts.cts_ptr)) { + cts.cts_vcol += lbr_chartabsize(&cts); + cts.cts_ptr++; } + that = (char_u *)cts.cts_ptr; + amount = cts.cts_vcol; + clear_chartabsize_arg(&cts); if (*that && (*that != ';')) { // Not a comment line. @@ -1072,33 +1079,38 @@ int get_lisp_indent(void) parencount = 0; quotecount = 0; + init_chartabsize_arg(&cts, curwin, + (colnr_T)(that - line), amount, line, that); if (vi_lisp || ((*that != '"') && (*that != '\'') && (*that != '#') && ((*that < '0') || (*that > '9')))) { - while (*that - && (!ascii_iswhite(*that) || quotecount || parencount) - && (!((*that == '(' || *that == '[') + while (*cts.cts_ptr + && (!ascii_iswhite(*cts.cts_ptr) || quotecount || parencount) + && (!((*cts.cts_ptr == '(' || *cts.cts_ptr == '[') && !quotecount && !parencount && vi_lisp))) { - if (*that == '"') { + if (*cts.cts_ptr == '"') { quotecount = !quotecount; } - if (((*that == '(') || (*that == '[')) && !quotecount) { + if (((*cts.cts_ptr == '(') || (*cts.cts_ptr == '[')) && !quotecount) { parencount++; } - if (((*that == ')') || (*that == ']')) && !quotecount) { + if (((*cts.cts_ptr == ')') || (*cts.cts_ptr == ']')) && !quotecount) { parencount--; } - if ((*that == '\\') && (*(that + 1) != NUL)) { - amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount); + if ((*cts.cts_ptr == '\\') && (*(cts.cts_ptr + 1) != NUL)) { + cts.cts_vcol += lbr_chartabsize_adv(&cts); } - amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount); + cts.cts_vcol += lbr_chartabsize_adv(&cts); } } - while (ascii_iswhite(*that)) { - amount += lbr_chartabsize(line, that, (colnr_T)amount); - that++; + while (ascii_iswhite(*cts.cts_ptr)) { + cts.cts_vcol += lbr_chartabsize(&cts); + cts.cts_ptr++; } + that = (char_u *)cts.cts_ptr; + amount = cts.cts_vcol; + clear_chartabsize_arg(&cts); if (!*that || (*that == ';')) { amount = firsttry; diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index 3dfbeec048..5ebe97aa61 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -631,14 +631,16 @@ colnr_T vcol2col(win_T *const wp, const linenr_T lnum, const colnr_T vcol) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { // try to advance to the specified column - char_u *ptr = ml_get_buf(wp->w_buffer, lnum, false); - char_u *const line = ptr; - colnr_T count = 0; - while (count < vcol && *ptr != NUL) { - count += win_lbr_chartabsize(wp, line, ptr, count, NULL); - MB_PTR_ADV(ptr); - } - return (colnr_T)(ptr - line); + char_u *line = ml_get_buf(wp->w_buffer, lnum, false); + chartabsize_T cts; + init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + while (cts.cts_vcol < vcol && *cts.cts_ptr != NUL) { + cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); + MB_PTR_ADV(cts.cts_ptr); + } + clear_chartabsize_arg(&cts); + + return (colnr_T)((char_u *)cts.cts_ptr - line); } /// Set UI mouse depending on current mode and 'mouse'. @@ -667,7 +669,7 @@ static colnr_T scroll_line_len(linenr_T lnum) char_u *line = ml_get(lnum); if (*line != NUL) { for (;;) { - int numchar = win_chartabsize(curwin, line, col); + int numchar = win_chartabsize(curwin, (char *)line, col); MB_PTR_ADV(line); if (*line == NUL) { // don't count the last character break; @@ -790,7 +792,7 @@ static int mouse_adjust_click(win_T *wp, int row, int col) // checked for concealed characters. vcol = 0; while (vcol < offset && *ptr != NUL) { - vcol += win_chartabsize(curwin, ptr, vcol); + vcol += win_chartabsize(curwin, (char *)ptr, vcol); ptr += utfc_ptr2len((char *)ptr); } @@ -801,7 +803,7 @@ static int mouse_adjust_click(win_T *wp, int row, int col) vcol = offset; ptr_end = ptr_row_offset; while (vcol < col && *ptr_end != NUL) { - vcol += win_chartabsize(curwin, ptr_end, vcol); + vcol += win_chartabsize(curwin, (char *)ptr_end, vcol); ptr_end += utfc_ptr2len((char *)ptr_end); } @@ -816,7 +818,7 @@ static int mouse_adjust_click(win_T *wp, int row, int col) #define DECR() nudge--; ptr_end -= utfc_ptr2len((char *)ptr_end) while (ptr < ptr_end && *ptr != NUL) { - cwidth = win_chartabsize(curwin, ptr, vcol); + cwidth = win_chartabsize(curwin, (char *)ptr, vcol); vcol += cwidth; if (cwidth > 1 && *ptr == '\t' && nudge > 0) { // A tab will "absorb" any previous adjustments. diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 0fc15b9382..896cfa6098 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -378,12 +378,20 @@ static void shift_block(oparg_T *oap, int amount) bd.startspaces = 0; } } - for (; ascii_iswhite(*bd.textstart);) { - // TODO(fmoralesc): is passing bd.textstart for start of the line OK? - incr = lbr_chartabsize_adv(bd.textstart, &bd.textstart, bd.start_vcol); + + // TODO(vim): is passing bd.textstart for start of the line OK? + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, + bd.start_vcol, bd.textstart, bd.textstart); + while (ascii_iswhite(*cts.cts_ptr)) { + incr = lbr_chartabsize_adv(&cts); total += incr; - bd.start_vcol += incr; + cts.cts_vcol += incr; } + bd.textstart = (char_u *)cts.cts_ptr; + bd.start_vcol = cts.cts_vcol; + clear_chartabsize_arg(&cts); + // OK, now total=all the VWS reqd, and textstart points at the 1st // non-ws char in the block. if (!curbuf->b_p_et) { @@ -438,10 +446,16 @@ static void shift_block(oparg_T *oap, int amount) // The character's column is in "bd.start_vcol". colnr_T non_white_col = bd.start_vcol; - while (ascii_iswhite(*non_white)) { - incr = lbr_chartabsize_adv(bd.textstart, &non_white, non_white_col); - non_white_col += incr; + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, + non_white_col, bd.textstart, non_white); + while (ascii_iswhite(*cts.cts_ptr)) { + incr = lbr_chartabsize_adv(&cts); + cts.cts_vcol += incr; } + non_white_col = cts.cts_vcol; + non_white = (char_u *)cts.cts_ptr; + clear_chartabsize_arg(&cts); const colnr_T block_space_width = non_white_col - oap->start_vcol; // We will shift by "total" or "block_space_width", whichever is less. @@ -462,17 +476,19 @@ static void shift_block(oparg_T *oap, int amount) if (bd.startspaces) { verbatim_copy_width -= bd.start_char_vcols; } - while (verbatim_copy_width < destination_col) { - char_u *line = verbatim_copy_end; - - // TODO: is passing verbatim_copy_end for start of the line OK? - incr = lbr_chartabsize(line, verbatim_copy_end, verbatim_copy_width); - if (verbatim_copy_width + incr > destination_col) { + init_chartabsize_arg(&cts, curwin, 0, verbatim_copy_width, + bd.textstart, verbatim_copy_end); + while (cts.cts_vcol < destination_col) { + incr = lbr_chartabsize(&cts); + if (cts.cts_vcol + incr > destination_col) { break; } - verbatim_copy_width += incr; - MB_PTR_ADV(verbatim_copy_end); + cts.cts_vcol += incr; + MB_PTR_ADV(cts.cts_ptr); } + verbatim_copy_width = cts.cts_vcol; + verbatim_copy_end = (char_u *)cts.cts_ptr; + clear_chartabsize_arg(&cts); // If "destination_col" is different from the width of the initial // part of the line that will be copied, it means we encountered a tab @@ -1550,6 +1566,7 @@ int op_delete(oparg_T *oap) // Put deleted text into register 1 and shift number registers if the // delete contains a line break, or when using a specific operator (Vi // compatible) + if (oap->motion_type == kMTLineWise || oap->line_count > 1 || oap->use_reg_one) { shift_delete_registers(is_append_register(oap->regname)); reg = &y_regs[1]; @@ -3280,12 +3297,19 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) // get the old line and advance to the position to insert at oldp = get_cursor_line_ptr(); oldlen = STRLEN(oldp); - for (ptr = oldp; vcol < col && *ptr;) { + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0, + oldp, oldp); + + while (cts.cts_vcol < col && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) - incr = lbr_chartabsize_adv(oldp, &ptr, vcol); - vcol += incr; + incr = lbr_chartabsize_adv(&cts); + cts.cts_vcol += incr; } + vcol = cts.cts_vcol; + ptr = (char_u *)cts.cts_ptr; bd.textcol = (colnr_T)(ptr - oldp); + clear_chartabsize_arg(&cts); shortline = (vcol < col) || (vcol == col && !*ptr); @@ -3312,9 +3336,14 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) // calculate number of spaces required to fill right side of // block spaces = y_width + 1; + init_chartabsize_arg(&cts, curwin, 0, 0, + (char_u *)y_array[i], (char_u *)y_array[i]); for (int j = 0; j < yanklen; j++) { - spaces -= lbr_chartabsize(NULL, (char_u *)(&y_array[i][j]), 0); + spaces -= lbr_chartabsize(&cts); + cts.cts_ptr++; + cts.cts_vcol = 0; } + clear_chartabsize_arg(&cts); if (spaces < 0) { spaces = 0; } @@ -4227,22 +4256,28 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool bdp->start_char_vcols = 0; line = ml_get(lnum); - pstart = line; prev_pstart = line; - while (bdp->start_vcol < oap->start_vcol && *pstart) { + + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, lnum, bdp->start_vcol, line, line); + while (cts.cts_vcol < oap->start_vcol && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) - incr = lbr_chartabsize(line, pstart, bdp->start_vcol); - bdp->start_vcol += incr; - if (ascii_iswhite(*pstart)) { + incr = lbr_chartabsize(&cts); + cts.cts_vcol += incr; + if (ascii_iswhite(*cts.cts_ptr)) { bdp->pre_whitesp += incr; bdp->pre_whitesp_c++; } else { bdp->pre_whitesp = 0; bdp->pre_whitesp_c = 0; } - prev_pstart = pstart; - MB_PTR_ADV(pstart); + prev_pstart = (char_u *)cts.cts_ptr; + MB_PTR_ADV(cts.cts_ptr); } + bdp->start_vcol = cts.cts_vcol; + pstart = (char_u *)cts.cts_ptr; + clear_chartabsize_arg(&cts); + bdp->start_char_vcols = incr; if (bdp->start_vcol < oap->start_vcol) { // line too short bdp->end_vcol = bdp->start_vcol; @@ -4278,13 +4313,19 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool } } } else { + init_chartabsize_arg(&cts, curwin, lnum, bdp->end_vcol, + line, pend); prev_pend = pend; - while (bdp->end_vcol <= oap->end_vcol && *pend != NUL) { + while (cts.cts_vcol <= oap->end_vcol && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) - prev_pend = pend; - incr = lbr_chartabsize_adv(line, &pend, bdp->end_vcol); - bdp->end_vcol += incr; + prev_pend = (char_u *)cts.cts_ptr; + incr = lbr_chartabsize_adv(&cts); + cts.cts_vcol += incr; } + bdp->end_vcol = cts.cts_vcol; + pend = (char_u *)cts.cts_ptr; + clear_chartabsize_arg(&cts); + if (bdp->end_vcol <= oap->end_vcol && (!is_del || oap->op_type == OP_APPEND diff --git a/src/nvim/plines.c b/src/nvim/plines.c index 70bdbd8b1d..f13e83ca9b 100644 --- a/src/nvim/plines.c +++ b/src/nvim/plines.c @@ -98,15 +98,15 @@ int plines_win_nofill(win_T *wp, linenr_T lnum, bool winheight) /// "wp". Does not care about folding, 'wrap' or 'diff'. int plines_win_nofold(win_T *wp, linenr_T lnum) { - char_u *s; + char *s; unsigned int col; int width; - s = ml_get_buf(wp->w_buffer, lnum, false); + s = (char *)ml_get_buf(wp->w_buffer, lnum, false); if (*s == NUL) { // empty line return 1; } - col = win_linetabsize(wp, s, MAXCOL); + col = win_linetabsize(wp, lnum, (char_u *)s, MAXCOL); // If list mode is on, then the '$' at the end of the line may take up one // extra column. @@ -145,23 +145,27 @@ int plines_win_col(win_T *wp, linenr_T lnum, long column) } char_u *line = ml_get_buf(wp->w_buffer, lnum, false); - char_u *s = line; colnr_T col = 0; - while (*s != NUL && --column >= 0) { - col += win_lbr_chartabsize(wp, line, s, col, NULL); - MB_PTR_ADV(s); + chartabsize_T cts; + + init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + while (*cts.cts_ptr != NUL && --column >= 0) { + cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); + MB_PTR_ADV(cts.cts_ptr); } - // If *s is a TAB, and the TAB is not displayed as ^I, and we're not in - // MODE_INSERT state, then col must be adjusted so that it represents the + // If *cts.cts_ptr is a TAB, and the TAB is not displayed as ^I, and we're not + // in MODE_INSERT state, then col must be adjusted so that it represents the // last screen position of the TAB. This only fixes an error when the TAB // wraps from one screen line to the next (when 'columns' is not a multiple // of 'ts') -- webb. - if (*s == TAB && (State & MODE_NORMAL) + col = cts.cts_vcol; + if (*cts.cts_ptr == TAB && (State & MODE_NORMAL) && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) { - col += win_lbr_chartabsize(wp, line, s, col, NULL) - 1; + col += win_lbr_chartabsize(&cts, NULL) - 1; } + clear_chartabsize_arg(&cts); // Add column offset for 'number', 'relativenumber', 'foldcolumn', etc. int width = wp->w_width_inner - win_col_off(wp); @@ -223,7 +227,7 @@ int plines_m_win(win_T *wp, linenr_T first, linenr_T last) /// @param col /// /// @return Number of characters. -int win_chartabsize(win_T *wp, char_u *p, colnr_T col) +int win_chartabsize(win_T *wp, char *p, colnr_T col) { buf_T *buf = wp->w_buffer; if (*p == TAB && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) { @@ -241,24 +245,24 @@ int win_chartabsize(win_T *wp, char_u *p, colnr_T col) /// @return Number of characters the string will take on the screen. int linetabsize(char_u *s) { - return linetabsize_col(0, s); + return linetabsize_col(0, (char *)s); } -/// Like linetabsize(), but starting at column "startcol". +/// Like linetabsize(), but "s" starts at column "startcol". /// /// @param startcol /// @param s /// /// @return Number of characters the string will take on the screen. -int linetabsize_col(int startcol, char_u *s) +int linetabsize_col(int startcol, char *s) { - colnr_T col = startcol; - char_u *line = s; // pointer to start of line, for breakindent - - while (*s != NUL) { - col += lbr_chartabsize_adv(line, &s, col); + chartabsize_T cts; + init_chartabsize_arg(&cts, curwin, 0, startcol, (char_u *)s, (char_u *)s); + while (*cts.cts_ptr != NUL) { + cts.cts_vcol += lbr_chartabsize_adv(&cts); } - return (int)col; + clear_chartabsize_arg(&cts); + return (int)cts.cts_vcol; } /// Like linetabsize(), but for a given window instead of the current one. @@ -268,19 +272,39 @@ int linetabsize_col(int startcol, char_u *s) /// @param len /// /// @return Number of characters the string will take on the screen. -unsigned int win_linetabsize(win_T *wp, char_u *line, colnr_T len) +unsigned int win_linetabsize(win_T *wp, linenr_T lnum, char_u *line, colnr_T len) { - colnr_T col = 0; - - for (char_u *s = line; - *s != NUL && (len == MAXCOL || s < line + len); - MB_PTR_ADV(s)) { - col += win_lbr_chartabsize(wp, line, s, col, NULL); + chartabsize_T cts; + init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + for (; *cts.cts_ptr != NUL && (len == MAXCOL || cts.cts_ptr < (char *)line + len); + MB_PTR_ADV(cts.cts_ptr)) { + cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); } + clear_chartabsize_arg(&cts); + return (unsigned int)cts.cts_vcol; +} - return (unsigned int)col; +/// Prepare the structure passed to chartabsize functions. +/// +/// "line" is the start of the line, "ptr" is the first relevant character. +/// When "lnum" is zero do not use text properties that insert text. +void init_chartabsize_arg(chartabsize_T *cts, win_T *wp, linenr_T lnum, colnr_T col, char_u *line, + char_u *ptr) +{ + cts->cts_win = wp; + cts->cts_lnum = lnum; + cts->cts_vcol = col; + cts->cts_line = (char *)line; + cts->cts_ptr = (char *)ptr; + cts->cts_cur_text_width = 0; + // TODO(bfredl): actually lookup inline virtual text here + cts->cts_has_virt_text = false; } +/// Free any allocated item in "cts". +void clear_chartabsize_arg(chartabsize_T *cts) +{} + /// like win_chartabsize(), but also check for line breaks on the screen /// /// @param line @@ -288,16 +312,16 @@ unsigned int win_linetabsize(win_T *wp, char_u *line, colnr_T len) /// @param col /// /// @return The number of characters taken up on the screen. -int lbr_chartabsize(char_u *line, unsigned char *s, colnr_T col) +int lbr_chartabsize(chartabsize_T *cts) { if (!curwin->w_p_lbr && *get_showbreak_value(curwin) == NUL - && !curwin->w_p_bri) { + && !curwin->w_p_bri && !cts->cts_has_virt_text) { if (curwin->w_p_wrap) { - return win_nolbr_chartabsize(curwin, s, col, NULL); + return win_nolbr_chartabsize(cts, NULL); } - return win_chartabsize(curwin, s, col); + return win_chartabsize(curwin, cts->cts_ptr, cts->cts_vcol); } - return win_lbr_chartabsize(curwin, line == NULL ? s: line, s, col, NULL); + return win_lbr_chartabsize(cts, NULL); } /// Call lbr_chartabsize() and advance the pointer. @@ -307,12 +331,12 @@ int lbr_chartabsize(char_u *line, unsigned char *s, colnr_T col) /// @param col /// /// @return The number of characters take up on the screen. -int lbr_chartabsize_adv(char_u *line, char_u **s, colnr_T col) +int lbr_chartabsize_adv(chartabsize_T *cts) { int retval; - retval = lbr_chartabsize(line, *s, col); - MB_PTR_ADV(*s); + retval = lbr_chartabsize(cts); + MB_PTR_ADV(cts->cts_ptr); return retval; } @@ -322,17 +346,19 @@ int lbr_chartabsize_adv(char_u *line, char_u **s, colnr_T col) /// string at start of line. Warning: *headp is only set if it's a non-zero /// value, init to 0 before calling. /// -/// @param wp -/// @param line -/// @param s -/// @param col +/// @param cts /// @param headp /// /// @return The number of characters taken up on the screen. -int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *headp) +int win_lbr_chartabsize(chartabsize_T *cts, int *headp) { + win_T *wp = cts->cts_win; + char *line = cts->cts_line; // start of the line + char_u *s = (char_u *)cts->cts_ptr; + colnr_T vcol = cts->cts_vcol; + colnr_T col2; - colnr_T col_adj = 0; // col + screen size of tab + colnr_T col_adj = 0; // vcol + screen size of tab colnr_T colmax; int added; int mb_added = 0; @@ -340,16 +366,23 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *he char_u *ps; int n; + cts->cts_cur_text_width = 0; + // No 'linebreak', 'showbreak' and 'breakindent': return quickly. - if (!wp->w_p_lbr && !wp->w_p_bri && *get_showbreak_value(wp) == NUL) { + if (!wp->w_p_lbr && !wp->w_p_bri && *get_showbreak_value(wp) == NUL + && !cts->cts_has_virt_text) { if (wp->w_p_wrap) { - return win_nolbr_chartabsize(wp, s, col, headp); + return win_nolbr_chartabsize(cts, headp); } - return win_chartabsize(wp, s, col); + return win_chartabsize(wp, (char *)s, vcol); + } + + // First get normal size, without 'linebreak' or virtual text + int size = win_chartabsize(wp, (char *)s, vcol); + if (cts->cts_has_virt_text) { + // TODO(bfredl): inline virtual text } - // First get normal size, without 'linebreak' - int size = win_chartabsize(wp, s, col); int c = *s; if (*s == TAB) { col_adj = size - 1; @@ -365,15 +398,15 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *he // Count all characters from first non-blank after a blank up to next // non-blank after a blank. numberextra = win_col_off(wp); - col2 = col; + col2 = vcol; colmax = (colnr_T)(wp->w_width_inner - numberextra - col_adj); - if (col >= colmax) { + if (vcol >= colmax) { colmax += col_adj; n = colmax + win_col_off2(wp); if (n > 0) { - colmax += (((col - colmax) / n) + 1) * n - col_adj; + colmax += (((vcol - colmax) / n) + 1) * n - col_adj; } } @@ -383,21 +416,21 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *he c = *s; if (!(c != NUL - && (vim_isbreak(c) || col2 == col || !vim_isbreak((int)(*ps))))) { + && (vim_isbreak(c) || col2 == vcol || !vim_isbreak((int)(*ps))))) { break; } - col2 += win_chartabsize(wp, s, col2); + col2 += win_chartabsize(wp, (char *)s, col2); if (col2 >= colmax) { // doesn't fit - size = colmax - col + col_adj; + size = colmax - vcol + col_adj; break; } } } else if ((size == 2) && (MB_BYTE2LEN(*s) > 1) && wp->w_p_wrap - && in_win_border(wp, col)) { + && in_win_border(wp, vcol)) { // Count the ">" in the last column. size++; mb_added = 1; @@ -409,40 +442,40 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *he added = 0; char *const sbr = (char *)get_showbreak_value(wp); - if ((*sbr != NUL || wp->w_p_bri) && wp->w_p_wrap && col != 0) { + if ((*sbr != NUL || wp->w_p_bri) && wp->w_p_wrap && vcol != 0) { colnr_T sbrlen = 0; int numberwidth = win_col_off(wp); numberextra = numberwidth; - col += numberextra + mb_added; + vcol += numberextra + mb_added; - if (col >= (colnr_T)wp->w_width_inner) { - col -= wp->w_width_inner; + if (vcol >= (colnr_T)wp->w_width_inner) { + vcol -= wp->w_width_inner; numberextra = wp->w_width_inner - (numberextra - win_col_off2(wp)); - if (col >= numberextra && numberextra > 0) { - col %= numberextra; + if (vcol >= numberextra && numberextra > 0) { + vcol %= numberextra; } if (*sbr != NUL) { sbrlen = (colnr_T)mb_charlen((char_u *)sbr); - if (col >= sbrlen) { - col -= sbrlen; + if (vcol >= sbrlen) { + vcol -= sbrlen; } } - if (col >= numberextra && numberextra > 0) { - col %= numberextra; - } else if (col > 0 && numberextra > 0) { - col += numberwidth - win_col_off2(wp); + if (vcol >= numberextra && numberextra > 0) { + vcol %= numberextra; + } else if (vcol > 0 && numberextra > 0) { + vcol += numberwidth - win_col_off2(wp); } numberwidth -= win_col_off2(wp); } - if (col == 0 || (col + size + sbrlen > (colnr_T)wp->w_width_inner)) { + if (vcol == 0 || (vcol + size + sbrlen > (colnr_T)wp->w_width_inner)) { if (*sbr != NUL) { if (size + sbrlen + numberwidth > (colnr_T)wp->w_width_inner) { // Calculate effective window width. int width = (colnr_T)wp->w_width_inner - sbrlen - numberwidth; - int prev_width = col ? ((colnr_T)wp->w_width_inner - (sbrlen + col)) + int prev_width = vcol ? ((colnr_T)wp->w_width_inner - (sbrlen + vcol)) : 0; if (width <= 0) { @@ -459,11 +492,11 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *he } if (wp->w_p_bri) { - added += get_breakindent_win(wp, line); + added += get_breakindent_win(wp, (char_u *)line); } size += added; - if (col != 0) { + if (vcol != 0) { added = 0; } } @@ -485,8 +518,11 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, colnr_T col, int *he /// @param headp /// /// @return The number of characters take up on the screen. -static int win_nolbr_chartabsize(win_T *wp, char_u *s, colnr_T col, int *headp) +static int win_nolbr_chartabsize(chartabsize_T *cts, int *headp) { + win_T *wp = cts->cts_win; + char *s = cts->cts_ptr; + colnr_T col = cts->cts_vcol; int n; if ((*s == TAB) && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) { @@ -498,7 +534,7 @@ static int win_nolbr_chartabsize(win_T *wp, char_u *s, colnr_T col, int *headp) // Add one cell for a double-width character in the last column of the // window, displayed with a ">". - if ((n == 2) && (MB_BYTE2LEN(*s) > 1) && in_win_border(wp, col)) { + if ((n == 2) && (MB_BYTE2LEN((uint8_t)(*s)) > 1) && in_win_border(wp, col)) { if (headp != NULL) { *headp = 1; } diff --git a/src/nvim/plines.h b/src/nvim/plines.h index 32778b69f1..7b228f3e91 100644 --- a/src/nvim/plines.h +++ b/src/nvim/plines.h @@ -3,6 +3,20 @@ #include "nvim/vim.h" +// Argument for lbr_chartabsize(). +typedef struct { + win_T *cts_win; + linenr_T cts_lnum; // zero when not using text properties + char *cts_line; // start of the line + char *cts_ptr; // current position in line + + bool cts_has_virt_text; // true if if a property inserts text + int cts_cur_text_width; // width of current inserted text + // TODO(bfredl): iterator in to the marktree for scanning virt text + + int cts_vcol; // virtual column at current position +} chartabsize_T; + #ifdef INCLUDE_GENERATED_DECLARATIONS # include "plines.h.generated.h" #endif diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index b7ec4bf94e..75bd7b4cc1 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -1165,7 +1165,7 @@ static bool reg_match_visual(void) rex.line = reg_getline(rex.lnum); rex.input = rex.line + col; - unsigned int cols_u = win_linetabsize(wp, rex.line, col); + unsigned int cols_u = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, rex.line, col); assert(cols_u <= MAXCOL); colnr_T cols = (colnr_T)cols_u; if (cols < start || cols > end - (*p_sel == 'e')) { diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c index d7a4f40ecf..88f0d781af 100644 --- a/src/nvim/regexp_bt.c +++ b/src/nvim/regexp_bt.c @@ -3764,6 +3764,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) case RE_VCOL: if (!re_num_cmp(win_linetabsize(rex.reg_win == NULL ? curwin : rex.reg_win, + rex.reg_firstlnum + rex.lnum, rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan)) { diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c index 554def5b8a..d4db710d93 100644 --- a/src/nvim/regexp_nfa.c +++ b/src/nvim/regexp_nfa.c @@ -6910,7 +6910,7 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, regsubs_T *subm result = col > t->state->val * ts; } if (!result) { - uintmax_t lts = win_linetabsize(wp, rex.line, col); + uintmax_t lts = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, rex.line, col); assert(t->state->val >= 0); result = nfa_re_num_cmp((uintmax_t)t->state->val, op, lts + 1); } -- cgit From 92bc11a891538e5c306915bffef437f097572d09 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 29 Aug 2022 20:22:15 +0800 Subject: vim-patch:9.0.0316: screen flickers when 'cmdheight' is zero (#19991) Problem: Screen flickers when 'cmdheight' is zero. Solution: Redraw over existing text instead of clearing. https://github.com/vim/vim/commit/f73e5ba56f4aca1cd6e38f1c8ea24e941bf6b33f --- src/nvim/drawscreen.c | 50 ++++++++++++++++++++++++++------------------------ src/nvim/ex_getln.c | 2 +- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/src/nvim/drawscreen.c b/src/nvim/drawscreen.c index cf8178a30f..a601a82495 100644 --- a/src/nvim/drawscreen.c +++ b/src/nvim/drawscreen.c @@ -469,35 +469,37 @@ int update_screen(int type) } msg_grid_set_pos(Rows - (int)p_ch, false); msg_grid_invalid = false; - } else if (msg_scrolled > Rows - 5) { // clearing is faster - type = UPD_CLEAR; } else if (type != UPD_CLEAR) { - check_for_delay(false); - grid_ins_lines(&default_grid, 0, msg_scrolled, Rows, 0, Columns); - FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { - if (wp->w_floating) { - continue; - } - if (wp->w_winrow < msg_scrolled) { - if (W_ENDROW(wp) > msg_scrolled - && wp->w_redr_type < UPD_REDRAW_TOP - && wp->w_lines_valid > 0 - && wp->w_topline == wp->w_lines[0].wl_lnum) { - wp->w_upd_rows = msg_scrolled - wp->w_winrow; - wp->w_redr_type = UPD_REDRAW_TOP; - } else { - wp->w_redr_type = UPD_NOT_VALID; - if (wp->w_winrow + wp->w_winbar_height <= msg_scrolled) { - wp->w_redr_status = true; + if (msg_scrolled > Rows - 5) { // redrawing is faster + type = UPD_NOT_VALID; + } else { + check_for_delay(false); + grid_ins_lines(&default_grid, 0, msg_scrolled, Rows, 0, Columns); + FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { + if (wp->w_floating) { + continue; + } + if (wp->w_winrow < msg_scrolled) { + if (W_ENDROW(wp) > msg_scrolled + && wp->w_redr_type < UPD_REDRAW_TOP + && wp->w_lines_valid > 0 + && wp->w_topline == wp->w_lines[0].wl_lnum) { + wp->w_upd_rows = msg_scrolled - wp->w_winrow; + wp->w_redr_type = UPD_REDRAW_TOP; + } else { + wp->w_redr_type = UPD_NOT_VALID; + if (wp->w_winrow + wp->w_winbar_height <= msg_scrolled) { + wp->w_redr_status = true; + } } } } + if (is_stl_global && Rows - p_ch - 1 <= msg_scrolled) { + curwin->w_redr_status = true; + } + redraw_cmdline = true; + redraw_tabline = true; } - if (is_stl_global && Rows - p_ch - 1 <= msg_scrolled) { - curwin->w_redr_status = true; - } - redraw_cmdline = true; - redraw_tabline = true; } msg_scrolled = 0; msg_scrolled_at_flush = 0; diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 3d991996d6..0cca4b69e8 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -918,7 +918,7 @@ theend: // Restore cmdheight set_option_value("ch", 0L, NULL, 0); // Redraw is needed for command line completion - redraw_all_later(UPD_CLEAR); + redraw_all_later(UPD_NOT_VALID); made_cmdheight_nonzero = false; } -- cgit From 58f30a326f34319801e7921f32c83e8320d85f6c Mon Sep 17 00:00:00 2001 From: Dundar Göc Date: Fri, 26 Aug 2022 23:11:25 +0200 Subject: refactor: replace char_u with char Work on https://github.com/neovim/neovim/issues/459 --- src/nvim/arglist.c | 2 +- src/nvim/buffer.c | 2 +- src/nvim/buffer_defs.h | 6 +- src/nvim/change.c | 140 ++++++++++++++++++++++----------------------- src/nvim/charset.c | 18 +++--- src/nvim/cmdexpand.c | 9 ++- src/nvim/debugger.c | 10 ++-- src/nvim/diff.c | 78 ++++++++++++------------- src/nvim/drawline.c | 10 ++-- src/nvim/drawscreen.c | 2 +- src/nvim/edit.c | 40 ++++++------- src/nvim/eval.c | 2 +- src/nvim/eval/funcs.c | 24 ++++---- src/nvim/eval/userfunc.c | 4 +- src/nvim/eval/vars.c | 2 +- src/nvim/ex_cmds.c | 14 ++--- src/nvim/ex_docmd.c | 14 ++--- src/nvim/ex_eval.c | 6 +- src/nvim/ex_getln.c | 2 +- src/nvim/fileio.c | 4 +- src/nvim/getchar.c | 2 +- src/nvim/grid.c | 25 ++++---- src/nvim/hardcopy.c | 21 +++---- src/nvim/help.c | 4 +- src/nvim/highlight_group.c | 2 +- src/nvim/if_cscope.c | 8 +-- src/nvim/indent.c | 10 ++-- src/nvim/indent_c.c | 14 ++--- src/nvim/insexpand.c | 4 +- src/nvim/log.c | 2 +- src/nvim/lua/stdlib.c | 4 +- src/nvim/mapping.c | 4 +- src/nvim/mark.c | 6 +- src/nvim/match.c | 4 +- src/nvim/mbyte.c | 48 +++++++--------- src/nvim/memline.c | 12 ++-- src/nvim/message.c | 16 +++--- src/nvim/normal.c | 26 ++++----- src/nvim/ops.c | 16 +++--- src/nvim/option.c | 2 +- src/nvim/os/env.c | 4 +- src/nvim/os/fs.c | 2 +- src/nvim/path.c | 24 ++++---- src/nvim/plines.c | 2 +- src/nvim/popupmenu.c | 9 ++- src/nvim/quickfix.c | 12 ++-- src/nvim/regexp.c | 10 ++-- src/nvim/runtime.c | 30 ++++++---- src/nvim/screen.c | 14 ++--- src/nvim/search.c | 29 +++++----- src/nvim/shada.c | 2 +- src/nvim/spellfile.c | 88 ++++++++++++++-------------- src/nvim/statusline.c | 15 +++-- src/nvim/strings.c | 4 +- src/nvim/syntax.c | 20 +++---- src/nvim/tag.c | 33 ++++++----- src/nvim/textformat.c | 6 +- src/nvim/usercmd.c | 24 ++++---- src/nvim/usercmd.h | 6 +- src/nvim/version.c | 13 ++--- src/nvim/window.c | 12 ++-- 61 files changed, 479 insertions(+), 499 deletions(-) diff --git a/src/nvim/arglist.c b/src/nvim/arglist.c index 21aa5afbae..70b2e71949 100644 --- a/src/nvim/arglist.c +++ b/src/nvim/arglist.c @@ -202,7 +202,7 @@ static char *do_one_arg(char *str) for (p = str; *str; str++) { // When the backslash is used for escaping the special meaning of a // character we need to keep it until wildcard expansion. - if (rem_backslash((char_u *)str)) { + if (rem_backslash(str)) { *p++ = *str++; *p++ = *str; } else { diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index 5dc7083a01..514be4c56b 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -2701,7 +2701,7 @@ void buflist_list(exarg_T *eap) home_replace(buf, buf->b_fname, (char *)NameBuff, MAXPATHL, true); } - if (message_filtered((char_u *)NameBuff)) { + if (message_filtered(NameBuff)) { continue; } diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index 319c2addba..c1ac20fd98 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -325,7 +325,7 @@ typedef struct argentry { * Used for the typeahead buffer: typebuf. */ typedef struct { - char_u *tb_buf; // buffer for typed characters + uint8_t *tb_buf; // buffer for typed characters uint8_t *tb_noremap; // mapping flags for characters in tb_buf[] int tb_buflen; // size of tb_buf[] int tb_off; // current position in tb_buf[] @@ -353,7 +353,7 @@ typedef struct { typedef struct mapblock mapblock_T; struct mapblock { mapblock_T *m_next; // next mapblock in list - char_u *m_keys; // mapped from, lhs + uint8_t *m_keys; // mapped from, lhs char *m_str; // mapped to, rhs char *m_orig_str; // rhs as entered by the user LuaRef m_luaref; // lua function reference as rhs @@ -703,7 +703,7 @@ struct file_buffer { char *b_p_cms; ///< 'commentstring' char *b_p_cpt; ///< 'complete' #ifdef BACKSLASH_IN_FILENAME - char_u *b_p_csl; ///< 'completeslash' + char *b_p_csl; ///< 'completeslash' #endif char *b_p_cfu; ///< 'completefunc' char *b_p_ofu; ///< 'omnifunc' diff --git a/src/nvim/change.c b/src/nvim/change.c index 074700f4df..fd079f8eef 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -589,17 +589,17 @@ bool file_ff_differs(buf_T *buf, bool ignore_empty) /// Handles Replace mode and multi-byte characters. void ins_bytes(char *p) { - ins_bytes_len((char_u *)p, STRLEN(p)); + ins_bytes_len(p, STRLEN(p)); } /// Insert string "p" with length "len" at the cursor position. /// Handles Replace mode and multi-byte characters. -void ins_bytes_len(char_u *p, size_t len) +void ins_bytes_len(char *p, size_t len) { size_t n; for (size_t i = 0; i < len; i += n) { // avoid reading past p[len] - n = (size_t)utfc_ptr2len_len(p + i, (int)(len - i)); + n = (size_t)utfc_ptr2len_len((char_u *)p + i, (int)(len - i)); ins_char_bytes(p + i, n); } } @@ -611,18 +611,18 @@ void ins_bytes_len(char_u *p, size_t len) /// convert bytes to a character. void ins_char(int c) { - char_u buf[MB_MAXBYTES + 1]; - size_t n = (size_t)utf_char2bytes(c, (char *)buf); + char buf[MB_MAXBYTES + 1]; + size_t n = (size_t)utf_char2bytes(c, buf); // When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte. // Happens for CTRL-Vu9900. if (buf[0] == 0) { buf[0] = '\n'; } - ins_char_bytes((char_u *)buf, n); + ins_char_bytes(buf, n); } -void ins_char_bytes(char_u *buf, size_t charlen) +void ins_char_bytes(char *buf, size_t charlen) { // Break tabs if needed. if (virtual_active() && curwin->w_cursor.coladd > 0) { @@ -631,7 +631,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) size_t col = (size_t)curwin->w_cursor.col; linenr_T lnum = curwin->w_cursor.lnum; - char_u *oldp = ml_get(lnum); + char *oldp = (char *)ml_get(lnum); size_t linelen = STRLEN(oldp) + 1; // length of old line including NUL // The lengths default to the values for when not replacing. @@ -661,7 +661,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) if (vcol > new_vcol && oldp[col + oldlen] == TAB) { break; } - oldlen += (size_t)utfc_ptr2len((char *)oldp + col + oldlen); + oldlen += (size_t)utfc_ptr2len(oldp + col + oldlen); // Deleted a bit too much, insert spaces. if (vcol > new_vcol) { newlen += (size_t)(vcol - new_vcol); @@ -670,7 +670,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) curwin->w_p_list = old_list; } else if (oldp[col] != NUL) { // normal replace - oldlen = (size_t)utfc_ptr2len((char *)oldp + col); + oldlen = (size_t)utfc_ptr2len(oldp + col); } // Push the replaced bytes onto the replace stack, so that they can be @@ -683,7 +683,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) } } - char_u *newp = xmalloc(linelen + newlen - oldlen); + char *newp = xmalloc(linelen + newlen - oldlen); // Copy bytes before the cursor. if (col > 0) { @@ -691,7 +691,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) } // Copy bytes after the changed character(s). - char_u *p = newp + col; + char *p = newp + col; if (linelen > col + oldlen) { memmove(p + newlen, oldp + col + oldlen, (size_t)(linelen - col - oldlen)); @@ -706,7 +706,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) } // Replace the line in the buffer. - ml_replace(lnum, (char *)newp, false); + ml_replace(lnum, newp, false); // mark the buffer as changed and prepare for displaying inserted_bytes(lnum, (colnr_T)col, (int)oldlen, (int)newlen); @@ -716,7 +716,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) if (p_sm && (State & MODE_INSERT) && msg_silent == 0 && !ins_compl_active()) { - showmatch(utf_ptr2char((char *)buf)); + showmatch(utf_ptr2char(buf)); } if (!p_ri || (State & REPLACE_FLAG)) { @@ -729,7 +729,7 @@ void ins_char_bytes(char_u *buf, size_t charlen) /// Insert a string at the cursor position. /// Note: Does NOT handle Replace mode. /// Caller must have prepared for undo. -void ins_str(char_u *s) +void ins_str(char *s) { int newlen = (int)STRLEN(s); linenr_T lnum = curwin->w_cursor.lnum; @@ -739,10 +739,10 @@ void ins_str(char_u *s) } colnr_T col = curwin->w_cursor.col; - char_u *oldp = ml_get(lnum); + char *oldp = (char *)ml_get(lnum); int oldlen = (int)STRLEN(oldp); - char_u *newp = (char_u *)xmalloc((size_t)oldlen + (size_t)newlen + 1); + char *newp = xmalloc((size_t)oldlen + (size_t)newlen + 1); if (col > 0) { memmove(newp, oldp, (size_t)col); } @@ -750,7 +750,7 @@ void ins_str(char_u *s) int bytes = oldlen - col + 1; assert(bytes >= 0); memmove(newp + col + newlen, oldp + col, (size_t)bytes); - ml_replace(lnum, (char *)newp, false); + ml_replace(lnum, newp, false); inserted_bytes(lnum, col, 0, newlen); curwin->w_cursor.col += newlen; } @@ -774,9 +774,9 @@ int del_char(bool fixpos) int del_chars(long count, int fixpos) { int bytes = 0; - char_u *p = get_cursor_pos_ptr(); + char *p = (char *)get_cursor_pos_ptr(); for (long i = 0; i < count && *p != NUL; i++) { - int l = utfc_ptr2len((char *)p); + int l = utfc_ptr2len(p); bytes += l; p += l; } @@ -797,7 +797,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) linenr_T lnum = curwin->w_cursor.lnum; colnr_T col = curwin->w_cursor.col; bool fixpos = fixpos_arg; - char_u *oldp = ml_get(lnum); + char *oldp = (char *)ml_get(lnum); colnr_T oldlen = (colnr_T)STRLEN(oldp); // Can't do anything when the cursor is on the NUL after the line. @@ -817,7 +817,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) // If 'delcombine' is set and deleting (less than) one character, only // delete the last combining character. if (p_deco && use_delcombine - && utfc_ptr2len((char *)oldp + col) >= count) { + && utfc_ptr2len(oldp + col) >= count) { int cc[MAX_MCO]; (void)utfc_ptr2char(oldp + col, cc); @@ -826,9 +826,9 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) int n = col; do { col = n; - count = utf_ptr2len((char *)oldp + n); + count = utf_ptr2len(oldp + n); n += count; - } while (utf_composinglike(oldp + col, oldp + n)); + } while (utf_composinglike((char_u *)oldp + col, (char_u *)oldp + n)); fixpos = false; } } @@ -843,7 +843,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) && (get_ve_flags() & VE_ONEMORE) == 0) { curwin->w_cursor.col--; curwin->w_cursor.coladd = 0; - curwin->w_cursor.col -= utf_head_off(oldp, oldp + curwin->w_cursor.col); + curwin->w_cursor.col -= utf_head_off((char_u *)oldp, (char_u *)oldp + curwin->w_cursor.col); } count = oldlen - col; movelen = 1; @@ -852,7 +852,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) // If the old line has been allocated the deletion can be done in the // existing line. Otherwise a new line has to be allocated. bool was_alloced = ml_line_alloced(); // check if oldp was allocated - char_u *newp; + char *newp; if (was_alloced) { ml_add_deleted_len(curbuf->b_ml.ml_line_ptr, oldlen); newp = oldp; // use same allocated memory @@ -862,7 +862,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) } memmove(newp + col, oldp + col + count, (size_t)movelen); if (!was_alloced) { - ml_replace(lnum, (char *)newp, false); + ml_replace(lnum, newp, false); } // mark the buffer as changed and prepare for displaying @@ -874,10 +874,10 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) /// Copy the indent from ptr to the current line (and fill to size). /// Leaves the cursor on the first non-blank in the line. /// @return true if the line was changed. -int copy_indent(int size, char_u *src) +int copy_indent(int size, char *src) { - char_u *p = NULL; - char_u *line = NULL; + char *p = NULL; + char *line = NULL; int ind_len; int line_len = 0; int tab_pad; @@ -889,7 +889,7 @@ int copy_indent(int size, char_u *src) ind_len = 0; int ind_done = 0; int ind_col = 0; - char_u *s = src; + char *s = src; // Count/copy the usable portion of the source line. while (todo > 0 && ascii_iswhite(*s)) { @@ -975,7 +975,7 @@ int copy_indent(int size, char_u *src) memmove(p, get_cursor_line_ptr(), (size_t)line_len); // Replace the line - ml_replace(curwin->w_cursor.lnum, (char *)line, false); + ml_replace(curwin->w_cursor.lnum, line, false); // Put the cursor after the indent. curwin->w_cursor.col = ind_len; @@ -1006,8 +1006,8 @@ int copy_indent(int size, char_u *src) /// @return true on success, false on failure int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) { - char_u *next_line = NULL; // copy of the next line - char_u *p_extra = NULL; // what goes to next line + char *next_line = NULL; // copy of the next line + char *p_extra = NULL; // what goes to next line colnr_T less_cols = 0; // less columns for mark in new line colnr_T less_cols_off = 0; // columns to skip for mark adjust pos_T old_cursor; // old cursor position @@ -1020,9 +1020,9 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) int comment_start = 0; // start index of the comment leader char *lead_flags; // position in 'comments' for comment leader char *leader = NULL; // copy of comment leader - char_u *allocated = NULL; // allocated memory + char *allocated = NULL; // allocated memory char *p; - char_u saved_char = NUL; // init for GCC + char saved_char = NUL; // init for GCC pos_T *pos; bool do_si = may_do_si(); bool do_cindent; @@ -1036,7 +1036,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) colnr_T mincol = curwin->w_cursor.col + 1; // make a copy of the current line so we can mess with it - char_u *saved_line = vim_strsave(get_cursor_line_ptr()); + char *saved_line = (char *)vim_strsave(get_cursor_line_ptr()); if (State & VREPLACE_FLAG) { // With MODE_VREPLACE we make a copy of the next line, which we will be @@ -1047,9 +1047,9 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // the line, replacing what was there before and pushing the right // stuff onto the replace stack. -- webb. if (curwin->w_cursor.lnum < orig_line_count) { - next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1)); + next_line = (char *)vim_strsave(ml_get(curwin->w_cursor.lnum + 1)); } else { - next_line = vim_strsave((char_u *)""); + next_line = xstrdup(""); } // In MODE_VREPLACE state, a NL replaces the rest of the line, and @@ -1059,9 +1059,9 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // autoindent etc) a bit later. replace_push(NUL); // Call twice because BS over NL expects it replace_push(NUL); - p = (char *)saved_line + curwin->w_cursor.col; + p = saved_line + curwin->w_cursor.col; while (*p != NUL) { - p += replace_push_mb((char_u *)p); + p += replace_push_mb(p); } saved_line[curwin->w_cursor.col] = NUL; } @@ -1069,7 +1069,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) if ((State & MODE_INSERT) && (State & VREPLACE_FLAG) == 0) { p_extra = saved_line + curwin->w_cursor.col; if (do_si) { // need first char after new line break - p = skipwhite((char *)p_extra); + p = skipwhite(p_extra); first_char = (unsigned char)(*p); } extra_len = (int)STRLEN(p_extra); @@ -1109,7 +1109,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) char *ptr; old_cursor = curwin->w_cursor; - ptr = (char *)saved_line; + ptr = saved_line; if (flags & OPENLINE_DO_COM) { lead_len = get_leader_len(ptr, NULL, false, true); } else { @@ -1193,7 +1193,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // Don't do this if the previous line ended in ';' or // '}'. } else if (last_char != ';' && last_char != '}' - && cin_is_cinword((char_u *)ptr)) { + && cin_is_cinword(ptr)) { did_si = true; } } @@ -1243,13 +1243,13 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // This may then be inserted in front of the new line. end_comment_pending = NUL; if (flags & OPENLINE_DO_COM) { - lead_len = get_leader_len((char *)saved_line, &lead_flags, dir == BACKWARD, true); + lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, true); if (lead_len == 0 && curbuf->b_p_cin && do_cindent && dir == FORWARD && (!has_format_option(FO_NO_OPEN_COMS) || (flags & OPENLINE_FORMAT))) { // Check for a line comment after code. comment_start = check_linecomment(saved_line); if (comment_start != MAXCOL) { - lead_len = get_leader_len((char *)saved_line + comment_start, &lead_flags, false, true); + lead_len = get_leader_len(saved_line + comment_start, &lead_flags, false, true); if (lead_len != 0) { lead_len += comment_start; if (did_do_comment != NULL) { @@ -1264,13 +1264,13 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) if (lead_len > 0) { char *lead_repl = NULL; // replaces comment leader int lead_repl_len = 0; // length of *lead_repl - char_u lead_middle[COM_MAX_LEN]; // middle-comment string - char_u lead_end[COM_MAX_LEN]; // end-comment string - char_u *comment_end = NULL; // where lead_end has been found + char lead_middle[COM_MAX_LEN]; // middle-comment string + char lead_end[COM_MAX_LEN]; // end-comment string + char *comment_end = NULL; // where lead_end has been found int extra_space = false; // append extra space int current_flag; int require_blank = false; // requires blank after middle - char_u *p2; + char *p2; // If the comment leader has the start, middle or end flag, it may not // be used or may be replaced with the middle leader. @@ -1312,15 +1312,15 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) size_t n = copy_option_part(&p, (char *)lead_end, COM_MAX_LEN, ","); if (end_comment_pending == -1) { // we can set it now - end_comment_pending = lead_end[n - 1]; + end_comment_pending = (unsigned char)lead_end[n - 1]; } // If the end of the comment is in the same line, don't use // the comment leader. if (dir == FORWARD) { - for (p = (char *)saved_line + lead_len; *p; p++) { + for (p = saved_line + lead_len; *p; p++) { if (STRNCMP(p, lead_end, n) == 0) { - comment_end = (char_u *)p; + comment_end = p; lead_len = 0; break; } @@ -1353,7 +1353,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // Remember where the end is, might want to use it to find the // start (for C-comments). if (dir == FORWARD) { - comment_end = (char_u *)skipwhite((char *)saved_line); + comment_end = skipwhite(saved_line); lead_len = 0; break; } @@ -1372,7 +1372,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) extra_space = true; // Check whether we allow automatic ending of comments - for (p2 = (char_u *)p; *p2 && *p2 != ':'; p2++) { + for (p2 = p; *p2 && *p2 != ':'; p2++) { if (*p2 == COM_AUTO_END) { end_comment_pending = -1; // means we want to set it } @@ -1382,7 +1382,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) while (*p2 && *p2 != ',') { p2++; } - end_comment_pending = p2[-1]; + end_comment_pending = (unsigned char)p2[-1]; } break; } @@ -1408,7 +1408,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) + 1; assert(bytes >= 0); leader = xmalloc((size_t)bytes); - allocated = (char_u *)leader; // remember to free it later + allocated = leader; // remember to free it later STRLCPY(leader, saved_line, lead_len + 1); @@ -1442,7 +1442,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // Compute the length of the replaced characters in // screen characters, not bytes. { - int repl_size = vim_strnsize((char_u *)lead_repl, lead_repl_len); + int repl_size = vim_strnsize(lead_repl, lead_repl_len); int old_size = 0; char *endp = p; int l; @@ -1487,13 +1487,13 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // screen characters, not bytes. Move the part that is // not to be overwritten. { - int repl_size = vim_strnsize((char_u *)lead_repl, lead_repl_len); + int repl_size = vim_strnsize(lead_repl, lead_repl_len); int i; int l; for (i = 0; i < lead_len && p[i] != NUL; i += l) { l = utfc_ptr2len(p + i); - if (vim_strnsize((char_u *)p, i + l) > repl_size) { + if (vim_strnsize(p, i + l) > repl_size) { break; } } @@ -1536,7 +1536,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // Recompute the indent, it may have changed. if (curbuf->b_p_ai || do_si) { - newindent = get_indent_str_vtab((char_u *)leader, + newindent = get_indent_str_vtab(leader, curbuf->b_p_ts, curbuf->b_p_vts_array, false); } @@ -1619,7 +1619,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) } if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES)) { while ((*p_extra == ' ' || *p_extra == '\t') - && !utf_iscomposing(utf_ptr2char((char *)p_extra + 1))) { + && !utf_iscomposing(utf_ptr2char(p_extra + 1))) { if (REPLACE_NORMAL(State)) { replace_push(*p_extra); } @@ -1633,7 +1633,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) } if (p_extra == NULL) { - p_extra = (char_u *)""; // append empty line + p_extra = ""; // append empty line } // concatenate leader and p_extra, if there is a leader @@ -1653,7 +1653,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) } } STRCAT(leader, p_extra); - p_extra = (char_u *)leader; + p_extra = leader; did_ai = true; // So truncating blanks works with comments less_cols -= lead_len; } else { @@ -1666,7 +1666,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) curwin->w_cursor.lnum--; } if ((State & VREPLACE_FLAG) == 0 || old_cursor.lnum >= orig_line_count) { - if (ml_append(curwin->w_cursor.lnum, (char *)p_extra, (colnr_T)0, false) == FAIL) { + if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, false) == FAIL) { goto theend; } // Postpone calling changed_lines(), because it would mess up folding @@ -1688,7 +1688,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) (void)u_save_cursor(); // errors are ignored! vr_lines_changed++; } - ml_replace(curwin->w_cursor.lnum, (char *)p_extra, true); + ml_replace(curwin->w_cursor.lnum, p_extra, true); changed_bytes(curwin->w_cursor.lnum, 0); // TODO(vigoux): extmark_splice_cols here?? curwin->w_cursor.lnum--; @@ -1753,7 +1753,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) if (trunc_line && !(flags & OPENLINE_KEEPTRAIL)) { truncate_spaces(saved_line); } - ml_replace(curwin->w_cursor.lnum, (char *)saved_line, false); + ml_replace(curwin->w_cursor.lnum, saved_line, false); int new_len = (int)STRLEN(saved_line); @@ -1838,15 +1838,15 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // stuff onto the replace stack (via ins_char()). if (State & VREPLACE_FLAG) { // Put new line in p_extra - p_extra = vim_strsave(get_cursor_line_ptr()); + p_extra = (char *)vim_strsave(get_cursor_line_ptr()); // Put back original line - ml_replace(curwin->w_cursor.lnum, (char *)next_line, false); + ml_replace(curwin->w_cursor.lnum, next_line, false); // Insert new stuff into line again curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; - ins_bytes((char *)p_extra); // will call changed_bytes() + ins_bytes(p_extra); // will call changed_bytes() xfree(p_extra); next_line = NULL; } diff --git a/src/nvim/charset.c b/src/nvim/charset.c index e0f798121a..2632279565 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -313,7 +313,7 @@ size_t transstr_len(const char *const s, bool untab) const size_t l = (size_t)utfc_ptr2len(p); if (l > 1) { int pcc[MAX_MCO + 1]; - pcc[0] = utfc_ptr2char((const char_u *)p, &pcc[1]); + pcc[0] = utfc_ptr2char(p, &pcc[1]); if (vim_isprintc(pcc[0])) { len += l; @@ -359,7 +359,7 @@ size_t transstr_buf(const char *const s, char *const buf, const size_t len, bool break; // Exceeded `buf` size. } int pcc[MAX_MCO + 1]; - pcc[0] = utfc_ptr2char((const char_u *)p, &pcc[1]); + pcc[0] = utfc_ptr2char(p, &pcc[1]); if (vim_isprintc(pcc[0])) { memmove(buf_p, p, l); @@ -709,7 +709,7 @@ int ptr2cells(const char *p_in) /// @return number of character cells. int vim_strsize(char *s) { - return vim_strnsize((char_u *)s, MAXCOL); + return vim_strnsize(s, MAXCOL); } /// Return the number of character cells string "s[len]" will take on the @@ -721,13 +721,13 @@ int vim_strsize(char *s) /// @param len /// /// @return Number of character cells. -int vim_strnsize(char_u *s, int len) +int vim_strnsize(char *s, int len) { assert(s != NULL); int size = 0; while (*s != NUL && --len >= 0) { - int l = utfc_ptr2len((char *)s); - size += ptr2cells((char *)s); + int l = utfc_ptr2len(s); + size += ptr2cells(s); s += l; len -= l - 1; } @@ -1687,12 +1687,12 @@ int hexhex2nr(const char_u *p) /// characters. /// /// @param str file path string to check -bool rem_backslash(const char_u *str) +bool rem_backslash(const char *str) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL { #ifdef BACKSLASH_IN_FILENAME return str[0] == '\\' - && str[1] < 0x80 + && (uint8_t)str[1] < 0x80 && (str[1] == ' ' || (str[1] != NUL && str[1] != '*' @@ -1710,7 +1710,7 @@ bool rem_backslash(const char_u *str) void backslash_halve(char_u *p) { for (; *p; p++) { - if (rem_backslash(p)) { + if (rem_backslash((char *)p)) { STRMOVE(p, p + 1); } } diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 7f9a8b2a5c..dbf169c801 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -787,7 +787,7 @@ static bool expand_showtail(expand_T *xp) for (s = (char_u *)xp->xp_pattern; s < end; s++) { // Skip escaped wildcards. Only when the backslash is not a path // separator, on DOS the '*' "path\*\file" must not be skipped. - if (rem_backslash(s)) { + if (rem_backslash((char *)s)) { s++; } else if (vim_strchr("*?[", *s) != NULL) { return false; @@ -1242,11 +1242,10 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons arg = (const char *)skipwhite((char *)skiptowhite((const char_u *)arg)); if (*arg != NUL) { xp->xp_context = EXPAND_NOTHING; - arg = (const char *)skip_regexp((char_u *)arg + 1, (uint8_t)(*arg), - p_magic, NULL); + arg = (const char *)skip_regexp((char *)arg + 1, (uint8_t)(*arg), p_magic, NULL); } } - return (const char *)find_nextcmd((char_u *)arg); + return (const char *)find_nextcmd(arg); // All completion for the +cmdline_compl feature goes here. @@ -1282,7 +1281,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons if (delim) { // Skip "from" part. arg++; - arg = (const char *)skip_regexp((char_u *)arg, delim, p_magic, NULL); + arg = (const char *)skip_regexp((char *)arg, delim, p_magic, NULL); } // Skip "to" part. while (arg[0] != NUL && (uint8_t)arg[0] != delim) { diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c index 9aee023f0c..9fdeebf68a 100644 --- a/src/nvim/debugger.c +++ b/src/nvim/debugger.c @@ -47,7 +47,7 @@ struct debuggy { /// Debug mode. Repeatedly get Ex commands, until told to continue normal /// execution. -void do_debug(char_u *cmd) +void do_debug(char *cmd) { int save_msg_scroll = msg_scroll; int save_State = State; @@ -239,11 +239,11 @@ void do_debug(char_u *cmd) last_cmd = CMD_STEP; break; case CMD_BACKTRACE: - do_showbacktrace(cmd); + do_showbacktrace((char_u *)cmd); continue; case CMD_FRAME: if (*p == NUL) { - do_showbacktrace(cmd); + do_showbacktrace((char_u *)cmd); } else { p = skipwhite(p); do_setdebugtracelevel((char_u *)p); @@ -414,7 +414,7 @@ void dbg_check_breakpoint(exarg_T *eap) debug_breakpoint_name + (*p == NUL ? 0 : 3), (int64_t)debug_breakpoint_lnum); debug_breakpoint_name = NULL; - do_debug((char_u *)eap->cmd); + do_debug(eap->cmd); } else { debug_skipped = true; debug_skipped_name = debug_breakpoint_name; @@ -422,7 +422,7 @@ void dbg_check_breakpoint(exarg_T *eap) } } else if (ex_nesting_level <= debug_break_level) { if (!eap->skip) { - do_debug((char_u *)eap->cmd); + do_debug(eap->cmd); } else { debug_skipped = true; debug_skipped_name = NULL; diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 23fdc728f3..1cfb535fe8 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -573,9 +573,9 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp) if (dir == BACKWARD) { off_org = dp->df_count[i_org] - 1; } - char_u *line_org = vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org], - dp->df_lnum[i_org] + off_org, - false)); + char *line_org = (char *)vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org], + dp->df_lnum[i_org] + off_org, + false)); int i_new; for (i_new = i_org + 1; i_new < DB_COUNT; i_new++) { @@ -592,9 +592,9 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp) break; } - if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new], - dp->df_lnum[i_new] + off_new, - false)) != 0) { + if (diff_cmp((char_u *)line_org, ml_get_buf(tp->tp_diffbuf[i_new], + dp->df_lnum[i_new] + off_new, + false)) != 0) { break; } } @@ -1539,8 +1539,8 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio) diff_T *dp = curtab->tp_first_diff; diff_T *dn, *dpl; diffout_T *dout = &dio->dio_diff; - char_u linebuf[LBUFLEN]; // only need to hold the diff line - char_u *line; + char linebuf[LBUFLEN]; // only need to hold the diff line + char *line; linenr_T off; int i; int notset = true; // block "*dp" not set yet @@ -1576,9 +1576,9 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio) if (line_idx >= dout->dout_ga.ga_len) { break; // did last line } - line = ((char_u **)dout->dout_ga.ga_data)[line_idx++]; + line = ((char **)dout->dout_ga.ga_data)[line_idx++]; } else { - if (vim_fgets(linebuf, LBUFLEN, fd)) { + if (vim_fgets((char_u *)linebuf, LBUFLEN, fd)) { break; // end of file } line = linebuf; @@ -1600,9 +1600,9 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio) } else if ((STRNCMP(line, "@@ ", 3) == 0)) { diffstyle = DIFF_UNIFIED; } else if ((STRNCMP(line, "--- ", 4) == 0) // -V501 - && (vim_fgets(linebuf, LBUFLEN, fd) == 0) // -V501 + && (vim_fgets((char_u *)linebuf, LBUFLEN, fd) == 0) // -V501 && (STRNCMP(line, "+++ ", 4) == 0) - && (vim_fgets(linebuf, LBUFLEN, fd) == 0) // -V501 + && (vim_fgets((char_u *)linebuf, LBUFLEN, fd) == 0) // -V501 && (STRNCMP(line, "@@ ", 3) == 0)) { diffstyle = DIFF_UNIFIED; } else { @@ -1616,7 +1616,7 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio) if (!isdigit(*line)) { continue; // not the start of a diff block } - if (parse_diff_ed(line, hunk) == FAIL) { + if (parse_diff_ed((char_u *)line, hunk) == FAIL) { continue; } } else { @@ -1624,7 +1624,7 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio) if (STRNCMP(line, "@@ ", 3) != 0) { continue; // not the start of a diff block } - if (parse_diff_unified(line, hunk) == FAIL) { + if (parse_diff_unified((char_u *)line, hunk) == FAIL) { continue; } } @@ -1920,11 +1920,11 @@ static bool diff_equal_entry(diff_T *dp, int idx1, int idx2) } for (int i = 0; i < dp->df_count[idx1]; i++) { - char_u *line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1], - dp->df_lnum[idx1] + i, false)); + char *line = (char *)vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1], + dp->df_lnum[idx1] + i, false)); - int cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2], - dp->df_lnum[idx2] + i, false)); + int cmp = diff_cmp((char_u *)line, ml_get_buf(curtab->tp_diffbuf[idx2], + dp->df_lnum[idx2] + i, false)); xfree(line); if (cmp != 0) { @@ -2281,7 +2281,7 @@ bool diffopt_filler(void) bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL { - char_u *line_new; + char *line_new; int si_org; int si_new; int ei_org; @@ -2290,7 +2290,7 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) int l; // Make a copy of the line, the next ml_get() will invalidate it. - char_u *line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, false)); + char *line_org = (char *)vim_strsave(ml_get_buf(wp->w_buffer, lnum, false)); int idx = diff_buf_idx(wp->w_buffer); if (idx == DB_COUNT) { @@ -2322,8 +2322,8 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) continue; } added = false; - line_new = ml_get_buf(curtab->tp_diffbuf[i], - dp->df_lnum[i] + off, false); + line_new = (char *)ml_get_buf(curtab->tp_diffbuf[i], + dp->df_lnum[i] + off, false); // Search for start of difference si_org = si_new = 0; @@ -2335,10 +2335,10 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) || ((diff_flags & DIFF_IWHITEALL) && (ascii_iswhite(line_org[si_org]) || ascii_iswhite(line_new[si_new])))) { - si_org = (int)((char_u *)skipwhite((char *)line_org + si_org) - line_org); - si_new = (int)((char_u *)skipwhite((char *)line_new + si_new) - line_new); + si_org = (int)(skipwhite(line_org + si_org) - line_org); + si_new = (int)(skipwhite(line_new + si_new) - line_new); } else { - if (!diff_equal_char(line_org + si_org, line_new + si_new, &l)) { + if (!diff_equal_char((char_u *)line_org + si_org, (char_u *)line_new + si_new, &l)) { break; } si_org += l; @@ -2348,8 +2348,8 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) // Move back to first byte of character in both lines (may // have "nn^" in line_org and "n^ in line_new). - si_org -= utf_head_off(line_org, line_org + si_org); - si_new -= utf_head_off(line_new, line_new + si_new); + si_org -= utf_head_off((char_u *)line_org, (char_u *)line_org + si_org); + si_new -= utf_head_off((char_u *)line_new, (char_u *)line_new + si_new); if (*startp > si_org) { *startp = si_org; @@ -2378,11 +2378,11 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) ei_new--; } } else { - const char_u *p1 = line_org + ei_org; - const char_u *p2 = line_new + ei_new; + const char_u *p1 = (char_u *)line_org + ei_org; + const char_u *p2 = (char_u *)line_new + ei_new; - p1 -= utf_head_off(line_org, p1); - p2 -= utf_head_off(line_new, p2); + p1 -= utf_head_off((char_u *)line_org, p1); + p2 -= utf_head_off((char_u *)line_new, p2); if (!diff_equal_char(p1, p2, &l)) { break; @@ -2511,7 +2511,7 @@ void ex_diffgetput(exarg_T *eap) diff_T *dfree; int i; int added; - char_u *p; + char *p; aco_save_T aco; buf_T *buf; linenr_T start_skip; @@ -2565,18 +2565,18 @@ void ex_diffgetput(exarg_T *eap) } } else { // Buffer number or pattern given. Ignore trailing white space. - p = (char_u *)eap->arg + STRLEN(eap->arg); - while (p > (char_u *)eap->arg && ascii_iswhite(p[-1])) { + p = eap->arg + STRLEN(eap->arg); + while (p > eap->arg && ascii_iswhite(p[-1])) { p--; } - for (i = 0; ascii_isdigit(eap->arg[i]) && (char_u *)eap->arg + i < p; i++) {} + for (i = 0; ascii_isdigit(eap->arg[i]) && eap->arg + i < p; i++) {} - if ((char_u *)eap->arg + i == p) { + if (eap->arg + i == p) { // digits only i = (int)atol(eap->arg); } else { - i = buflist_findpat(eap->arg, (char *)p, false, true, false); + i = buflist_findpat(eap->arg, p, false, true, false); if (i < 0) { // error message already given @@ -2718,8 +2718,8 @@ void ex_diffgetput(exarg_T *eap) if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) { break; } - p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, false)); - ml_append(lnum + i - 1, (char *)p, 0, false); + p = (char *)vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, false)); + ml_append(lnum + i - 1, p, 0, false); xfree(p); added++; if (buf_empty && (curbuf->b_ml.ml_line_count == 2)) { diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index 4b5f6c6c06..b6654699d8 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -116,7 +116,7 @@ static int line_putchar(buf_T *buf, LineState *s, schar_T *dest, int maxcells, b if (cells > maxcells) { return -1; } - u8c = utfc_ptr2char(p, u8cc); + u8c = utfc_ptr2char((char *)p, u8cc); if (*p == TAB) { cells = MIN(tabstop_padding(vcol, buf->b_p_ts, buf->b_p_vts_array), maxcells); for (int c = 0; c < cells; c++) { @@ -141,7 +141,7 @@ static int line_putchar(buf_T *buf, LineState *s, schar_T *dest, int maxcells, b nc = utf_ptr2char((char *)p + c_len); s->prev_c1 = u8cc[0]; } else { - pc = utfc_ptr2char(p + c_len, pcc); + pc = utfc_ptr2char((char *)p + c_len, pcc); nc = s->prev_c; pc1 = pcc[0]; } @@ -1489,7 +1489,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, if (mb_l > n_extra) { mb_l = 1; } else if (mb_l > 1) { - mb_c = utfc_ptr2char(p_extra, u8cc); + mb_c = utfc_ptr2char((char *)p_extra, u8cc); mb_utf8 = true; c = 0xc0; } @@ -1540,7 +1540,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, mb_l = utfc_ptr2len((char *)ptr); mb_utf8 = false; if (mb_l > 1) { - mb_c = utfc_ptr2char(ptr, u8cc); + mb_c = utfc_ptr2char((char *)ptr, u8cc); // Overlong encoded ASCII or ASCII with composing char // is displayed normally, except a NUL. if (mb_c < 0x80) { @@ -1598,7 +1598,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, nc = utf_ptr2char((char *)ptr + mb_l); prev_c1 = u8cc[0]; } else { - pc = utfc_ptr2char(ptr + mb_l, pcc); + pc = utfc_ptr2char((char *)ptr + mb_l, pcc); nc = prev_c; pc1 = pcc[0]; } diff --git a/src/nvim/drawscreen.c b/src/nvim/drawscreen.c index a601a82495..40dbec8a5b 100644 --- a/src/nvim/drawscreen.c +++ b/src/nvim/drawscreen.c @@ -1889,7 +1889,7 @@ win_update_start: int scr_row = wp->w_grid.rows - 1; // Last line isn't finished: Display "@@@" in the last screen line. - grid_puts_len(&wp->w_grid, (char_u *)"@@", MIN(wp->w_grid.cols, 2), scr_row, 0, at_attr); + grid_puts_len(&wp->w_grid, "@@", MIN(wp->w_grid.cols, 2), scr_row, 0, at_attr); grid_fill(&wp->w_grid, scr_row, scr_row + 1, 2, wp->w_grid.cols, '@', ' ', at_attr); diff --git a/src/nvim/edit.c b/src/nvim/edit.c index b9432ca362..b0174de01f 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1523,8 +1523,7 @@ void edit_unputchar(void) if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT) { redrawWinline(curwin, curwin->w_cursor.lnum); } else { - grid_puts(&curwin->w_grid, pc_bytes, pc_row - msg_scrolled, pc_col, - pc_attr); + grid_puts(&curwin->w_grid, (char *)pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr); } } } @@ -1698,7 +1697,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang ptr = xmallocz(i); memset(ptr, ' ', i); new_cursor_col += (int)i; - ins_str(ptr); + ins_str((char *)ptr); xfree(ptr); } @@ -1797,7 +1796,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang /// Truncate the space at the end of a line. This is to be used only in an /// insert mode. It handles fixing the replace stack for MODE_REPLACE and /// MODE_VREPLACE modes. -void truncate_spaces(char_u *line) +void truncate_spaces(char *line) { int i; @@ -1989,7 +1988,7 @@ static void insert_special(int c, int allow_modmask, int ctrlv) return; } p[len - 1] = NUL; - ins_str(p); + ins_str((char *)p); AppendToRedobuffLit((char *)p, -1); ctrlv = false; } @@ -2117,7 +2116,7 @@ void insertchar(int c, int flags, int second_indent) // Insert the end-comment string, except for the last // character, which will get inserted as normal later. - ins_bytes_len(lead_end, (size_t)(end_len - 1)); + ins_bytes_len((char *)lead_end, (size_t)(end_len - 1)); } } } @@ -2177,7 +2176,7 @@ void insertchar(int c, int flags, int second_indent) do_digraph(-1); // clear digraphs do_digraph(buf[i - 1]); // may be the start of a digraph buf[i] = NUL; - ins_str(buf); + ins_str((char *)buf); if (flags & INSCHAR_CTRLV) { redo_literal(*buf); i = 1; @@ -2195,7 +2194,7 @@ void insertchar(int c, int flags, int second_indent) utf_char2bytes(c, (char *)buf); buf[cc] = NUL; - ins_char_bytes((char_u *)buf, (size_t)cc); + ins_char_bytes(buf, (size_t)cc); AppendCharToRedobuff(c); } else { ins_char(c); @@ -2848,14 +2847,13 @@ void replace_push(int c) replace_stack_nr++; } -/* - * Push a character onto the replace stack. Handles a multi-byte character in - * reverse byte order, so that the first byte is popped off first. - * Return the number of bytes done (includes composing characters). - */ -int replace_push_mb(char_u *p) +/// Push a character onto the replace stack. Handles a multi-byte character in +/// reverse byte order, so that the first byte is popped off first. +/// +/// @return the number of bytes done (includes composing characters). +int replace_push_mb(char *p) { - int l = utfc_ptr2len((char *)p); + int l = utfc_ptr2len(p); int j; for (j = l - 1; j >= 0; j--) { @@ -2919,7 +2917,7 @@ static void mb_replace_pop_ins(int cc) for (i = 1; i < n; i++) { buf[i] = (char_u)replace_pop(); } - ins_bytes_len(buf, (size_t)n); + ins_bytes_len((char *)buf, (size_t)n); } else { ins_char(cc); } @@ -2942,7 +2940,7 @@ static void mb_replace_pop_ins(int cc) buf[i] = (char_u)replace_pop(); } if (utf_iscomposing(utf_ptr2char((char *)buf))) { - ins_bytes_len(buf, (size_t)n); + ins_bytes_len((char *)buf, (size_t)n); } else { // Not a composing char, put it back. for (i = n - 1; i >= 0; i--) { @@ -4078,7 +4076,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) if (State & VREPLACE_FLAG) { ins_char(' '); } else { - ins_str((char_u *)" "); + ins_str(" "); if ((State & REPLACE_FLAG)) { replace_push(NUL); } @@ -4122,7 +4120,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) } else { const int l_p_deco = p_deco; if (l_p_deco) { - (void)utfc_ptr2char(get_cursor_pos_ptr(), cpc); + (void)utfc_ptr2char((char *)get_cursor_pos_ptr(), cpc); } (void)del_char(false); // If there are combining characters and 'delcombine' is set @@ -4584,7 +4582,7 @@ static bool ins_tab(void) if (State & VREPLACE_FLAG) { ins_char(' '); } else { - ins_str((char_u *)" "); + ins_str(" "); if (State & REPLACE_FLAG) { // no char replaced replace_push(NUL); } @@ -4718,7 +4716,7 @@ static bool ins_tab(void) // Insert each char in saved_line from changed_col to // ptr-cursor - ins_bytes_len(saved_line + change_col, (size_t)(cursor->col - change_col)); + ins_bytes_len((char *)saved_line + change_col, (size_t)(cursor->col - change_col)); } } diff --git a/src/nvim/eval.c b/src/nvim/eval.c index ecac7e75ae..f89b06843a 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -8162,7 +8162,7 @@ repeat: while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h') { valid |= VALID_HEAD; *usedlen += 2; - s = (char *)get_past_head((char_u *)(*fnamep)); + s = get_past_head(*fnamep); while (tail > s && after_pathsep(s, tail)) { MB_PTR_BACK(*fnamep, tail); } diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 0c3d2d6935..0bf3ad6901 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -851,7 +851,8 @@ static void get_col(typval_T *argvars, typval_T *rettv, bool charcol) if (virtual_active() && fp == &curwin->w_cursor) { char *p = (char *)get_cursor_pos_ptr(); if (curwin->w_cursor.coladd >= - (colnr_T)win_chartabsize(curwin, p, curwin->w_virtcol - curwin->w_cursor.coladd)) { + (colnr_T)win_chartabsize(curwin, p, + curwin->w_virtcol - curwin->w_cursor.coladd)) { int l; if (*p != NUL && p[(l = utfc_ptr2len(p))] == NUL) { col += l; @@ -3896,12 +3897,12 @@ static void f_iconv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) const char *const str = tv_get_string(&argvars[0]); char buf1[NUMBUFLEN]; char_u *const from = - (char_u *)enc_canonize((char *)enc_skip((char_u *)tv_get_string_buf(&argvars[1], buf1))); + (char_u *)enc_canonize(enc_skip((char *)tv_get_string_buf(&argvars[1], buf1))); char buf2[NUMBUFLEN]; char_u *const to = - (char_u *)enc_canonize((char *)enc_skip((char_u *)tv_get_string_buf(&argvars[2], buf2))); + (char_u *)enc_canonize(enc_skip((char *)tv_get_string_buf(&argvars[2], buf2))); vimconv.vc_type = CONV_NONE; - convert_setup(&vimconv, from, to); + convert_setup(&vimconv, (char *)from, (char *)to); // If the encodings are equal, no conversion needed. if (vimconv.vc_type == CONV_NONE) { @@ -7072,7 +7073,7 @@ static void f_screenchars(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) return; } int pcc[MAX_MCO]; - int c = utfc_ptr2char(grid->chars[grid->line_offset[row] + (size_t)col], pcc); + int c = utfc_ptr2char((char *)grid->chars[grid->line_offset[row] + (size_t)col], pcc); int composing_len = 0; while (pcc[composing_len] != 0) { composing_len++; @@ -7605,7 +7606,7 @@ static void f_setcharsearch(typval_T *argvars, typval_T *rettv, EvalFuncData fpt char_u *const csearch = (char_u *)tv_dict_get_string(d, "char", false); if (csearch != NULL) { int pcc[MAX_MCO]; - const int c = utfc_ptr2char(csearch, pcc); + const int c = utfc_ptr2char((char *)csearch, pcc); set_last_csearch(c, csearch, utfc_ptr2len((char *)csearch)); } @@ -8402,11 +8403,10 @@ static void f_strftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) rettv->vval.v_string = xstrdup(_("(Invalid)")); } else { vimconv_T conv; - char_u *enc; conv.vc_type = CONV_NONE; - enc = enc_locale(); - convert_setup(&conv, (char_u *)p_enc, enc); + char *enc = (char *)enc_locale(); + convert_setup(&conv, p_enc, enc); if (conv.vc_type != CONV_NONE) { p = (char *)string_convert(&conv, (char_u *)p, NULL); } @@ -8420,7 +8420,7 @@ static void f_strftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (conv.vc_type != CONV_NONE) { xfree(p); } - convert_setup(&conv, enc, (char_u *)p_enc); + convert_setup(&conv, enc, p_enc); if (conv.vc_type != CONV_NONE) { rettv->vval.v_string = (char *)string_convert(&conv, (char_u *)result_buf, NULL); } else { @@ -8665,8 +8665,8 @@ static void f_strptime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) vimconv_T conv = { .vc_type = CONV_NONE, }; - char_u *enc = enc_locale(); - convert_setup(&conv, (char_u *)p_enc, enc); + char *enc = (char *)enc_locale(); + convert_setup(&conv, p_enc, enc); if (conv.vc_type != CONV_NONE) { fmt = (char *)string_convert(&conv, (char_u *)fmt, NULL); } diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 8cb7a075cb..2a48de5e41 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -1933,7 +1933,7 @@ void ex_function(exarg_T *eap) if (!HASHITEM_EMPTY(hi)) { todo--; fp = HI2UF(hi); - if (message_filtered(fp->uf_name)) { + if (message_filtered((char *)fp->uf_name)) { continue; } if (!func_name_refcount(fp->uf_name)) { @@ -1950,7 +1950,7 @@ void ex_function(exarg_T *eap) * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { - p = skip_regexp((char_u *)eap->arg + 1, '/', true, NULL); + p = (char_u *)skip_regexp(eap->arg + 1, '/', true, NULL); if (!eap->skip) { regmatch_T regmatch; diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index 0086cc41ca..e73bba16e2 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -413,7 +413,7 @@ void list_hashtable_vars(hashtab_T *ht, const char *prefix, int empty, int *firs // apply :filter /pat/ to variable name xstrlcpy(buf, prefix, IOSIZE); xstrlcat(buf, (char *)di->di_key, IOSIZE); - if (message_filtered((char_u *)buf)) { + if (message_filtered(buf)) { continue; } diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 6886ce0987..57eb2f526f 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -120,7 +120,7 @@ void do_ascii(const exarg_T *const eap) { char *dig; int cc[MAX_MCO]; - int c = utfc_ptr2char(get_cursor_pos_ptr(), cc); + int c = utfc_ptr2char((char *)get_cursor_pos_ptr(), cc); if (c == NUL) { msg("NUL"); return; @@ -513,7 +513,7 @@ void ex_sort(exarg_T *eap) eap->nextcmd = (char *)check_nextcmd((char_u *)p); break; } else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL) { - s = (char *)skip_regexp((char_u *)p + 1, *p, true, NULL); + s = skip_regexp(p + 1, *p, true, NULL); if (*s != *p) { emsg(_(e_invalpat)); goto sortend; @@ -1709,7 +1709,7 @@ void print_line(linenr_T lnum, int use_number, int list) int save_silent = silent_mode; // apply :filter /pat/ - if (message_filtered(ml_get(lnum))) { + if (message_filtered((char *)ml_get(lnum))) { return; } @@ -3546,7 +3546,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T which_pat = RE_LAST; // use last used regexp delimiter = (char_u)(*cmd++); // remember delimiter character pat = cmd; // remember start of search pat - cmd = (char *)skip_regexp((char_u *)cmd, delimiter, p_magic, &eap->arg); + cmd = skip_regexp(cmd, delimiter, p_magic, &eap->arg); if (cmd[0] == delimiter) { // end delimiter found *cmd++ = NUL; // replace it with a NUL has_second_delim = true; @@ -4631,7 +4631,7 @@ void ex_global(exarg_T *eap) delim = *cmd; // get the delimiter cmd++; // skip delimiter if there is one pat = cmd; // remember start of pattern - cmd = (char *)skip_regexp((char_u *)cmd, delim, p_magic, &eap->arg); + cmd = skip_regexp(cmd, delim, p_magic, &eap->arg); if (cmd[0] == delim) { // end delimiter found *cmd++ = NUL; // replace it with a NUL } @@ -4948,7 +4948,7 @@ char *skip_vimgrep_pat(char *p, char **s, int *flags) *s = p + 1; } c = (char_u)(*p); - p = (char *)skip_regexp((char_u *)p + 1, c, true, NULL); + p = skip_regexp(p + 1, c, true, NULL); if (*p != c) { return NULL; } @@ -4993,7 +4993,7 @@ void ex_oldfiles(exarg_T *eap) } nr++; const char *fname = tv_get_string(TV_LIST_ITEM_TV(li)); - if (!message_filtered((char_u *)fname)) { + if (!message_filtered((char *)fname)) { msg_outnum(nr); msg_puts(": "); msg_outtrans((char *)tv_get_string(TV_LIST_ITEM_TV(li))); diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 206fd515e3..3cd4369107 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -851,8 +851,8 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) || getline_equal(fgetline, cookie, get_func_line)) && ex_nesting_level + 1 <= debug_break_level) { do_debug(getline_equal(fgetline, cookie, getsourceline) - ? (char_u *)_("End of sourced file") - : (char_u *)_("End of function")); + ? _("End of sourced file") + : _("End of function")); } } @@ -3310,7 +3310,7 @@ static linenr_T get_address(exarg_T *eap, char **ptr, cmd_addr_T addr_type, int goto error; } if (skip) { // skip "/pat/" - cmd = (char *)skip_regexp((char_u *)cmd, c, p_magic, NULL); + cmd = skip_regexp(cmd, c, p_magic, NULL); if (*cmd == c) { cmd++; } @@ -4295,7 +4295,7 @@ int ends_excmd(int c) FUNC_ATTR_CONST /// @return the next command, after the first '|' or '\n' or, /// NULL if not found. -char_u *find_nextcmd(const char_u *p) +char *find_nextcmd(const char *p) { while (*p != '|' && *p != '\n') { if (*p == NUL) { @@ -4303,7 +4303,7 @@ char_u *find_nextcmd(const char_u *p) } p++; } - return (char_u *)p + 1; + return (char *)p + 1; } /// Check if *p is a separator between Ex commands, skipping over white space. @@ -5499,7 +5499,7 @@ bool changedir_func(char *new_dir, CdScope scope) if (*new_dir == NUL && p_cdh) { #endif // Use NameBuff for home directory name. - expand_env((char_u *)"$HOME", (char_u *)NameBuff, MAXPATHL); + expand_env("$HOME", NameBuff, MAXPATHL); new_dir = (char *)NameBuff; } @@ -6454,7 +6454,7 @@ static void ex_findpat(exarg_T *eap) if (*eap->arg == '/') { // Match regexp, not just whole words whole = false; eap->arg++; - char *p = (char *)skip_regexp((char_u *)eap->arg, '/', p_magic, NULL); + char *p = skip_regexp(eap->arg, '/', p_magic, NULL); if (*p) { *p++ = NUL; p = skipwhite(p); diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c index 19dcc06825..e2b02929d2 100644 --- a/src/nvim/ex_eval.c +++ b/src/nvim/ex_eval.c @@ -1333,10 +1333,10 @@ void ex_catch(exarg_T *eap) if (ends_excmd(*eap->arg)) { // no argument, catch all errors pat = ".*"; end = NULL; - eap->nextcmd = (char *)find_nextcmd((char_u *)eap->arg); + eap->nextcmd = find_nextcmd(eap->arg); } else { pat = eap->arg + 1; - end = (char *)skip_regexp((char_u *)pat, *eap->arg, true, NULL); + end = skip_regexp(pat, *eap->arg, true, NULL); } if (!give_up) { @@ -1439,7 +1439,7 @@ void ex_catch(exarg_T *eap) } if (end != NULL) { - eap->nextcmd = (char *)find_nextcmd((char_u *)end); + eap->nextcmd = find_nextcmd(end); } } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 0cca4b69e8..ec2672c675 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -315,7 +315,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s p = skipwhite(p); delim = (delim_optional && vim_isIDc(*p)) ? ' ' : *p++; *search_delim = delim; - end = (char *)skip_regexp((char_u *)p, delim, p_magic, NULL); + end = skip_regexp(p, delim, p_magic, NULL); use_last_pat = end == p && *end == delim; if (end == p && !use_last_pat) { diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index b873388473..450c608fad 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -2024,7 +2024,7 @@ void prep_exarg(exarg_T *eap, const buf_T *buf) snprintf(eap->cmd, cmd_len, "e ++enc=%s", buf->b_p_fenc); eap->force_enc = 8; eap->bad_char = buf->b_bad_char; - eap->force_ff = *buf->b_p_ff; + eap->force_ff = (unsigned char)(*buf->b_p_ff); eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN; eap->read_edit = false; @@ -5317,7 +5317,7 @@ static void vim_mktempdir(void) mode_t umask_save = umask(0077); for (size_t i = 0; i < ARRAY_SIZE(temp_dirs); i++) { // Expand environment variables, leave room for "/tmp/nvim./XXXXXX/999999999". - expand_env((char_u *)temp_dirs[i], (char_u *)tmp, TEMP_FILE_PATH_MAXLEN - 64); + expand_env((char *)temp_dirs[i], tmp, TEMP_FILE_PATH_MAXLEN - 64); if (!os_isdir((char_u *)tmp)) { continue; } diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index 574eba9bdd..af3895b793 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -1302,7 +1302,7 @@ void openscript(char_u *name, bool directly) curscript++; } // use NameBuff for expanded name - expand_env(name, (char_u *)NameBuff, MAXPATHL); + expand_env((char *)name, NameBuff, MAXPATHL); int error; if ((scriptin[curscript] = file_open_new(&error, (char *)NameBuff, kFileReadOnly, 0)) == NULL) { diff --git a/src/nvim/grid.c b/src/nvim/grid.c index c805c238c6..329adfda12 100644 --- a/src/nvim/grid.c +++ b/src/nvim/grid.c @@ -125,7 +125,7 @@ void grid_putchar(ScreenGrid *grid, int c, int row, int col, int attr) char buf[MB_MAXBYTES + 1]; buf[utf_char2bytes(c, buf)] = NUL; - grid_puts(grid, (char_u *)buf, row, col, attr); + grid_puts(grid, buf, row, col, attr); } /// get a single character directly from grid.chars into "bytes[]". @@ -148,7 +148,7 @@ void grid_getbytes(ScreenGrid *grid, int row, int col, char_u *bytes, int *attrp /// attributes 'attr', and update chars[] and attrs[]. /// Note: only outputs within one row, message is truncated at grid boundary! /// Note: if grid, row and/or col is invalid, nothing is done. -void grid_puts(ScreenGrid *grid, char_u *text, int row, int col, int attr) +void grid_puts(ScreenGrid *grid, char *text, int row, int col, int attr) { grid_puts_len(grid, text, -1, row, col, attr); } @@ -187,10 +187,10 @@ void grid_put_schar(ScreenGrid *grid, int row, int col, char_u *schar, int attr) /// like grid_puts(), but output "text[len]". When "len" is -1 output up to /// a NUL. -void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col, int attr) +void grid_puts_len(ScreenGrid *grid, char *text, int textlen, int row, int col, int attr) { size_t off; - char_u *ptr = text; + char *ptr = text; int len = textlen; int c; size_t max_off; @@ -237,13 +237,13 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col while (col < grid->cols && (len < 0 || (int)(ptr - text) < len) && *ptr != NUL) { - c = *ptr; + c = (unsigned char)(*ptr); // check if this is the first byte of a multibyte mbyte_blen = len > 0 - ? utfc_ptr2len_len(ptr, (int)((text + len) - ptr)) - : utfc_ptr2len((char *)ptr); + ? utfc_ptr2len_len((char_u *)ptr, (int)((text + len) - ptr)) + : utfc_ptr2len(ptr); u8c = len >= 0 - ? utfc_ptr2char_len(ptr, u8cc, (int)((text + len) - ptr)) + ? utfc_ptr2char_len((char_u *)ptr, u8cc, (int)((text + len) - ptr)) : utfc_ptr2char(ptr, u8cc); mbyte_cells = utf_char2cells(u8c); if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c)) { @@ -254,7 +254,8 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col nc1 = NUL; } else { nc = len >= 0 - ? utfc_ptr2char_len(ptr + mbyte_blen, pcc, (int)((text + len) - ptr - mbyte_blen)) + ? utfc_ptr2char_len((char_u *)ptr + mbyte_blen, pcc, + (int)((text + len) - ptr - mbyte_blen)) : utfc_ptr2char(ptr + mbyte_blen, pcc); nc1 = pcc[0]; } @@ -320,7 +321,7 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col ptr += mbyte_blen; if (clear_next_cell) { // This only happens at the end, display one space next. - ptr = (char_u *)" "; + ptr = " "; len = -1; } } @@ -393,11 +394,11 @@ void grid_fill(ScreenGrid *grid, int start_row, int end_row, int start_col, int // double wide-char clear out the right half. Only needed in a // terminal. if (start_col > 0 && grid_fix_col(grid, start_col, row) != start_col) { - grid_puts_len(grid, (char_u *)" ", 1, row, start_col - 1, 0); + grid_puts_len(grid, " ", 1, row, start_col - 1, 0); } if (end_col < grid->cols && grid_fix_col(grid, end_col, row) != end_col) { - grid_puts_len(grid, (char_u *)" ", 1, row, end_col, 0); + grid_puts_len(grid, " ", 1, row, end_col, 0); } // if grid was resized (in ext_multigrid mode), the UI has no redraw updates diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c index 6f98e25f56..6e424f2fd6 100644 --- a/src/nvim/hardcopy.c +++ b/src/nvim/hardcopy.c @@ -613,7 +613,7 @@ static void prt_message(char_u *s) { // TODO(bfredl): delete this grid_fill(&default_grid, Rows - 1, Rows, 0, Columns, ' ', ' ', 0); - grid_puts(&default_grid, s, Rows - 1, 0, HL_ATTR(HLF_R)); + grid_puts(&default_grid, (char *)s, Rows - 1, 0, HL_ATTR(HLF_R)); ui_flush(); } @@ -2147,17 +2147,14 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) char_u *p; int props; int cmap = 0; - char_u *p_encoding; struct prt_ps_encoding_S *p_mbenc; struct prt_ps_encoding_S *p_mbenc_first; struct prt_ps_charset_S *p_mbchar = NULL; - /* - * Set up font and encoding. - */ - p_encoding = enc_skip((char_u *)p_penc); + // Set up font and encoding. + char_u *p_encoding = (char_u *)enc_skip(p_penc); if (*p_encoding == NUL) { - p_encoding = enc_skip((char_u *)p_enc); + p_encoding = (char_u *)enc_skip(p_enc); } // Look for a multi-byte font that matches the encoding and character set. @@ -2591,13 +2588,13 @@ bool mch_print_begin(prt_settings_T *psettings) // that cannot be found then default to "latin1". // Note: VIM specific encoding header is always skipped. if (!prt_out_mbyte) { - p_encoding = (char *)enc_skip((char_u *)p_penc); + p_encoding = enc_skip(p_penc); if (*p_encoding == NUL || !prt_find_resource(p_encoding, &res_encoding)) { // 'printencoding' not set or not supported - find alternate int props; - p_encoding = (char *)enc_skip((char_u *)p_enc); + p_encoding = enc_skip(p_enc); props = enc_canon_props((char_u *)p_encoding); if (!(props & ENC_8BIT) || !prt_find_resource(p_encoding, &res_encoding)) { @@ -2617,9 +2614,9 @@ bool mch_print_begin(prt_settings_T *psettings) // For the moment there are no checks on encoding resource files to // perform } else { - p_encoding = (char *)enc_skip((char_u *)p_penc); + p_encoding = enc_skip(p_penc); if (*p_encoding == NUL) { - p_encoding = (char *)enc_skip((char_u *)p_enc); + p_encoding = enc_skip(p_enc); } if (prt_use_courier) { // Include ASCII range encoding vector @@ -2639,7 +2636,7 @@ bool mch_print_begin(prt_settings_T *psettings) prt_conv.vc_type = CONV_NONE; if (!(enc_canon_props((char_u *)p_enc) & enc_canon_props((char_u *)p_encoding) & ENC_8BIT)) { // Set up encoding conversion if required - if (convert_setup(&prt_conv, (char_u *)p_enc, (char_u *)p_encoding) == FAIL) { + if (convert_setup(&prt_conv, p_enc, p_encoding) == FAIL) { semsg(_("E620: Unable to convert to print encoding \"%s\""), p_encoding); return false; diff --git a/src/nvim/help.c b/src/nvim/help.c index 4b2b113437..b25fabca48 100644 --- a/src/nvim/help.c +++ b/src/nvim/help.c @@ -803,8 +803,8 @@ void fix_help_buffer(void) // 'encoding' may be required. vc.vc_type = CONV_NONE; convert_setup(&vc, - (char_u *)(this_utf == kTrue ? "utf-8" : "latin1"), - (char_u *)p_enc); + (this_utf == kTrue ? "utf-8" : "latin1"), + p_enc); if (vc.vc_type == CONV_NONE) { // No conversion needed. cp = (char *)IObuff; diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c index a63768a8e3..e2d4a81345 100644 --- a/src/nvim/highlight_group.c +++ b/src/nvim/highlight_group.c @@ -1421,7 +1421,7 @@ static void highlight_list_one(const int id) const HlGroup *sgp = &hl_table[id - 1]; // index is ID minus one bool didh = false; - if (message_filtered(sgp->sg_name)) { + if (message_filtered((char *)sgp->sg_name)) { return; } diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index 50ec444d51..975fa0ca92 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -423,7 +423,7 @@ static int cs_add_common(char *arg1, char *arg2, char *flags) // get the filename (arg1), expand it, and try to stat it fname = xmalloc(MAXPATHL + 1); - expand_env((char_u *)arg1, (char_u *)fname, MAXPATHL); + expand_env(arg1, fname, MAXPATHL); size_t len = STRLEN(fname); fbuf = fname; (void)modify_fname(":p", false, &usedlen, &fname, &fbuf, &len); @@ -445,7 +445,7 @@ staterr: // get the prepend path (arg2), expand it, and see if it exists if (arg2 != NULL) { ppath = xmalloc(MAXPATHL + 1); - expand_env((char_u *)arg2, (char_u *)ppath, MAXPATHL); + expand_env(arg2, ppath, MAXPATHL); if (!os_path_exists((char_u *)ppath)) { goto staterr; } @@ -757,14 +757,14 @@ err_closing: #endif // expand the cscope exec for env var's prog = xmalloc(MAXPATHL + 1); - expand_env((char_u *)p_csprg, (char_u *)prog, MAXPATHL); + expand_env(p_csprg, prog, MAXPATHL); // alloc space to hold the cscope command size_t len = strlen(prog) + strlen(csinfo[i].fname) + 32; if (csinfo[i].ppath) { // expand the prepend path for env var's ppath = xmalloc(MAXPATHL + 1); - expand_env((char_u *)csinfo[i].ppath, (char_u *)ppath, MAXPATHL); + expand_env(csinfo[i].ppath, ppath, MAXPATHL); len += strlen(ppath); } diff --git a/src/nvim/indent.c b/src/nvim/indent.c index c983de6d5e..792f4d93c4 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -343,7 +343,7 @@ int get_sts_value(void) // Count the size (in window cells) of the indent in the current line. int get_indent(void) { - return get_indent_str_vtab(get_cursor_line_ptr(), + return get_indent_str_vtab((char *)get_cursor_line_ptr(), curbuf->b_p_ts, curbuf->b_p_vts_array, false); @@ -352,7 +352,7 @@ int get_indent(void) // Count the size (in window cells) of the indent in line "lnum". int get_indent_lnum(linenr_T lnum) { - return get_indent_str_vtab(ml_get(lnum), + return get_indent_str_vtab((char *)ml_get(lnum), curbuf->b_p_ts, curbuf->b_p_vts_array, false); @@ -362,7 +362,7 @@ int get_indent_lnum(linenr_T lnum) // "buf". int get_indent_buf(buf_T *buf, linenr_T lnum) { - return get_indent_str_vtab(ml_get_buf(buf, lnum, false), + return get_indent_str_vtab((char *)ml_get_buf(buf, lnum, false), curbuf->b_p_ts, buf->b_p_vts_array, false); @@ -400,7 +400,7 @@ int get_indent_str(const char_u *ptr, int ts, bool list) /// Count the size (in window cells) of the indent in line "ptr", using /// variable tabstops. /// if "list" is true, count only screen size for tabs. -int get_indent_str_vtab(const char_u *ptr, long ts, long *vts, bool list) +int get_indent_str_vtab(const char *ptr, long ts, long *vts, bool list) { int count = 0; @@ -800,7 +800,7 @@ int get_breakindent_win(win_T *wp, char_u *line) prev_ts = wp->w_buffer->b_p_ts; prev_tick = buf_get_changedtick(wp->w_buffer); prev_vts = wp->w_buffer->b_p_vts_array; - prev_indent = get_indent_str_vtab(line, + prev_indent = get_indent_str_vtab((char *)line, wp->w_buffer->b_p_ts, wp->w_buffer->b_p_vts_array, wp->w_p_list); diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c index 128eea915d..8ef6667374 100644 --- a/src/nvim/indent_c.c +++ b/src/nvim/indent_c.c @@ -212,16 +212,14 @@ int is_pos_in_string(const char_u *line, colnr_T col) * Below "XXX" means that this function may unlock the current line. */ -/* - * Return true if the string "line" starts with a word from 'cinwords'. - */ -bool cin_is_cinword(const char_u *line) +/// @return true if the string "line" starts with a word from 'cinwords'. +bool cin_is_cinword(const char *line) { bool retval = false; size_t cinw_len = STRLEN(curbuf->b_p_cinw) + 1; char_u *cinw_buf = xmalloc(cinw_len); - line = (char_u *)skipwhite((char *)line); + line = skipwhite((char *)line); for (char *cinw = curbuf->b_p_cinw; *cinw;) { size_t len = copy_option_part(&cinw, (char *)cinw_buf, cinw_len, ","); @@ -2021,7 +2019,7 @@ int get_c_indent(void) if (trypos == NULL && curwin->w_cursor.lnum > 1) { // There may be a statement before the comment, search from the end // of the line for a comment start. - linecomment_pos.col = check_linecomment(ml_get(curwin->w_cursor.lnum - 1)); + linecomment_pos.col = check_linecomment((char *)ml_get(curwin->w_cursor.lnum - 1)); if (linecomment_pos.col != MAXCOL) { trypos = &linecomment_pos; trypos->lnum = curwin->w_cursor.lnum - 1; @@ -2854,7 +2852,7 @@ int get_c_indent(void) if (n) { amount = n; l = after_label(get_cursor_line_ptr()); - if (l != NULL && cin_is_cinword(l)) { + if (l != NULL && cin_is_cinword((char *)l)) { if (theline[0] == '{') { amount += curbuf->b_ind_open_extra; } else { @@ -3108,7 +3106,7 @@ int get_c_indent(void) * Check if we are after an "if", "while", etc. * Also allow " } else". */ - if (cin_is_cinword(l) || cin_iselse((char_u *)skipwhite((char *)l))) { + if (cin_is_cinword((char *)l) || cin_iselse((char_u *)skipwhite((char *)l))) { // Found an unterminated line after an if (), line up // with the last one. // if (cond) diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index 981a8d42a6..3c32d0755e 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -1732,7 +1732,7 @@ void ins_compl_addleader(int c) utf_char2bytes(c, (char *)buf); buf[cc] = NUL; - ins_char_bytes((char_u *)buf, (size_t)cc); + ins_char_bytes(buf, (size_t)cc); } else { ins_char(c); } @@ -2014,7 +2014,7 @@ static bool ins_compl_stop(const int c, const int prev_mode, bool retval) const int compl_len = get_compl_len(); const int len = (int)STRLEN(p); if (len > compl_len) { - ins_bytes_len(p + compl_len, (size_t)(len - compl_len)); + ins_bytes_len((char *)p + compl_len, (size_t)(len - compl_len)); } } retval = true; diff --git a/src/nvim/log.c b/src/nvim/log.c index 99b17a612b..9f25543be7 100644 --- a/src/nvim/log.c +++ b/src/nvim/log.c @@ -60,7 +60,7 @@ static bool log_try_create(char *fname) static void log_path_init(void) { size_t size = sizeof(log_file_path); - expand_env((char_u *)"$" ENV_LOGFILE, (char_u *)log_file_path, (int)size - 1); + expand_env("$" ENV_LOGFILE, log_file_path, (int)size - 1); if (strequal("$" ENV_LOGFILE, log_file_path) || log_file_path[0] == '\0' || os_isdir((char_u *)log_file_path) diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 0d08817285..7e8dda6ca1 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -494,8 +494,8 @@ static int nlua_iconv(lua_State *lstate) size_t str_len = 0; const char *str = lua_tolstring(lstate, 1, &str_len); - char_u *from = (char_u *)enc_canonize((char *)enc_skip((char_u *)lua_tolstring(lstate, 2, NULL))); - char_u *to = (char_u *)enc_canonize((char *)enc_skip((char_u *)lua_tolstring(lstate, 3, NULL))); + char_u *from = (char_u *)enc_canonize(enc_skip((char *)lua_tolstring(lstate, 2, NULL))); + char_u *to = (char_u *)enc_canonize(enc_skip((char *)lua_tolstring(lstate, 3, NULL))); vimconv_T vimconv; vimconv.vc_type = CONV_NONE; diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 2364a388b3..333fb847f6 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -150,8 +150,8 @@ static void showmap(mapblock_T *mp, bool local) { size_t len = 1; - if (message_filtered(mp->m_keys) && message_filtered((char_u *)mp->m_str) - && (mp->m_desc == NULL || message_filtered((char_u *)mp->m_desc))) { + if (message_filtered((char *)mp->m_keys) && message_filtered(mp->m_str) + && (mp->m_desc == NULL || message_filtered(mp->m_desc))) { return; } diff --git a/src/nvim/mark.c b/src/nvim/mark.c index 883371c5fb..92a7c7c4b0 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -674,7 +674,7 @@ static void fname2fnum(xfmark_T *fm) )) { int len; - expand_env((char_u *)"~/", (char_u *)NameBuff, MAXPATHL); + expand_env("~/", NameBuff, MAXPATHL); len = (int)STRLEN(NameBuff); STRLCPY(NameBuff + len, fm->fname + 2, MAXPATHL - len); } else { @@ -911,7 +911,7 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu name = mark_line(p, 15); mustfree = true; } - if (!message_filtered(name)) { + if (!message_filtered((char *)name)) { if (!did_title) { // Highlight title msg_puts_title(_("\nmark line col file/text")); @@ -1037,7 +1037,7 @@ void ex_jumps(exarg_T *eap) name = vim_strsave((char_u *)"-invalid-"); } // apply :filter /pat/ or file name not available - if (name == NULL || message_filtered(name)) { + if (name == NULL || message_filtered((char *)name)) { xfree(name); continue; } diff --git a/src/nvim/match.c b/src/nvim/match.c index 31fa35d84b..cabd008591 100644 --- a/src/nvim/match.c +++ b/src/nvim/match.c @@ -1194,7 +1194,7 @@ void ex_match(exarg_T *eap) semsg(_(e_invarg2), eap->arg); return; } - end = skip_regexp(p + 1, *p, true, NULL); + end = (char_u *)skip_regexp((char *)p + 1, *p, true, NULL); if (!eap->skip) { if (*end != NUL && !ends_excmd(*skipwhite((char *)end + 1))) { xfree(g); @@ -1215,5 +1215,5 @@ void ex_match(exarg_T *eap) *end = (char_u)c; } } - eap->nextcmd = (char *)find_nextcmd(end); + eap->nextcmd = find_nextcmd((char *)end); } diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index dab6c8fbd3..e703280032 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -754,21 +754,19 @@ bool utf_composinglike(const char_u *p1, const char_u *p2) /// space at least for #MAX_MCO + 1 elements. /// /// @return leading character. -int utfc_ptr2char(const char_u *p, int *pcc) +int utfc_ptr2char(const char *p_in, int *pcc) { - int len; - int c; - int cc; + uint8_t *p = (uint8_t *)p_in; int i = 0; - c = utf_ptr2char((char *)p); - len = utf_ptr2len((char *)p); + int c = utf_ptr2char((char *)p); + int len = utf_ptr2len((char *)p); // Only accept a composing char when the first char isn't illegal. if ((len > 1 || *p < 0x80) && p[len] >= 0x80 && utf_composinglike(p, p + len)) { - cc = utf_ptr2char((char *)p + len); + int cc = utf_ptr2char((char *)p + len); for (;;) { pcc[i++] = cc; if (i == MAX_MCO) { @@ -1936,7 +1934,7 @@ void utf_find_illegal(void) // 'encoding' is "utf-8" but we are editing a 8-bit encoded file, // possibly a utf-8 file with illegal bytes. Setup for conversion // from utf-8 to 'fileencoding'. - convert_setup(&vimconv, (char_u *)p_enc, (char_u *)curbuf->b_p_fenc); + convert_setup(&vimconv, p_enc, curbuf->b_p_fenc); } curwin->w_cursor.coladd = 0; @@ -2146,10 +2144,8 @@ const char *mb_unescape(const char **const pp) return NULL; } -/* - * Skip the Vim specific head of a 'encoding' name. - */ -char_u *enc_skip(char_u *p) +/// Skip the Vim specific head of a 'encoding' name. +char *enc_skip(char *p) { if (STRNCMP(p, "2byte-", 6) == 0) { return p + 6; @@ -2169,8 +2165,6 @@ char *enc_canonize(char *enc) FUNC_ATTR_NONNULL_RET { char_u *p, *s; - int i; - if (STRCMP(enc, "default") == 0) { // Use the default encoding as found by set_init_1(). return (char *)vim_strsave(fenc_default); @@ -2190,7 +2184,7 @@ char *enc_canonize(char *enc) *p = NUL; // Skip "2byte-" and "8bit-". - p = enc_skip(r); + p = (char_u *)enc_skip((char *)r); // Change "microsoft-cp" to "cp". Used in some spell files. if (STRNCMP(p, "microsoft-cp", 12) == 0) { @@ -2214,6 +2208,7 @@ char *enc_canonize(char *enc) STRMOVE(p + 5, p + 6); } + int i; if (enc_canon_search(p) >= 0) { // canonical name can be used unmodified if (p != r) { @@ -2332,7 +2327,7 @@ void *my_iconv_open(char_u *to, char_u *from) if (iconv_working == kBroken) { return (void *)-1; // detected a broken iconv() previously } - fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from)); + fd = iconv_open(enc_skip((char *)to), enc_skip((char *)from)); if (fd != (iconv_t)-1 && iconv_working == kUnknown) { /* @@ -2443,18 +2438,17 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen #endif // HAVE_ICONV -/* - * Setup "vcp" for conversion from "from" to "to". - * The names must have been made canonical with enc_canonize(). - * vcp->vc_type must have been initialized to CONV_NONE. - * Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8 - * instead). - * Afterwards invoke with "from" and "to" equal to NULL to cleanup. - * Return FAIL when conversion is not supported, OK otherwise. - */ -int convert_setup(vimconv_T *vcp, char_u *from, char_u *to) +/// Setup "vcp" for conversion from "from" to "to". +/// The names must have been made canonical with enc_canonize(). +/// vcp->vc_type must have been initialized to CONV_NONE. +/// Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8 +/// instead). +/// Afterwards invoke with "from" and "to" equal to NULL to cleanup. +/// +/// @return FAIL when conversion is not supported, OK otherwise. +int convert_setup(vimconv_T *vcp, char *from, char *to) { - return convert_setup_ext(vcp, from, true, to, true); + return convert_setup_ext(vcp, (char_u *)from, true, (char_u *)to, true); } /// As convert_setup(), but only when from_unicode_is_utf8 is true will all diff --git a/src/nvim/memline.c b/src/nvim/memline.c index ee90ae6b15..b940040c45 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -922,11 +922,9 @@ void ml_recover(bool checkext) b0p = hp->bh_data; } - /* - * If .swp file name given directly, use name from swap file for buffer. - */ + // If .swp file name given directly, use name from swap file for buffer. if (directly) { - expand_env(b0p->b0_fname, (char_u *)NameBuff, MAXPATHL); + expand_env((char *)b0p->b0_fname, NameBuff, MAXPATHL); if (setfname(curbuf, (char *)NameBuff, NULL, true) == FAIL) { goto theend; } @@ -1873,7 +1871,7 @@ errorret: // when the GUI redraws part of the text. recursive++; get_trans_bufname(buf); - shorten_dir((char_u *)NameBuff); + shorten_dir(NameBuff); siemsg(_("E316: ml_get: cannot find line %" PRId64 " in buffer %d %s"), (int64_t)lnum, buf->b_fnum, NameBuff); recursive--; @@ -3472,7 +3470,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ // Symlinks may point to the same file even // when the name differs, need to check the // inode too. - expand_env(b0.b0_fname, (char_u *)NameBuff, MAXPATHL); + expand_env((char *)b0.b0_fname, NameBuff, MAXPATHL); if (fnamecmp_ino((char_u *)buf->b_ffname, (char_u *)NameBuff, char_to_long(b0.b0_ino))) { differ = true; @@ -3481,7 +3479,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ } else { // The name in the swap file may be // "~user/path/file". Expand it first. - expand_env(b0.b0_fname, (char_u *)NameBuff, MAXPATHL); + expand_env((char *)b0.b0_fname, NameBuff, MAXPATHL); if (fnamecmp_ino((char_u *)buf->b_ffname, (char_u *)NameBuff, char_to_long(b0.b0_ino))) { differ = true; diff --git a/src/nvim/message.c b/src/nvim/message.c index fbf9c9b603..7b198371c5 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -305,7 +305,7 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) // Skip messages not match ":filter pattern". // Don't filter when there is an error. - if (!emsg_on_display && message_filtered((char_u *)s)) { + if (!emsg_on_display && message_filtered((char *)s)) { return true; } @@ -1990,7 +1990,7 @@ static char_u *screen_puts_mbyte(char_u *s, int l, int attr) return s; } - grid_puts_len(&msg_grid_adj, s, l, msg_row, msg_col, attr); + grid_puts_len(&msg_grid_adj, (char *)s, l, msg_row, msg_col, attr); if (cmdmsg_rl) { msg_col -= cw; if (msg_col == 0) { @@ -2353,13 +2353,13 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs /// @return true when ":filter pattern" was used and "msg" does not match /// "pattern". -bool message_filtered(char_u *msg) +bool message_filtered(char *msg) { if (cmdmod.cmod_filter_regmatch.regprog == NULL) { return false; } - bool match = vim_regexec(&cmdmod.cmod_filter_regmatch, (char *)msg, (colnr_T)0); + bool match = vim_regexec(&cmdmod.cmod_filter_regmatch, msg, (colnr_T)0); return cmdmod.cmod_filter_force ? match : !match; } @@ -2703,8 +2703,7 @@ static void t_puts(int *t_col, const char_u *t_s, const char_u *s, int attr) attr = hl_combine_attr(HL_ATTR(HLF_MSG), attr); // Output postponed text. msg_didout = true; // Remember that line is not empty. - grid_puts_len(&msg_grid_adj, (char_u *)t_s, (int)(s - t_s), msg_row, msg_col, - attr); + grid_puts_len(&msg_grid_adj, (char *)t_s, (int)(s - t_s), msg_row, msg_col, attr); msg_col += *t_col; *t_col = 0; // If the string starts with a composing character don't increment the @@ -3083,10 +3082,9 @@ void msg_moremsg(int full) char_u *s = (char_u *)_("-- More --"); attr = hl_combine_attr(HL_ATTR(HLF_MSG), HL_ATTR(HLF_M)); - grid_puts(&msg_grid_adj, s, Rows - 1, 0, attr); + grid_puts(&msg_grid_adj, (char *)s, Rows - 1, 0, attr); if (full) { - grid_puts(&msg_grid_adj, (char_u *) - _(" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit "), + grid_puts(&msg_grid_adj, _(" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit "), Rows - 1, vim_strsize((char *)s), attr); } } diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 8c5b1a033c..6430070f1b 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -2718,8 +2718,6 @@ void clear_showcmd(void) /// @return true if output has been written (and setcursor() has been called). bool add_to_showcmd(int c) { - char_u *p; - int i; static int ignore[] = { K_IGNORE, K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE, K_MOUSEMOVE, @@ -2742,14 +2740,14 @@ bool add_to_showcmd(int c) // Ignore keys that are scrollbar updates and mouse clicks if (IS_SPECIAL(c)) { - for (i = 0; ignore[i] != 0; i++) { + for (int i = 0; ignore[i] != 0; i++) { if (ignore[i] == c) { return false; } } } - p = transchar(c); + char *p = (char *)transchar(c); if (*p == ' ') { STRCPY(p, "<20>"); } @@ -2845,12 +2843,12 @@ static void display_showcmd(void) grid_puts_line_start(&msg_grid_adj, showcmd_row); if (!showcmd_is_clear) { - grid_puts(&msg_grid_adj, showcmd_buf, showcmd_row, sc_col, + grid_puts(&msg_grid_adj, (char *)showcmd_buf, showcmd_row, sc_col, HL_ATTR(HLF_MSG)); } // clear the rest of an old message by outputting up to SHOWCMD_COLS spaces - grid_puts(&msg_grid_adj, (char_u *)" " + len, showcmd_row, + grid_puts(&msg_grid_adj, (char *)" " + len, showcmd_row, sc_col + len, HL_ATTR(HLF_MSG)); grid_puts_line_flush(false); @@ -4392,8 +4390,7 @@ static void nv_ident(cmdarg_T *cap) init_history(); add_to_history(HIST_SEARCH, (char_u *)buf, true, NUL); - (void)normal_search(cap, cmdchar == '*' ? '/' : '?', (char_u *)buf, 0, - NULL); + (void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0, NULL); } else { g_tag_at_cursor = true; do_cmdline_cmd(buf); @@ -4813,7 +4810,7 @@ static void nv_search(cmdarg_T *cap) return; } - (void)normal_search(cap, cap->cmdchar, (char_u *)cap->searchbuf, + (void)normal_search(cap, cap->cmdchar, cap->searchbuf, (cap->arg || !equalpos(save_cursor, curwin->w_cursor)) ? 0 : SEARCH_MARK, NULL); } @@ -4842,9 +4839,8 @@ static void nv_next(cmdarg_T *cap) /// @param opt extra flags for do_search() /// /// @return 0 for failure, 1 for found, 2 for found and line offset added. -static int normal_search(cmdarg_T *cap, int dir, char_u *pat, int opt, int *wrapped) +static int normal_search(cmdarg_T *cap, int dir, char *pat, int opt, int *wrapped) { - int i; searchit_arg_T sia; cap->oap->motion_type = kMTCharWise; @@ -4853,8 +4849,8 @@ static int normal_search(cmdarg_T *cap, int dir, char_u *pat, int opt, int *wrap curwin->w_set_curswant = true; CLEAR_FIELD(sia); - i = do_search(cap->oap, dir, dir, pat, cap->count1, - opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, &sia); + int i = do_search(cap->oap, dir, dir, (char_u *)pat, cap->count1, + opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, &sia); if (wrapped != NULL) { *wrapped = sia.sa_wrapped; } @@ -5625,7 +5621,7 @@ static MarkMoveRes nv_mark_move_to(cmdarg_T *cap, MarkMove flags, fmark_T *fm) /// Handle commands that are operators in Visual mode. static void v_visop(cmdarg_T *cap) { - static char_u trans[] = "YyDdCcxdXdAAIIrr"; + static char trans[] = "YyDdCcxdXdAAIIrr"; // Uppercase means linewise, except in block mode, then "D" deletes till // the end of the line, and "C" replaces till EOL @@ -5637,7 +5633,7 @@ static void v_visop(cmdarg_T *cap) curwin->w_curswant = MAXCOL; } } - cap->cmdchar = (uint8_t)(*(vim_strchr((char *)trans, cap->cmdchar) + 1)); + cap->cmdchar = (uint8_t)(*(vim_strchr(trans, cap->cmdchar) + 1)); nv_operator(cap); } diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 092487fd3e..7b6f9e6370 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -3839,7 +3839,7 @@ void ex_display(exarg_T *eap) bool do_show = false; for (size_t j = 0; !do_show && j < yb->y_size; j++) { - do_show = !message_filtered((char_u *)yb->y_array[j]); + do_show = !message_filtered(yb->y_array[j]); } if (do_show || yb->y_size == 0) { @@ -3876,14 +3876,14 @@ void ex_display(exarg_T *eap) // display last inserted text if ((p = get_last_insert()) != NULL && (arg == NULL || vim_strchr((char *)arg, '.') != NULL) && !got_int - && !message_filtered(p)) { + && !message_filtered((char *)p)) { msg_puts("\n c \". "); dis_msg(p, true); } // display last command line if (last_cmdline != NULL && (arg == NULL || vim_strchr((char *)arg, ':') != NULL) - && !got_int && !message_filtered((char_u *)last_cmdline)) { + && !got_int && !message_filtered(last_cmdline)) { msg_puts("\n c \": "); dis_msg((char_u *)last_cmdline, false); } @@ -3891,7 +3891,7 @@ void ex_display(exarg_T *eap) // display current file name if (curbuf->b_fname != NULL && (arg == NULL || vim_strchr((char *)arg, '%') != NULL) && !got_int - && !message_filtered((char_u *)curbuf->b_fname)) { + && !message_filtered(curbuf->b_fname)) { msg_puts("\n c \"% "); dis_msg((char_u *)curbuf->b_fname, false); } @@ -3901,7 +3901,7 @@ void ex_display(exarg_T *eap) char *fname; linenr_T dummy; - if (buflist_name_nr(0, &fname, &dummy) != FAIL && !message_filtered((char_u *)fname)) { + if (buflist_name_nr(0, &fname, &dummy) != FAIL && !message_filtered(fname)) { msg_puts("\n c \"# "); dis_msg((char_u *)fname, false); } @@ -3910,14 +3910,14 @@ void ex_display(exarg_T *eap) // display last search pattern if (last_search_pat() != NULL && (arg == NULL || vim_strchr((char *)arg, '/') != NULL) && !got_int - && !message_filtered(last_search_pat())) { + && !message_filtered((char *)last_search_pat())) { msg_puts("\n c \"/ "); dis_msg(last_search_pat(), false); } // display last used expression if (expr_line != NULL && (arg == NULL || vim_strchr((char *)arg, '=') != NULL) - && !got_int && !message_filtered(expr_line)) { + && !got_int && !message_filtered((char *)expr_line)) { msg_puts("\n c \"= "); dis_msg(expr_line, false); } @@ -4802,7 +4802,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) } *ptr = NUL; STRCAT(buf1, buf2); - ins_str(buf1); // insert the new number + ins_str((char *)buf1); // insert the new number endpos = curwin->w_cursor; if (curwin->w_cursor.col) { curwin->w_cursor.col--; diff --git a/src/nvim/option.c b/src/nvim/option.c index c3f803e543..f9b32d50af 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -3299,7 +3299,7 @@ static void showoptions(int all, int opt_flags) item_count = 0; for (p = &options[0]; p->fullname != NULL; p++) { // apply :filter /pat/ - if (message_filtered((char_u *)p->fullname)) { + if (message_filtered(p->fullname)) { continue; } diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c index ea9a803a86..274e13e3c6 100644 --- a/src/nvim/os/env.c +++ b/src/nvim/os/env.c @@ -553,9 +553,9 @@ char_u *expand_env_save_opt(char_u *src, bool one) /// @param src Input string e.g. "$HOME/vim.hlp" /// @param dst[out] Where to put the result /// @param dstlen Maximum length of the result -void expand_env(char_u *src, char_u *dst, int dstlen) +void expand_env(char *src, char *dst, int dstlen) { - expand_env_esc(src, dst, dstlen, false, false, NULL); + expand_env_esc((char_u *)src, (char_u *)dst, dstlen, false, false, NULL); } /// Expand environment variable with path name and escaping. diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c index 0d62a5f5f9..dc96c39d25 100644 --- a/src/nvim/os/fs.c +++ b/src/nvim/os/fs.c @@ -911,7 +911,7 @@ int os_mkdir_recurse(const char *const dir, int32_t mode, char **const failed_di // We're done when it's "/" or "c:/". const size_t dirlen = strlen(dir); char *const curdir = xmemdupz(dir, dirlen); - char *const past_head = (char *)get_past_head((char_u *)curdir); + char *const past_head = get_past_head(curdir); char *e = curdir + dirlen; const char *const real_end = e; const char past_head_save = *past_head; diff --git a/src/nvim/path.c b/src/nvim/path.c index d786ccbf73..e40729b114 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -62,7 +62,7 @@ FileComparison path_full_compare(char *const s1, char *const s2, const bool chec FileID file_id_1, file_id_2; if (expandenv) { - expand_env((char_u *)s1, (char_u *)exp1, MAXPATHL); + expand_env(s1, exp1, MAXPATHL); } else { STRLCPY(exp1, s1, MAXPATHL); } @@ -104,7 +104,7 @@ char *path_tail(const char *fname) return ""; } - const char *tail = (char *)get_past_head((char_u *)fname); + const char *tail = get_past_head(fname); const char *p = tail; // Find last part of path. while (*p != NUL) { @@ -130,7 +130,7 @@ char *path_tail_with_sep(char *fname) assert(fname != NULL); // Don't remove the '/' from "c:/file". - char *past_head = (char *)get_past_head((char_u *)fname); + char *past_head = get_past_head(fname); char *tail = path_tail(fname); while (tail > past_head && after_pathsep(fname, tail)) { tail--; @@ -150,7 +150,7 @@ char *path_tail_with_sep(char *fname) const char_u *invocation_path_tail(const char_u *invocation, size_t *len) FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1) { - const char_u *tail = get_past_head((char_u *)invocation); + const char_u *tail = (char_u *)get_past_head((char *)invocation); const char_u *p = tail; while (*p != NUL && *p != ' ') { bool was_sep = vim_ispathsep_nocolon(*p); @@ -215,13 +215,13 @@ bool is_path_head(const char_u *path) /// Get a pointer to one character past the head of a path name. /// Unix: after "/"; Win: after "c:\" /// If there is no head, path is returned. -char_u *get_past_head(const char_u *path) +char *get_past_head(const char *path) { - const char_u *retval = path; + const char *retval = path; #ifdef WIN32 // May skip "c:" - if (is_path_head(path)) { + if (is_path_head((char_u *)path)) { retval = path + 2; } #endif @@ -230,7 +230,7 @@ char_u *get_past_head(const char_u *path) retval++; } - return (char_u *)retval; + return (char *)retval; } /// Return true if 'c' is a path separator. @@ -310,9 +310,9 @@ void shorten_dir_len(char_u *str, int trim_len) /// Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname" /// It's done in-place. -void shorten_dir(char_u *str) +void shorten_dir(char *str) { - shorten_dir_len(str, 1); + shorten_dir_len((char_u *)str, 1); } /// Return true if the directory of "fname" exists, false otherwise. @@ -631,7 +631,7 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, while (*path_end != NUL) { /* May ignore a wildcard that has a backslash before it; it will * be removed by rem_backslash() or file_pat_to_reg_pat() below. */ - if (path_end >= path + wildoff && rem_backslash(path_end)) { + if (path_end >= path + wildoff && rem_backslash((char *)path_end)) { *p++ = *path_end++; } else if (vim_ispathsep_nocolon(*path_end)) { if (e != NULL) { @@ -658,7 +658,7 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, /* Remove backslashes between "wildoff" and the start of the wildcard * component. */ for (p = buf + wildoff; p < s; p++) { - if (rem_backslash(p)) { + if (rem_backslash((char *)p)) { STRMOVE(p, p + 1); e--; s--; diff --git a/src/nvim/plines.c b/src/nvim/plines.c index f13e83ca9b..11b6951edd 100644 --- a/src/nvim/plines.c +++ b/src/nvim/plines.c @@ -233,7 +233,7 @@ int win_chartabsize(win_T *wp, char *p, colnr_T col) if (*p == TAB && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) { return tabstop_padding(col, buf->b_p_ts, buf->b_p_vts_array); } else { - return ptr2cells((char *)p); + return ptr2cells(p); } } diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c index 529e351f33..b144348188 100644 --- a/src/nvim/popupmenu.c +++ b/src/nvim/popupmenu.c @@ -542,14 +542,13 @@ void pum_redraw(void) size++; } } - grid_puts_len(&pum_grid, (char_u *)rt, (int)STRLEN(rt), row, - grid_col - size + 1, attr); + grid_puts_len(&pum_grid, rt, (int)STRLEN(rt), row, grid_col - size + 1, attr); xfree(rt_start); xfree(st); grid_col -= width; } else { // use grid_puts_len() to truncate the text - grid_puts(&pum_grid, st, row, grid_col, attr); + grid_puts(&pum_grid, (char *)st, row, grid_col, attr); xfree(st); grid_col += width; } @@ -560,11 +559,11 @@ void pum_redraw(void) // Display two spaces for a Tab. if (pum_rl) { - grid_puts_len(&pum_grid, (char_u *)" ", 2, row, grid_col - 1, + grid_puts_len(&pum_grid, " ", 2, row, grid_col - 1, attr); grid_col -= 2; } else { - grid_puts_len(&pum_grid, (char_u *)" ", 2, row, grid_col, attr); + grid_puts_len(&pum_grid, " ", 2, row, grid_col, attr); grid_col += 2; } totwidth += 2; diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index 53bb17364e..20e6893ea5 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -1000,7 +1000,7 @@ static int qf_setup_state(qfstate_T *pstate, char *restrict enc, const char *res { pstate->vc.vc_type = CONV_NONE; if (enc != NULL && *enc != NUL) { - convert_setup(&pstate->vc, (char_u *)enc, (char_u *)p_enc); + convert_setup(&pstate->vc, enc, p_enc); } if (efile != NULL @@ -1244,7 +1244,7 @@ static int qf_parse_fmt_f(regmatch_T *rmp, int midx, qffields_T *fields, int pre // Expand ~/file and $HOME/file to full path. char c = (char)(*rmp->endp[midx]); *rmp->endp[midx] = NUL; - expand_env(rmp->startp[midx], (char_u *)fields->namebuf, CMDBUFFSIZE); + expand_env((char *)rmp->startp[midx], fields->namebuf, CMDBUFFSIZE); *rmp->endp[midx] = (char_u)c; // For separate filename patterns (%O, %P and %Q), the specified file @@ -3038,16 +3038,16 @@ static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel) // text of the entry. bool filter_entry = true; if (qfp->qf_module != NULL && *qfp->qf_module != NUL) { - filter_entry &= message_filtered((char_u *)qfp->qf_module); + filter_entry &= message_filtered(qfp->qf_module); } if (filter_entry && fname != NULL) { - filter_entry &= message_filtered((char_u *)fname); + filter_entry &= message_filtered(fname); } if (filter_entry && qfp->qf_pattern != NULL) { - filter_entry &= message_filtered((char_u *)qfp->qf_pattern); + filter_entry &= message_filtered(qfp->qf_pattern); } if (filter_entry) { - filter_entry &= message_filtered((char_u *)qfp->qf_text); + filter_entry &= message_filtered(qfp->qf_text); } if (filter_entry) { return; diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index 75bd7b4cc1..a52343e28b 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -488,10 +488,10 @@ static char_u *skip_anyof(char *p) /// When "newp" is not NULL and "dirc" is '?', make an allocated copy of the /// expression and change "\?" to "?". If "*newp" is not NULL the expression /// is changed in-place. -char_u *skip_regexp(char_u *startp, int dirc, int magic, char **newp) +char *skip_regexp(char *startp, int dirc, int magic, char **newp) { int mymagic; - char_u *p = startp; + char *p = startp; if (magic) { mymagic = MAGIC_ON; @@ -506,7 +506,7 @@ char_u *skip_regexp(char_u *startp, int dirc, int magic, char **newp) } if ((p[0] == '[' && mymagic >= MAGIC_ON) || (p[0] == '\\' && p[1] == '[' && mymagic <= MAGIC_OFF)) { - p = skip_anyof((char *)p + 1); + p = (char *)skip_anyof(p + 1); if (p[0] == NUL) { break; } @@ -514,8 +514,8 @@ char_u *skip_regexp(char_u *startp, int dirc, int magic, char **newp) if (dirc == '?' && newp != NULL && p[1] == '?') { // change "\?" to "?", make a copy first. if (*newp == NULL) { - *newp = (char *)vim_strsave(startp); - p = (char_u *)(*newp) + (p - startp); + *newp = xstrdup(startp); + p = *newp + (p - startp); } STRMOVE(p, p + 1); } else { diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index 25f85b6193..41056a2773 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -815,15 +815,21 @@ static void source_all_matches(char *pat) /// @param is_pack whether the added dir is a "pack/*/start/*/" style package static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) { - char_u *p4, *p3, *p2, *p1, *p; - char_u *buf = NULL; + char *p; + char *buf = NULL; char *afterdir = NULL; int retval = FAIL; - p4 = p3 = p2 = p1 = get_past_head(fname); + char *p1 = get_past_head((char *)fname); + char *p2 = p1; + char *p3 = p1; + char *p4 = p1; for (p = p1; *p; MB_PTR_ADV(p)) { if (vim_ispathsep_nocolon(*p)) { - p4 = p3; p3 = p2; p2 = p1; p1 = p; + p4 = p3; + p3 = p2; + p2 = p1; + p1 = p; } } @@ -833,7 +839,7 @@ static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) // // find the part up to "pack" in 'runtimepath' p4++; // append pathsep in order to expand symlink - char_u c = *p4; + char c = *p4; *p4 = NUL; char *const ffname = fix_fname((char *)fname); *p4 = c; @@ -854,10 +860,10 @@ static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) for (const char *entry = (const char *)p_rtp; *entry != NUL;) { const char *cur_entry = entry; - copy_option_part((char **)&entry, (char *)buf, MAXPATHL, ","); + copy_option_part((char **)&entry, buf, MAXPATHL, ","); if (insp == NULL) { - add_pathsep((char *)buf); - char *const rtp_ffname = fix_fname((char *)buf); + add_pathsep(buf); + char *const rtp_ffname = fix_fname(buf); if (rtp_ffname == NULL) { goto theend; } @@ -869,7 +875,7 @@ static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) } } - if ((p = (char_u *)strstr((char *)buf, "after")) != NULL + if ((p = strstr(buf, "after")) != NULL && p > buf && vim_ispathsep(p[-1]) && (vim_ispathsep(p[5]) || p[5] == NUL || p[5] == ',')) { @@ -2018,7 +2024,7 @@ int do_source(char *fname, int check_other, int is_vimrc) if (firstline != NULL && STRLEN(firstline) >= 3 && firstline[0] == 0xef && firstline[1] == 0xbb && firstline[2] == 0xbf) { // Found BOM; setup conversion, skip over BOM and recode the line. - convert_setup(&cookie.conv, (char_u *)"utf-8", (char_u *)p_enc); + convert_setup(&cookie.conv, "utf-8", p_enc); p = (char *)string_convert(&cookie.conv, (char_u *)firstline + 3, NULL); if (p == NULL) { p = xstrdup((char *)firstline + 3); @@ -2149,7 +2155,7 @@ void ex_scriptnames(exarg_T *eap) if (SCRIPT_ITEM(i).sn_name != NULL) { home_replace(NULL, (char *)SCRIPT_ITEM(i).sn_name, (char *)NameBuff, MAXPATHL, true); vim_snprintf((char *)IObuff, IOSIZE, "%3d: %s", i, NameBuff); - if (!message_filtered(IObuff)) { + if (!message_filtered((char *)IObuff)) { msg_putchar('\n'); msg_outtrans((char *)IObuff); line_breakcheck(); @@ -2439,7 +2445,7 @@ void ex_scriptencoding(exarg_T *eap) // Setup for conversion from the specified encoding to 'encoding'. sp = (struct source_cookie *)getline_cookie(eap->getline, eap->cookie); - convert_setup(&sp->conv, (char_u *)name, (char_u *)p_enc); + convert_setup(&sp->conv, name, p_enc); if (name != eap->arg) { xfree(name); diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 3258dc11d6..6efaae3725 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -277,7 +277,7 @@ static int wildmenu_match_len(expand_T *xp, char_u *s) /// These are backslashes used for escaping. Do show backslashes in help tags. static int skip_wildmenu_char(expand_T *xp, char_u *s) { - if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP) + if ((rem_backslash((char *)s) && xp->xp_context != EXPAND_HELP) || ((xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES) && (s[0] == '\t' @@ -469,10 +469,10 @@ void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int match, i ScreenGrid *grid = (wild_menu_showing == WM_SCROLLED) ? &msg_grid_adj : &default_grid; - grid_puts(grid, buf, row, 0, attr); + grid_puts(grid, (char *)buf, row, 0, attr); if (selstart != NULL && highlight) { *selend = NUL; - grid_puts(grid, selstart, row, selstart_col, HL_ATTR(HLF_WM)); + grid_puts(grid, (char *)selstart, row, selstart_col, HL_ATTR(HLF_WM)); } grid_fill(grid, row, row + 1, clen, Columns, @@ -1026,12 +1026,12 @@ void draw_tabline(void) if (col + len >= Columns - 3) { break; } - grid_puts_len(&default_grid, (char_u *)NameBuff, len, 0, col, + grid_puts_len(&default_grid, NameBuff, len, 0, col, hl_combine_attr(attr, win_hl_attr(cwp, HLF_T))); col += len; } if (modified) { - grid_puts_len(&default_grid, (char_u *)"+", 1, 0, col++, attr); + grid_puts_len(&default_grid, "+", 1, 0, col++, attr); } grid_putchar(&default_grid, ' ', 0, col++, attr); } @@ -1040,7 +1040,7 @@ void draw_tabline(void) if (room > 0) { // Get buffer name in NameBuff[] get_trans_bufname(cwp->w_buffer); - shorten_dir((char_u *)NameBuff); + shorten_dir(NameBuff); len = vim_strsize((char *)NameBuff); p = (char_u *)NameBuff; while (len > room) { @@ -1051,7 +1051,7 @@ void draw_tabline(void) len = Columns - col - 1; } - grid_puts_len(&default_grid, p, (int)STRLEN(p), 0, col, attr); + grid_puts_len(&default_grid, (char *)p, (int)STRLEN(p), 0, col, attr); col += len; } grid_putchar(&default_grid, ' ', 0, col++, attr); diff --git a/src/nvim/search.c b/src/nvim/search.c index 892d531633..c1c2f0dbe9 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -1124,7 +1124,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, * If there is a matching '/' or '?', toss it. */ ps = (char_u *)strcopy; - p = skip_regexp(pat, search_delim, p_magic, &strcopy); + p = (char_u *)skip_regexp((char *)pat, search_delim, p_magic, &strcopy); if (strcopy != (char *)ps) { // made a copy of "pat" to change "\?" to "?" searchcmdlen += (int)(STRLEN(pat) - STRLEN(strcopy)); @@ -1977,7 +1977,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) // backward search: Check if this line contains a single-line comment if ((backwards && comment_dir) || lisp) { - comment_col = check_linecomment(linep); + comment_col = check_linecomment((char *)linep); } if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col) { lispcomm = true; // find match inside this comment @@ -2010,7 +2010,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) // Check if this line contains a single-line comment if (comment_dir || lisp) { - comment_col = check_linecomment(linep); + comment_col = check_linecomment((char *)linep); } // skip comment if (lisp && comment_col != MAXCOL) { @@ -2043,7 +2043,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) do_quotes = -1; line_breakcheck(); if (lisp) { // find comment pos in new line - comment_col = check_linecomment(linep); + comment_col = check_linecomment((char *)linep); } } else { pos.col += utfc_ptr2len((char *)linep + pos.col); @@ -2301,15 +2301,15 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) /// Check if line[] contains a / / comment. /// @returns MAXCOL if not, otherwise return the column. -int check_linecomment(const char_u *line) +int check_linecomment(const char *line) { - const char_u *p = line; // scan from start + const char *p = line; // scan from start // skip Lispish one-line comments if (curbuf->b_p_lisp) { if (vim_strchr((char *)p, ';') != NULL) { // there may be comments bool in_str = false; // inside of string - while ((p = (char_u *)strpbrk((char *)p, "\";")) != NULL) { + while ((p = strpbrk((char *)p, "\";")) != NULL) { if (*p == '"') { if (in_str) { if (*(p - 1) != '\\') { // skip escaped quote @@ -2322,7 +2322,7 @@ int check_linecomment(const char_u *line) } } else if (!in_str && ((p - line) < 2 || (*(p - 1) != '\\' && *(p - 2) != '#')) - && !is_pos_in_string(line, (colnr_T)(p - line))) { + && !is_pos_in_string((char_u *)line, (colnr_T)(p - line))) { break; // found! } p++; @@ -2331,12 +2331,12 @@ int check_linecomment(const char_u *line) p = NULL; } } else { - while ((p = (char_u *)vim_strchr((char *)p, '/')) != NULL) { + while ((p = vim_strchr((char *)p, '/')) != NULL) { // Accept a double /, unless it's preceded with * and followed by *, // because * / / * is an end and start of a C comment. Only // accept the position if it is not inside a string. if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*') - && !is_pos_in_string(line, (colnr_T)(p - line))) { + && !is_pos_in_string((char_u *)line, (colnr_T)(p - line))) { break; } p++; @@ -3536,7 +3536,6 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo int i; char_u *already = NULL; char_u *startp = NULL; - char_u *inc_opt = NULL; win_T *curwin_save = NULL; const int l_g_do_tagpreview = g_do_tagpreview; @@ -3561,9 +3560,9 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo goto fpip_end; } } - inc_opt = (*curbuf->b_p_inc == NUL) ? (char_u *)p_inc : (char_u *)curbuf->b_p_inc; + char *inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc; if (*inc_opt != NUL) { - incl_regmatch.regprog = vim_regcomp((char *)inc_opt, p_magic ? RE_MAGIC : 0); + incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0); if (incl_regmatch.regprog == NULL) { goto fpip_end; } @@ -3597,7 +3596,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo char_u *p_fname = (curr_fname == (char_u *)curbuf->b_fname) ? (char_u *)curbuf->b_ffname : curr_fname; - if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) { + if (inc_opt != NULL && strstr(inc_opt, "\\zs") != NULL) { // Use text from '\zs' to '\ze' (or end) of 'include'. new_fname = find_file_name_in_path(incl_regmatch.startp[0], (size_t)(incl_regmatch.endp[0] @@ -3674,7 +3673,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo * Include the surrounding "" or <> if present. */ if (inc_opt != NULL - && strstr((char *)inc_opt, "\\zs") != NULL) { + && strstr(inc_opt, "\\zs") != NULL) { // pattern contains \zs, use the match p = incl_regmatch.startp[0]; i = (int)(incl_regmatch.endp[0] diff --git a/src/nvim/shada.c b/src/nvim/shada.c index b45a041d96..88ad7d519a 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -1477,7 +1477,7 @@ static char *shada_filename(const char *file) // because various expansions must have already be done by the shell. // If shell is not performing them then they should be done in main.c // where arguments are parsed, *not here*. - expand_env((char_u *)file, (char_u *)&(NameBuff[0]), MAXPATHL); + expand_env((char *)file, &(NameBuff[0]), MAXPATHL); file = (const char *)&(NameBuff[0]); } } diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index 8d6307f123..33e8c5c099 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -2042,7 +2042,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) } vim_snprintf((char *)IObuff, IOSIZE, _("Reading affix file %s..."), fname); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); // Only do REP lines when not done in another .aff file already. do_rep = GA_EMPTY(&spin->si_rep); @@ -2123,7 +2123,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) // Setup for conversion from "ENC" to 'encoding'. aff->af_enc = (char_u *)enc_canonize((char *)items[1]); if (!spin->si_ascii - && convert_setup(&spin->si_conv, aff->af_enc, (char_u *)p_enc) == FAIL) { + && convert_setup(&spin->si_conv, (char *)aff->af_enc, p_enc) == FAIL) { smsg(_("Conversion in %s not supported: from %s to %s"), fname, aff->af_enc, p_enc); } @@ -3123,7 +3123,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) vim_snprintf((char *)IObuff, IOSIZE, _("Reading dictionary file %s..."), fname); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); // start with a message for the first line spin->si_msg_count = 999999; @@ -3676,7 +3676,7 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) } vim_snprintf((char *)IObuff, IOSIZE, _("Reading word file %s..."), fname); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); // Read all the lines in the file one by one. while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int) { @@ -3723,13 +3723,13 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) smsg(_("/encoding= line after word ignored in %s line %ld: %s"), fname, lnum, line - 1); } else { - char_u *enc; + char *enc; // Setup for conversion to 'encoding'. line += 9; - enc = (char_u *)enc_canonize((char *)line); + enc = enc_canonize((char *)line); if (!spin->si_ascii - && convert_setup(&spin->si_conv, enc, (char_u *)p_enc) == FAIL) { + && convert_setup(&spin->si_conv, enc, p_enc) == FAIL) { smsg(_("Conversion in %s not supported: from %s to %s"), fname, line, p_enc); } @@ -3820,7 +3820,7 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) if (spin->si_ascii && non_ascii > 0) { vim_snprintf((char *)IObuff, IOSIZE, _("Ignored %d words with non-ASCII characters"), non_ascii); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); } return retval; @@ -3894,13 +3894,13 @@ static wordnode_T *wordtree_alloc(spellinfo_T *spin) /// Return true if "word" contains valid word characters. /// Control characters and trailing '/' are invalid. Space is OK. -static bool valid_spell_word(const char_u *word, const char_u *end) +static bool valid_spell_word(const char *word, const char *end) { - if (!utf_valid_string(word, end)) { + if (!utf_valid_string((char_u *)word, (char_u *)end)) { return false; } - for (const char_u *p = word; *p != NUL && p < end; p += utfc_ptr2len((const char *)p)) { - if (*p < ' ' || (p[0] == '/' && p[1] == NUL)) { + for (const char *p = word; *p != NUL && p < end; p += utfc_ptr2len(p)) { + if ((uint8_t)(*p) < ' ' || (p[0] == '/' && p[1] == NUL)) { return false; } } @@ -3928,7 +3928,7 @@ static int store_word(spellinfo_T *spin, char_u *word, int flags, int region, co int res = OK; // Avoid adding illegal bytes to the word tree. - if (!valid_spell_word(word, word + len)) { + if (!valid_spell_word((char *)word, (char *)word + len)) { return FAIL; } @@ -4213,7 +4213,7 @@ static void wordtree_compress(spellinfo_T *spin, wordnode_T *root, const char *n vim_snprintf((char *)IObuff, IOSIZE, _("Compressed %s of %ld nodes; %ld (%ld%%) remaining"), name, tot, tot - n, perc); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); } #ifdef SPELL_PRINTTREE spell_print_tree(root->wn_sibling); @@ -4347,14 +4347,15 @@ static int rep_compare(const void *s1, const void *s2) return STRCMP(p1->ft_from, p2->ft_from); } -// Write the Vim .spl file "fname". -// Return OK/FAIL. -static int write_vim_spell(spellinfo_T *spin, char_u *fname) +/// Write the Vim .spl file "fname". +/// +/// @return OK/FAIL. +static int write_vim_spell(spellinfo_T *spin, char *fname) { int retval = OK; int regionmask; - FILE *fd = os_fopen((char *)fname, "w"); + FILE *fd = os_fopen(fname, "w"); if (fd == NULL) { semsg(_(e_notopen), fname); return FAIL; @@ -4893,7 +4894,7 @@ void ex_mkspell(exarg_T *eap) // Create the .sug file. // Uses the soundfold info in "spin". // Writes the file with the name "wfname", with ".spl" changed to ".sug". -static void spell_make_sugfile(spellinfo_T *spin, char_u *wfname) +static void spell_make_sugfile(spellinfo_T *spin, char *wfname) { char_u *fname = NULL; int len; @@ -4906,14 +4907,14 @@ static void spell_make_sugfile(spellinfo_T *spin, char_u *wfname) // of the code for the soundfolding stuff. // It might have been done already by spell_reload_one(). for (slang = first_lang; slang != NULL; slang = slang->sl_next) { - if (path_full_compare((char *)wfname, (char *)slang->sl_fname, false, true) + if (path_full_compare(wfname, (char *)slang->sl_fname, false, true) == kEqualFiles) { break; } } if (slang == NULL) { - spell_message(spin, (char_u *)_("Reading back spell file...")); - slang = spell_load_file(wfname, NULL, NULL, false); + spell_message(spin, _("Reading back spell file...")); + slang = spell_load_file((char_u *)wfname, NULL, NULL, false); if (slang == NULL) { return; } @@ -4930,7 +4931,7 @@ static void spell_make_sugfile(spellinfo_T *spin, char_u *wfname) // Go through the trie of good words, soundfold each word and add it to // the soundfold trie. - spell_message(spin, (char_u *)_("Performing soundfolding...")); + spell_message(spin, _("Performing soundfolding...")); if (sug_filltree(spin, slang) == FAIL) { goto theend; } @@ -4947,7 +4948,7 @@ static void spell_make_sugfile(spellinfo_T *spin, char_u *wfname) (int64_t)spin->si_spellbuf->b_ml.ml_line_count); // Compress the soundfold trie. - spell_message(spin, (char_u *)_(msg_compressing)); + spell_message(spin, _(msg_compressing)); wordtree_compress(spin, spin->si_foldroot, "case-folded"); // Write the .sug file. @@ -5193,7 +5194,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname) vim_snprintf((char *)IObuff, IOSIZE, _("Writing suggestion file %s..."), fname); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); // : if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) { // @@ -5249,7 +5250,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname) vim_snprintf((char *)IObuff, IOSIZE, _("Estimated runtime memory use: %d bytes"), spin->si_memtot); - spell_message(spin, IObuff); + spell_message(spin, (char *)IObuff); theend: // close the file @@ -5268,7 +5269,6 @@ theend: static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool added_word) { char_u *fname = NULL; - char_u *wfname; char **innames; int incount; afffile_T *(afile[MAXREGIONS]); @@ -5296,7 +5296,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool innames = &fnames[fcount == 1 ? 0 : 1]; incount = fcount - 1; - wfname = xmalloc(MAXPATHL); + char *wfname = xmalloc(MAXPATHL); if (fcount >= 1) { len = (int)STRLEN(fnames[0]); @@ -5304,46 +5304,46 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool // For ":mkspell path/en.latin1.add" output file is // "path/en.latin1.add.spl". incount = 1; - vim_snprintf((char *)wfname, MAXPATHL, "%s.spl", fnames[0]); + vim_snprintf(wfname, MAXPATHL, "%s.spl", fnames[0]); } else if (fcount == 1) { // For ":mkspell path/vim" output file is "path/vim.latin1.spl". incount = 1; - vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL, + vim_snprintf(wfname, MAXPATHL, SPL_FNAME_TMPL, fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc()); } else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0) { // Name ends in ".spl", use as the file name. STRLCPY(wfname, fnames[0], MAXPATHL); } else { // Name should be language, make the file name from it. - vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL, + vim_snprintf(wfname, MAXPATHL, SPL_FNAME_TMPL, fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc()); } // Check for .ascii.spl. - if (strstr(path_tail((char *)wfname), SPL_FNAME_ASCII) != NULL) { + if (strstr(path_tail(wfname), SPL_FNAME_ASCII) != NULL) { spin.si_ascii = true; } // Check for .add.spl. - if (strstr(path_tail((char *)wfname), SPL_FNAME_ADD) != NULL) { + if (strstr(path_tail(wfname), SPL_FNAME_ADD) != NULL) { spin.si_add = true; } } if (incount <= 0) { emsg(_(e_invarg)); // need at least output and input names - } else if (vim_strchr(path_tail((char *)wfname), '_') != NULL) { + } else if (vim_strchr(path_tail(wfname), '_') != NULL) { emsg(_("E751: Output file name must not have region name")); } else if (incount > MAXREGIONS) { semsg(_("E754: Only up to %d regions supported"), MAXREGIONS); } else { // Check for overwriting before doing things that may take a lot of // time. - if (!over_write && os_path_exists(wfname)) { + if (!over_write && os_path_exists((char_u *)wfname)) { emsg(_(e_exists)); goto theend; } - if (os_isdir(wfname)) { + if (os_isdir((char_u *)wfname)) { semsg(_(e_isadir2), wfname); goto theend; } @@ -5421,7 +5421,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool if (!error && !got_int) { // Combine tails in the tree. - spell_message(&spin, (char_u *)_(msg_compressing)); + spell_message(&spin, _(msg_compressing)); wordtree_compress(&spin, spin.si_foldroot, "case-folded"); wordtree_compress(&spin, spin.si_keeproot, "keep-case"); wordtree_compress(&spin, spin.si_prefroot, "prefixes"); @@ -5431,18 +5431,18 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool // Write the info in the spell file. vim_snprintf((char *)IObuff, IOSIZE, _("Writing spell file %s..."), wfname); - spell_message(&spin, IObuff); + spell_message(&spin, (char *)IObuff); error = write_vim_spell(&spin, wfname) == FAIL; - spell_message(&spin, (char_u *)_("Done!")); + spell_message(&spin, _("Done!")); vim_snprintf((char *)IObuff, IOSIZE, _("Estimated runtime memory use: %d bytes"), spin.si_memtot); - spell_message(&spin, IObuff); + spell_message(&spin, (char *)IObuff); // If the file is loaded need to reload it. if (!error) { - spell_reload_one(wfname, added_word); + spell_reload_one((char_u *)wfname, added_word); } } @@ -5479,14 +5479,14 @@ theend: // Display a message for spell file processing when 'verbose' is set or using // ":mkspell". "str" can be IObuff. -static void spell_message(const spellinfo_T *spin, char_u *str) +static void spell_message(const spellinfo_T *spin, char *str) FUNC_ATTR_NONNULL_ALL { if (spin->si_verbose || p_verbose > 2) { if (!spin->si_verbose) { verbose_enter(); } - msg((char *)str); + msg(str); ui_flush(); if (!spin->si_verbose) { verbose_leave(); @@ -5524,7 +5524,7 @@ void spell_add_word(char_u *word, int len, SpellAddType what, int idx, bool undo int i; char_u *spf; - if (!valid_spell_word(word, word + len)) { + if (!valid_spell_word((char *)word, (char *)word + len)) { emsg(_(e_illegal_character_in_word)); return; } diff --git a/src/nvim/statusline.c b/src/nvim/statusline.c index b9cddb7b94..9b441ba0a9 100644 --- a/src/nvim/statusline.c +++ b/src/nvim/statusline.c @@ -132,13 +132,13 @@ void win_redr_status(win_T *wp) row = is_stl_global ? (Rows - (int)p_ch - 1) : W_ENDROW(wp); col = is_stl_global ? 0 : wp->w_wincol; - grid_puts(&default_grid, p, row, col, attr); + grid_puts(&default_grid, (char *)p, row, col, attr); grid_fill(&default_grid, row, row + 1, len + col, this_ru_col + col, fillchar, fillchar, attr); if (get_keymap_str(wp, "<%s>", (char *)NameBuff, MAXPATHL) && this_ru_col - len > (int)(STRLEN(NameBuff) + 1)) { - grid_puts(&default_grid, (char_u *)NameBuff, row, + grid_puts(&default_grid, NameBuff, row, (int)((size_t)this_ru_col - STRLEN(NameBuff) - 1), attr); } @@ -342,7 +342,7 @@ void win_redr_ruler(win_T *wp, bool always) } ScreenGrid *grid = part_of_status ? &default_grid : &msg_grid_adj; - grid_puts(grid, (char_u *)buffer, row, this_ru_col + off, attr); + grid_puts(grid, buffer, row, this_ru_col + off, attr); grid_fill(grid, row, row + 1, this_ru_col + off + (int)STRLEN(buffer), off + width, fillchar, fillchar, attr); @@ -571,8 +571,8 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler) p = buf; for (n = 0; hltab[n].start != NULL; n++) { int textlen = (int)(hltab[n].start - p); - grid_puts_len(grid, (char_u *)p, textlen, row, col, curattr); - col += vim_strnsize((char_u *)p, textlen); + grid_puts_len(grid, p, textlen, row, col, curattr); + col += vim_strnsize(p, textlen); p = hltab[n].start; if (hltab[n].userhl == 0) { @@ -586,8 +586,7 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler) } } // Make sure to use an empty string instead of p, if p is beyond buf + len. - grid_puts(grid, p >= buf + len ? (char_u *)"" : (char_u *)p, row, col, - curattr); + grid_puts(grid, p >= buf + len ? "" : p, row, col, curattr); grid_puts_line_flush(false); @@ -608,7 +607,7 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler) .type = kStlClickDisabled, }; for (n = 0; tabtab[n].start != NULL; n++) { - len += vim_strnsize((char_u *)p, (int)(tabtab[n].start - p)); + len += vim_strnsize(p, (int)(tabtab[n].start - p)); while (col < len) { click_defs[col++] = cur_click_def; } diff --git a/src/nvim/strings.c b/src/nvim/strings.c index ac9d414be2..bd0f122f99 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -104,7 +104,7 @@ char_u *vim_strsave_escaped_ext(const char_u *string, const char_u *esc_chars, c p += l - 1; continue; } - if (vim_strchr((char *)esc_chars, *p) != NULL || (bsl && rem_backslash(p))) { + if (vim_strchr((char *)esc_chars, *p) != NULL || (bsl && rem_backslash((char *)p))) { length++; // count a backslash } length++; // count an ordinary char @@ -120,7 +120,7 @@ char_u *vim_strsave_escaped_ext(const char_u *string, const char_u *esc_chars, c p += l - 1; // skip multibyte char continue; } - if (vim_strchr((char *)esc_chars, *p) != NULL || (bsl && rem_backslash(p))) { + if (vim_strchr((char *)esc_chars, *p) != NULL || (bsl && rem_backslash((char *)p))) { *p2++ = cc; } *p2++ = *p; diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index 187dc4eed4..e88b1b17f6 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -3008,7 +3008,7 @@ static void syn_cmd_conceal(exarg_T *eap, int syncing) char_u *arg = (char_u *)eap->arg; char_u *next; - eap->nextcmd = (char *)find_nextcmd(arg); + eap->nextcmd = find_nextcmd((char *)arg); if (eap->skip) { return; } @@ -3037,7 +3037,7 @@ static void syn_cmd_case(exarg_T *eap, int syncing) char_u *arg = (char_u *)eap->arg; char_u *next; - eap->nextcmd = (char *)find_nextcmd(arg); + eap->nextcmd = find_nextcmd((char *)arg); if (eap->skip) { return; } @@ -3064,7 +3064,7 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) char_u *arg = (char_u *)eap->arg; char_u *arg_end; - eap->nextcmd = (char *)find_nextcmd(arg); + eap->nextcmd = find_nextcmd((char *)arg); if (eap->skip) { return; } @@ -3105,7 +3105,7 @@ static void syn_cmd_spell(exarg_T *eap, int syncing) char_u *arg = (char_u *)eap->arg; char_u *next; - eap->nextcmd = (char *)find_nextcmd(arg); + eap->nextcmd = find_nextcmd((char *)arg); if (eap->skip) { return; } @@ -3312,7 +3312,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) char_u *arg_end; int id; - eap->nextcmd = (char *)find_nextcmd(arg); + eap->nextcmd = find_nextcmd((char *)arg); if (eap->skip) { return; } @@ -3465,7 +3465,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing) char_u *arg = (char_u *)eap->arg; char_u *arg_end; - eap->nextcmd = (char *)find_nextcmd(arg); + eap->nextcmd = find_nextcmd((char *)arg); if (eap->skip) { return; } @@ -4237,7 +4237,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) int prev_syn_inc_tag; bool source = false; - eap->nextcmd = (char *)find_nextcmd((char_u *)arg); + eap->nextcmd = find_nextcmd(arg); if (eap->skip) { return; } @@ -4958,7 +4958,7 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) int opt_len; int list_op; - eap->nextcmd = (char *)find_nextcmd((char_u *)arg); + eap->nextcmd = find_nextcmd(arg); if (eap->skip) { return; } @@ -5042,7 +5042,7 @@ static char *get_syn_pattern(char_u *arg, synpat_T *ci) return NULL; } - end = (char *)skip_regexp(arg + 1, *arg, true, NULL); + end = skip_regexp((char *)arg + 1, *arg, true, NULL); if (*end != (char)(*arg)) { // end delimiter not found semsg(_("E401: Pattern delimiter not found: %s"), arg); return NULL; @@ -5199,7 +5199,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) finished = true; break; } - arg_end = (char *)skip_regexp(next_arg + 1, *next_arg, true, NULL); + arg_end = skip_regexp((char *)next_arg + 1, *next_arg, true, NULL); if (*arg_end != (char)(*next_arg)) { // end delimiter not found illegal = true; break; diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 50121832ba..11825ce1c4 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -1781,7 +1781,7 @@ line_read_in: // encoding to 'encoding'. for (p = lbuf + 20; *p > ' ' && *p < 127; p++) {} *p = NUL; - convert_setup(&vimconv, lbuf + 20, (char_u *)p_enc); + convert_setup(&vimconv, (char *)lbuf + 20, p_enc); } // Read the next line. Unrecognized flags are ignored. @@ -2055,8 +2055,9 @@ parse_line: mtt = MT_GL_OTH; } else { // Decide in which array to store this match. - is_current = test_for_current(tagp.fname, tagp.fname_end, tag_fname, - (char_u *)buf_ffname); + is_current = test_for_current((char *)tagp.fname, (char *)tagp.fname_end, + (char *)tag_fname, + buf_ffname); is_static = test_for_static(&tagp); // Decide in which of the sixteen tables to store this match. @@ -2826,7 +2827,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) */ str = pbuf; if (pbuf[0] == '/' || pbuf[0] == '?') { - str = skip_regexp(pbuf + 1, pbuf[0], false, NULL) + 1; + str = (char_u *)skip_regexp((char *)pbuf + 1, pbuf[0], false, NULL) + 1; } if (str > pbuf_end - 1) { // search command with nothing following save_p_ws = p_ws; @@ -3012,27 +3013,25 @@ static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bo return retval; } -/* - * Check if we have a tag for the buffer with name "buf_ffname". - * This is a bit slow, because of the full path compare in path_full_compare(). - * Return true if tag for file "fname" if tag file "tag_fname" is for current - * file. - */ -static int test_for_current(char_u *fname, char_u *fname_end, char_u *tag_fname, char_u *buf_ffname) +/// Check if we have a tag for the buffer with name "buf_ffname". +/// This is a bit slow, because of the full path compare in path_full_compare(). +/// +/// @return true if tag for file "fname" if tag file "tag_fname" is for current +/// file. +static int test_for_current(char *fname, char *fname_end, char *tag_fname, char *buf_ffname) { int c; int retval = false; - char_u *fullname; if (buf_ffname != NULL) { // if the buffer has a name { - c = *fname_end; + c = (unsigned char)(*fname_end); *fname_end = NUL; } - fullname = expand_tag_fname(fname, tag_fname, true); - retval = (path_full_compare((char *)fullname, (char *)buf_ffname, true, true) & kEqualFiles); + char *fullname = (char *)expand_tag_fname((char_u *)fname, (char_u *)tag_fname, true); + retval = (path_full_compare(fullname, buf_ffname, true, true) & kEqualFiles); xfree(fullname); - *fname_end = (char_u)c; + *fname_end = (char)c; } return retval; @@ -3052,7 +3051,7 @@ static int find_extra(char_u **pp) if (ascii_isdigit(*str)) { str = (char_u *)skipdigits((char *)str + 1); } else if (*str == '/' || *str == '?') { - str = skip_regexp(str + 1, *str, false, NULL); + str = (char_u *)skip_regexp((char *)str + 1, *str, false, NULL); if (*str != first_char) { str = NULL; } else { diff --git a/src/nvim/textformat.c b/src/nvim/textformat.c index b2bfca08ed..125146f712 100644 --- a/src/nvim/textformat.c +++ b/src/nvim/textformat.c @@ -121,7 +121,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on leader_len = get_leader_len((char *)line, NULL, false, true); if (leader_len == 0 && curbuf->b_p_cin) { // Check for a line comment after code. - int comment_start = check_linecomment(line); + int comment_start = check_linecomment((char *)line); if (comment_start != MAXCOL) { leader_len = get_leader_len((char *)line + comment_start, NULL, false, true); if (leader_len != 0) { @@ -411,7 +411,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on // add the additional whitespace needed after the // comment leader for the numbered list. for (int i = 0; i < padding; i++) { - ins_str((char_u *)" "); + ins_str(" "); } changed_bytes(curwin->w_cursor.lnum, leader_len); } else { @@ -1026,7 +1026,7 @@ void format_lines(linenr_T line_count, bool avoid_fex) // paragraph doesn't really end. if (next_leader_flags == NULL || STRNCMP(next_leader_flags, "://", 3) != 0 - || check_linecomment(get_cursor_line_ptr()) == MAXCOL) { + || check_linecomment((char *)get_cursor_line_ptr()) == MAXCOL) { is_end_par = true; } } diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index 834aad2872..ae312de61a 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -127,7 +127,7 @@ char *find_ucmd(exarg_T *eap, char *p, int *full, expand_T *xp, int *complp) for (j = 0; j < gap->ga_len; j++) { uc = USER_CMD_GA(gap, j); cp = eap->cmd; - np = (char *)uc->uc_name; + np = uc->uc_name; k = 0; while (k < len && *np != NUL && *cp++ == *np++) { k++; @@ -167,7 +167,7 @@ char *find_ucmd(exarg_T *eap, char *p, int *full, expand_T *xp, int *complp) } if (xp != NULL) { xp->xp_luaref = uc->uc_compl_luaref; - xp->xp_arg = (char *)uc->uc_compl_arg; + xp->xp_arg = uc->uc_compl_arg; xp->xp_script_ctx = uc->uc_script_ctx; xp->xp_script_ctx.sc_lnum += SOURCING_LNUM; } @@ -272,12 +272,12 @@ char *get_user_commands(expand_T *xp FUNC_ATTR_UNUSED, int idx) const buf_T *const buf = prevwin_curwin()->w_buffer; if (idx < buf->b_ucmds.ga_len) { - return (char *)USER_CMD_GA(&buf->b_ucmds, idx)->uc_name; + return USER_CMD_GA(&buf->b_ucmds, idx)->uc_name; } idx -= buf->b_ucmds.ga_len; if (idx < ucmds.ga_len) { - char *name = (char *)USER_CMD(idx)->uc_name; + char *name = USER_CMD(idx)->uc_name; for (int i = 0; i < buf->b_ucmds.ga_len; i++) { if (STRCMP(name, USER_CMD_GA(&buf->b_ucmds, i)->uc_name) == 0) { @@ -297,14 +297,14 @@ char *get_user_commands(expand_T *xp FUNC_ATTR_UNUSED, int idx) char *get_user_command_name(int idx, int cmdidx) { if (cmdidx == CMD_USER && idx < ucmds.ga_len) { - return (char *)USER_CMD(idx)->uc_name; + return USER_CMD(idx)->uc_name; } if (cmdidx == CMD_USER_BUF) { // In cmdwin, the alternative buffer should be used. const buf_T *const buf = prevwin_curwin()->w_buffer; if (idx < buf->b_ucmds.ga_len) { - return (char *)USER_CMD_GA(&buf->b_ucmds, idx)->uc_name; + return USER_CMD_GA(&buf->b_ucmds, idx)->uc_name; } } return NULL; @@ -434,7 +434,7 @@ static void uc_list(char *name, size_t name_len) msg_putchar(' '); } - msg_outtrans_attr(cmd->uc_name, HL_ATTR(HLF_D)); + msg_outtrans_attr((char_u *)cmd->uc_name, HL_ATTR(HLF_D)); len = (int)STRLEN(cmd->uc_name) + 4; do { @@ -531,7 +531,7 @@ static void uc_list(char *name, size_t name_len) } } - msg_outtrans_special(cmd->uc_rep, false, + msg_outtrans_special((char_u *)cmd->uc_rep, false, name_len == 0 ? Columns - 47 : 0); if (p_verbose > 0) { last_set_msg(cmd->uc_script_ctx); @@ -883,17 +883,17 @@ int uc_add_command(char *name, size_t name_len, const char *rep, uint32_t argt, gap->ga_len++; - cmd->uc_name = (char_u *)p; + cmd->uc_name = p; } - cmd->uc_rep = (char_u *)rep_buf; + cmd->uc_rep = rep_buf; cmd->uc_argt = argt; cmd->uc_def = def; cmd->uc_compl = compl; cmd->uc_script_ctx = current_sctx; cmd->uc_script_ctx.sc_lnum += SOURCING_LNUM; nlua_set_sctx(&cmd->uc_script_ctx); - cmd->uc_compl_arg = (char_u *)compl_arg; + cmd->uc_compl_arg = compl_arg; cmd->uc_compl_luaref = compl_luaref; cmd->uc_preview_luaref = preview_luaref; cmd->uc_addr_type = addr_type; @@ -1569,7 +1569,7 @@ int do_ucmd(exarg_T *eap, bool preview) // Second round: copy result into "buf". buf = NULL; for (;;) { - p = (char *)cmd->uc_rep; // source + p = cmd->uc_rep; // source q = buf; // destination totlen = 0; diff --git a/src/nvim/usercmd.h b/src/nvim/usercmd.h index 637862b216..4d2cf0d9de 100644 --- a/src/nvim/usercmd.h +++ b/src/nvim/usercmd.h @@ -4,14 +4,14 @@ #include "nvim/ex_cmds_defs.h" typedef struct ucmd { - char_u *uc_name; // The command name + char *uc_name; // The command name uint32_t uc_argt; // The argument type - char_u *uc_rep; // The command's replacement string + char *uc_rep; // The command's replacement string long uc_def; // The default value for a range/count int uc_compl; // completion type cmd_addr_T uc_addr_type; // The command's address type sctx_T uc_script_ctx; // SCTX where the command was defined - char_u *uc_compl_arg; // completion argument if any + char *uc_compl_arg; // completion argument if any LuaRef uc_compl_luaref; // Reference to Lua completion function LuaRef uc_preview_luaref; // Reference to Lua preview function LuaRef uc_luaref; // Reference to Lua function diff --git a/src/nvim/version.c b/src/nvim/version.c index 46e3a67388..5888d4614e 100644 --- a/src/nvim/version.c +++ b/src/nvim/version.c @@ -2274,7 +2274,7 @@ void intro_message(int colon) } if (*p != NUL) { - do_intro_line(row, (char_u *)_(p), 0); + do_intro_line(row, _(p), 0); } row++; } @@ -2287,15 +2287,14 @@ void intro_message(int colon) } } -static void do_intro_line(long row, char_u *mesg, int attr) +static void do_intro_line(long row, char *mesg, int attr) { - long col; - char_u *p; + char *p; int l; int clen; // Center the message horizontally. - col = vim_strsize((char *)mesg); + long col = vim_strsize(mesg); col = (Columns - col) / 2; @@ -2310,8 +2309,8 @@ static void do_intro_line(long row, char_u *mesg, int attr) for (l = 0; p[l] != NUL && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); l++) { - clen += ptr2cells((char *)p + l); - l += utfc_ptr2len((char *)p + l) - 1; + clen += ptr2cells(p + l); + l += utfc_ptr2len(p + l) - 1; } assert(row <= INT_MAX && col <= INT_MAX); grid_puts_len(&default_grid, p, l, (int)row, (int)col, diff --git a/src/nvim/window.c b/src/nvim/window.c index 5b8a69f6eb..29b1b05ade 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -215,7 +215,7 @@ newwindow: case Ctrl_Q: case 'q': reset_VIsual_and_resel(); // stop Visual mode - cmd_with_count("quit", (char_u *)cbuf, sizeof(cbuf), Prenum); + cmd_with_count("quit", cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; @@ -223,7 +223,7 @@ newwindow: case Ctrl_C: case 'c': reset_VIsual_and_resel(); // stop Visual mode - cmd_with_count("close", (char_u *)cbuf, sizeof(cbuf), Prenum); + cmd_with_count("close", cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; @@ -256,7 +256,7 @@ newwindow: case 'o': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode - cmd_with_count("only", (char_u *)cbuf, sizeof(cbuf), Prenum); + cmd_with_count("only", cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; @@ -622,12 +622,12 @@ wingotofile: } } -static void cmd_with_count(char *cmd, char_u *bufp, size_t bufsize, int64_t Prenum) +static void cmd_with_count(char *cmd, char *bufp, size_t bufsize, int64_t Prenum) { size_t len = STRLCPY(bufp, cmd, bufsize); if (Prenum > 0 && len < bufsize) { - vim_snprintf((char *)bufp + len, bufsize - len, "%" PRId64, Prenum); + vim_snprintf(bufp + len, bufsize - len, "%" PRId64, Prenum); } } @@ -2082,7 +2082,7 @@ static int get_maximum_wincount(frame_T *fr, int height) void win_equal(win_T *next_curwin, bool current, int dir) { if (dir == 0) { - dir = *p_ead; + dir = (unsigned char)(*p_ead); } win_equal_rec(next_curwin == NULL ? curwin : next_curwin, current, topframe, dir, 0, tabline_height(), -- cgit From efacb6e974fa6391bcc916749103f04fa9b9f6f7 Mon Sep 17 00:00:00 2001 From: Raphael Date: Tue, 30 Aug 2022 01:09:14 +0800 Subject: fix(lsp): clean the diagnostic cache when buffer delete (#19449) Co-authored-by: Gregory Anders --- runtime/lua/vim/diagnostic.lua | 30 ++++++++++++++++++------------ test/functional/lua/diagnostic_spec.lua | 22 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua index 3f71d4f70d..db92085423 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -45,18 +45,24 @@ local bufnr_and_namespace_cacher_mt = { end, } -local diagnostic_cache = setmetatable({}, { - __index = function(t, bufnr) - assert(bufnr > 0, 'Invalid buffer number') - vim.api.nvim_buf_attach(bufnr, false, { - on_detach = function() - rawset(t, bufnr, nil) -- clear cache - end, - }) - t[bufnr] = {} - return t[bufnr] - end, -}) +local diagnostic_cache +do + local group = vim.api.nvim_create_augroup('DiagnosticBufDelete', {}) + diagnostic_cache = setmetatable({}, { + __index = function(t, bufnr) + assert(bufnr > 0, 'Invalid buffer number') + vim.api.nvim_create_autocmd('BufDelete', { + group = group, + buffer = bufnr, + callback = function() + rawset(t, bufnr, nil) + end, + }) + t[bufnr] = {} + return t[bufnr] + end, + }) +end local diagnostic_cache_extmarks = setmetatable({}, bufnr_and_namespace_cacher_mt) local diagnostic_attached_buffers = {} diff --git a/test/functional/lua/diagnostic_spec.lua b/test/functional/lua/diagnostic_spec.lua index f9647f5b6a..4226bcebac 100644 --- a/test/functional/lua/diagnostic_spec.lua +++ b/test/functional/lua/diagnostic_spec.lua @@ -128,6 +128,28 @@ describe('vim.diagnostic', function() eq('Diagnostic #1', result[1].message) end) + it('removes diagnostics from the cache when a buffer is removed', function() + eq(2, exec_lua [[ + vim.api.nvim_win_set_buf(0, diagnostic_bufnr) + local other_bufnr = vim.fn.bufadd('test | test') + local lines = vim.api.nvim_buf_get_lines(diagnostic_bufnr, 0, -1, true) + vim.api.nvim_buf_set_lines(other_bufnr, 0, 1, false, lines) + vim.cmd('bunload! ' .. other_bufnr) + + vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { + make_error('Diagnostic #1', 1, 1, 1, 1), + make_error('Diagnostic #2', 2, 1, 2, 1), + }) + vim.diagnostic.set(diagnostic_ns, other_bufnr, { + make_error('Diagnostic #3', 3, 1, 3, 1), + }) + vim.api.nvim_set_current_buf(other_bufnr) + vim.opt_local.buflisted = true + vim.cmd('bwipeout!') + return #vim.diagnostic.get() + ]]) + end) + it('resolves buffer number 0 to the current buffer', function() eq(2, exec_lua [[ vim.api.nvim_set_current_buf(diagnostic_bufnr) -- cgit From 8fd66ff5c57d29a4349c80d3ae769cde12357ac0 Mon Sep 17 00:00:00 2001 From: bfredl Date: Mon, 29 Aug 2022 21:58:07 +0200 Subject: fix(redraw): handle switching to a tabpage with larger p_ch value --- src/nvim/window.c | 5 +++++ test/functional/legacy/cmdline_spec.lua | 4 +--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/nvim/window.c b/src/nvim/window.c index 29b1b05ade..832cb82bda 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -4343,6 +4343,11 @@ static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, bool trigger_enter_a // Use the stored value of p_ch, so that it can be different for each tab page. if (p_ch != curtab->tp_ch_used) { clear_cmdline = true; + if (msg_grid.chars && p_ch < curtab->tp_ch_used) { + // TODO(bfredl): a bit expensive, should be enough to invalidate the + // region between the old and the new p_ch. + grid_invalidate(&msg_grid); + } } p_ch = curtab->tp_ch_used; diff --git a/test/functional/legacy/cmdline_spec.lua b/test/functional/legacy/cmdline_spec.lua index fb054eed9a..65b46f793d 100644 --- a/test/functional/legacy/cmdline_spec.lua +++ b/test/functional/legacy/cmdline_spec.lua @@ -19,8 +19,6 @@ describe('cmdline', function() [3] = {reverse = true}; [4] = {bold = true, foreground = Screen.colors.Blue1}; } - -- TODO(bfredl): redraw with tabs is severly broken. fix it - feed_command [[ set display-=msgsep ]] feed_command([[call setline(1, range(30))]]) screen:expect([[ @@ -61,7 +59,7 @@ describe('cmdline', function() {4:~ }| | | - :tabnew | + | ]]} feed [[gt]] -- cgit From f58a9795990a3b324f66912e4ae33dae7eb7474d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 30 Aug 2022 06:26:06 +0800 Subject: vim-patch:9.0.0318: clearing screen causes flicker (#19993) Problem: Clearing screen causes flicker. Solution: Do not clear but redraw in more cases. Add () to "wait_return". https://github.com/vim/vim/commit/13608d851a0470ced30921428b3313c023d395d8 Only 2 lines of actual code change. --- src/nvim/ex_cmds.c | 3 ++- src/nvim/ex_cmds2.c | 2 +- src/nvim/ex_docmd.c | 4 ++-- src/nvim/getchar.c | 2 +- src/nvim/if_cscope.c | 2 +- src/nvim/input.c | 2 +- src/nvim/memline.c | 2 +- src/nvim/message.c | 12 ++++++------ src/nvim/option.c | 2 +- src/nvim/os/shell.c | 2 +- 10 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 57eb2f526f..ba6594fd7a 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -1347,7 +1347,8 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b msg_putchar('\n'); // Keep message from buf_write(). no_wait_return--; if (!aborting()) { - semsg(_("E482: Can't create file %s"), itmp); // Will call wait_return. + // will call wait_return() + semsg(_("E482: Can't create file %s"), itmp); } goto filterend; } diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c index 2ed2b5519b..11280eecbb 100644 --- a/src/nvim/ex_cmds2.c +++ b/src/nvim/ex_cmds2.c @@ -364,7 +364,7 @@ bool check_changed_any(bool hidden, bool unload) exiting = false; // When ":confirm" used, don't give an error message. if (!(p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM))) { - // There must be a wait_return for this message, do_buffer() + // There must be a wait_return() for this message, do_buffer() // may cause a redraw. But wait_return() is a no-op when vgetc() // is busy (Quit used from window menu), then make sure we don't // cause a scroll up. diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 3cd4369107..08709ec228 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -516,7 +516,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2, true)) == NULL) { - // Don't call wait_return for aborted command line. The NULL + // Don't call wait_return() for aborted command line. The NULL // returned for the end of a sourced file or executed function // doesn't do this. if (KeyTyped && !(flags & DOCMD_REPEAT)) { @@ -888,7 +888,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) need_wait_return = false; msg_didany = false; // don't wait when restarting edit } else if (need_wait_return) { - // The msg_start() above clears msg_didout. The wait_return we do + // The msg_start() above clears msg_didout. The wait_return() we do // here should not overwrite the command that may be shown before // doing that. msg_didout |= msg_didout_before_start; diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index af3895b793..bb8cd5a1eb 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -1768,7 +1768,7 @@ static void getchar_common(typval_T *argvars, typval_T *rettv) if (!ui_has_messages()) { // redraw the screen after getchar() - update_screen(UPD_CLEAR); + update_screen(UPD_NOT_VALID); } set_vim_var_nr(VV_MOUSE_WIN, 0); diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index 975fa0ca92..2a9d2c357e 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -2035,7 +2035,7 @@ static int cs_show(exarg_T *eap) } } - wait_return(true); + wait_return(false); return CSCOPE_SUCCESS; } diff --git a/src/nvim/input.c b/src/nvim/input.c index 37c2903cfd..0aa9feaca3 100644 --- a/src/nvim/input.c +++ b/src/nvim/input.c @@ -46,7 +46,7 @@ int ask_yesno(const char *const str, const bool direct) int r = ' '; while (r != 'y' && r != 'n') { - // Same highlighting as for wait_return. + // same highlighting as for wait_return() smsg_attr(HL_ATTR(HLF_R), "%s (y/n)?", str); if (direct) { r = get_keystroke(NULL); diff --git a/src/nvim/memline.c b/src/nvim/memline.c index b940040c45..044655ef2b 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -523,7 +523,7 @@ void ml_open_file(buf_T *buf) } if (*p_dir != NUL && mfp->mf_fname == NULL) { - need_wait_return = true; // call wait_return later + need_wait_return = true; // call wait_return() later no_wait_return++; (void)semsg(_("E303: Unable to open swap file for \"%s\", recovery impossible"), buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname); diff --git a/src/nvim/message.c b/src/nvim/message.c index 7b198371c5..4fba78feca 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -215,7 +215,7 @@ void msg_grid_validate(void) /// Displays the string 's' on the status line /// When terminal not initialized (yet) mch_errmsg(..) is used. /// -/// @return true if wait_return not called +/// @return true if wait_return() not called int msg(char *s) { return msg_attr_keep(s, 0, false, false); @@ -745,7 +745,7 @@ static bool emsg_multiline(const char *s, bool multiline) attr = HL_ATTR(HLF_E); // set highlight mode for error messages if (msg_scrolled != 0) { need_wait_return = true; // needed in case emsg() is called after - } // wait_return has reset need_wait_return + } // wait_return() has reset need_wait_return // and a redraw is expected because // msg_scrolled is non-zero if (msg_ext_kind == NULL) { @@ -766,7 +766,7 @@ static bool emsg_multiline(const char *s, bool multiline) /// Rings the bell, if appropriate, and calls message() to do the real work /// When terminal not initialized (yet) mch_errmsg(..) is used. /// -/// @return true if wait_return not called +/// @return true if wait_return() not called bool emsg(const char *s) { return emsg_multiline(s, false); @@ -2243,7 +2243,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs } inc_msg_scrolled(); - need_wait_return = true; // may need wait_return in main() + need_wait_return = true; // may need wait_return() in main() redraw_cmdline = true; if (cmdline_row > 0 && !exmode_active) { cmdline_row--; @@ -3164,9 +3164,9 @@ void msg_clr_cmdline(void) } /// end putting a message on the screen -/// call wait_return if the message does not fit in the available space +/// call wait_return() if the message does not fit in the available space /// -/// @return true if wait_return not called. +/// @return true if wait_return() not called. int msg_end(void) { /* diff --git a/src/nvim/option.c b/src/nvim/option.c index f9b32d50af..455070c742 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1553,7 +1553,7 @@ skip: // make sure all characters are printable trans_characters((char *)IObuff, IOSIZE); - no_wait_return++; // wait_return done later + no_wait_return++; // wait_return() done later emsg((char *)IObuff); // show error highlighted no_wait_return--; diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index 574543b1a5..c8267ede14 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -911,7 +911,7 @@ static int do_os_system(char **argv, const char *input, size_t len, char **outpu out_data_ring(NULL, SIZE_MAX); } if (forward_output) { - // caller should decide if wait_return is invoked + // caller should decide if wait_return() is invoked no_wait_return++; msg_end(); no_wait_return--; -- cgit From 2c83d7b2ddf74966777e3bb72230a3605b92ffe2 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 29 Aug 2022 15:12:30 +0800 Subject: refactor: move cmdline functions to ex_getln.c --- src/nvim/eval/funcs.c | 69 ------------------------ src/nvim/ex_getln.c | 144 +++++++++++++++++++++++++++++++------------------- 2 files changed, 91 insertions(+), 122 deletions(-) diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 0bf3ad6901..c442f5c465 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -2721,40 +2721,6 @@ static void f_getcharsearch(typval_T *argvars, typval_T *rettv, EvalFuncData fpt tv_dict_add_nr(dict, S_LEN("until"), last_csearch_until()); } -/// "getcmdcompltype()" function -static void f_getcmdcompltype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - rettv->v_type = VAR_STRING; - rettv->vval.v_string = (char *)get_cmdline_completion(); -} - -/// "getcmdline()" function -static void f_getcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - rettv->v_type = VAR_STRING; - rettv->vval.v_string = (char *)get_cmdline_str(); -} - -/// "getcmdpos()" function -static void f_getcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - rettv->vval.v_number = get_cmdline_pos() + 1; -} - -/// "getcmdscreenpos()" function -static void f_getcmdscreenpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - rettv->vval.v_number = get_cmdline_screen_pos() + 1; -} - -/// "getcmdtype()" function -static void f_getcmdtype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - rettv->v_type = VAR_STRING; - rettv->vval.v_string = xmallocz(1); - rettv->vval.v_string[0] = (char)get_cmdline_type(); -} - /// "getcmdwintype()" function static void f_getcmdwintype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { @@ -7622,41 +7588,6 @@ static void f_setcharsearch(typval_T *argvars, typval_T *rettv, EvalFuncData fpt } } -/// "setcmdline()" function -static void f_setcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - if (argvars[0].v_type != VAR_STRING || argvars[0].vval.v_string == NULL) { - emsg(_(e_stringreq)); - return; - } - - int pos = -1; - if (argvars[1].v_type != VAR_UNKNOWN) { - bool error = false; - - pos = (int)tv_get_number_chk(&argvars[1], &error) - 1; - if (error) { - return; - } - if (pos < 0) { - emsg(_(e_positive)); - return; - } - } - - rettv->vval.v_number = set_cmdline_str(argvars[0].vval.v_string, pos); -} - -/// "setcmdpos()" function -static void f_setcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) -{ - const int pos = (int)tv_get_number(&argvars[0]) - 1; - - if (pos >= 0) { - rettv->vval.v_number = set_cmdline_pos(pos); - } -} - /// "setcursorcharpos" function static void f_setcursorcharpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index ec2672c675..7dac5fbe7e 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -3933,8 +3933,41 @@ static CmdlineInfo *get_ccline_ptr(void) } } +/// Get the current command-line type. +/// Returns ':' or '/' or '?' or '@' or '>' or '-' +/// Only works when the command line is being edited. +/// Returns NUL when something is wrong. +static int get_cmdline_type(void) +{ + CmdlineInfo *p = get_ccline_ptr(); + + if (p == NULL) { + return NUL; + } + if (p->cmdfirstc == NUL) { + return (p->input_fn) ? '@' : '-'; + } + return p->cmdfirstc; +} + +/// Get the current command line in allocated memory. +/// Only works when the command line is being edited. +/// Returns NULL when something is wrong. +static char_u *get_cmdline_str(void) +{ + if (cmdline_star > 0) { + return NULL; + } + CmdlineInfo *p = get_ccline_ptr(); + + if (p == NULL) { + return NULL; + } + return vim_strnsave(p->cmdbuff, (size_t)p->cmdlen); +} + /// Get the current command-line completion type. -char_u *get_cmdline_completion(void) +static char_u *get_cmdline_completion(void) { if (cmdline_star > 0) { return NULL; @@ -3952,54 +3985,45 @@ char_u *get_cmdline_completion(void) return NULL; } -/* - * Get the current command line in allocated memory. - * Only works when the command line is being edited. - * Returns NULL when something is wrong. - */ -char_u *get_cmdline_str(void) +/// "getcmdcompltype()" function +void f_getcmdcompltype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { - if (cmdline_star > 0) { - return NULL; - } - CmdlineInfo *p = get_ccline_ptr(); + rettv->v_type = VAR_STRING; + rettv->vval.v_string = (char *)get_cmdline_completion(); +} - if (p == NULL) { - return NULL; - } - return vim_strnsave(p->cmdbuff, (size_t)p->cmdlen); +/// "getcmdline()" function +void f_getcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) +{ + rettv->v_type = VAR_STRING; + rettv->vval.v_string = (char *)get_cmdline_str(); } -/* - * Get the current command line position, counted in bytes. - * Zero is the first position. - * Only works when the command line is being edited. - * Returns -1 when something is wrong. - */ -int get_cmdline_pos(void) +/// "getcmdpos()" function +void f_getcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { CmdlineInfo *p = get_ccline_ptr(); - - if (p == NULL) { - return -1; - } - return p->cmdpos; + rettv->vval.v_number = p != NULL ? p->cmdpos + 1 : 0; } -/// Get the command line cursor screen position. -int get_cmdline_screen_pos(void) +/// "getcmdscreenpos()" function +void f_getcmdscreenpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { CmdlineInfo *p = get_ccline_ptr(); + rettv->vval.v_number = p != NULL ? p->cmdspos + 1 : 0; +} - if (p == NULL) { - return -1; - } - return p->cmdspos; +/// "getcmdtype()" function +void f_getcmdtype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) +{ + rettv->v_type = VAR_STRING; + rettv->vval.v_string = xmallocz(1); + rettv->vval.v_string[0] = (char)get_cmdline_type(); } /// Set the command line str to "str". /// @return 1 when failed, 0 when OK. -int set_cmdline_str(const char *str, int pos) +static int set_cmdline_str(const char *str, int pos) { CmdlineInfo *p = get_ccline_ptr(); @@ -4023,12 +4047,10 @@ int set_cmdline_str(const char *str, int pos) return 0; } -/* - * Set the command line byte position to "pos". Zero is the first position. - * Only works when the command line is being edited. - * Returns 1 when failed, 0 when OK. - */ -int set_cmdline_pos(int pos) +/// Set the command line byte position to "pos". Zero is the first position. +/// Only works when the command line is being edited. +/// @return 1 when failed, 0 when OK. +static int set_cmdline_pos(int pos) { CmdlineInfo *p = get_ccline_ptr(); @@ -4046,23 +4068,39 @@ int set_cmdline_pos(int pos) return 0; } -/* - * Get the current command-line type. - * Returns ':' or '/' or '?' or '@' or '>' or '-' - * Only works when the command line is being edited. - * Returns NUL when something is wrong. - */ -int get_cmdline_type(void) +/// "setcmdline()" function +void f_setcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { - CmdlineInfo *p = get_ccline_ptr(); + if (argvars[0].v_type != VAR_STRING || argvars[0].vval.v_string == NULL) { + emsg(_(e_stringreq)); + return; + } - if (p == NULL) { - return NUL; + int pos = -1; + if (argvars[1].v_type != VAR_UNKNOWN) { + bool error = false; + + pos = (int)tv_get_number_chk(&argvars[1], &error) - 1; + if (error) { + return; + } + if (pos < 0) { + emsg(_(e_positive)); + return; + } } - if (p->cmdfirstc == NUL) { - return (p->input_fn) ? '@' : '-'; + + rettv->vval.v_number = set_cmdline_str(argvars[0].vval.v_string, pos); +} + +/// "setcmdpos()" function +void f_setcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) +{ + const int pos = (int)tv_get_number(&argvars[0]) - 1; + + if (pos >= 0) { + rettv->vval.v_number = set_cmdline_pos(pos); } - return p->cmdfirstc; } /// Return the first character of the current command line. -- cgit From e6e9879cb3eecf9d5c3f3964259a89dc36f60d52 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 30 Aug 2022 06:32:14 +0800 Subject: vim-patch:9.0.0320: command line type of CmdlineChange differs from getcmdtype() Problem: Command line type of CmdlineChange differs from getcmdtype(). Solution: Use the same type. (closes vim/vim#11005) https://github.com/vim/vim/commit/54acb90d9e672315e3bd13f8dc71f828df97c868 --- src/nvim/ex_getln.c | 2 +- src/nvim/testdir/test_cmdline.vim | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 7dac5fbe7e..66c3327ce3 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -4042,7 +4042,7 @@ static int set_cmdline_str(const char *str, int pos) redrawcmd(); // Trigger CmdlineChanged autocommands. - do_autocmd_cmdlinechanged(ccline.cmdfirstc == NUL ? '-' : ccline.cmdfirstc); + do_autocmd_cmdlinechanged(get_cmdline_type()); return 0; } diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index a5a30b7953..045504b8bf 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -2187,9 +2187,13 @@ endfunc func Test_setcmdline() func SetText(text, pos) + autocmd CmdlineChanged * let g:cmdtype = expand('') call assert_equal(0, setcmdline(a:text)) call assert_equal(a:text, getcmdline()) call assert_equal(len(a:text) + 1, getcmdpos()) + call assert_equal(getcmdtype(), g:cmdtype) + unlet g:cmdtype + autocmd! CmdlineChanged call assert_equal(0, setcmdline(a:text, a:pos)) call assert_equal(a:text, getcmdline()) @@ -2205,6 +2209,13 @@ func Test_setcmdline() call feedkeys(":\=SetText('set rtp?', 2)\\", 'xt') call assert_equal('set rtp?', @:) + call feedkeys(":let g:str = input('? ')\", 't') + call feedkeys("\=SetText('foo', 4)\\", 'xt') + call assert_equal('foo', g:str) + unlet g:str + + delfunc SetText + " setcmdline() returns 1 when not editing the command line. call assert_equal(1, 'foo'->setcmdline()) @@ -2217,6 +2228,8 @@ func Test_setcmdline() com! -nargs=* -complete=custom,CustomComplete DoCmd : call feedkeys(":DoCmd \\\"\", 'tx') call assert_equal('"DoCmd January February Mars', @:) + delcom DoCmd + delfunc CustomComplete " Called in cnoremap a setcmdline('let foo=') -- cgit From 568737d5b39a4b58cab05d4edc2599653979770c Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 30 Aug 2022 10:55:00 +0800 Subject: feat(tui): recognize sidescroll events (#19992) Ref https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Other-buttons This works in xterm and kitty. CSI < 66 ; x ; y M sequence is for ScrollWheelLeft. CSI < 67 ; x ; y M sequence is for ScrollWheelRight. --- src/nvim/tui/input.c | 15 ++- test/functional/terminal/tui_spec.lua | 193 ++++++++++++++++++++++++++++++++++ 2 files changed, 206 insertions(+), 2 deletions(-) diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index 03cfb830e6..d269878f46 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -398,6 +398,14 @@ static void forward_mouse_event(TermInput *input, TermKeyKey *key) button = last_pressed_button; } + if (ev == TERMKEY_MOUSE_UNKNOWN && !(key->code.mouse[0] & 0x20)) { + int code = key->code.mouse[0] & ~0x3c; + if (code == 66 || code == 67) { + ev = TERMKEY_MOUSE_PRESS; + button = code - 60; + } + } + if (button == 0 || (ev != TERMKEY_MOUSE_PRESS && ev != TERMKEY_MOUSE_DRAG && ev != TERMKEY_MOUSE_RELEASE)) { return; @@ -431,8 +439,11 @@ static void forward_mouse_event(TermInput *input, TermKeyKey *key) if (button == 4) { len += (size_t)snprintf(buf + len, sizeof(buf) - len, "ScrollWheelUp"); } else if (button == 5) { - len += (size_t)snprintf(buf + len, sizeof(buf) - len, - "ScrollWheelDown"); + len += (size_t)snprintf(buf + len, sizeof(buf) - len, "ScrollWheelDown"); + } else if (button == 6) { + len += (size_t)snprintf(buf + len, sizeof(buf) - len, "ScrollWheelLeft"); + } else if (button == 7) { + len += (size_t)snprintf(buf + len, sizeof(buf) - len, "ScrollWheelRight"); } else { len += (size_t)snprintf(buf + len, sizeof(buf) - len, "Mouse"); last_pressed_button = button; diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua index 99f69ef556..4f444316c3 100644 --- a/test/functional/terminal/tui_spec.lua +++ b/test/functional/terminal/tui_spec.lua @@ -297,6 +297,199 @@ describe('TUI', function() ]], attrs) end) + it('accepts mouse wheel events #19992', function() + child_session:request('nvim_command', [[ + set number nostartofline nowrap mousescroll=hor:1,ver:1 + call setline(1, repeat([join(range(10), '----')], 10)) + vsplit + ]]) + screen:expect([[ + {11: 1 }{1:0}----1----2----3----4│{11: 1 }0----1----2----3----| + {11: 2 }0----1----2----3----4│{11: 2 }0----1----2----3----| + {11: 3 }0----1----2----3----4│{11: 3 }0----1----2----3----| + {11: 4 }0----1----2----3----4│{11: 4 }0----1----2----3----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<65;8;1M') + screen:expect([[ + {11: 2 }{1:0}----1----2----3----4│{11: 1 }0----1----2----3----| + {11: 3 }0----1----2----3----4│{11: 2 }0----1----2----3----| + {11: 4 }0----1----2----3----4│{11: 3 }0----1----2----3----| + {11: 5 }0----1----2----3----4│{11: 4 }0----1----2----3----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<65;48;1M') + screen:expect([[ + {11: 2 }{1:0}----1----2----3----4│{11: 2 }0----1----2----3----| + {11: 3 }0----1----2----3----4│{11: 3 }0----1----2----3----| + {11: 4 }0----1----2----3----4│{11: 4 }0----1----2----3----| + {11: 5 }0----1----2----3----4│{11: 5 }0----1----2----3----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<67;8;1M') + screen:expect([[ + {11: 2 }{1:-}---1----2----3----4-│{11: 2 }0----1----2----3----| + {11: 3 }----1----2----3----4-│{11: 3 }0----1----2----3----| + {11: 4 }----1----2----3----4-│{11: 4 }0----1----2----3----| + {11: 5 }----1----2----3----4-│{11: 5 }0----1----2----3----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<67;48;1M') + screen:expect([[ + {11: 2 }{1:-}---1----2----3----4-│{11: 2 }----1----2----3----4| + {11: 3 }----1----2----3----4-│{11: 3 }----1----2----3----4| + {11: 4 }----1----2----3----4-│{11: 4 }----1----2----3----4| + {11: 5 }----1----2----3----4-│{11: 5 }----1----2----3----4| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<69;8;1M') + screen:expect([[ + {11: 5 }{1:-}---1----2----3----4-│{11: 2 }----1----2----3----4| + {11: 6 }----1----2----3----4-│{11: 3 }----1----2----3----4| + {11: 7 }----1----2----3----4-│{11: 4 }----1----2----3----4| + {11: 8 }----1----2----3----4-│{11: 5 }----1----2----3----4| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<69;48;1M') + screen:expect([[ + {11: 5 }{1:-}---1----2----3----4-│{11: 5 }----1----2----3----4| + {11: 6 }----1----2----3----4-│{11: 6 }----1----2----3----4| + {11: 7 }----1----2----3----4-│{11: 7 }----1----2----3----4| + {11: 8 }----1----2----3----4-│{11: 8 }----1----2----3----4| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<71;8;1M') + screen:expect([[ + {11: 5 }{1:-}---6----7----8----9 │{11: 5 }----1----2----3----4| + {11: 6 }----6----7----8----9 │{11: 6 }----1----2----3----4| + {11: 7 }----6----7----8----9 │{11: 7 }----1----2----3----4| + {11: 8 }----6----7----8----9 │{11: 8 }----1----2----3----4| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<71;48;1M') + screen:expect([[ + {11: 5 }{1:-}---6----7----8----9 │{11: 5 }5----6----7----8----| + {11: 6 }----6----7----8----9 │{11: 6 }5----6----7----8----| + {11: 7 }----6----7----8----9 │{11: 7 }5----6----7----8----| + {11: 8 }----6----7----8----9 │{11: 8 }5----6----7----8----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<64;8;1M') + screen:expect([[ + {11: 4 }----6----7----8----9 │{11: 5 }5----6----7----8----| + {11: 5 }{1:-}---6----7----8----9 │{11: 6 }5----6----7----8----| + {11: 6 }----6----7----8----9 │{11: 7 }5----6----7----8----| + {11: 7 }----6----7----8----9 │{11: 8 }5----6----7----8----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<64;48;1M') + screen:expect([[ + {11: 4 }----6----7----8----9 │{11: 4 }5----6----7----8----| + {11: 5 }{1:-}---6----7----8----9 │{11: 5 }5----6----7----8----| + {11: 6 }----6----7----8----9 │{11: 6 }5----6----7----8----| + {11: 7 }----6----7----8----9 │{11: 7 }5----6----7----8----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<66;8;1M') + screen:expect([[ + {11: 4 }5----6----7----8----9│{11: 4 }5----6----7----8----| + {11: 5 }5{1:-}---6----7----8----9│{11: 5 }5----6----7----8----| + {11: 6 }5----6----7----8----9│{11: 6 }5----6----7----8----| + {11: 7 }5----6----7----8----9│{11: 7 }5----6----7----8----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<66;48;1M') + screen:expect([[ + {11: 4 }5----6----7----8----9│{11: 4 }-5----6----7----8---| + {11: 5 }5{1:-}---6----7----8----9│{11: 5 }-5----6----7----8---| + {11: 6 }5----6----7----8----9│{11: 6 }-5----6----7----8---| + {11: 7 }5----6----7----8----9│{11: 7 }-5----6----7----8---| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<68;8;1M') + screen:expect([[ + {11: 1 }5----6----7----8----9│{11: 4 }-5----6----7----8---| + {11: 2 }5----6----7----8----9│{11: 5 }-5----6----7----8---| + {11: 3 }5----6----7----8----9│{11: 6 }-5----6----7----8---| + {11: 4 }5{1:-}---6----7----8----9│{11: 7 }-5----6----7----8---| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<68;48;1M') + screen:expect([[ + {11: 1 }5----6----7----8----9│{11: 1 }-5----6----7----8---| + {11: 2 }5----6----7----8----9│{11: 2 }-5----6----7----8---| + {11: 3 }5----6----7----8----9│{11: 3 }-5----6----7----8---| + {11: 4 }5{1:-}---6----7----8----9│{11: 4 }-5----6----7----8---| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in active window + feed_data('\027[<70;8;1M') + screen:expect([[ + {11: 1 }0----1----2----3----4│{11: 1 }-5----6----7----8---| + {11: 2 }0----1----2----3----4│{11: 2 }-5----6----7----8---| + {11: 3 }0----1----2----3----4│{11: 3 }-5----6----7----8---| + {11: 4 }0----1----2----3----{1:4}│{11: 4 }-5----6----7----8---| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + -- in inactive window + feed_data('\027[<70;48;1M') + screen:expect([[ + {11: 1 }0----1----2----3----4│{11: 1 }0----1----2----3----| + {11: 2 }0----1----2----3----4│{11: 2 }0----1----2----3----| + {11: 3 }0----1----2----3----4│{11: 3 }0----1----2----3----| + {11: 4 }0----1----2----3----{1:4}│{11: 4 }0----1----2----3----| + {5:[No Name] [+] }{1:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]]) + end) + it('accepts keypad keys from kitty keyboard protocol #19180', function() feed_data('i') feed_data(funcs.nr2char(57399)) -- KP_0 -- cgit From 6ab2bf68196292721b71e096f45bfa3dd0192ee0 Mon Sep 17 00:00:00 2001 From: bfredl Date: Mon, 22 Aug 2022 17:29:26 +0200 Subject: fix(highlight): set the window namespace when redrawing statusline --- src/nvim/drawscreen.c | 6 +++++ test/functional/ui/highlight_spec.lua | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/nvim/drawscreen.c b/src/nvim/drawscreen.c index 40dbec8a5b..29ff261461 100644 --- a/src/nvim/drawscreen.c +++ b/src/nvim/drawscreen.c @@ -748,6 +748,8 @@ void show_cursor_info(bool always) if (!always && !redrawing()) { return; } + + win_check_ns_hl(curwin); if ((*p_stl != NUL || *curwin->w_p_stl != NUL) && (curwin->w_status_height || global_stl_height())) { redraw_custom_statusline(curwin); @@ -764,6 +766,7 @@ void show_cursor_info(bool always) maketitle(); } + win_check_ns_hl(NULL); // Redraw the tab pages line if needed. if (redraw_tabline) { draw_tabline(); @@ -2119,10 +2122,13 @@ void redraw_statuslines(void) { FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { if (wp->w_redr_status) { + win_check_ns_hl(wp); win_redr_winbar(wp); win_redr_status(wp); } } + + win_check_ns_hl(NULL); if (redraw_tabline) { draw_tabline(); } diff --git a/test/functional/ui/highlight_spec.lua b/test/functional/ui/highlight_spec.lua index 4e3d62509c..5ffe9ddaad 100644 --- a/test/functional/ui/highlight_spec.lua +++ b/test/functional/ui/highlight_spec.lua @@ -2333,6 +2333,51 @@ describe("'winhighlight' highlight", function() helpers.assert_alive() end) + + it('can redraw statusline on cursor movement', function() + screen:try_resize(40, 8) + exec [[ + set statusline=%f%=%#Background1#%l,%c%V\ %P + split + ]] + insert [[ + some text + more text]] + screen:expect{grid=[[ + some text | + more tex^t | + {0:~ }| + {3:[No Name] }{1:2,9 All}| + some text | + more text | + {4:[No Name] }{1:1,1 All}| + | + ]]} + + command 'set winhl=Background1:Background2' + screen:expect{grid=[[ + some text | + more tex^t | + {0:~ }| + {3:[No Name] }{5:2,9 All}| + some text | + more text | + {4:[No Name] }{1:1,1 All}| + | + ]]} + + feed 'k' + screen:expect{grid=[[ + some tex^t | + more text | + {0:~ }| + {3:[No Name] }{5:1,9 All}| + some text | + more text | + {4:[No Name] }{1:1,1 All}| + | + ]]} + end) end) describe('highlight namespaces', function() -- cgit From 0368ca70c437e82ae4709f8ed9562fb9aaf03c8c Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Tue, 30 Aug 2022 13:14:09 +0200 Subject: docs(lsp): replace formatting_sync example in lsp-faq (#19994) `formatting_sync` is deprecated --- runtime/doc/lsp.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 82d94afdc8..aba5c9a4a0 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -126,13 +126,14 @@ FAQ *lsp-faq* "after/ftplugin/python.vim". - Q: How do I run a request synchronously (e.g. for formatting on file save)? - A: Use the `_sync` variant of the function provided by |lsp-buf|, if it - exists. + A: Check if the function has an `async` parameter and set the value to + false. E.g. code formatting: > " Auto-format *.rs (rust) files prior to saving them - autocmd BufWritePre *.rs lua vim.lsp.buf.formatting_sync(nil, 1000) + " (async = false is the default for format) + autocmd BufWritePre *.rs lua vim.lsp.buf.format({ async = false }) < *lsp-vs-treesitter* -- cgit From 981ae83fadd3bf8603f144a8bc27347e4fb7b3ad Mon Sep 17 00:00:00 2001 From: Mathias Fußenegger Date: Tue, 30 Aug 2022 13:14:27 +0200 Subject: fix(docs): update lsp.rpc.start docs to match return value changes (#20003) Follow up to https://github.com/neovim/neovim/pull/19916 --- runtime/doc/lsp.txt | 7 ++----- runtime/lua/vim/lsp/rpc.lua | 7 ++----- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index aba5c9a4a0..3393a1a1fd 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -1982,11 +1982,8 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) Methods: • `notify()` |vim.lsp.rpc.notify()| • `request()` |vim.lsp.rpc.request()| - - Members: - • {pid} (number) The LSP server's PID. - • {handle} A handle for low-level interaction with the LSP server - process |vim.loop|. + • `is_closing()` returns a boolean indicating if the RPC is closing. + • `terminate()` terminates the RPC client. ============================================================================== diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 238c6c0570..70f838f34d 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -654,11 +654,8 @@ end ---@returns Methods: --- - `notify()` |vim.lsp.rpc.notify()| --- - `request()` |vim.lsp.rpc.request()| ---- ----@returns Members: ---- - {pid} (number) The LSP server's PID. ---- - {handle} A handle for low-level interaction with the LSP server process ---- |vim.loop|. +--- - `is_closing()` returns a boolean indicating if the RPC is closing. +--- - `terminate()` terminates the RPC client. local function start(cmd, cmd_args, dispatchers, extra_spawn_params) local _ = log.info() and log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) -- cgit From 9397e70b9e51ea17c71bd959e337e7e5892d97e1 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 30 Aug 2022 14:46:38 +0200 Subject: docs(lua): present vim.o as default and vim.opt as special-purpose #19982 Problem: People are confused about `vim.o` and `vim.opt` Solution: Clarify that `vim.o` is the default interface, with `vim.opt` specifically meant for interacting with list-style options. --- runtime/doc/lua.txt | 218 ++++++++++++++++++++++++++++------------------------ 1 file changed, 116 insertions(+), 102 deletions(-) diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 28d5605c2d..499b3f9a6f 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -1091,17 +1091,13 @@ vim.env *vim.env* print(vim.env.TERM) < + *lua-options* *lua-vim-options* - *lua-vim-opt* *lua-vim-set* - *lua-vim-optlocal* *lua-vim-setlocal* -In Vimscript, there is a way to set options |set-option|. In Lua, the -corresponding method is `vim.opt`. - -`vim.opt` provides several conveniences for setting and controlling options -from within Lua. +Vim options can be accessed through |vim.o|, which behaves like Vimscript +|:set|. Examples: ~ @@ -1110,62 +1106,145 @@ from within Lua. `set number` In Lua: - `vim.opt.number = true` + `vim.o.number = true` - To set an array of values: + To set a string value: In Vimscript: `set wildignore=*.o,*.a,__pycache__` - In Lua, there are two ways you can do this now. One is very similar to - the Vimscript form: - `vim.opt.wildignore = '*.o,*.a,__pycache__'` + In Lua: + `vim.o.wildignore = '*.o,*.a,__pycache__'` + +Similarly, there exist |vim.bo| and |vim.wo| for setting buffer-local and +window-local options, respectively, similarly to |:setlocal|. There is also +|vim.go| that only sets the global value of a |global-local| option, see +|:setglobal|. The following table summarizes this relation. + + lua command global_value local_value ~ +vim.o :set set set +vim.bo/vim.wo :setlocal - set +vim.go :setglobal set - + + +vim.o *vim.o* + Get or set editor options, like |:set|. Invalid key is an error. + + Example: > + vim.o.cmdheight = 4 + print(vim.o.columns) + print(vim.o.foo) -- error: invalid key +< +vim.go *vim.go* + Get or set an |option|. Invalid key is an error. + + This is a wrapper around |nvim_set_option_value()| and + |nvim_get_option_value()|. + + NOTE: This is different from |vim.o| because this ONLY sets the global + option, which generally produces confusing behavior for options with + |global-local| values. + + Example: > + vim.go.cmdheight = 4 + print(vim.go.columns) + print(vim.go.bar) -- error: invalid key +< +vim.bo[{bufnr}] *vim.bo* + Get or set buffer-scoped |local-options| for the buffer with number {bufnr}. + If [{bufnr}] is omitted, use the current buffer. Invalid {bufnr} or key is + an error. - However, vim.opt also supports a more elegent way of setting - list-style options by using lua tables: + This is a wrapper around |nvim_set_option_value()| and + |nvim_get_option_value()| with `opts = {scope = local, buf = bufnr}` . + + Example: > + local bufnr = vim.api.nvim_get_current_buf() + vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true + print(vim.bo.comments) + print(vim.bo.baz) -- error: invalid key +< +vim.wo[{winid}] *vim.wo* + Get or set window-scoped |local-options| for the window with handle {winid}. + If [{winid}] is omitted, use the current window. Invalid {winid} or key + is an error. + + This is a wrapper around |nvim_set_option_value()| and + |nvim_get_option_value()| with `opts = {scope = local, win = winid}` . + + Example: > + local winid = vim.api.nvim_get_current_win() + vim.wo[winid].number = true -- same as vim.wo.number = true + print(vim.wo.foldmarker) + print(vim.wo.quux) -- error: invalid key +< + + + + *lua-vim-opt* + *lua-vim-optlocal* + *lua-vim-optglobal* + *vim.opt* + + +A special interface |vim.opt| exists for conveniently interacting with list- +and map-style option from Lua: It allows accessing them as Lua tables and +offers object-oriented method for adding and removing entries. + + Examples: ~ + + The following methods of setting a list-style option are equivalent: + In Vimscript: + `set wildignore=*.o,*.a,__pycache__` + + In Lua using `vim.o`: + `vim.o.wildignore = '*.o,*.a,__pycache__'` + + In Lua using `vim.opt`: `vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }` To replicate the behavior of |:set+=|, use: > - -- vim.opt supports appending options via the "+" operator - vim.opt.wildignore = vim.opt.wildignore + { "*.pyc", "node_modules" } - - -- or using the `:append(...)` method vim.opt.wildignore:append { "*.pyc", "node_modules" } < To replicate the behavior of |:set^=|, use: > - -- vim.opt supports prepending options via the "^" operator - vim.opt.wildignore = vim.opt.wildignore ^ { "new_first_value" } - - -- or using the `:prepend(...)` method vim.opt.wildignore:prepend { "new_first_value" } < To replicate the behavior of |:set-=|, use: > - -- vim.opt supports removing options via the "-" operator - vim.opt.wildignore = vim.opt.wildignore - { "node_modules" } - - -- or using the `:remove(...)` method vim.opt.wildignore:remove { "node_modules" } < - To set a map of values: + The following methods of setting a map-style option are equivalent: In Vimscript: `set listchars=space:_,tab:>~` - In Lua: + In Lua using `vim.o`: + `vim.o.listchars = 'space:_,tab:>~'` + + In Lua using `vim.opt`: `vim.opt.listchars = { space = '_', tab = '>~' }` +Note that |vim.opt| returns an `Option` object, not the value of the option, +which is accessed through |Option:get()|: + + Examples: ~ + + The following methods of getting a list-style option are equivalent: + In Vimscript: + `echo wildignore` + + In Lua using `vim.o`: + `print(vim.o.wildignore)` + + In Lua using `vim.opt`: + `vim.pretty_print(vim.opt.wildignore:get())` + + In any of the above examples, to replicate the behavior |setlocal|, use `vim.opt_local`. Additionally, to replicate the behavior of |setglobal|, use `vim.opt_global`. - *vim.opt* - -|vim.opt| returns an Option object. - -For example: `local listchar_object = vim.opt.listchars` -An `Option` has the following methods: *vim.opt:get()* @@ -1178,7 +1257,7 @@ Option:get() the values as entries in the array: > vim.cmd [[set wildignore=*.pyc,*.o]] - print(vim.inspect(vim.opt.wildignore:get())) + vim.pretty_print(vim.opt.wildignore:get()) -- { "*.pyc", "*.o", } for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do @@ -1191,7 +1270,7 @@ Option:get() the names as keys and the values as entries: > vim.cmd [[set listchars=space:_,tab:>~]] - print(vim.inspect(vim.opt.listchars:get())) + vim.pretty_print(vim.opt.listchars:get()) -- { space = "_", tab = ">~", } for char, representation in pairs(vim.opt.listchars:get()) do @@ -1202,7 +1281,7 @@ Option:get() as keys and `true` as entries. > vim.cmd [[set formatoptions=njtcroql]] - print(vim.inspect(vim.opt.formatoptions:get())) + vim.pretty_print(vim.opt.formatoptions:get()) -- { n = true, j = true, c = true, ... } local format_opts = vim.opt.formatoptions:get() @@ -1238,71 +1317,6 @@ Option:remove(value) `vim.opt.wildignore = vim.opt.wildignore - '*.pyc'` -In general, using `vim.opt` will provide the expected result when the user is -used to interacting with editor |options| via `set`. There are still times -where the user may want to set particular options via a shorthand in Lua, -which is where |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| come into play. - -The behavior of |vim.o|, |vim.bo|, |vim.wo|, and |vim.go| is designed to -follow that of |:set|, |:setlocal|, and |:setglobal| which can be seen in the -table below: - - lua command global_value local_value ~ -vim.o :set set set -vim.bo/vim.wo :setlocal - set -vim.go :setglobal set - - -vim.o *vim.o* - Get or set editor options, like |:set|. Invalid key is an error. - - Example: > - vim.o.cmdheight = 4 - print(vim.o.columns) - print(vim.o.foo) -- error: invalid key -< -vim.go *vim.go* - Get or set an |option|. Invalid key is an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()|. - - NOTE: This is different from |vim.o| because this ONLY sets the global - option, which generally produces confusing behavior for options with - |global-local| values. - - Example: > - vim.go.cmdheight = 4 - print(vim.go.columns) - print(vim.go.bar) -- error: invalid key -< -vim.bo[{bufnr}] *vim.bo* - Get or set buffer-scoped |local-options| for the buffer with number {bufnr}. - If [{bufnr}] is omitted, use the current buffer. Invalid {bufnr} or key is - an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()| with `opts = {scope = local, buf = bufnr}` . - - Example: > - local bufnr = vim.api.nvim_get_current_buf() - vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true - print(vim.bo.comments) - print(vim.bo.baz) -- error: invalid key -< -vim.wo[{winid}] *vim.wo* - Get or set window-scoped |local-options| for the window with handle {winid}. - If [{winid}] is omitted, use the current window. Invalid {winid} or key - is an error. - - This is a wrapper around |nvim_set_option_value()| and - |nvim_get_option_value()| with `opts = {scope = local, win = winid}` . - - Example: > - local winid = vim.api.nvim_get_current_win() - vim.wo[winid].number = true -- same as vim.wo.number = true - print(vim.wo.foldmarker) - print(vim.wo.quux) -- error: invalid key -< ============================================================================== Lua module: vim *lua-vim* -- cgit From 2828aae7b49921380f229ebf4d7432f39c6c2c2b Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Tue, 30 Aug 2022 14:52:09 +0200 Subject: refactor: replace char_u with char 4 (#19987) * refactor: replace char_u with char Work on https://github.com/neovim/neovim/issues/459 --- src/nvim/change.c | 4 +- src/nvim/charset.c | 49 ++++---- src/nvim/cmdexpand.c | 32 ++--- src/nvim/debugger.c | 12 +- src/nvim/digraph.c | 8 +- src/nvim/drawline.c | 4 +- src/nvim/edit.c | 12 +- src/nvim/eval.c | 16 +-- src/nvim/eval/executor.c | 3 +- src/nvim/eval/funcs.c | 28 ++--- src/nvim/eval/typval.c | 2 +- src/nvim/eval/userfunc.c | 39 +++--- src/nvim/eval/vars.c | 9 +- src/nvim/ex_cmds.c | 11 +- src/nvim/ex_docmd.c | 19 ++- src/nvim/ex_eval.c | 4 +- src/nvim/ex_getln.c | 4 +- src/nvim/ex_session.c | 2 +- src/nvim/file_search.c | 12 +- src/nvim/fileio.c | 12 +- src/nvim/getchar.c | 4 +- src/nvim/globals.h | 2 +- src/nvim/hardcopy.c | 3 +- src/nvim/help.c | 10 +- src/nvim/highlight_group.c | 20 +-- src/nvim/if_cscope.c | 4 +- src/nvim/indent_c.c | 4 +- src/nvim/insexpand.c | 4 +- src/nvim/locale.c | 2 +- src/nvim/log.c | 4 +- src/nvim/lua/stdlib.c | 2 +- src/nvim/main.c | 4 +- src/nvim/mark.c | 6 +- src/nvim/match.c | 2 +- src/nvim/mbyte.c | 18 ++- src/nvim/memline.c | 10 +- src/nvim/menu.c | 2 +- src/nvim/message.c | 55 +++++---- src/nvim/normal.c | 8 +- src/nvim/ops.c | 10 +- src/nvim/os/env.c | 6 +- src/nvim/os/fs.c | 8 +- src/nvim/os/shell.c | 4 +- src/nvim/path.c | 32 ++--- src/nvim/plines.c | 4 +- src/nvim/popupmenu.c | 2 +- src/nvim/profile.c | 8 +- src/nvim/quickfix.c | 6 +- src/nvim/runtime.c | 277 +++++++++++++++++++++--------------------- src/nvim/runtime.h | 2 +- src/nvim/screen.c | 2 +- src/nvim/search.c | 8 +- src/nvim/shada.c | 2 +- src/nvim/sign.c | 20 +-- src/nvim/spell.c | 22 ++-- src/nvim/spell_defs.h | 6 +- src/nvim/spellfile.c | 24 ++-- src/nvim/spellsuggest.c | 14 +-- src/nvim/strings.c | 16 ++- src/nvim/syntax.c | 28 ++--- src/nvim/tag.c | 38 +++--- src/nvim/undo.c | 2 +- src/nvim/usercmd.c | 8 +- src/nvim/vim.h | 5 +- src/nvim/viml/parser/parser.h | 4 +- src/nvim/window.c | 4 +- 66 files changed, 499 insertions(+), 509 deletions(-) diff --git a/src/nvim/change.c b/src/nvim/change.c index fd079f8eef..85ab92e49b 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -653,9 +653,9 @@ void ins_char_bytes(char *buf, size_t charlen) // cells. May result in adding spaces to fill a gap. colnr_T vcol; getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL); - colnr_T new_vcol = vcol + win_chartabsize(curwin, (char *)buf, vcol); + colnr_T new_vcol = vcol + win_chartabsize(curwin, buf, vcol); while (oldp[col + oldlen] != NUL && vcol < new_vcol) { - vcol += win_chartabsize(curwin, (char *)oldp + col + oldlen, vcol); + vcol += win_chartabsize(curwin, oldp + col + oldlen, vcol); // Don't need to remove a TAB that takes us to the right // position. if (vcol > new_vcol && oldp[col + oldlen] == TAB) { diff --git a/src/nvim/charset.c b/src/nvim/charset.c index 2632279565..4efd8a4ad1 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -1157,7 +1157,7 @@ char *skipwhite(const char *const p) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { - return (char *)skipwhite_len((char_u *)p, STRLEN(p)); + return skipwhite_len(p, STRLEN(p)); } /// Like `skipwhite`, but skip up to `len` characters. @@ -1168,27 +1168,27 @@ char *skipwhite(const char *const p) /// /// @return Pointer to character after the skipped whitespace, or the `len`-th /// character in the string. -char_u *skipwhite_len(const char_u *p, size_t len) +char *skipwhite_len(const char *p, size_t len) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { for (; len > 0 && ascii_iswhite(*p); len--) { p++; } - return (char_u *)p; + return (char *)p; } // getwhitecols: return the number of whitespace // columns (bytes) at the start of a given line intptr_t getwhitecols_curline(void) { - return getwhitecols(get_cursor_line_ptr()); + return getwhitecols((char *)get_cursor_line_ptr()); } -intptr_t getwhitecols(const char_u *p) +intptr_t getwhitecols(const char *p) FUNC_ATTR_PURE { - return (char_u *)skipwhite((char *)p) - p; + return skipwhite(p) - p; } /// Skip over digits @@ -1232,10 +1232,10 @@ const char *skipbin(const char *q) /// /// @return Pointer to the character after the skipped digits and hex /// characters. -char_u *skiphex(char_u *q) +char *skiphex(char *q) FUNC_ATTR_PURE { - char_u *p = q; + char *p = q; while (ascii_isxdigit(*p)) { // skip to next non-digit p++; @@ -1248,10 +1248,10 @@ char_u *skiphex(char_u *q) /// @param q /// /// @return Pointer to the digit or (NUL after the string). -char_u *skiptodigit(char_u *q) +char *skiptodigit(char *q) FUNC_ATTR_PURE { - char_u *p = q; + char *p = q; while (*p != NUL && !ascii_isdigit(*p)) { // skip to next digit p++; @@ -1282,10 +1282,10 @@ const char *skiptobin(const char *q) /// @param q /// /// @return Pointer to the hex character or (NUL after the string). -char_u *skiptohex(char_u *q) +char *skiptohex(char *q) FUNC_ATTR_PURE { - char_u *p = q; + char *p = q; while (*p != NUL && !ascii_isxdigit(*p)) { // skip to next digit p++; @@ -1298,13 +1298,13 @@ char_u *skiptohex(char_u *q) /// @param[in] p Text to skip over. /// /// @return Pointer to the next whitespace or NUL character. -char_u *skiptowhite(const char_u *p) +char *skiptowhite(const char *p) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE { while (*p != ' ' && *p != '\t' && *p != NUL) { p++; } - return (char_u *)p; + return (char *)p; } /// skiptowhite_esc: Like skiptowhite(), but also skip escaped chars @@ -1329,11 +1329,11 @@ char *skiptowhite_esc(char *p) /// @param[in] p Text to skip over. /// /// @return Pointer to the next '\n' or NUL character. -char_u *skip_to_newline(const char_u *const p) +char *skip_to_newline(const char *const p) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { - return (char_u *)xstrchrnul((const char *)p, NL); + return xstrchrnul(p, NL); } /// Gets a number from a string and skips over it, signalling overflow. @@ -1422,10 +1422,10 @@ int32_t getdigits_int32(char **pp, bool strict, long def) /// Check that "lbuf" is empty or only contains blanks. /// /// @param lbuf line buffer to check -bool vim_isblankline(char_u *lbuf) +bool vim_isblankline(char *lbuf) FUNC_ATTR_PURE { - char_u *p = (char_u *)skipwhite((char *)lbuf); + char *p = skipwhite(lbuf); return *p == NUL || *p == '\r' || *p == '\n'; } @@ -1664,8 +1664,9 @@ int hex2nr(int c) } /// Convert two hex characters to a byte. -/// Return -1 if one of the characters is not hex. -int hexhex2nr(const char_u *p) +/// +/// @return -1 if one of the characters is not hex. +int hexhex2nr(const char *p) FUNC_ATTR_PURE { if (!ascii_isxdigit(p[0]) || !ascii_isxdigit(p[1])) { @@ -1707,10 +1708,10 @@ bool rem_backslash(const char *str) /// Halve the number of backslashes in a file name argument. /// /// @param p -void backslash_halve(char_u *p) +void backslash_halve(char *p) { for (; *p; p++) { - if (rem_backslash((char *)p)) { + if (rem_backslash(p)) { STRMOVE(p, p + 1); } } @@ -1721,11 +1722,11 @@ void backslash_halve(char_u *p) /// @param p /// /// @return String with the number of backslashes halved. -char_u *backslash_halve_save(const char_u *p) +char *backslash_halve_save(const char *p) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { // TODO(philix): simplify and improve backslash_halve_save algorithm - char_u *res = vim_strsave(p); + char *res = xstrdup(p); backslash_halve(res); return res; } diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index dbf169c801..5c54404aab 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -387,7 +387,7 @@ static char_u *ExpandOne_start(int mode, expand_T *xp, char_u *str, int options) } /// Return the longest common part in the list of cmdline completion matches. -static char_u *find_longest_match(expand_T *xp, int options) +static char *find_longest_match(expand_T *xp, int options) { size_t len = 0; @@ -417,7 +417,7 @@ static char_u *find_longest_match(expand_T *xp, int options) } } - return (char_u *)xstrndup(xp->xp_files[0], len); + return xstrndup(xp->xp_files[0], len); } /// Do wildcard expansion on the string 'str'. @@ -500,7 +500,7 @@ char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode // Find longest common part if (mode == WILD_LONGEST && xp->xp_numfiles > 0) { - ss = find_longest_match(xp, options); + ss = (char_u *)find_longest_match(xp, options); findex = -1; // next p_wc gets first one } @@ -670,7 +670,7 @@ int showmatches(expand_T *xp, int wildmenu) lastlen = 999; for (k = i; k < num_files; k += lines) { if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - msg_outtrans_attr((char_u *)files_found[k], HL_ATTR(HLF_D)); + msg_outtrans_attr(files_found[k], HL_ATTR(HLF_D)); p = (char_u *)files_found[k] + STRLEN(files_found[k]) + 1; msg_advance(maxlen + 1); msg_puts((const char *)p); @@ -691,15 +691,15 @@ int showmatches(expand_T *xp, int wildmenu) // $HOME has been replaced with ~/. char_u *exp_path = expand_env_save_opt((char_u *)files_found[k], true); char_u *path = exp_path != NULL ? exp_path : (char_u *)files_found[k]; - char_u *halved_slash = backslash_halve_save(path); - j = os_isdir(halved_slash); + char_u *halved_slash = (char_u *)backslash_halve_save((char *)path); + j = os_isdir((char *)halved_slash); xfree(exp_path); if (halved_slash != path) { xfree(halved_slash); } } else { // Expansion was done here, file names are literal. - j = os_isdir((char_u *)files_found[k]); + j = os_isdir(files_found[k]); } if (showtail) { p = (char_u *)L_SHOWFILE(k); @@ -711,7 +711,7 @@ int showmatches(expand_T *xp, int wildmenu) j = false; p = (char_u *)L_SHOWFILE(k); } - lastlen = msg_outtrans_attr(p, j ? attr : 0); + lastlen = msg_outtrans_attr((char *)p, j ? attr : 0); } if (msg_col > 0) { // when not wrapped around msg_clr_eos(); @@ -1239,7 +1239,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons if (*arg == NUL || !ends_excmd(*arg)) { // also complete "None" set_context_in_echohl_cmd(xp, arg); - arg = (const char *)skipwhite((char *)skiptowhite((const char_u *)arg)); + arg = (const char *)skipwhite(skiptowhite(arg)); if (*arg != NUL) { xp->xp_context = EXPAND_NOTHING; arg = (const char *)skip_regexp((char *)arg + 1, (uint8_t)(*arg), p_magic, NULL); @@ -1592,7 +1592,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons #ifdef HAVE_WORKING_LIBINTL case CMD_language: - p = (const char *)skiptowhite((const char_u *)arg); + p = (const char *)skiptowhite(arg); if (*p == NUL) { xp->xp_context = EXPAND_LANGUAGE; xp->xp_pattern = (char *)arg; @@ -2161,19 +2161,19 @@ static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char ***f } if (xp->xp_context == EXPAND_COLORS) { char *directories[] = { "colors", NULL }; - return ExpandRTDir(pat, DIP_START + DIP_OPT + DIP_LUA, num_file, file, directories); + return ExpandRTDir((char *)pat, DIP_START + DIP_OPT + DIP_LUA, num_file, file, directories); } if (xp->xp_context == EXPAND_COMPILER) { char *directories[] = { "compiler", NULL }; - return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); + return ExpandRTDir((char *)pat, DIP_LUA, num_file, file, directories); } if (xp->xp_context == EXPAND_OWNSYNTAX) { char *directories[] = { "syntax", NULL }; - return ExpandRTDir(pat, 0, num_file, file, directories); + return ExpandRTDir((char *)pat, 0, num_file, file, directories); } if (xp->xp_context == EXPAND_FILETYPE) { char *directories[] = { "syntax", "indent", "ftplugin", NULL }; - return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); + return ExpandRTDir((char *)pat, DIP_LUA, num_file, file, directories); } if (xp->xp_context == EXPAND_USER_LIST) { return ExpandUserList(xp, num_file, file); @@ -2182,7 +2182,7 @@ static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char ***f return ExpandUserLua(xp, num_file, file); } if (xp->xp_context == EXPAND_PACKADD) { - return ExpandPackAddDir(pat, num_file, file); + return ExpandPackAddDir((char *)pat, num_file, file); } // When expanding a function name starting with s:, match the nr_ @@ -2573,7 +2573,7 @@ static int ExpandUserLua(expand_T *xp, int *num_file, char ***file) /// Expand `file` for all comma-separated directories in `path`. /// Adds matches to `ga`. -void globpath(char *path, char_u *file, garray_T *ga, int expand_options) +void globpath(char *path, char *file, garray_T *ga, int expand_options) { expand_T xpc; ExpandInit(&xpc); diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c index 9fdeebf68a..36df62b502 100644 --- a/src/nvim/debugger.c +++ b/src/nvim/debugger.c @@ -718,9 +718,9 @@ void ex_breaklist(exarg_T *eap) /// @param file true for a file, false for a function /// @param fname file or function name /// @param after after this line number -linenr_T dbg_find_breakpoint(bool file, char_u *fname, linenr_T after) +linenr_T dbg_find_breakpoint(bool file, char *fname, linenr_T after) { - return debuggy_find(file, fname, after, &dbg_breakp, NULL); + return debuggy_find(file, (char_u *)fname, after, &dbg_breakp, NULL); } /// @param file true for a file, false for a function @@ -728,9 +728,9 @@ linenr_T dbg_find_breakpoint(bool file, char_u *fname, linenr_T after) /// @param fp[out] forceit /// /// @returns true if profiling is on for a function or sourced file. -bool has_profiling(bool file, char_u *fname, bool *fp) +bool has_profiling(bool file, char *fname, bool *fp) { - return debuggy_find(file, fname, (linenr_T)0, &prof_ga, fp) + return debuggy_find(file, (char_u *)fname, (linenr_T)0, &prof_ga, fp) != (linenr_T)0; } @@ -825,9 +825,9 @@ static linenr_T debuggy_find(bool file, char_u *fname, linenr_T after, garray_T } /// Called when a breakpoint was encountered. -void dbg_breakpoint(char_u *name, linenr_T lnum) +void dbg_breakpoint(char *name, linenr_T lnum) { // We need to check if this line is actually executed in do_one_cmd() - debug_breakpoint_name = name; + debug_breakpoint_name = (char_u *)name; debug_breakpoint_lnum = lnum; } diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c index de2dd09d1c..e4528f9038 100644 --- a/src/nvim/digraph.c +++ b/src/nvim/digraph.c @@ -1695,7 +1695,7 @@ static void digraph_header(const char *msg) if (msg_col > 0) { msg_putchar('\n'); } - msg_outtrans_attr((const char_u *)msg, HL_ATTR(HLF_CM)); + msg_outtrans_attr(msg, HL_ATTR(HLF_CM)); msg_putchar('\n'); } @@ -1856,7 +1856,7 @@ static void printdigraph(const digr_T *dp, result_T *previous) p += utf_char2bytes(dp->result, (char *)p); *p = NUL; - msg_outtrans_attr(buf, HL_ATTR(HLF_8)); + msg_outtrans_attr((char *)buf, HL_ATTR(HLF_8)); p = buf; if (char2cells(dp->result) == 1) { *p++ = ' '; @@ -2096,10 +2096,10 @@ void ex_loadkeymap(exarg_T *eap) if ((*p != '"') && (*p != NUL)) { kmap_T *kp = GA_APPEND_VIA_PTR(kmap_T, &curbuf->b_kmap_ga); - s = skiptowhite(p); + s = (char_u *)skiptowhite((char *)p); kp->from = vim_strnsave(p, (size_t)(s - p)); p = (char_u *)skipwhite((char *)s); - s = skiptowhite(p); + s = (char_u *)skiptowhite((char *)p); kp->to = vim_strnsave(p, (size_t)(s - p)); if ((STRLEN(kp->from) + STRLEN(kp->to) >= KMAP_LLEN) diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index b6654699d8..b6c4400c60 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -870,7 +870,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, if (has_spell && !number_only) { // For checking first word with a capital skip white space. if (cap_col == 0) { - cap_col = (int)getwhitecols(line); + cap_col = (int)getwhitecols((char *)line); } // To be able to spell-check over line boundaries copy the end of the @@ -1171,7 +1171,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, if (wp->w_p_rl) { // reverse line numbers // like rl_mirror(), but keep the space at the end char_u *p2 = (char_u *)skipwhite((char *)extra); - p2 = skiptowhite(p2) - 1; + p2 = (char_u *)skiptowhite((char *)p2) - 1; for (char_u *p1 = (char_u *)skipwhite((char *)extra); p1 < p2; p1++, p2--) { const char_u t = *p1; *p1 = *p2; diff --git a/src/nvim/edit.c b/src/nvim/edit.c index b0174de01f..aee8389900 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -2698,12 +2698,12 @@ int cursor_down(long n, int upd_topline) /// @param no_esc Don't add an ESC at the end int stuff_inserted(int c, long count, int no_esc) { - char_u *esc_ptr; - char_u *ptr; - char_u *last_ptr; - char_u last = NUL; + char *esc_ptr; + char *ptr; + char *last_ptr; + char last = NUL; - ptr = get_last_insert(); + ptr = (char *)get_last_insert(); if (ptr == NULL) { emsg(_(e_noinstext)); return FAIL; @@ -2713,7 +2713,7 @@ int stuff_inserted(int c, long count, int no_esc) if (c != NUL) { stuffcharReadbuff(c); } - if ((esc_ptr = STRRCHR(ptr, ESC)) != NULL) { + if ((esc_ptr = strrchr(ptr, ESC)) != NULL) { // remove the ESC. *esc_ptr = NUL; } diff --git a/src/nvim/eval.c b/src/nvim/eval.c index f89b06843a..508d7cf491 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -2042,7 +2042,7 @@ void set_context_for_expression(expand_T *xp, char *arg, cmdidx_T cmdidx) || cmdidx == CMD_echomsg) && xp->xp_context == EXPAND_EXPRESSION) { for (;;) { - char *const n = (char *)skiptowhite((char_u *)arg); + char *const n = skiptowhite(arg); if (n == arg || ascii_iswhite_or_nul(*skipwhite(n))) { break; @@ -2658,7 +2658,7 @@ static int eval5(char **arg, typval_T *rettv, int evaluate) tv_clear(&var2); return FAIL; } - p = (char *)concat_str((const char_u *)s1, (const char_u *)s2); + p = concat_str(s1, s2); tv_clear(rettv); rettv->v_type = VAR_STRING; rettv->vval.v_string = p; @@ -7400,7 +7400,7 @@ hashtab_T *find_var_ht_dict(const char *name, const size_t name_len, const char bool should_free; // should_free is ignored as script_sctx will be resolved to a fnmae // & new_script_item will consume it. - char *sc_name = (char *)get_scriptname(last_set, &should_free); + char *sc_name = get_scriptname(last_set, &should_free); new_script_item(sc_name, ¤t_sctx.sc_sid); } } @@ -7527,9 +7527,9 @@ int var_item_copy(const vimconv_T *const conv, typval_T *const from, typval_T *c } else { to->v_type = VAR_STRING; to->v_lock = VAR_UNLOCKED; - if ((to->vval.v_string = (char *)string_convert((vimconv_T *)conv, - (char_u *)from->vval.v_string, - NULL)) + if ((to->vval.v_string = string_convert((vimconv_T *)conv, + from->vval.v_string, + NULL)) == NULL) { to->vval.v_string = xstrdup(from->vval.v_string); } @@ -7980,7 +7980,7 @@ void option_last_set_msg(LastSet last_set) { if (last_set.script_ctx.sc_sid != 0) { bool should_free; - char *p = (char *)get_scriptname(last_set, &should_free); + char *p = get_scriptname(last_set, &should_free); verbose_enter(); msg_puts(_("\n\tLast set from ")); msg_puts(p); @@ -8077,7 +8077,7 @@ repeat: } // Append a path separator to a directory. - if (os_isdir((char_u *)(*fnamep))) { + if (os_isdir(*fnamep)) { // Make room for one or two extra characters. *fnamep = xstrnsave(*fnamep, STRLEN(*fnamep) + 2); xfree(*bufp); // free any allocated file name diff --git a/src/nvim/eval/executor.c b/src/nvim/eval/executor.c index b461456a3a..0e0d0fe696 100644 --- a/src/nvim/eval/executor.c +++ b/src/nvim/eval/executor.c @@ -108,8 +108,7 @@ int eexe_mod_op(typval_T *const tv1, const typval_T *const tv2, const char *cons const char *tvs = tv_get_string(tv1); char numbuf[NUMBUFLEN]; char *const s = - (char *)concat_str((const char_u *)tvs, (const char_u *)tv_get_string_buf(tv2, - numbuf)); + concat_str(tvs, tv_get_string_buf(tv2, numbuf)); tv_clear(tv1); tv1->v_type = VAR_STRING; tv1->vval.v_string = s; diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index c442f5c465..f21011d22b 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -2210,7 +2210,7 @@ static void f_filereadable(typval_T *argvars, typval_T *rettv, EvalFuncData fptr { const char *const p = tv_get_string(&argvars[0]); rettv->vval.v_number = - (*p && !os_isdir((const char_u *)p) && os_file_is_readable(p)); + (*p && !os_isdir(p) && os_file_is_readable(p)); } /// @return 0 for not writable @@ -2888,7 +2888,7 @@ static void f_getfsize(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) FileInfo file_info; if (os_fileinfo(fname, &file_info)) { uint64_t filesize = os_fileinfo_size(&file_info); - if (os_isdir((const char_u *)fname)) { + if (os_isdir(fname)) { rettv->vval.v_number = 0; } else { rettv->vval.v_number = (varnumber_T)filesize; @@ -3491,7 +3491,7 @@ static void f_globpath(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (file != NULL && !error) { garray_T ga; ga_init(&ga, (int)sizeof(char_u *), 10); - globpath((char *)tv_get_string(&argvars[0]), (char_u *)file, &ga, flags); + globpath((char *)tv_get_string(&argvars[0]), (char *)file, &ga, flags); if (rettv->v_type == VAR_STRING) { rettv->vval.v_string = ga_concat_strings_sep(&ga, "\n"); @@ -3874,7 +3874,7 @@ static void f_iconv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (vimconv.vc_type == CONV_NONE) { rettv->vval.v_string = xstrdup(str); } else { - rettv->vval.v_string = (char *)string_convert(&vimconv, (char_u *)str, NULL); + rettv->vval.v_string = string_convert(&vimconv, (char *)str, NULL); } convert_setup(&vimconv, NULL, NULL); @@ -4131,7 +4131,7 @@ static void f_invert(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// "isdirectory()" function static void f_isdirectory(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { - rettv->vval.v_number = os_isdir((const char_u *)tv_get_string(&argvars[0])); + rettv->vval.v_number = os_isdir(tv_get_string(&argvars[0])); } /// "islocked()" function @@ -4458,7 +4458,7 @@ static void f_jobstart(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (new_cwd && *new_cwd != NUL) { cwd = new_cwd; // The new cwd must be a directory. - if (!os_isdir((const char_u *)cwd)) { + if (!os_isdir(cwd)) { semsg(_(e_invarg2), "expected valid directory"); shell_free_argv(argv); return; @@ -5891,7 +5891,7 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) // their own about CR-LF conversion. const char *const fname = tv_get_string(&argvars[0]); - if (os_isdir((const char_u *)fname)) { + if (os_isdir(fname)) { semsg(_(e_isadir2), fname); return; } @@ -6343,7 +6343,7 @@ static void f_resolve(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (*q != NUL) { cpy = remain; remain = (remain - ? (char *)concat_str((char_u *)q - 1, (char_u *)remain) + ? concat_str(q - 1, remain) : xstrdup(q - 1)); xfree(cpy); q[-1] = NUL; @@ -6402,7 +6402,7 @@ static void f_resolve(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) && (p[2] == NUL || vim_ispathsep(p[2])))))) { // Prepend "./". - cpy = (char *)concat_str((const char_u *)"./", (const char_u *)p); + cpy = concat_str("./", p); xfree(p); p = cpy; } else if (!is_relative_to_current) { @@ -8339,7 +8339,7 @@ static void f_strftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) char *enc = (char *)enc_locale(); convert_setup(&conv, p_enc, enc); if (conv.vc_type != CONV_NONE) { - p = (char *)string_convert(&conv, (char_u *)p, NULL); + p = string_convert(&conv, p, NULL); } char result_buf[256]; if (p != NULL) { @@ -8353,7 +8353,7 @@ static void f_strftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } convert_setup(&conv, enc, p_enc); if (conv.vc_type != CONV_NONE) { - rettv->vval.v_string = (char *)string_convert(&conv, (char_u *)result_buf, NULL); + rettv->vval.v_string = string_convert(&conv, result_buf, NULL); } else { rettv->vval.v_string = xstrdup(result_buf); } @@ -8599,7 +8599,7 @@ static void f_strptime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) char *enc = (char *)enc_locale(); convert_setup(&conv, p_enc, enc); if (conv.vc_type != CONV_NONE) { - fmt = (char *)string_convert(&conv, (char_u *)fmt, NULL); + fmt = string_convert(&conv, fmt, NULL); } if (fmt == NULL || os_strptime(str, fmt, &tmval) == NULL @@ -9070,7 +9070,7 @@ static void f_tagfiles(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) bool first = true; tagname_T tn; - while (get_tagfname(&tn, first, (char_u *)fname) == OK) { + while (get_tagfname(&tn, first, fname) == OK) { tv_list_append_string(rettv->vval.v_list, fname, -1); first = false; } @@ -9148,7 +9148,7 @@ static void f_termopen(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (new_cwd && *new_cwd != NUL) { cwd = new_cwd; // The new cwd must be a directory. - if (!os_isdir((const char_u *)cwd)) { + if (!os_isdir(cwd)) { semsg(_(e_invarg2), "expected valid directory"); shell_free_argv(argv); return; diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index 152c2eff8f..d5b2b1f2ae 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -2533,7 +2533,7 @@ dict_T *tv_dict_copy(const vimconv_T *const conv, dict_T *const orig, const bool new_di = tv_dict_item_alloc((const char *)di->di_key); } else { size_t len = STRLEN(di->di_key); - char *const key = (char *)string_convert(conv, di->di_key, &len); + char *const key = (char *)string_convert(conv, (char *)di->di_key, &len); if (key == NULL) { new_di = tv_dict_item_alloc_len((const char *)di->di_key, len); } else { diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 2a48de5e41..b9a94a971b 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -409,7 +409,7 @@ void emsg_funcname(char *ermsg, const char_u *name) char_u *p; if (*name == K_SPECIAL) { - p = concat_str((char_u *)"", name + 3); + p = (char_u *)concat_str("", (char *)name + 3); } else { p = (char_u *)name; } @@ -863,7 +863,7 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rett fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. - fc->breakpoint = dbg_find_breakpoint(false, fp->uf_name, (linenr_T)0); + fc->breakpoint = dbg_find_breakpoint(false, (char *)fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. @@ -1058,7 +1058,7 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rett bool func_not_yet_profiling_but_should = do_profiling_yes - && !fp->uf_profiling && has_profiling(false, fp->uf_name, NULL); + && !fp->uf_profiling && has_profiling(false, (char *)fp->uf_name, NULL); if (func_not_yet_profiling_but_should) { started_profiling = true; @@ -2332,7 +2332,7 @@ void ex_function(exarg_T *eap) } // heredoc: Check for ":python <func; - char_u *retval; + char *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { - fcp->breakpoint = dbg_find_breakpoint(false, fp->uf_name, SOURCING_LNUM); + fcp->breakpoint = dbg_find_breakpoint(false, (char *)fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } if (do_profiling == PROF_YES) { @@ -3159,7 +3160,7 @@ char *get_func_line(int c, void *cookie, int indent, bool do_concat) if (fcp->linenr >= gap->ga_len) { retval = NULL; } else { - retval = (char_u *)xstrdup(((char **)(gap->ga_data))[fcp->linenr++]); + retval = xstrdup(((char **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; if (do_profiling == PROF_YES) { func_line_start(cookie); @@ -3169,13 +3170,13 @@ char *get_func_line(int c, void *cookie, int indent, bool do_concat) // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { - dbg_breakpoint(fp->uf_name, SOURCING_LNUM); + dbg_breakpoint((char *)fp->uf_name, SOURCING_LNUM); // Find next breakpoint. - fcp->breakpoint = dbg_find_breakpoint(false, fp->uf_name, SOURCING_LNUM); + fcp->breakpoint = dbg_find_breakpoint(false, (char *)fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } - return (char *)retval; + return retval; } /// @return true if the currently active function should be ended, because a diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index e73bba16e2..75410d40d8 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -81,7 +81,7 @@ static list_T *heredoc_get(exarg_T *eap, char *cmd) // The marker is the next word. if (*cmd != NUL && *cmd != '"') { marker = skipwhite(cmd); - p = (char *)skiptowhite((char_u *)marker); + p = skiptowhite(marker); if (*skipwhite(p) != NUL && *skipwhite(p) != '"') { semsg(_(e_trailing_arg), p); return NULL; @@ -587,7 +587,7 @@ static char *ex_let_one(char *arg, typval_T *const tv, const bool copy, const bo char *s = vim_getenv(name); if (s != NULL) { - tofree = (char *)concat_str((const char_u *)s, (const char_u *)p); + tofree = concat_str(s, p); p = (const char *)tofree; xfree(s); } @@ -663,8 +663,7 @@ static char *ex_let_one(char *arg, typval_T *const tv, const bool copy, const bo } else if (opt_type == gov_string && stringval != NULL && s != NULL) { // string char *const oldstringval = stringval; - stringval = (char *)concat_str((const char_u *)stringval, - (const char_u *)s); + stringval = concat_str(stringval, s); xfree(oldstringval); s = stringval; } @@ -705,7 +704,7 @@ static char *ex_let_one(char *arg, typval_T *const tv, const bool copy, const bo if (p != NULL && op != NULL && *op == '.') { s = get_reg_contents(*arg == '@' ? '"' : *arg, kGRegExprSrc); if (s != NULL) { - ptofree = (char *)concat_str((char_u *)s, (const char_u *)p); + ptofree = concat_str(s, p); p = (const char *)ptofree; xfree(s); } diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index ba6594fd7a..fc753cf65c 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -586,11 +586,11 @@ void ex_sort(exarg_T *eap) p = s + start_col; if (sort_nr) { if (sort_what & STR2NR_HEX) { - s = (char *)skiptohex((char_u *)p); + s = skiptohex(p); } else if (sort_what & STR2NR_BIN) { s = (char *)skiptobin(p); } else { - s = (char *)skiptodigit((char_u *)p); + s = skiptodigit(p); } if (s > p && s[-1] == '-') { s--; // include preceding negative sign @@ -2006,7 +2006,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char *fname, char *ffname, int oth if (!eap->forceit && !eap->append) { #ifdef UNIX // It is possible to open a directory on Unix. - if (os_isdir((char_u *)ffname)) { + if (os_isdir(ffname)) { semsg(_(e_isadir2), ffname); return FAIL; } @@ -3940,8 +3940,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T // what matches. Temporarily replace the line // and change it back afterwards. orig_line = (char *)vim_strsave(ml_get(lnum)); - char *new_line = (char *)concat_str((char_u *)new_start, - (char_u *)sub_firstline + copycol); + char *new_line = concat_str(new_start, sub_firstline + copycol); // Position the cursor relative to the end of the line, the // previous substitute may have inserted or deleted characters @@ -4939,7 +4938,7 @@ char *skip_vimgrep_pat(char *p, char **s, int *flags) if (s != NULL) { *s = p; } - p = (char *)skiptowhite((char_u *)p); + p = skiptowhite(p); if (s != NULL && *p != NUL) { *p++ = NUL; } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 08709ec228..1fa14f4e4f 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -462,7 +462,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) if (breakpoint != NULL && dbg_tick != NULL && *dbg_tick != debug_tick) { *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), - (char_u *)fname, SOURCING_LNUM); + fname, SOURCING_LNUM); *dbg_tick = debug_tick; } @@ -471,10 +471,10 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // Did we encounter a breakpoint? if (breakpoint != NULL && *breakpoint != 0 && *breakpoint <= SOURCING_LNUM) { - dbg_breakpoint((char_u *)fname, SOURCING_LNUM); + dbg_breakpoint(fname, SOURCING_LNUM); // Find next breakpoint. *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), - (char_u *)fname, SOURCING_LNUM); + fname, SOURCING_LNUM); *dbg_tick = debug_tick; } if (do_profiling == PROF_YES) { @@ -639,8 +639,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // Check for the next breakpoint at or after the ":while" // or ":for". if (breakpoint != NULL) { - *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), - (char_u *)fname, + *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), fname, ((wcmd_T *)lines_ga.ga_data)[current_line].lnum - 1); *dbg_tick = debug_tick; } @@ -3665,7 +3664,7 @@ char *replace_makeprg(exarg_T *eap, char *arg, char **cmdlinep) STRCAT(new_cmdline, arg); } - msg_make((char_u *)arg); + msg_make(arg); // 'eap->cmd' is not set here, because it is not used at CMD_make xfree(*cmdlinep); @@ -3807,7 +3806,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp) // done by ExpandOne() below. #ifdef UNIX if (!has_wildcards) { - backslash_halve((char_u *)eap->arg); + backslash_halve(eap->arg); } #else backslash_halve((char_u *)eap->arg); @@ -5032,7 +5031,7 @@ static void ex_tabs(exarg_T *eap) msg_putchar('\n'); vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++); - msg_outtrans_attr(IObuff, HL_ATTR(HLF_T)); + msg_outtrans_attr((char *)IObuff, HL_ATTR(HLF_T)); ui_flush(); // output one line at a time os_breakcheck(); @@ -6154,7 +6153,7 @@ FILE *open_exfile(char_u *fname, int forceit, char *mode) { #ifdef UNIX // with Unix it is possible to open a directory - if (os_isdir(fname)) { + if (os_isdir((char *)fname)) { semsg(_(e_isadir2), fname); return NULL; } @@ -6881,7 +6880,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum if (src[*usedlen] == '<') { (*usedlen)++; char *s; - if ((s = (char *)STRRCHR(result, '.')) != NULL + if ((s = strrchr(result, '.')) != NULL && s >= path_tail(result)) { resultlen = (size_t)(s - result); } diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c index e2b02929d2..11795684cf 100644 --- a/src/nvim/ex_eval.c +++ b/src/nvim/ex_eval.c @@ -726,14 +726,14 @@ static void report_pending(int action, int pending, void *value) break; case CSTP_RETURN: // ":return" command producing value, allocated - s = (char *)get_return_cmd(value); + s = get_return_cmd(value); break; default: if (pending & CSTP_THROW) { vim_snprintf((char *)IObuff, IOSIZE, mesg, _("Exception")); - mesg = (char *)concat_str(IObuff, (char_u *)": %s"); + mesg = concat_str((char *)IObuff, ": %s"); s = ((except_T *)value)->value; } else if ((pending & CSTP_ERROR) && (pending & CSTP_INTERRUPT)) { s = _("Error and interrupt"); diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 66c3327ce3..0998bdd867 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -3198,7 +3198,7 @@ static void draw_cmdline(int start, int len) } } - msg_outtrans_len((char_u *)arshape_buf, newlen); + msg_outtrans_len(arshape_buf, newlen); } else { draw_cmdline_no_arabicshape: if (kv_size(ccline.last_colors.colors)) { @@ -3213,7 +3213,7 @@ draw_cmdline_no_arabicshape: chunk.attr); } } else { - msg_outtrans_len(ccline.cmdbuff + start, len); + msg_outtrans_len((char *)ccline.cmdbuff + start, len); } } } diff --git a/src/nvim/ex_session.c b/src/nvim/ex_session.c index 453de89aea..e907c45e79 100644 --- a/src/nvim/ex_session.c +++ b/src/nvim/ex_session.c @@ -956,7 +956,7 @@ void ex_mkrc(exarg_T *eap) } // When using 'viewdir' may have to create the directory. - if (using_vdir && !os_isdir(p_vdir)) { + if (using_vdir && !os_isdir((char *)p_vdir)) { vim_mkdir_emsg((const char *)p_vdir, 0755); } diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index a990043017..bbc6e53aa8 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -471,7 +471,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le STRCPY(buf, ff_expand_buffer); STRCPY(buf + eb_len, search_ctx->ffsc_fix_path); - if (os_isdir(buf)) { + if (os_isdir((char *)buf)) { STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path); add_pathsep((char *)ff_expand_buffer); } else { @@ -796,7 +796,7 @@ char_u *vim_findfile(void *search_ctx_arg) */ for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) { if (!path_with_url(stackp->ffs_filearray[i]) - && !os_isdir((char_u *)stackp->ffs_filearray[i])) { + && !os_isdir(stackp->ffs_filearray[i])) { continue; // not a directory } // prepare the filename to be checked for existence below @@ -828,7 +828,7 @@ char_u *vim_findfile(void *search_ctx_arg) || (os_path_exists(file_path) && (search_ctx->ffsc_find_what == FINDFILE_BOTH || ((search_ctx->ffsc_find_what == FINDFILE_DIR) - == os_isdir(file_path))))) + == os_isdir((char *)file_path))))) #ifndef FF_VERBOSE && (ff_check_visited(&search_ctx->ffsc_visited_list->ffvl_visited_list, file_path, (char_u *)"") == OK) @@ -885,7 +885,7 @@ char_u *vim_findfile(void *search_ctx_arg) } else { // still wildcards left, push the directories for further search for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) { - if (!os_isdir((char_u *)stackp->ffs_filearray[i])) { + if (!os_isdir(stackp->ffs_filearray[i])) { continue; // not a directory } ff_push(search_ctx, @@ -909,7 +909,7 @@ char_u *vim_findfile(void *search_ctx_arg) stackp->ffs_fix_path) == 0) { continue; // don't repush same directory } - if (!os_isdir((char_u *)stackp->ffs_filearray[i])) { + if (!os_isdir(stackp->ffs_filearray[i])) { continue; // not a directory } ff_push(search_ctx, @@ -1476,7 +1476,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first (os_path_exists((char_u *)NameBuff) && (find_what == FINDFILE_BOTH || ((find_what == FINDFILE_DIR) - == os_isdir((char_u *)NameBuff))))) { + == os_isdir(NameBuff))))) { file_name = vim_strsave((char_u *)NameBuff); goto theend; } diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 450c608fad..d67cd36a85 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -143,7 +143,7 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr) msg_scroll = msg_scroll_save; msg_scrolled_ign = true; // may truncate the message to avoid a hit-return prompt - msg_outtrans_attr(msg_may_trunc(false, IObuff), attr); + msg_outtrans_attr((char *)msg_may_trunc(false, IObuff), attr); msg_clr_eos(); ui_flush(); msg_scrolled_ign = false; @@ -2775,7 +2775,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en if (trailing_pathseps) { IObuff[dir_len - 2] = NUL; } - if (*dirp == NUL && !os_isdir(IObuff)) { + if (*dirp == NUL && !os_isdir((char *)IObuff)) { int ret; char *failed_dir; if ((ret = os_mkdir_recurse((char *)IObuff, 0755, &failed_dir)) != 0) { @@ -2936,7 +2936,7 @@ nobackup: if (trailing_pathseps) { IObuff[dir_len - 2] = NUL; } - if (*dirp == NUL && !os_isdir(IObuff)) { + if (*dirp == NUL && !os_isdir((char *)IObuff)) { int ret; char *failed_dir; if ((ret = os_mkdir_recurse((char *)IObuff, 0755, &failed_dir)) != 0) { @@ -4948,7 +4948,7 @@ int buf_check_timestamp(buf_T *buf) buf_store_file_info(buf, &file_info); } - if (os_isdir((char_u *)buf->b_fname)) { + if (os_isdir(buf->b_fname)) { // Don't do anything for a directory. Might contain the file explorer. } else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar) && !bufIsChanged(buf) && file_info_ok) { @@ -5318,7 +5318,7 @@ static void vim_mktempdir(void) for (size_t i = 0; i < ARRAY_SIZE(temp_dirs); i++) { // Expand environment variables, leave room for "/tmp/nvim./XXXXXX/999999999". expand_env((char *)temp_dirs[i], tmp, TEMP_FILE_PATH_MAXLEN - 64); - if (!os_isdir((char_u *)tmp)) { + if (!os_isdir(tmp)) { continue; } @@ -5328,7 +5328,7 @@ static void vim_mktempdir(void) xstrlcat(tmp, user, sizeof(tmp)); (void)os_mkdir(tmp, 0700); // Always create, to avoid a race. bool owned = os_file_owned(tmp); - bool isdir = os_isdir((char_u *)tmp); + bool isdir = os_isdir(tmp); #ifdef UNIX int perm = os_getperm(tmp); // XDG_RUNTIME_DIR must be owned by the user, mode 0700. bool valid = isdir && owned && 0700 == (perm & 0777); diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index bb8cd5a1eb..0a9457ef35 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -1280,7 +1280,7 @@ void restore_typeahead(tasave_T *tp) /// Open a new script file for the ":source!" command. /// /// @param directly when true execute directly -void openscript(char_u *name, bool directly) +void openscript(char *name, bool directly) { if (curscript + 1 == NSCRIPT) { emsg(_(e_nesting)); @@ -1302,7 +1302,7 @@ void openscript(char_u *name, bool directly) curscript++; } // use NameBuff for expanded name - expand_env((char *)name, NameBuff, MAXPATHL); + expand_env(name, NameBuff, MAXPATHL); int error; if ((scriptin[curscript] = file_open_new(&error, (char *)NameBuff, kFileReadOnly, 0)) == NULL) { diff --git a/src/nvim/globals.h b/src/nvim/globals.h index 77784defd1..ddbe727db9 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -177,7 +177,7 @@ EXTERN bool msg_scrolled_ign INIT(= false); // is reset before the screen is redrawn, so we need to keep track of this. EXTERN bool msg_did_scroll INIT(= false); -EXTERN char_u *keep_msg INIT(= NULL); // msg to be shown after redraw +EXTERN char *keep_msg INIT(= NULL); // msg to be shown after redraw EXTERN int keep_msg_attr INIT(= 0); // highlight attr for keep_msg EXTERN bool need_fileinfo INIT(= false); // do fileinfo() after redraw EXTERN int msg_scroll INIT(= false); // msg_start() will scroll diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c index 6e424f2fd6..602fa8b71d 100644 --- a/src/nvim/hardcopy.c +++ b/src/nvim/hardcopy.c @@ -3062,7 +3062,8 @@ int mch_print_text_out(char_u *const textp, size_t len) if (prt_do_conv) { // Convert from multi-byte to 8-bit encoding - tofree = p = string_convert(&prt_conv, p, &len); + p = (char_u *)string_convert(&prt_conv, (char *)p, &len); + tofree = p; if (p == NULL) { p = (char_u *)""; len = 0; diff --git a/src/nvim/help.c b/src/nvim/help.c index b25fabca48..245d80489f 100644 --- a/src/nvim/help.c +++ b/src/nvim/help.c @@ -741,8 +741,8 @@ void fix_help_buffer(void) const char *const f2 = fnames[i2]; const char *const t1 = path_tail(f1); const char *const t2 = path_tail(f2); - const char *const e1 = (char *)STRRCHR(t1, '.'); - const char *const e2 = (char *)STRRCHR(t2, '.'); + const char *const e1 = strrchr(t1, '.'); + const char *const e2 = strrchr(t2, '.'); if (e1 == NULL || e2 == NULL) { continue; } @@ -811,7 +811,7 @@ void fix_help_buffer(void) } else { // Do the conversion. If it fails // use the unconverted text. - cp = (char *)string_convert(&vc, IObuff, NULL); + cp = string_convert(&vc, (char *)IObuff, NULL); if (cp == NULL) { cp = (char *)IObuff; } @@ -1163,13 +1163,13 @@ void ex_helptags(exarg_T *eap) } if (STRCMP(eap->arg, "ALL") == 0) { - do_in_path((char_u *)p_rtp, "doc", DIP_ALL + DIP_DIR, helptags_cb, &add_help_tags); + do_in_path(p_rtp, "doc", DIP_ALL + DIP_DIR, helptags_cb, &add_help_tags); } else { ExpandInit(&xpc); xpc.xp_context = EXPAND_DIRECTORIES; dirname = (char *)ExpandOne(&xpc, (char_u *)eap->arg, NULL, WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE); - if (dirname == NULL || !os_isdir((char_u *)dirname)) { + if (dirname == NULL || !os_isdir(dirname)) { semsg(_("E150: Not a directory: %s"), eap->arg); } else { do_helptags(dirname, add_help_tags, false); diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c index e2d4a81345..ed1f0185b7 100644 --- a/src/nvim/highlight_group.c +++ b/src/nvim/highlight_group.c @@ -852,14 +852,14 @@ void do_highlight(const char *line, const bool forceit, const bool init) } // Isolate the name. - name_end = (const char *)skiptowhite((const char_u *)line); + name_end = (const char *)skiptowhite(line); linep = (const char *)skipwhite(name_end); // Check for "default" argument. if (strncmp(line, "default", (size_t)(name_end - line)) == 0) { dodefault = true; line = linep; - name_end = (const char *)skiptowhite((const char_u *)line); + name_end = (const char *)skiptowhite(line); linep = (const char *)skipwhite(name_end); } @@ -891,9 +891,9 @@ void do_highlight(const char *line, const bool forceit, const bool init) int to_id; HlGroup *hlgroup = NULL; - from_end = (const char *)skiptowhite((const char_u *)from_start); + from_end = (const char *)skiptowhite(from_start); to_start = (const char *)skipwhite(from_end); - to_end = (const char *)skiptowhite((const char_u *)to_start); + to_end = (const char *)skiptowhite(to_start); if (ends_excmd((uint8_t)(*from_start)) || ends_excmd((uint8_t)(*to_start))) { @@ -969,7 +969,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) redraw_all_later(UPD_NOT_VALID); return; } - name_end = (const char *)skiptowhite((const char_u *)line); + name_end = (const char *)skiptowhite(line); linep = (const char *)skipwhite(name_end); } @@ -1054,7 +1054,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) } } else { arg_start = linep; - linep = (const char *)skiptowhite((const char_u *)linep); + linep = (const char *)skiptowhite(linep); } if (linep == arg_start) { semsg(_("E417: missing argument: %s"), key_start); @@ -2074,13 +2074,13 @@ void set_context_in_highlight_cmd(expand_T *xp, const char *arg) // (part of) subcommand already typed if (*arg != NUL) { - const char *p = (const char *)skiptowhite((const char_u *)arg); + const char *p = (const char *)skiptowhite(arg); if (*p != NUL) { // Past "default" or group name. include_default = 0; if (strncmp("default", arg, (unsigned)(p - arg)) == 0) { arg = (const char *)skipwhite(p); xp->xp_pattern = (char *)arg; - p = (const char *)skiptowhite((const char_u *)arg); + p = (const char *)skiptowhite(arg); } if (*p != NUL) { // past group name include_link = 0; @@ -2090,10 +2090,10 @@ void set_context_in_highlight_cmd(expand_T *xp, const char *arg) if (strncmp("link", arg, (unsigned)(p - arg)) == 0 || strncmp("clear", arg, (unsigned)(p - arg)) == 0) { xp->xp_pattern = skipwhite(p); - p = (const char *)skiptowhite((char_u *)xp->xp_pattern); + p = (const char *)skiptowhite(xp->xp_pattern); if (*p != NUL) { // Past first group name. xp->xp_pattern = skipwhite(p); - p = (const char *)skiptowhite((char_u *)xp->xp_pattern); + p = (const char *)skiptowhite(xp->xp_pattern); } } if (*p != NUL) { // Past group name(s). diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index 2a9d2c357e..9413abb2e1 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -153,10 +153,10 @@ void set_context_in_cscope_cmd(expand_T *xp, const char *arg, cmdidx_T cmdidx) // (part of) subcommand already typed if (*arg != NUL) { - const char *p = (const char *)skiptowhite((const char_u *)arg); + const char *p = (const char *)skiptowhite(arg); if (*p != NUL) { // Past first word. xp->xp_pattern = skipwhite(p); - if (*skiptowhite((char_u *)xp->xp_pattern) != NUL) { + if (*skiptowhite(xp->xp_pattern) != NUL) { xp->xp_context = EXPAND_NOTHING; } else if (STRNICMP(arg, "add", p - arg) == 0) { xp->xp_context = EXPAND_FILES; diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c index 8ef6667374..166695ef5b 100644 --- a/src/nvim/indent_c.c +++ b/src/nvim/indent_c.c @@ -676,10 +676,10 @@ static int cin_first_id_amount(void) line = get_cursor_line_ptr(); p = (char_u *)skipwhite((char *)line); - len = (int)(skiptowhite(p) - p); + len = (int)((char_u *)skiptowhite((char *)p) - p); if (len == 6 && STRNCMP(p, "static", 6) == 0) { p = (char_u *)skipwhite((char *)p + 6); - len = (int)(skiptowhite(p) - p); + len = (int)((char_u *)skiptowhite((char *)p) - p); } if (len == 6 && STRNCMP(p, "struct", 6) == 0) { p = (char_u *)skipwhite((char *)p + 6); diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index 3c32d0755e..ba0a36cafe 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -3767,7 +3767,7 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) /// Sets the global variables: compl_col, compl_length and compl_pattern. static int get_wholeline_compl_info(char_u *line, colnr_T curs_col) { - compl_col = (colnr_T)getwhitecols(line); + compl_col = (colnr_T)getwhitecols((char *)line); compl_length = (int)curs_col - (int)compl_col; if (compl_length < 0) { // cursor in indent: empty pattern compl_length = 0; @@ -3985,7 +3985,7 @@ static void ins_compl_continue_search(char_u *line) // first non_blank in the line, if it is not a wordchar // include it to get a better pattern, but then we don't // want the "\\<" prefix, check it below. - compl_col = (colnr_T)getwhitecols(line); + compl_col = (colnr_T)getwhitecols((char *)line); compl_startpos.col = compl_col; compl_startpos.lnum = curwin->w_cursor.lnum; compl_cont_status &= ~CONT_SOL; // clear SOL if present diff --git a/src/nvim/locale.c b/src/nvim/locale.c index ba0566011c..3e0774c096 100644 --- a/src/nvim/locale.c +++ b/src/nvim/locale.c @@ -188,7 +188,7 @@ void ex_language(exarg_T *eap) // Check for "messages {name}", "ctype {name}" or "time {name}" argument. // Allow abbreviation, but require at least 3 characters to avoid // confusion with a two letter language name "me" or "ct". - p = (char *)skiptowhite((char_u *)eap->arg); + p = skiptowhite(eap->arg); if ((*p == NUL || ascii_iswhite(*p)) && p - eap->arg >= 3) { if (STRNICMP(eap->arg, "messages", p - eap->arg) == 0) { what = VIM_LC_MESSAGES; diff --git a/src/nvim/log.c b/src/nvim/log.c index 9f25543be7..9bdf327430 100644 --- a/src/nvim/log.c +++ b/src/nvim/log.c @@ -63,13 +63,13 @@ static void log_path_init(void) expand_env("$" ENV_LOGFILE, log_file_path, (int)size - 1); if (strequal("$" ENV_LOGFILE, log_file_path) || log_file_path[0] == '\0' - || os_isdir((char_u *)log_file_path) + || os_isdir(log_file_path) || !log_try_create(log_file_path)) { // Make $XDG_STATE_HOME if it does not exist. char *loghome = get_xdg_home(kXDGStateHome); char *failed_dir = NULL; bool log_dir_failure = false; - if (!os_isdir((char_u *)loghome)) { + if (!os_isdir(loghome)) { log_dir_failure = (os_mkdir_recurse(loghome, 0700, &failed_dir) != 0); } XFREE_CLEAR(loghome); diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 7e8dda6ca1..1b874e673a 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -501,7 +501,7 @@ static int nlua_iconv(lua_State *lstate) vimconv.vc_type = CONV_NONE; convert_setup_ext(&vimconv, from, false, to, false); - char_u *ret = string_convert(&vimconv, (char_u *)str, &str_len); + char_u *ret = (char_u *)string_convert(&vimconv, (char *)str, &str_len); convert_setup(&vimconv, NULL, NULL); diff --git a/src/nvim/main.c b/src/nvim/main.c index 09a387262c..883f946cad 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1342,8 +1342,8 @@ scripterror: ga_grow(&global_alist.al_ga, 1); char *p = xstrdup(argv[0]); - if (parmp->diff_mode && os_isdir((char_u *)p) && GARGCOUNT > 0 - && !os_isdir((char_u *)alist_name(&GARGLIST[0]))) { + if (parmp->diff_mode && os_isdir(p) && GARGCOUNT > 0 + && !os_isdir(alist_name(&GARGLIST[0]))) { char *r = concat_fnames(p, path_tail(alist_name(&GARGLIST[0])), true); xfree(p); p = r; diff --git a/src/nvim/mark.c b/src/nvim/mark.c index 92a7c7c4b0..9df4d416ff 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -922,7 +922,7 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu snprintf((char *)IObuff, IOSIZE, " %c %6" PRIdLINENR " %4d ", c, p->lnum, p->col); msg_outtrans((char *)IObuff); if (name != NULL) { - msg_outtrans_attr(name, current ? HL_ATTR(HLF_D) : 0); + msg_outtrans_attr((char *)name, current ? HL_ATTR(HLF_D) : 0); } } ui_flush(); // show one line at a time @@ -1052,7 +1052,7 @@ void ex_jumps(exarg_T *eap) i > curwin->w_jumplistidx ? i - curwin->w_jumplistidx : curwin->w_jumplistidx - i, curwin->w_jumplist[i].fmark.mark.lnum, curwin->w_jumplist[i].fmark.mark.col); msg_outtrans((char *)IObuff); - msg_outtrans_attr(name, + msg_outtrans_attr((char *)name, curwin->w_jumplist[i].fmark.fnum == curbuf->b_fnum ? HL_ATTR(HLF_D) : 0); xfree(name); @@ -1097,7 +1097,7 @@ void ex_changes(exarg_T *eap) curbuf->b_changelist[i].mark.col); msg_outtrans((char *)IObuff); name = mark_line(&curbuf->b_changelist[i].mark, 17); - msg_outtrans_attr(name, HL_ATTR(HLF_D)); + msg_outtrans_attr((char *)name, HL_ATTR(HLF_D)); xfree(name); os_breakcheck(); } diff --git a/src/nvim/match.c b/src/nvim/match.c index cabd008591..48f0d0fc05 100644 --- a/src/nvim/match.c +++ b/src/nvim/match.c @@ -1183,7 +1183,7 @@ void ex_match(exarg_T *eap) && (ascii_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4])))) { end = (char_u *)eap->arg + 4; } else { - p = skiptowhite((char_u *)eap->arg); + p = (char_u *)skiptowhite(eap->arg); if (!eap->skip) { g = vim_strnsave((char_u *)eap->arg, (size_t)(p - (char_u *)eap->arg)); } diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index e703280032..b874f0dc94 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -1942,7 +1942,7 @@ void utf_find_illegal(void) p = get_cursor_pos_ptr(); if (vimconv.vc_type != CONV_NONE) { xfree(tofree); - tofree = string_convert(&vimconv, p, NULL); + tofree = (char_u *)string_convert(&vimconv, (char *)p, NULL); if (tofree == NULL) { break; } @@ -2521,16 +2521,14 @@ int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, c return OK; } -/* - * Convert text "ptr[*lenp]" according to "vcp". - * Returns the result in allocated memory and sets "*lenp". - * When "lenp" is NULL, use NUL terminated strings. - * Illegal chars are often changed to "?", unless vcp->vc_fail is set. - * When something goes wrong, NULL is returned and "*lenp" is unchanged. - */ -char_u *string_convert(const vimconv_T *const vcp, char_u *ptr, size_t *lenp) +/// Convert text "ptr[*lenp]" according to "vcp". +/// Returns the result in allocated memory and sets "*lenp". +/// When "lenp" is NULL, use NUL terminated strings. +/// Illegal chars are often changed to "?", unless vcp->vc_fail is set. +/// When something goes wrong, NULL is returned and "*lenp" is unchanged. +char *string_convert(const vimconv_T *const vcp, char *ptr, size_t *lenp) { - return string_convert_ext(vcp, ptr, lenp, NULL); + return (char *)string_convert_ext(vcp, (char_u *)ptr, lenp, NULL); } /* diff --git a/src/nvim/memline.c b/src/nvim/memline.c index 044655ef2b..b0b6b675cb 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -857,7 +857,7 @@ void ml_recover(bool checkext) if ((hp = mf_get(mfp, 0, 1)) == NULL) { msg_start(); msg_puts_attr(_("Unable to read block 0 from "), attr | MSG_HIST); - msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); + msg_outtrans_attr((char *)mfp->mf_fname, attr | MSG_HIST); msg_puts_attr(_("\nMaybe no changes were made or Vim did not update the swap file."), attr | MSG_HIST); msg_end(); @@ -866,7 +866,7 @@ void ml_recover(bool checkext) b0p = hp->bh_data; if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0) { msg_start(); - msg_outtrans_attr(mfp->mf_fname, MSG_HIST); + msg_outtrans_attr((char *)mfp->mf_fname, MSG_HIST); msg_puts_attr(_(" cannot be used with this version of Vim.\n"), MSG_HIST); msg_puts_attr(_("Use Vim version 3.0.\n"), MSG_HIST); @@ -879,7 +879,7 @@ void ml_recover(bool checkext) } if (b0_magic_wrong(b0p)) { msg_start(); - msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); + msg_outtrans_attr((char *)mfp->mf_fname, attr | MSG_HIST); msg_puts_attr(_(" cannot be used on this computer.\n"), attr | MSG_HIST); msg_puts_attr(_("The file was created on "), attr | MSG_HIST); @@ -901,7 +901,7 @@ void ml_recover(bool checkext) mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size)); if (mfp->mf_page_size < previous_page_size) { msg_start(); - msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST); + msg_outtrans_attr((char *)mfp->mf_fname, attr | MSG_HIST); msg_puts_attr(_(" has been damaged (page size is smaller than minimum value).\n"), attr | MSG_HIST); msg_end(); @@ -3614,7 +3614,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ fname[n - 1]--; // ".swo", ".swn", etc. } - if (os_isdir((char_u *)dir_name)) { + if (os_isdir(dir_name)) { *found_existing_dir = true; } else if (!*found_existing_dir && **dirp == NUL) { int ret; diff --git a/src/nvim/menu.c b/src/nvim/menu.c index b1d729f71d..cb6918cd27 100644 --- a/src/nvim/menu.c +++ b/src/nvim/menu.c @@ -853,7 +853,7 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth) msg_puts(" "); } // Same highlighting as for directories!? - msg_outtrans_attr((char_u *)menu->name, HL_ATTR(HLF_D)); + msg_outtrans_attr(menu->name, HL_ATTR(HLF_D)); } if (menu != NULL && menu->children == NULL) { diff --git a/src/nvim/message.c b/src/nvim/message.c index 4fba78feca..80b5f53f4e 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -265,7 +265,7 @@ void msg_multiline_attr(const char *s, int attr, bool check_int, bool *need_clea // Print the rest of the message. We know there is no special // character because strpbrk returned NULL if (*s != NUL) { - msg_outtrans_attr((char_u *)s, attr); + msg_outtrans_attr(s, attr); } } @@ -325,7 +325,7 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) // Add message to history (unless it's a repeated kept message or a // truncated message) - if ((const char_u *)s != keep_msg + if (s != keep_msg || (*s != '<' && last_msg_hist != NULL && last_msg_hist->msg != NULL @@ -344,7 +344,7 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) if (multiline) { msg_multiline_attr(s, attr, false, &need_clear); } else { - msg_outtrans_attr((char_u *)s, attr); + msg_outtrans_attr(s, attr); } if (need_clear) { msg_clr_eos(); @@ -1307,7 +1307,7 @@ void wait_return(int redraw) emsg_on_display = false; // can delete error message now lines_left = -1; // reset lines_left at next msg_start() reset_last_sourcing(); - if (keep_msg != NULL && vim_strsize((char *)keep_msg) >= + if (keep_msg != NULL && vim_strsize(keep_msg) >= (Rows - cmdline_row - 1) * Columns + sc_col) { XFREE_CLEAR(keep_msg); // don't redisplay message, it's too long } @@ -1350,7 +1350,7 @@ void set_keep_msg(char *s, int attr) { xfree(keep_msg); if (s != NULL && msg_silent == 0) { - keep_msg = vim_strsave((char_u *)s); + keep_msg = xstrdup(s); } else { keep_msg = NULL; } @@ -1510,7 +1510,7 @@ void msg_home_replace_hl(char_u *fname) static void msg_home_replace_attr(char_u *fname, int attr) { char *name = home_replace_save(NULL, (char *)fname); - msg_outtrans_attr((char_u *)name, attr); + msg_outtrans_attr(name, attr); xfree(name); } @@ -1521,29 +1521,29 @@ static void msg_home_replace_attr(char_u *fname, int attr) /// @return the number of characters it takes on the screen. int msg_outtrans(char *str) { - return msg_outtrans_attr((char_u *)str, 0); + return msg_outtrans_attr(str, 0); } -int msg_outtrans_attr(const char_u *str, int attr) +int msg_outtrans_attr(const char *str, int attr) { - return msg_outtrans_len_attr(str, (int)STRLEN(str), attr); + return msg_outtrans_len_attr((char_u *)str, (int)STRLEN(str), attr); } -int msg_outtrans_len(const char_u *str, int len) +int msg_outtrans_len(const char *str, int len) { - return msg_outtrans_len_attr(str, len, 0); + return msg_outtrans_len_attr((char_u *)str, len, 0); } /// Output one character at "p". /// Handles multi-byte characters. /// /// @return pointer to the next character. -char_u *msg_outtrans_one(char_u *p, int attr) +char *msg_outtrans_one(char *p, int attr) { int l; - if ((l = utfc_ptr2len((char *)p)) > 1) { - msg_outtrans_len_attr(p, l, attr); + if ((l = utfc_ptr2len(p)) > 1) { + msg_outtrans_len_attr((char_u *)p, l, attr); return p + l; } msg_puts_attr((const char *)transchar_byte(*p), attr); @@ -1628,12 +1628,13 @@ int msg_outtrans_len_attr(const char_u *msgstr, int len, int attr) return retval; } -void msg_make(char_u *arg) +void msg_make(char *arg) { int i; - static char_u *str = (char_u *)"eeffoc", *rs = (char_u *)"Plon#dqg#vxjduB"; + static char *str = "eeffoc"; + static char *rs = "Plon#dqg#vxjduB"; - arg = (char_u *)skipwhite((char *)arg); + arg = skipwhite(arg); for (i = 5; *arg && i >= 0; i--) { if (*arg++ != str[i]) { break; @@ -1976,13 +1977,13 @@ void msg_prt_line(char_u *s, int list) /// Use grid_puts() to output one multi-byte character. /// /// @return the pointer "s" advanced to the next character. -static char_u *screen_puts_mbyte(char_u *s, int l, int attr) +static char *screen_puts_mbyte(char *s, int l, int attr) { int cw; attr = hl_combine_attr(HL_ATTR(HLF_MSG), attr); msg_didout = true; // remember that line is not empty - cw = utf_ptr2cells((char *)s); + cw = utf_ptr2cells(s); if (cw > 1 && (cmdmsg_rl ? msg_col <= 1 : msg_col == Columns - 1)) { // Doesn't fit, print a highlighted '>' to fill it up. @@ -1990,7 +1991,7 @@ static char_u *screen_puts_mbyte(char_u *s, int l, int attr) return s; } - grid_puts_len(&msg_grid_adj, (char *)s, l, msg_row, msg_col, attr); + grid_puts_len(&msg_grid_adj, s, l, msg_row, msg_col, attr); if (cmdmsg_rl) { msg_col -= cw; if (msg_col == 0) { @@ -2197,7 +2198,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs // ourselves). if (t_col > 0) { // output postponed text - t_puts(&t_col, t_s, s, attr); + t_puts(&t_col, (char *)t_s, (char *)s, attr); } // When no more prompt and no more room, truncate here @@ -2222,7 +2223,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs } else { l = utfc_ptr2len((char *)s); } - s = screen_puts_mbyte((char_u *)s, l, attr); + s = (char_u *)screen_puts_mbyte((char *)s, l, attr); did_last_char = true; } else { did_last_char = false; @@ -2281,7 +2282,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs if (t_col > 0 && (wrap || *s == '\r' || *s == '\b' || *s == '\t' || *s == BELL)) { // Output any postponed text. - t_puts(&t_col, t_s, s, attr); + t_puts(&t_col, (char *)t_s, (char *)s, attr); } if (wrap && p_more && !recurse) { @@ -2324,7 +2325,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs // characters and draw them all at once later. if (cmdmsg_rl || (cw > 1 && msg_col + t_col >= Columns - 1)) { if (l > 1) { - s = screen_puts_mbyte((char_u *)s, l, attr) - 1; + s = (char_u *)screen_puts_mbyte((char *)s, l, attr) - 1; } else { msg_screen_putchar(*s, attr); } @@ -2342,7 +2343,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs // Output any postponed text. if (t_col > 0) { - t_puts(&t_col, t_s, s, attr); + t_puts(&t_col, (char *)t_s, (char *)s, attr); } if (p_more && !recurse) { store_sb_text((char **)&sb_str, (char *)s, attr, &sb_col, false); @@ -2698,7 +2699,7 @@ static msgchunk_T *disp_sb_line(int row, msgchunk_T *smp) } /// Output any postponed text for msg_puts_attr_len(). -static void t_puts(int *t_col, const char_u *t_s, const char_u *s, int attr) +static void t_puts(int *t_col, const char *t_s, const char *s, int attr) { attr = hl_combine_attr(HL_ATTR(HLF_MSG), attr); // Output postponed text. @@ -2708,7 +2709,7 @@ static void t_puts(int *t_col, const char_u *t_s, const char_u *s, int attr) *t_col = 0; // If the string starts with a composing character don't increment the // column position for it. - if (utf_iscomposing(utf_ptr2char((char *)t_s))) { + if (utf_iscomposing(utf_ptr2char(t_s))) { msg_col--; } if (msg_col >= Columns) { diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 6430070f1b..47ad000385 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -631,16 +631,16 @@ static void normal_redraw_mode_message(NormalState *s) if (must_redraw && keep_msg != NULL && !emsg_on_display) { char_u *kmsg; - kmsg = keep_msg; + kmsg = (char_u *)keep_msg; keep_msg = NULL; // Showmode() will clear keep_msg, but we want to use it anyway. // First update w_topline. setcursor(); update_screen(0); // now reset it, otherwise it's put in the history again - keep_msg = kmsg; + keep_msg = (char *)kmsg; - kmsg = vim_strsave(keep_msg); + kmsg = vim_strsave((char_u *)keep_msg); msg_attr((const char *)kmsg, keep_msg_attr); xfree(kmsg); } @@ -1302,7 +1302,7 @@ static void normal_redraw(NormalState *s) // Display message after redraw. If an external message is still visible, // it contains the kept message already. if (keep_msg != NULL && !msg_ext_is_visible()) { - char_u *const p = vim_strsave(keep_msg); + char *const p = xstrdup(keep_msg); // msg_start() will set keep_msg to NULL, make a copy // first. Don't reset keep_msg, msg_attr_keep() uses it to diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 7b6f9e6370..4f2b84d20f 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -2500,7 +2500,7 @@ int op_change(oparg_T *oap) } firstline = ml_get(oap->start.lnum); pre_textlen = (long)STRLEN(firstline); - pre_indent = (long)getwhitecols(firstline); + pre_indent = (long)getwhitecols((char *)firstline); bd.textcol = curwin->w_cursor.col; } @@ -2521,7 +2521,7 @@ int op_change(oparg_T *oap) // the indent, exclude that indent change from the inserted text. firstline = ml_get(oap->start.lnum); if (bd.textcol > (colnr_T)pre_indent) { - long new_indent = (long)getwhitecols(firstline); + long new_indent = (long)getwhitecols((char *)firstline); pre_textlen += new_indent - pre_indent; bd.textcol += (colnr_T)(new_indent - pre_indent); @@ -3860,7 +3860,7 @@ void ex_display(exarg_T *eap) for (p = (char_u *)yb->y_array[j]; *p != NUL && (n -= ptr2cells((char *)p)) >= 0; p++) { // -V1019 clen = utfc_ptr2len((char *)p); - msg_outtrans_len(p, clen); + msg_outtrans_len((char *)p, clen); p += clen - 1; } } @@ -3938,10 +3938,10 @@ static void dis_msg(const char_u *p, bool skip_esc) && !(*p == ESC && skip_esc && *(p + 1) == NUL) && (n -= ptr2cells((char *)p)) >= 0) { if ((l = utfc_ptr2len((char *)p)) > 1) { - msg_outtrans_len(p, l); + msg_outtrans_len((char *)p, l); p += l; } else { - msg_outtrans_len(p++, 1); + msg_outtrans_len((char *)p++, 1); } } os_breakcheck(); diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c index 274e13e3c6..c940c86675 100644 --- a/src/nvim/os/env.c +++ b/src/nvim/os/env.c @@ -765,12 +765,12 @@ static char *vim_version_dir(const char *vimdir) return NULL; } char *p = concat_fnames(vimdir, VIM_VERSION_NODOT, true); - if (os_isdir((char_u *)p)) { + if (os_isdir(p)) { return p; } xfree(p); p = concat_fnames(vimdir, RUNTIME_DIRNAME, true); - if (os_isdir((char_u *)p)) { + if (os_isdir(p)) { return p; } xfree(p); @@ -976,7 +976,7 @@ char *vim_getenv(const char *name) assert(vim_path_end >= vim_path); vim_path = xstrndup(vim_path, (size_t)(vim_path_end - vim_path)); - if (!os_isdir((char_u *)vim_path)) { + if (!os_isdir(vim_path)) { xfree(vim_path); vim_path = NULL; } diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c index dc96c39d25..c0d5616666 100644 --- a/src/nvim/os/fs.c +++ b/src/nvim/os/fs.c @@ -129,10 +129,10 @@ bool os_isrealdir(const char *name) /// Check if the given path exists and is a directory. /// /// @return `true` if `name` is a directory. -bool os_isdir(const char_u *name) +bool os_isdir(const char *name) FUNC_ATTR_NONNULL_ALL { - int32_t mode = os_getperm((const char *)name); + int32_t mode = os_getperm(name); if (mode < 0) { return false; } @@ -865,7 +865,7 @@ int os_file_is_writable(const char *name) int r; RUN_UV_FS_FUNC(r, uv_fs_access, name, W_OK, NULL); if (r == 0) { - return os_isdir((char_u *)name) ? 2 : 1; + return os_isdir(name) ? 2 : 1; } return 0; } @@ -915,7 +915,7 @@ int os_mkdir_recurse(const char *const dir, int32_t mode, char **const failed_di char *e = curdir + dirlen; const char *const real_end = e; const char past_head_save = *past_head; - while (!os_isdir((char_u *)curdir)) { + while (!os_isdir(curdir)) { e = path_tail_with_sep(curdir); if (e <= past_head) { *past_head = NUL; diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index c8267ede14..461a79c37b 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -55,7 +55,7 @@ static void save_patterns(int num_pat, char **pat, int *num_file, char ***file) char_u *s = vim_strsave((char_u *)pat[i]); // Be compatible with expand_filename(): halve the number of // backslashes. - backslash_halve(s); + backslash_halve((char *)s); (*file)[i] = (char *)s; } *num_file = num_pat; @@ -508,7 +508,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in } // check if this entry should be included - dir = (os_isdir((char_u *)(*file)[i])); + dir = (os_isdir((*file)[i])); if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE))) { continue; } diff --git a/src/nvim/path.c b/src/nvim/path.c index e40729b114..a5cec6772f 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -326,7 +326,7 @@ bool dir_of_file_exists(char_u *fname) } char c = *p; *p = NUL; - bool retval = os_isdir(fname); + bool retval = os_isdir((char *)fname); *p = c; return retval; } @@ -752,7 +752,7 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, // no more wildcards, check if there is a match // remove backslashes for the remaining components only if (*path_end != NUL) { - backslash_halve(buf + len + 1); + backslash_halve((char *)buf + len + 1); } // add existing file or symbolic link if ((flags & EW_ALLLINKS) ? os_fileinfo_link((char *)buf, &file_info) @@ -1135,7 +1135,7 @@ static int expand_in_path(garray_T *const gap, char_u *const pattern, const int if (flags & EW_ADDSLASH) { glob_flags |= WILD_ADD_SLASH; } - globpath((char *)paths, pattern, gap, glob_flags); + globpath((char *)paths, (char *)pattern, gap, glob_flags); xfree(paths); return gap->ga_len; @@ -1312,7 +1312,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i } if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND))) { - char_u *t = backslash_halve_save(p); + char_u *t = (char_u *)backslash_halve_save((char *)p); /* When EW_NOTFOUND is used, always add files and dirs. Makes * "vim c:/" work. */ @@ -1472,7 +1472,7 @@ void addfile(garray_T *gap, char_u *f, int flags) } #endif - isdir = os_isdir(f); + isdir = os_isdir((char *)f); if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE))) { return; } @@ -1845,7 +1845,7 @@ int vim_FullName(const char *fname, char *buf, size_t len, bool force) return OK; } - int rv = path_to_absolute((char_u *)fname, (char_u *)buf, len, force); + int rv = path_to_absolute(fname, buf, len, force); if (rv == FAIL) { xstrlcpy(buf, fname, len); // something failed; use the filename } @@ -1904,7 +1904,7 @@ void path_fix_case(char *name) } // Open the directory where the file is located. - char *slash = (char *)STRRCHR(name, '/'); + char *slash = strrchr(name, '/'); char *tail; Directory dir; bool ok; @@ -2139,7 +2139,7 @@ int expand_wildcards_eval(char_u **pat, int *num_file, char ***file, int flags) true); emsg_off--; if (eval_pat != NULL) { - exp_pat = (char *)concat_str(eval_pat, (char_u *)exp_pat + usedlen); + exp_pat = concat_str((char *)eval_pat, exp_pat + usedlen); } } @@ -2353,20 +2353,20 @@ int append_path(char *path, const char *to_append, size_t max_len) /// @param force also expand when "fname" is already absolute. /// /// @return FAIL for failure, OK for success. -static int path_to_absolute(const char_u *fname, char_u *buf, size_t len, int force) +static int path_to_absolute(const char *fname, char *buf, size_t len, int force) { - char_u *p; + char *p; *buf = NUL; char *relative_directory = xmalloc(len); char *end_of_path = (char *)fname; // expand it if forced or not an absolute path - if (force || !path_is_absolute(fname)) { - p = STRRCHR(fname, '/'); + if (force || !path_is_absolute((char_u *)fname)) { + p = strrchr(fname, '/'); #ifdef WIN32 if (p == NULL) { - p = STRRCHR(fname, '\\'); + p = strrchr(fname, '\\'); } #endif if (p != NULL) { @@ -2380,19 +2380,19 @@ static int path_to_absolute(const char_u *fname, char_u *buf, size_t len, int fo memcpy(relative_directory, fname, (size_t)(p - fname)); relative_directory[p - fname] = NUL; } - end_of_path = (char *)(p + 1); + end_of_path = p + 1; } else { relative_directory[0] = NUL; end_of_path = (char *)fname; } - if (FAIL == path_full_dir_name(relative_directory, (char *)buf, len)) { + if (FAIL == path_full_dir_name(relative_directory, buf, len)) { xfree(relative_directory); return FAIL; } } xfree(relative_directory); - return append_path((char *)buf, end_of_path, len); + return append_path(buf, end_of_path, len); } /// Check if file `fname` is a full (absolute) path. diff --git a/src/nvim/plines.c b/src/nvim/plines.c index 11b6951edd..cc730ba307 100644 --- a/src/nvim/plines.c +++ b/src/nvim/plines.c @@ -262,7 +262,7 @@ int linetabsize_col(int startcol, char *s) cts.cts_vcol += lbr_chartabsize_adv(&cts); } clear_chartabsize_arg(&cts); - return (int)cts.cts_vcol; + return cts.cts_vcol; } /// Like linetabsize(), but for a given window instead of the current one. @@ -530,7 +530,7 @@ static int win_nolbr_chartabsize(chartabsize_T *cts, int *headp) wp->w_buffer->b_p_ts, wp->w_buffer->b_p_vts_array); } - n = ptr2cells((char *)s); + n = ptr2cells(s); // Add one cell for a double-width character in the last column of the // window, displayed with a ">". diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c index b144348188..0d9080ceb7 100644 --- a/src/nvim/popupmenu.c +++ b/src/nvim/popupmenu.c @@ -524,7 +524,7 @@ void pum_redraw(void) } if (pum_rl) { - char *rt = (char *)reverse_text(st); + char *rt = reverse_text((char *)st); char *rt_start = rt; int size = vim_strsize(rt); diff --git a/src/nvim/profile.c b/src/nvim/profile.c index d4f3756f4d..cded231c85 100644 --- a/src/nvim/profile.c +++ b/src/nvim/profile.c @@ -279,7 +279,7 @@ void ex_profile(exarg_T *eap) char *e; int len; - e = (char *)skiptowhite((char_u *)eap->arg); + e = skiptowhite(eap->arg); len = (int)(e - eap->arg); e = skipwhite(e); @@ -354,7 +354,7 @@ void set_context_in_profile_cmd(expand_T *xp, const char *arg) pexpand_what = PEXP_SUBCMD; xp->xp_pattern = (char *)arg; - char_u *const end_subcmd = skiptowhite((const char_u *)arg); + char_u *const end_subcmd = (char_u *)skiptowhite(arg); if (*end_subcmd == NUL) { return; } @@ -612,7 +612,7 @@ static void func_dump_profile(FILE *fd) .script_ctx = fp->uf_script_ctx, .channel_id = 0, }; - char *p = (char *)get_scriptname(last_set, &should_free); + char *p = get_scriptname(last_set, &should_free); fprintf(fd, " Defined: %s:%" PRIdLINENR "\n", p, fp->uf_script_ctx.sc_lnum); if (should_free) { @@ -721,7 +721,7 @@ static void script_dump_profile(FILE *fd) fprintf(fd, "\n"); fprintf(fd, "count total (s) self (s)\n"); - sfd = os_fopen((char *)si->sn_name, "r"); + sfd = os_fopen(si->sn_name, "r"); if (sfd == NULL) { fprintf(fd, "Cannot open file!\n"); } else { diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index 20e6893ea5..f9c4892b91 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -799,7 +799,7 @@ retry: // Convert a line if it contains a non-ASCII character if (state->vc.vc_type != CONV_NONE && has_non_ascii((char_u *)state->linebuf)) { - char *line = (char *)string_convert(&state->vc, (char_u *)state->linebuf, &state->linelen); + char *line = string_convert(&state->vc, state->linebuf, &state->linelen); if (line != NULL) { if (state->linelen < IOSIZE) { STRLCPY(state->linebuf, line, state->linelen + 1); @@ -2129,7 +2129,7 @@ static char *qf_push_dir(char *dirbuf, struct dir_stack_T **stackptr, bool is_fi while (ds_new) { xfree((*stackptr)->dirname); (*stackptr)->dirname = concat_fnames(ds_new->dirname, dirbuf, true); - if (os_isdir((char_u *)(*stackptr)->dirname)) { + if (os_isdir((*stackptr)->dirname)) { break; } @@ -3054,7 +3054,7 @@ static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel) } msg_putchar('\n'); - msg_outtrans_attr(IObuff, cursel ? HL_ATTR(HLF_QFL) : qfFileAttr); + msg_outtrans_attr((char *)IObuff, cursel ? HL_ATTR(HLF_QFL) : qfFileAttr); if (qfp->qf_lnum != 0) { msg_puts_attr(":", qfSepAttr); diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index 41056a2773..e85167f8fd 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -123,7 +123,7 @@ char *estack_sfile(estack_arg_T which) ? &entry->es_info.ufunc->uf_script_ctx : &entry->es_info.aucmd->script_ctx); return def_ctx->sc_sid > 0 - ? xstrdup((char *)(SCRIPT_ITEM(def_ctx->sc_sid).sn_name)) + ? xstrdup((SCRIPT_ITEM(def_ctx->sc_sid).sn_name)) : NULL; } else if (entry->es_type == ETYPE_SCRIPT) { return xstrdup(entry->es_name); @@ -192,7 +192,7 @@ void runtime_init(void) void ex_runtime(exarg_T *eap) { char *arg = eap->arg; - char *p = (char *)skiptowhite((char_u *)arg); + char *p = skiptowhite(arg); ptrdiff_t len = p - arg; int flags = eap->forceit ? DIP_ALL : 0; @@ -226,9 +226,9 @@ static void source_callback(char *fname, void *cookie) /// When "flags" has DIP_ERR: give an error message if there is no match. /// /// return FAIL when no file could be sourced, OK otherwise. -int do_in_path(char_u *path, char *name, int flags, DoInRuntimepathCB callback, void *cookie) +int do_in_path(char *path, char *name, int flags, DoInRuntimepathCB callback, void *cookie) { - char_u *tail; + char *tail; int num_files; char **files; int i; @@ -236,17 +236,17 @@ int do_in_path(char_u *path, char *name, int flags, DoInRuntimepathCB callback, // Make a copy of 'runtimepath'. Invoking the callback may change the // value. - char_u *rtp_copy = vim_strsave(path); + char *rtp_copy = xstrdup(path); char *buf = xmallocz(MAXPATHL); { if (p_verbose > 10 && name != NULL) { verbose_enter(); - smsg(_("Searching for \"%s\" in \"%s\""), name, (char *)path); + smsg(_("Searching for \"%s\" in \"%s\""), name, path); verbose_leave(); } // Loop over all entries in 'runtimepath'. - char *rtp = (char *)rtp_copy; + char *rtp = rtp_copy; while (*rtp != NUL && ((flags & DIP_ALL) || !did_one)) { // Copy the path from 'runtimepath' to buf[]. copy_option_part(&rtp, buf, MAXPATHL, ","); @@ -267,14 +267,14 @@ int do_in_path(char_u *path, char *name, int flags, DoInRuntimepathCB callback, did_one = true; } else if (buflen + STRLEN(name) + 2 < MAXPATHL) { add_pathsep(buf); - tail = (char_u *)buf + STRLEN(buf); + tail = buf + STRLEN(buf); // Loop over all patterns in "name" char *np = name; while (*np != NUL && ((flags & DIP_ALL) || !did_one)) { // Append the pattern from "name" to buf[]. - assert(MAXPATHL >= (tail - (char_u *)buf)); - copy_option_part(&np, (char *)tail, (size_t)(MAXPATHL - (tail - (char_u *)buf)), "\t "); + assert(MAXPATHL >= (tail - buf)); + copy_option_part(&np, tail, (size_t)(MAXPATHL - (tail - buf)), "\t "); if (p_verbose > 10) { verbose_enter(); @@ -303,7 +303,7 @@ int do_in_path(char_u *path, char *name, int flags, DoInRuntimepathCB callback, xfree(buf); xfree(rtp_copy); if (!did_one && name != NULL) { - char *basepath = path == (char_u *)p_rtp ? "runtimepath" : "packpath"; + char *basepath = path == p_rtp ? "runtimepath" : "packpath"; if (flags & DIP_ERR) { semsg(_(e_dirnotf), basepath, name); @@ -363,19 +363,19 @@ void runtime_search_path_unref(RuntimeSearchPath path, int *ref) /// When "flags" has DIP_ERR: give an error message if there is no match. /// /// return FAIL when no file could be sourced, OK otherwise. -int do_in_cached_path(char_u *name, int flags, DoInRuntimepathCB callback, void *cookie) +int do_in_cached_path(char *name, int flags, DoInRuntimepathCB callback, void *cookie) { - char_u *tail; + char *tail; int num_files; char **files; int i; bool did_one = false; - char_u buf[MAXPATHL]; + char buf[MAXPATHL]; if (p_verbose > 10 && name != NULL) { verbose_enter(); - smsg(_("Searching for \"%s\" in runtime path"), (char *)name); + smsg(_("Searching for \"%s\" in runtime path"), name); verbose_leave(); } @@ -399,15 +399,15 @@ int do_in_cached_path(char_u *name, int flags, DoInRuntimepathCB callback, void (*callback)(item.path, cookie); } else if (buflen + STRLEN(name) + 2 < MAXPATHL) { STRCPY(buf, item.path); - add_pathsep((char *)buf); + add_pathsep(buf); tail = buf + STRLEN(buf); // Loop over all patterns in "name" - char *np = (char *)name; + char *np = name; while (*np != NUL && ((flags & DIP_ALL) || !did_one)) { // Append the pattern from "name" to buf[]. assert(MAXPATHL >= (tail - buf)); - copy_option_part(&np, (char *)tail, (size_t)(MAXPATHL - (tail - buf)), "\t "); + copy_option_part(&np, tail, (size_t)(MAXPATHL - (tail - buf)), "\t "); if (p_verbose > 10) { verbose_enter(); @@ -419,7 +419,7 @@ int do_in_cached_path(char_u *name, int flags, DoInRuntimepathCB callback, void | (flags & DIP_DIRFILE) ? (EW_DIR|EW_FILE) : 0; // Expand wildcards, invoke the callback for each match. - char *(pat[]) = { (char *)buf }; + char *(pat[]) = { buf }; if (gen_expand_wildcards(1, pat, &num_files, &files, ew_flags) == OK) { for (i = 0; i < num_files; i++) { (*callback)(files[i], cookie); @@ -499,7 +499,7 @@ ArrayOf(String) runtime_get_named_common(bool lua, Array pat, bool all, if (lua) { if (item->has_lua == kNone) { size_t size = (size_t)snprintf(buf, buf_len, "%s/lua/", item->path); - item->has_lua = (size < buf_len && os_isdir((char_u *)buf)); + item->has_lua = (size < buf_len && os_isdir(buf)); } if (item->has_lua == kFalse) { continue; @@ -534,13 +534,13 @@ done: /// If "name" is NULL calls callback for each entry in "path". Cookie is /// passed by reference in this case, setting it to NULL indicates that callback /// has done its job. -int do_in_path_and_pp(char_u *path, char_u *name, int flags, DoInRuntimepathCB callback, - void *cookie) +int do_in_path_and_pp(char *path, char *name, int flags, DoInRuntimepathCB callback, void *cookie) { int done = FAIL; if ((flags & DIP_NORTP) == 0) { - done |= do_in_path(path, (char *)((name && !*name) ? NULL : name), flags, callback, cookie); + done |= do_in_path(path, (name && !*name) ? NULL : name, flags, callback, + cookie); } if ((done == FAIL || (flags & DIP_ALL)) && (flags & DIP_START)) { @@ -550,7 +550,7 @@ int do_in_path_and_pp(char_u *path, char_u *name, int flags, DoInRuntimepathCB c char *suffix = (flags & DIP_AFTER) ? "after/" : ""; vim_snprintf(s, len, start_dir, suffix, name); - done |= do_in_path((char_u *)p_pp, s, flags & ~DIP_AFTER, callback, cookie); + done |= do_in_path(p_pp, s, flags & ~DIP_AFTER, callback, cookie); xfree(s); @@ -560,7 +560,7 @@ int do_in_path_and_pp(char_u *path, char_u *name, int flags, DoInRuntimepathCB c s = xmallocz(len); vim_snprintf(s, len, start_dir, suffix, name); - done |= do_in_path((char_u *)p_pp, s, flags & ~DIP_AFTER, callback, cookie); + done |= do_in_path(p_pp, s, flags & ~DIP_AFTER, callback, cookie); xfree(s); } @@ -572,7 +572,7 @@ int do_in_path_and_pp(char_u *path, char_u *name, int flags, DoInRuntimepathCB c char *s = xmallocz(len); vim_snprintf(s, len, opt_dir, name); - done |= do_in_path((char_u *)p_pp, s, flags, callback, cookie); + done |= do_in_path(p_pp, s, flags, callback, cookie); xfree(s); @@ -582,7 +582,7 @@ int do_in_path_and_pp(char_u *path, char_u *name, int flags, DoInRuntimepathCB c s = xmallocz(len); vim_snprintf(s, len, opt_dir, name); - done |= do_in_path((char_u *)p_pp, s, flags, callback, cookie); + done |= do_in_path(p_pp, s, flags, callback, cookie); xfree(s); } @@ -625,7 +625,7 @@ static void expand_rtp_entry(RuntimeSearchPath *search_path, Map(String, handle_ } static void expand_pack_entry(RuntimeSearchPath *search_path, Map(String, handle_T) *rtp_used, - CharVec *after_path, char_u *pack_entry, size_t pack_entry_len) + CharVec *after_path, char *pack_entry, size_t pack_entry_len) { static char buf[MAXPATHL]; char *(start_pat[]) = { "/pack/*/start/*", "/start/*" }; // NOLINT @@ -664,10 +664,10 @@ RuntimeSearchPath runtime_search_path_build(void) RuntimeSearchPath search_path = KV_INITIAL_VALUE; CharVec after_path = KV_INITIAL_VALUE; - static char_u buf[MAXPATHL]; + static char buf[MAXPATHL]; for (char *entry = p_pp; *entry != NUL;) { char *cur_entry = entry; - copy_option_part(&entry, (char *)buf, MAXPATHL, ","); + copy_option_part(&entry, buf, MAXPATHL, ","); String the_entry = { .data = cur_entry, .size = STRLEN(buf) }; @@ -678,18 +678,18 @@ RuntimeSearchPath runtime_search_path_build(void) char *rtp_entry; for (rtp_entry = p_rtp; *rtp_entry != NUL;) { char *cur_entry = rtp_entry; - copy_option_part(&rtp_entry, (char *)buf, MAXPATHL, ","); + copy_option_part(&rtp_entry, buf, MAXPATHL, ","); size_t buflen = STRLEN(buf); - if (path_is_after((char *)buf, buflen)) { + if (path_is_after(buf, buflen)) { rtp_entry = cur_entry; break; } // fact: &rtp entries can contain wild chars - expand_rtp_entry(&search_path, &rtp_used, (char *)buf, false); + expand_rtp_entry(&search_path, &rtp_used, buf, false); - handle_T *h = map_ref(String, handle_T)(&pack_used, cstr_as_string((char *)buf), false); + handle_T *h = map_ref(String, handle_T)(&pack_used, cstr_as_string(buf), false); if (h) { (*h)++; expand_pack_entry(&search_path, &rtp_used, &after_path, buf, buflen); @@ -700,7 +700,7 @@ RuntimeSearchPath runtime_search_path_build(void) String item = kv_A(pack_entries, i); handle_T h = map_get(String, handle_T)(&pack_used, item); if (h == 0) { - expand_pack_entry(&search_path, &rtp_used, &after_path, (char_u *)item.data, item.size); + expand_pack_entry(&search_path, &rtp_used, &after_path, item.data, item.size); } } @@ -712,8 +712,8 @@ RuntimeSearchPath runtime_search_path_build(void) // "after" dirs in rtp for (; *rtp_entry != NUL;) { - copy_option_part(&rtp_entry, (char *)buf, MAXPATHL, ","); - expand_rtp_entry(&search_path, &rtp_used, (char *)buf, path_is_after((char *)buf, STRLEN(buf))); + copy_option_part(&rtp_entry, buf, MAXPATHL, ","); + expand_rtp_entry(&search_path, &rtp_used, buf, path_is_after(buf, STRLEN(buf))); } // strings are not owned @@ -767,13 +767,13 @@ int do_in_runtimepath(char *name, int flags, DoInRuntimepathCB callback, void *c { int success = FAIL; if (!(flags & DIP_NORTP)) { - success |= do_in_cached_path((name && !*name) ? NULL : (char_u *)name, flags, callback, cookie); + success |= do_in_cached_path((name && !*name) ? NULL : name, flags, callback, cookie); flags = (flags & ~DIP_START) | DIP_NORTP; } // TODO(bfredl): we could integrate disabled OPT dirs into the cached path // which would effectivize ":packadd myoptpack" as well if ((flags & (DIP_START|DIP_OPT)) && (success == FAIL || (flags & DIP_ALL))) { - success |= do_in_path_and_pp((char_u *)p_rtp, (char_u *)name, flags, callback, cookie); + success |= do_in_path_and_pp(p_rtp, name, flags, callback, cookie); } return success; } @@ -789,7 +789,7 @@ int source_runtime(char *name, int flags) } /// Just like source_runtime(), but use "path" instead of 'runtimepath'. -int source_in_path(char_u *path, char_u *name, int flags) +int source_in_path(char *path, char *name, int flags) { return do_in_path_and_pp(path, name, flags, source_callback, NULL); } @@ -813,14 +813,14 @@ static void source_all_matches(char *pat) /// /// @param fname the package path /// @param is_pack whether the added dir is a "pack/*/start/*/" style package -static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) +static int add_pack_dir_to_rtp(char *fname, bool is_pack) { char *p; char *buf = NULL; char *afterdir = NULL; int retval = FAIL; - char *p1 = get_past_head((char *)fname); + char *p1 = get_past_head(fname); char *p2 = p1; char *p3 = p1; char *p4 = p1; @@ -841,7 +841,7 @@ static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) p4++; // append pathsep in order to expand symlink char c = *p4; *p4 = NUL; - char *const ffname = fix_fname((char *)fname); + char *const ffname = fix_fname(fname); *p4 = c; if (ffname == NULL) { @@ -895,9 +895,9 @@ static int add_pack_dir_to_rtp(char_u *fname, bool is_pack) } // check if rtp/pack/name/start/name/after exists - afterdir = concat_fnames((char *)fname, "after", true); + afterdir = concat_fnames(fname, "after", true); size_t afterlen = 0; - if (is_pack ? pack_has_entries((char_u *)afterdir) : os_isdir((char_u *)afterdir)) { + if (is_pack ? pack_has_entries(afterdir) : os_isdir(afterdir)) { afterlen = strlen(afterdir) + 1; // add one for comma } @@ -964,29 +964,29 @@ theend: /// Load scripts in "plugin" directory of the package. /// For opt packages, also load scripts in "ftdetect" (start packages already /// load these from filetype.vim) -static int load_pack_plugin(bool opt, char_u *fname) +static int load_pack_plugin(bool opt, char *fname) { static const char *ftpat = "%s/ftdetect/*.vim"; // NOLINT - char *const ffname = fix_fname((char *)fname); + char *const ffname = fix_fname(fname); size_t len = strlen(ffname) + STRLEN(ftpat); - char_u *pat = xmallocz(len); + char *pat = xmallocz(len); - vim_snprintf((char *)pat, len, "%s/plugin/**/*.vim", ffname); // NOLINT - source_all_matches((char *)pat); - vim_snprintf((char *)pat, len, "%s/plugin/**/*.lua", ffname); // NOLINT - source_all_matches((char *)pat); + vim_snprintf(pat, len, "%s/plugin/**/*.vim", ffname); // NOLINT + source_all_matches(pat); + vim_snprintf(pat, len, "%s/plugin/**/*.lua", ffname); // NOLINT + source_all_matches(pat); - char_u *cmd = vim_strsave((char_u *)"g:did_load_filetypes"); + char *cmd = xstrdup("g:did_load_filetypes"); // If runtime/filetype.vim wasn't loaded yet, the scripts will be // found when it loads. - if (opt && eval_to_number((char *)cmd) > 0) { + if (opt && eval_to_number(cmd) > 0) { do_cmdline_cmd("augroup filetypedetect"); - vim_snprintf((char *)pat, len, ftpat, ffname); - source_all_matches((char *)pat); + vim_snprintf(pat, len, ftpat, ffname); + source_all_matches(pat); vim_snprintf((char *)pat, len, "%s/ftdetect/*.lua", ffname); // NOLINT - source_all_matches((char *)pat); + source_all_matches(pat); do_cmdline_cmd("augroup END"); } xfree(cmd); @@ -1001,7 +1001,7 @@ static int APP_ADD_DIR; static int APP_LOAD; static int APP_BOTH; -static void add_pack_plugin(bool opt, char_u *fname, void *cookie) +static void add_pack_plugin(bool opt, char *fname, void *cookie) { if (cookie != &APP_LOAD) { char *buf = xmalloc(MAXPATHL); @@ -1010,7 +1010,7 @@ static void add_pack_plugin(bool opt, char_u *fname, void *cookie) const char *p = (const char *)p_rtp; while (*p != NUL) { copy_option_part((char **)&p, buf, MAXPATHL, ","); - if (path_fnamecmp(buf, (char *)fname) == 0) { + if (path_fnamecmp(buf, fname) == 0) { found = true; break; } @@ -1031,25 +1031,25 @@ static void add_pack_plugin(bool opt, char_u *fname, void *cookie) static void add_start_pack_plugin(char *fname, void *cookie) { - add_pack_plugin(false, (char_u *)fname, cookie); + add_pack_plugin(false, fname, cookie); } static void add_opt_pack_plugin(char *fname, void *cookie) { - add_pack_plugin(true, (char_u *)fname, cookie); + add_pack_plugin(true, fname, cookie); } /// Add all packages in the "start" directory to 'runtimepath'. void add_pack_start_dirs(void) { - do_in_path((char_u *)p_pp, NULL, DIP_ALL + DIP_DIR, add_pack_start_dir, NULL); + do_in_path(p_pp, NULL, DIP_ALL + DIP_DIR, add_pack_start_dir, NULL); } -static bool pack_has_entries(char_u *buf) +static bool pack_has_entries(char *buf) { int num_files; char **files; - char *(pat[]) = { (char *)buf }; + char *(pat[]) = { buf }; if (gen_expand_wildcards(1, pat, &num_files, &files, EW_DIR) == OK) { FreeWild(num_files, files); } @@ -1058,7 +1058,7 @@ static bool pack_has_entries(char_u *buf) static void add_pack_start_dir(char *fname, void *cookie) { - static char_u buf[MAXPATHL]; + static char buf[MAXPATHL]; char *(start_pat[]) = { "/start/*", "/pack/*/start/*" }; // NOLINT for (int i = 0; i < 2; i++) { if (STRLEN(fname) + STRLEN(start_pat[i]) + 1 > MAXPATHL) { @@ -1076,9 +1076,9 @@ static void add_pack_start_dir(char *fname, void *cookie) void load_start_packages(void) { did_source_packages = true; - do_in_path((char_u *)p_pp, "pack/*/start/*", DIP_ALL + DIP_DIR, // NOLINT + do_in_path(p_pp, "pack/*/start/*", DIP_ALL + DIP_DIR, // NOLINT add_start_pack_plugin, &APP_LOAD); - do_in_path((char_u *)p_pp, "start/*", DIP_ALL + DIP_DIR, // NOLINT + do_in_path(p_pp, "start/*", DIP_ALL + DIP_DIR, // NOLINT add_start_pack_plugin, &APP_LOAD); } @@ -1099,12 +1099,12 @@ void ex_packloadall(exarg_T *eap) void load_plugins(void) { if (p_lpl) { - char_u *rtp_copy = (char_u *)p_rtp; - char_u *const plugin_pattern_vim = (char_u *)"plugin/**/*.vim"; // NOLINT - char_u *const plugin_pattern_lua = (char_u *)"plugin/**/*.lua"; // NOLINT + char *rtp_copy = p_rtp; + char *const plugin_pattern_vim = "plugin/**/*.vim"; // NOLINT + char *const plugin_pattern_lua = "plugin/**/*.lua"; // NOLINT if (!did_source_packages) { - rtp_copy = vim_strsave((char_u *)p_rtp); + rtp_copy = xstrdup(p_rtp); add_pack_start_dirs(); } @@ -1121,8 +1121,8 @@ void load_plugins(void) } TIME_MSG("loading packages"); - source_runtime((char *)plugin_pattern_vim, DIP_ALL | DIP_AFTER); - source_runtime((char *)plugin_pattern_lua, DIP_ALL | DIP_AFTER); + source_runtime(plugin_pattern_vim, DIP_ALL | DIP_AFTER); + source_runtime(plugin_pattern_lua, DIP_ALL | DIP_AFTER); TIME_MSG("loading after plugins"); } } @@ -1146,7 +1146,7 @@ void ex_packadd(exarg_T *eap) // The first round don't give a "not found" error, in the second round // only when nothing was found in the first round. res = - do_in_path((char_u *)p_pp, pat, DIP_ALL + DIP_DIR + (round == 2 && res == FAIL ? DIP_ERR : 0), + do_in_path(p_pp, pat, DIP_ALL + DIP_DIR + (round == 2 && res == FAIL ? DIP_ERR : 0), round == 1 ? add_start_pack_plugin : add_opt_pack_plugin, eap->forceit ? &APP_ADD_DIR : &APP_BOTH); xfree(pat); @@ -1162,7 +1162,7 @@ void ex_packadd(exarg_T *eap) /// 'packpath'/pack/ * /opt/ * /{dirnames}/{pat}.vim /// When "flags" has DIP_LUA: search also performed for .lua files /// "dirnames" is an array with one or more directory names. -int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirnames[]) +int ExpandRTDir(char *pat, int flags, int *num_file, char ***file, char *dirnames[]) { *num_file = 0; *file = NULL; @@ -1174,11 +1174,11 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna // TODO(bfredl): this is bullshit, exandpath should not reinvent path logic. for (int i = 0; dirnames[i] != NULL; i++) { size_t size = STRLEN(dirnames[i]) + pat_len + 7; - char_u *s = xmalloc(size); - snprintf((char *)s, size, "%s/%s*.vim", dirnames[i], pat); + char *s = xmalloc(size); + snprintf(s, size, "%s/%s*.vim", dirnames[i], pat); globpath(p_rtp, s, &ga, 0); if (flags & DIP_LUA) { - snprintf((char *)s, size, "%s/%s*.lua", dirnames[i], pat); + snprintf(s, size, "%s/%s*.lua", dirnames[i], pat); globpath(p_rtp, s, &ga, 0); } xfree(s); @@ -1187,11 +1187,11 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna if (flags & DIP_START) { for (int i = 0; dirnames[i] != NULL; i++) { size_t size = STRLEN(dirnames[i]) + pat_len + 22; - char_u *s = xmalloc(size); - snprintf((char *)s, size, "pack/*/start/*/%s/%s*.vim", dirnames[i], pat); // NOLINT + char *s = xmalloc(size); + snprintf(s, size, "pack/*/start/*/%s/%s*.vim", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); if (flags & DIP_LUA) { - snprintf((char *)s, size, "pack/*/start/*/%s/%s*.lua", dirnames[i], pat); // NOLINT + snprintf(s, size, "pack/*/start/*/%s/%s*.lua", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); } xfree(s); @@ -1199,11 +1199,11 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna for (int i = 0; dirnames[i] != NULL; i++) { size_t size = STRLEN(dirnames[i]) + pat_len + 22; - char_u *s = xmalloc(size); - snprintf((char *)s, size, "start/*/%s/%s*.vim", dirnames[i], pat); // NOLINT + char *s = xmalloc(size); + snprintf(s, size, "start/*/%s/%s*.vim", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); if (flags & DIP_LUA) { - snprintf((char *)s, size, "start/*/%s/%s*.lua", dirnames[i], pat); // NOLINT + snprintf(s, size, "start/*/%s/%s*.lua", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); } xfree(s); @@ -1213,11 +1213,11 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna if (flags & DIP_OPT) { for (int i = 0; dirnames[i] != NULL; i++) { size_t size = STRLEN(dirnames[i]) + pat_len + 20; - char_u *s = xmalloc(size); - snprintf((char *)s, size, "pack/*/opt/*/%s/%s*.vim", dirnames[i], pat); // NOLINT + char *s = xmalloc(size); + snprintf(s, size, "pack/*/opt/*/%s/%s*.vim", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); if (flags & DIP_LUA) { - snprintf((char *)s, size, "pack/*/opt/*/%s/%s*.lua", dirnames[i], pat); // NOLINT + snprintf(s, size, "pack/*/opt/*/%s/%s*.lua", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); } xfree(s); @@ -1225,11 +1225,11 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna for (int i = 0; dirnames[i] != NULL; i++) { size_t size = STRLEN(dirnames[i]) + pat_len + 20; - char_u *s = xmalloc(size); - snprintf((char *)s, size, "opt/*/%s/%s*.vim", dirnames[i], pat); // NOLINT + char *s = xmalloc(size); + snprintf(s, size, "opt/*/%s/%s*.vim", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); if (flags & DIP_LUA) { - snprintf((char *)s, size, "opt/*/%s/%s*.lua", dirnames[i], pat); // NOLINT + snprintf(s, size, "opt/*/%s/%s*.lua", dirnames[i], pat); // NOLINT globpath(p_pp, s, &ga, 0); } xfree(s); @@ -1237,9 +1237,9 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna } for (int i = 0; i < ga.ga_len; i++) { - char_u *match = ((char_u **)ga.ga_data)[i]; - char_u *s = match; - char_u *e = s + STRLEN(s); + char *match = ((char **)ga.ga_data)[i]; + char *s = match; + char *e = s + STRLEN(s); if (e - s > 4 && (STRNICMP(e - 4, ".vim", 4) == 0 || ((flags & DIP_LUA) && STRNICMP(e - 4, ".lua", 4) == 0))) { @@ -1271,7 +1271,7 @@ int ExpandRTDir(char_u *pat, int flags, int *num_file, char ***file, char *dirna /// Expand loadplugin names: /// 'packpath'/pack/ * /opt/{pat} -int ExpandPackAddDir(char_u *pat, int *num_file, char ***file) +int ExpandPackAddDir(char *pat, int *num_file, char ***file) { garray_T ga; @@ -1281,16 +1281,16 @@ int ExpandPackAddDir(char_u *pat, int *num_file, char ***file) ga_init(&ga, (int)sizeof(char *), 10); size_t buflen = pat_len + 26; - char_u *s = xmalloc(buflen); - snprintf((char *)s, buflen, "pack/*/opt/%s*", pat); // NOLINT + char *s = xmalloc(buflen); + snprintf(s, buflen, "pack/*/opt/%s*", pat); // NOLINT globpath(p_pp, s, &ga, 0); - snprintf((char *)s, buflen, "opt/%s*", pat); // NOLINT + snprintf(s, buflen, "opt/%s*", pat); // NOLINT globpath(p_pp, s, &ga, 0); xfree(s); for (int i = 0; i < ga.ga_len; i++) { - char_u *match = ((char_u **)ga.ga_data)[i]; - s = (char_u *)path_tail((char *)match); + char *match = ((char **)ga.ga_data)[i]; + s = path_tail(match); memmove(match, s, STRLEN(s) + 1); } @@ -1479,7 +1479,7 @@ char *get_lib_dir(void) // TODO(bfredl): too fragile? Ideally default_lib_dir would be made empty // in an appimage build if (strlen(default_lib_dir) != 0 - && os_isdir((const char_u *)default_lib_dir)) { + && os_isdir(default_lib_dir)) { return xstrdup(default_lib_dir); } @@ -1611,7 +1611,7 @@ static void cmd_source(char *fname, exarg_T *eap) // - after ":argdo", ":windo" or ":bufdo" // - another command follows // - inside a loop - openscript((char_u *)fname, global_busy || listcmd_busy || eap->nextcmd != NULL + openscript(fname, global_busy || listcmd_busy || eap->nextcmd != NULL || eap->cstack->cs_idx >= 0); // ":source" read ex commands @@ -1691,12 +1691,12 @@ static FILE *fopen_noinh_readbin(char *filename) /// /// @return true if this line did begin with a continuation (the next line /// should also be considered, if it exists); false otherwise -static bool concat_continued_line(garray_T *const ga, const int init_growsize, - const char_u *const p, size_t len) +static bool concat_continued_line(garray_T *const ga, const int init_growsize, const char *const p, + size_t len) FUNC_ATTR_NONNULL_ALL { - const char *const line = (char *)skipwhite_len(p, len); - len -= (size_t)((char_u *)line - p); + const char *const line = skipwhite_len((char *)p, len); + len -= (size_t)(line - p); // Skip lines starting with '\" ', concat lines starting with '\' if (len >= 3 && STRNCMP(line, "\"\\ ", 3) == 0) { return true; @@ -1732,15 +1732,15 @@ static char *get_str_line(int c, void *cookie, int indent, bool do_concat) return NULL; } const char *line = p->buf + p->offset; - const char *eol = (char *)skip_to_newline((char_u *)line); + const char *eol = skip_to_newline(line); garray_T ga; - ga_init(&ga, sizeof(char_u), 400); + ga_init(&ga, sizeof(char), 400); ga_concat_len(&ga, line, (size_t)(eol - line)); if (do_concat && vim_strchr(p_cpo, CPO_CONCAT) == NULL) { while (eol[0] != NUL) { line = eol + 1; - const char_u *const next_eol = skip_to_newline((char_u *)line); - if (!concat_continued_line(&ga, 400, (char_u *)line, (size_t)(next_eol - (char_u *)line))) { + const char *const next_eol = skip_to_newline(line); + if (!concat_continued_line(&ga, 400, line, (size_t)(next_eol - line))) { break; } eol = (char *)next_eol; @@ -1770,7 +1770,7 @@ scriptitem_T *new_script_item(char *const name, scid_T *const sid_out) SCRIPT_ITEM(script_items.ga_len).sn_name = NULL; SCRIPT_ITEM(script_items.ga_len).sn_prof_on = false; } - SCRIPT_ITEM(sid).sn_name = (char_u *)name; + SCRIPT_ITEM(sid).sn_name = name; new_script_vars(sid); // Allocate the local script variables to use for this script. return &SCRIPT_ITEM(sid); } @@ -1814,7 +1814,7 @@ static void cmd_source_buffer(const exarg_T *const eap) return; } garray_T ga; - ga_init(&ga, sizeof(char_u), 400); + ga_init(&ga, sizeof(char), 400); const linenr_T final_lnum = eap->line2; // Copy the contents to be executed. for (linenr_T curr_lnum = eap->line1; curr_lnum <= final_lnum; curr_lnum++) { @@ -1825,7 +1825,7 @@ static void cmd_source_buffer(const exarg_T *const eap) ga_concat(&ga, (char *)ml_get(curr_lnum)); ga_append(&ga, NL); } - ((char_u *)ga.ga_data)[ga.ga_len - 1] = NUL; + ((char *)ga.ga_data)[ga.ga_len - 1] = NUL; const GetStrLineCookie cookie = { .buf = ga.ga_data, .offset = 0, @@ -1886,7 +1886,7 @@ int do_source(char *fname, int check_other, int is_vimrc) if (fname_exp == NULL) { return retval; } - if (os_isdir((char_u *)fname_exp)) { + if (os_isdir(fname_exp)) { smsg(_("Cannot source a directory: \"%s\""), fname); goto theend; } @@ -1963,7 +1963,7 @@ int do_source(char *fname, int check_other, int is_vimrc) cookie.finished = false; // Check if this script has a breakpoint. - cookie.breakpoint = dbg_find_breakpoint(true, (char_u *)fname_exp, (linenr_T)0); + cookie.breakpoint = dbg_find_breakpoint(true, fname_exp, (linenr_T)0); cookie.fname = fname_exp; cookie.dbg_tick = debug_tick; @@ -1992,7 +1992,7 @@ int do_source(char *fname, int check_other, int is_vimrc) si = get_current_script_id(&fname_exp, ¤t_sctx); // Keep the sourcing name/lnum, for recursive calls. - estack_push(ETYPE_SCRIPT, (char *)si->sn_name, 0); + estack_push(ETYPE_SCRIPT, si->sn_name, 0); if (l_do_profiling == PROF_YES) { bool forceit = false; @@ -2025,7 +2025,7 @@ int do_source(char *fname, int check_other, int is_vimrc) && firstline[1] == 0xbb && firstline[2] == 0xbf) { // Found BOM; setup conversion, skip over BOM and recode the line. convert_setup(&cookie.conv, "utf-8", p_enc); - p = (char *)string_convert(&cookie.conv, (char_u *)firstline + 3, NULL); + p = string_convert(&cookie.conv, (char *)firstline + 3, NULL); if (p == NULL) { p = xstrdup((char *)firstline + 3); } @@ -2128,7 +2128,7 @@ scriptitem_T *get_current_script_id(char **fnamep, sctx_T *ret_sctx) } if (script_sctx.sc_sid == 0) { si = new_script_item(*fnamep, &script_sctx.sc_sid); - *fnamep = xstrdup((char *)si->sn_name); + *fnamep = xstrdup(si->sn_name); } if (ret_sctx != NULL) { *ret_sctx = script_sctx; @@ -2145,7 +2145,7 @@ void ex_scriptnames(exarg_T *eap) if (eap->line2 < 1 || eap->line2 > script_items.ga_len) { emsg(_(e_invarg)); } else { - eap->arg = (char *)SCRIPT_ITEM(eap->line2).sn_name; + eap->arg = SCRIPT_ITEM(eap->line2).sn_name; do_exedit(eap, NULL); } return; @@ -2153,7 +2153,7 @@ void ex_scriptnames(exarg_T *eap) for (int i = 1; i <= script_items.ga_len && !got_int; i++) { if (SCRIPT_ITEM(i).sn_name != NULL) { - home_replace(NULL, (char *)SCRIPT_ITEM(i).sn_name, (char *)NameBuff, MAXPATHL, true); + home_replace(NULL, SCRIPT_ITEM(i).sn_name, (char *)NameBuff, MAXPATHL, true); vim_snprintf((char *)IObuff, IOSIZE, "%3d: %s", i, NameBuff); if (!message_filtered((char *)IObuff)) { msg_putchar('\n'); @@ -2179,40 +2179,40 @@ void scriptnames_slash_adjust(void) /// Get a pointer to a script name. Used for ":verbose set". /// Message appended to "Last set from " -char_u *get_scriptname(LastSet last_set, bool *should_free) +char *get_scriptname(LastSet last_set, bool *should_free) { *should_free = false; switch (last_set.script_ctx.sc_sid) { case SID_MODELINE: - return (char_u *)_("modeline"); + return _("modeline"); case SID_CMDARG: - return (char_u *)_("--cmd argument"); + return _("--cmd argument"); case SID_CARG: - return (char_u *)_("-c argument"); + return _("-c argument"); case SID_ENV: - return (char_u *)_("environment variable"); + return _("environment variable"); case SID_ERROR: - return (char_u *)_("error handler"); + return _("error handler"); case SID_WINLAYOUT: - return (char_u *)_("changed window size"); + return _("changed window size"); case SID_LUA: - return (char_u *)_("Lua"); + return _("Lua"); case SID_API_CLIENT: snprintf((char *)IObuff, IOSIZE, _("API client (channel id %" PRIu64 ")"), last_set.channel_id); - return IObuff; + return (char *)IObuff; case SID_STR: - return (char_u *)_("anonymous :source"); + return _("anonymous :source"); default: { - char *const sname = (char *)SCRIPT_ITEM(last_set.script_ctx.sc_sid).sn_name; + char *const sname = SCRIPT_ITEM(last_set.script_ctx.sc_sid).sn_name; if (sname == NULL) { snprintf((char *)IObuff, IOSIZE, _("anonymous :source (script id %d)"), last_set.script_ctx.sc_sid); - return IObuff; + return (char *)IObuff; } *should_free = true; - return (char_u *)home_replace_save(NULL, sname); + return home_replace_save(NULL, sname); } } } @@ -2248,7 +2248,7 @@ char *getsourceline(int c, void *cookie, int indent, bool do_concat) // If breakpoints have been added/deleted need to check for it. if (sp->dbg_tick < debug_tick) { - sp->breakpoint = dbg_find_breakpoint(true, (char_u *)sp->fname, SOURCING_LNUM); + sp->breakpoint = dbg_find_breakpoint(true, sp->fname, SOURCING_LNUM); sp->dbg_tick = debug_tick; } if (do_profiling == PROF_YES) { @@ -2287,11 +2287,10 @@ char *getsourceline(int c, void *cookie, int indent, bool do_concat) || (p[0] == '"' && p[1] == '\\' && p[2] == ' '))) { garray_T ga; - ga_init(&ga, (int)sizeof(char_u), 400); + ga_init(&ga, (int)sizeof(char), 400); ga_concat(&ga, line); while (sp->nextline != NULL - && concat_continued_line(&ga, 400, (char_u *)sp->nextline, - STRLEN(sp->nextline))) { + && concat_continued_line(&ga, 400, sp->nextline, STRLEN(sp->nextline))) { xfree(sp->nextline); sp->nextline = get_one_sourceline(sp); } @@ -2305,7 +2304,7 @@ char *getsourceline(int c, void *cookie, int indent, bool do_concat) char *s; // Convert the encoding of the script line. - s = (char *)string_convert(&sp->conv, (char_u *)line, NULL); + s = string_convert(&sp->conv, line, NULL); if (s != NULL) { xfree(line); line = s; @@ -2314,9 +2313,9 @@ char *getsourceline(int c, void *cookie, int indent, bool do_concat) // Did we encounter a breakpoint? if (sp->breakpoint != 0 && sp->breakpoint <= SOURCING_LNUM) { - dbg_breakpoint((char_u *)sp->fname, SOURCING_LNUM); + dbg_breakpoint(sp->fname, SOURCING_LNUM); // Find next breakpoint. - sp->breakpoint = dbg_find_breakpoint(true, (char_u *)sp->fname, SOURCING_LNUM); + sp->breakpoint = dbg_find_breakpoint(true, sp->fname, SOURCING_LNUM); sp->dbg_tick = debug_tick; } diff --git a/src/nvim/runtime.h b/src/nvim/runtime.h index 03c426c79b..053c71212e 100644 --- a/src/nvim/runtime.h +++ b/src/nvim/runtime.h @@ -51,7 +51,7 @@ typedef enum { } estack_arg_T; typedef struct scriptitem_S { - char_u *sn_name; + char *sn_name; bool sn_prof_on; ///< true when script is/was profiled bool sn_pr_force; ///< forceit: profile functions in this script proftime_T sn_pr_child; ///< time set when going into first child diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 6efaae3725..d268dde845 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -1270,7 +1270,7 @@ static int get_encoded_char_adv(const char_u **p) int64_t num = 0; for (int bytes = s[1] == 'x' ? 1 : s[1] == 'u' ? 2 : 4; bytes > 0; bytes--) { *p += 2; - int n = hexhex2nr(*p); + int n = hexhex2nr((char *)(*p)); if (n < 0) { return 0; } diff --git a/src/nvim/search.c b/src/nvim/search.c index c1c2f0dbe9..e995081df8 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -170,7 +170,7 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc } if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { - mr_pattern = reverse_text(pat); + mr_pattern = (char_u *)reverse_text((char *)pat); mr_pattern_alloced = true; } else { mr_pattern = pat; @@ -1261,7 +1261,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, // it would be blanked out again very soon. Show it on the // left, but do reverse the text. if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { - char_u *r = reverse_text(trunc != NULL ? trunc : msgbuf); + char_u *r = (char_u *)reverse_text(trunc != NULL ? (char *)trunc : (char *)msgbuf); xfree(msgbuf); msgbuf = r; // move reversed text to beginning of buffer @@ -3666,7 +3666,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo if (new_fname != NULL) { // using "new_fname" is more reliable, e.g., when // 'includeexpr' is set. - msg_outtrans_attr(new_fname, HL_ATTR(HLF_D)); + msg_outtrans_attr((char *)new_fname, HL_ATTR(HLF_D)); } else { /* * Isolate the file name. @@ -3702,7 +3702,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo } save_char = p[i]; p[i] = NUL; - msg_outtrans_attr(p, HL_ATTR(HLF_D)); + msg_outtrans_attr((char *)p, HL_ATTR(HLF_D)); p[i] = save_char; } diff --git a/src/nvim/shada.c b/src/nvim/shada.c index 88ad7d519a..d2f1b39ca4 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -3023,7 +3023,7 @@ shada_write_file_nomerge: {} if (tail != fname) { const char tail_save = *tail; *tail = NUL; - if (!os_isdir((char_u *)fname)) { + if (!os_isdir(fname)) { int ret; char *failed_dir; if ((ret = os_mkdir_recurse(fname, 0700, &failed_dir)) != 0) { diff --git a/src/nvim/sign.c b/src/nvim/sign.c index a9640eacda..ed7f53d3ba 100644 --- a/src/nvim/sign.c +++ b/src/nvim/sign.c @@ -858,7 +858,7 @@ static void sign_define_init_icon(sign_T *sp, char_u *icon) { xfree(sp->sn_icon); sp->sn_icon = vim_strsave(icon); - backslash_halve(sp->sn_icon); + backslash_halve((char *)sp->sn_icon); } /// Initialize the text for a new sign @@ -1353,7 +1353,7 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si if (STRNCMP(arg, "line=", 5) == 0) { arg += 5; *lnum = atoi((char *)arg); - arg = skiptowhite(arg); + arg = (char_u *)skiptowhite((char *)arg); lnum_arg = true; } else if (STRNCMP(arg, "*", 1) == 0 && cmd == SIGNCMD_UNPLACE) { if (*signid != -1) { @@ -1361,11 +1361,11 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si return FAIL; } *signid = -2; - arg = skiptowhite(arg + 1); + arg = (char_u *)skiptowhite((char *)arg + 1); } else if (STRNCMP(arg, "name=", 5) == 0) { arg += 5; name = arg; - arg = skiptowhite(arg); + arg = (char_u *)skiptowhite((char *)arg); if (*arg != NUL) { *arg++ = NUL; } @@ -1376,14 +1376,14 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si } else if (STRNCMP(arg, "group=", 6) == 0) { arg += 6; *group = arg; - arg = skiptowhite(arg); + arg = (char_u *)skiptowhite((char *)arg); if (*arg != NUL) { *arg++ = NUL; } } else if (STRNCMP(arg, "priority=", 9) == 0) { arg += 9; *prio = atoi((char *)arg); - arg = skiptowhite(arg); + arg = (char_u *)skiptowhite((char *)arg); } else if (STRNCMP(arg, "file=", 5) == 0) { arg += 5; filename = arg; @@ -1427,7 +1427,7 @@ void ex_sign(exarg_T *eap) sign_T *sp; // Parse the subcommand. - p = skiptowhite(arg); + p = (char_u *)skiptowhite((char *)arg); idx = sign_cmd_idx(arg, p); if (idx == SIGNCMD_LAST) { semsg(_("E160: Unknown sign command: %s"), arg); @@ -1449,7 +1449,7 @@ void ex_sign(exarg_T *eap) // Isolate the sign name. If it's a number skip leading zeroes, // so that "099" and "99" are the same sign. But keep "0". - p = skiptowhite(arg); + p = (char_u *)skiptowhite((char *)arg); if (*p != NUL) { *p++ = NUL; } @@ -1789,7 +1789,7 @@ void set_context_in_sign_cmd(expand_T *xp, char_u *arg) expand_what = EXP_SUBCMD; xp->xp_pattern = (char *)arg; - end_subcmd = skiptowhite(arg); + end_subcmd = (char_u *)skiptowhite((char *)arg); if (*end_subcmd == NUL) { // expand subcmd name // :sign {subcmd} @@ -1814,7 +1814,7 @@ void set_context_in_sign_cmd(expand_T *xp, char_u *arg) do { p = (char_u *)skipwhite((char *)p); last = p; - p = skiptowhite(p); + p = (char_u *)skiptowhite((char *)p); } while (*p != NUL); p = (char_u *)vim_strchr((char *)last, '='); diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 10923829c3..1259736e0e 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -243,7 +243,7 @@ size_t spell_check(win_T *wp, char_u *ptr, hlf_T *attrp, int *capcol, bool docou if (*ptr == '0' && (ptr[1] == 'b' || ptr[1] == 'B')) { mi.mi_end = (char_u *)skipbin((char *)ptr + 2); } else if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X')) { - mi.mi_end = skiphex(ptr + 2); + mi.mi_end = (char_u *)skiphex((char *)ptr + 2); } else { mi.mi_end = (char_u *)skipdigits((char *)ptr); } @@ -1258,10 +1258,10 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att // For checking first word with a capital skip white space. if (capcol == 0) { - capcol = (int)getwhitecols(line); + capcol = (int)getwhitecols((char *)line); } else if (curline && wp == curwin) { // For spellbadword(): check if first word needs a capital. - col = (int)getwhitecols(line); + col = (int)getwhitecols((char *)line); if (check_need_cap(lnum, col)) { capcol = col; } @@ -1876,7 +1876,7 @@ char *did_set_spelllang(win_T *wp) // Check if we loaded this language before. for (slang = first_lang; slang != NULL; slang = slang->sl_next) { - if (path_full_compare((char *)lang, (char *)slang->sl_fname, false, true) + if (path_full_compare((char *)lang, slang->sl_fname, false, true) == kEqualFiles) { break; } @@ -1925,7 +1925,7 @@ char *did_set_spelllang(win_T *wp) // Loop over the languages, there can be several files for "lang". for (slang = first_lang; slang != NULL; slang = slang->sl_next) { if (filename - ? path_full_compare((char *)lang, (char *)slang->sl_fname, false, true) == kEqualFiles + ? path_full_compare((char *)lang, slang->sl_fname, false, true) == kEqualFiles : STRICMP(lang, slang->sl_name) == 0) { region_mask = REGION_ALL; if (!filename && region != NULL) { @@ -1981,7 +1981,7 @@ char *did_set_spelllang(win_T *wp) // If it was already found above then skip it. for (c = 0; c < ga.ga_len; c++) { - p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname; + p = (char_u *)LANGP_ENTRY(ga, c)->lp_slang->sl_fname; if (p != NULL && path_full_compare((char *)spf_name, (char *)p, false, true) == kEqualFiles) { break; @@ -1994,7 +1994,7 @@ char *did_set_spelllang(win_T *wp) // Check if it was loaded already. for (slang = first_lang; slang != NULL; slang = slang->sl_next) { - if (path_full_compare((char *)spf_name, (char *)slang->sl_fname, false, true) + if (path_full_compare((char *)spf_name, slang->sl_fname, false, true) == kEqualFiles) { break; } @@ -2473,7 +2473,7 @@ bool check_need_cap(linenr_T lnum, colnr_T col) char_u *line = get_cursor_line_ptr(); char_u *line_copy = NULL; colnr_T endcol = 0; - if (getwhitecols(line) >= (int)col) { + if (getwhitecols((char *)line) >= (int)col) { // At start of line, check if previous line is empty or sentence // ends there. if (lnum == 1) { @@ -2484,7 +2484,7 @@ bool check_need_cap(linenr_T lnum, colnr_T col) need_cap = true; } else { // Append a space in place of the line break. - line_copy = concat_str(line, (char_u *)" "); + line_copy = (char_u *)concat_str((char *)line, " "); line = line_copy; endcol = (colnr_T)STRLEN(line); } @@ -3599,8 +3599,8 @@ char *compile_cap_prog(synblock_T *synblock) synblock->b_cap_prog = NULL; } else { // Prepend a ^ so that we only match at one column - char_u *re = concat_str((char_u *)"^", (char_u *)synblock->b_p_spc); - synblock->b_cap_prog = vim_regcomp((char *)re, RE_MAGIC); + char *re = concat_str("^", synblock->b_p_spc); + synblock->b_cap_prog = vim_regcomp(re, RE_MAGIC); xfree(re); if (synblock->b_cap_prog == NULL) { synblock->b_cap_prog = rp; // restore the previous program diff --git a/src/nvim/spell_defs.h b/src/nvim/spell_defs.h index 61f722b9ee..27b9777dc2 100644 --- a/src/nvim/spell_defs.h +++ b/src/nvim/spell_defs.h @@ -115,9 +115,9 @@ typedef struct slang_S slang_T; struct slang_S { slang_T *sl_next; // next language - char_u *sl_name; // language name "en", "en.rare", "nl", etc. - char_u *sl_fname; // name of .spl file - bool sl_add; // true if it's a .add file. + char_u *sl_name; // language name "en", "en.rare", "nl", etc. + char *sl_fname; // name of .spl file + bool sl_add; // true if it's a .add file. char_u *sl_fbyts; // case-folded word bytes long sl_fbyts_len; // length of sl_fbyts diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index 33e8c5c099..0f8034312e 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -604,7 +604,7 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile lp = slang_alloc(lang); // Remember the file name, used to reload the file when it's updated. - lp->sl_fname = vim_strsave(fname); + lp->sl_fname = (char *)vim_strsave(fname); // Check for .add.spl. lp->sl_add = strstr(path_tail((char *)fname), SPL_FNAME_ADD) != NULL; @@ -869,12 +869,12 @@ static void tree_count_words(char_u *byts, idx_T *idxs) } } -// Load the .sug files for languages that have one and weren't loaded yet. +/// Load the .sug files for languages that have one and weren't loaded yet. void suggest_load_files(void) { langp_T *lp; slang_T *slang; - char_u *dotp; + char *dotp; FILE *fd; char_u buf[MAXWLEN]; int i; @@ -894,12 +894,12 @@ void suggest_load_files(void) // don't try again and again. slang->sl_sugloaded = true; - dotp = STRRCHR(slang->sl_fname, '.'); + dotp = strrchr(slang->sl_fname, '.'); if (dotp == NULL || FNAMECMP(dotp, ".spl") != 0) { continue; } STRCPY(dotp, ".sug"); - fd = os_fopen((char *)slang->sl_fname, "r"); + fd = os_fopen(slang->sl_fname, "r"); if (fd == NULL) { goto nextone; } @@ -1822,7 +1822,7 @@ static void spell_reload_one(char_u *fname, bool added_word) bool didit = false; for (slang = first_lang; slang != NULL; slang = slang->sl_next) { - if (path_full_compare((char *)fname, (char *)slang->sl_fname, false, true) == kEqualFiles) { + if (path_full_compare((char *)fname, slang->sl_fname, false, true) == kEqualFiles) { slang_clear(slang); if (spell_load_file(fname, NULL, slang, false) == NULL) { // reloading failed, clear the language @@ -2075,7 +2075,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname) // Convert from "SET" to 'encoding' when needed. xfree(pc); if (spin->si_conv.vc_type != CONV_NONE) { - pc = string_convert(&spin->si_conv, rline, NULL); + pc = (char_u *)string_convert(&spin->si_conv, (char *)rline, NULL); if (pc == NULL) { smsg(_("Conversion failure for word in %s line %d: %s"), fname, lnum, rline); @@ -3155,7 +3155,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) // Convert from "SET" to 'encoding' when needed. if (spin->si_conv.vc_type != CONV_NONE) { - pc = string_convert(&spin->si_conv, line, NULL); + pc = (char_u *)string_convert(&spin->si_conv, (char *)line, NULL); if (pc == NULL) { smsg(_("Conversion failure for word in %s line %d: %s"), fname, lnum, line); @@ -3701,7 +3701,7 @@ static int spell_read_wordfile(spellinfo_T *spin, char_u *fname) // Convert from "/encoding={encoding}" to 'encoding' when needed. xfree(pc); if (spin->si_conv.vc_type != CONV_NONE) { - pc = string_convert(&spin->si_conv, rline, NULL); + pc = (char_u *)string_convert(&spin->si_conv, (char *)rline, NULL); if (pc == NULL) { smsg(_("Conversion failure for word in %s line %ld: %s"), fname, lnum, rline); @@ -4907,7 +4907,7 @@ static void spell_make_sugfile(spellinfo_T *spin, char *wfname) // of the code for the soundfolding stuff. // It might have been done already by spell_reload_one(). for (slang = first_lang; slang != NULL; slang = slang->sl_next) { - if (path_full_compare(wfname, (char *)slang->sl_fname, false, true) + if (path_full_compare(wfname, slang->sl_fname, false, true) == kEqualFiles) { break; } @@ -5343,7 +5343,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool emsg(_(e_exists)); goto theend; } - if (os_isdir((char_u *)wfname)) { + if (os_isdir(wfname)) { semsg(_(e_isadir2), wfname); goto theend; } @@ -5723,7 +5723,7 @@ static void init_spellfile(void) "/%.*s", (int)(lend - lstart), lstart); } l = (int)STRLEN(buf); - fname = LANGP_ENTRY(curwin->w_s->b_langp, 0) + fname = (char_u *)LANGP_ENTRY(curwin->w_s->b_langp, 0) ->lp_slang->sl_fname; vim_snprintf((char *)buf + l, MAXPATHL - (size_t)l, ".%s.add", ((fname != NULL diff --git a/src/nvim/spellsuggest.c b/src/nvim/spellsuggest.c index fa46d94342..23c8c621b5 100644 --- a/src/nvim/spellsuggest.c +++ b/src/nvim/spellsuggest.c @@ -972,7 +972,7 @@ static void suggest_try_special(suginfo_T *su) char_u word[MAXWLEN]; // Recognize a word that is repeated: "the the". - char_u *p = skiptowhite(su->su_fbadword); + char_u *p = (char_u *)skiptowhite((char *)su->su_fbadword); size_t len = (size_t)(p - su->su_fbadword); p = (char_u *)skipwhite((char *)p); if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0) { @@ -1369,8 +1369,8 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so if (compound_ok) { p = preword; - while (*skiptowhite(p) != NUL) { - p = (char_u *)skipwhite((char *)skiptowhite(p)); + while (*skiptowhite((char *)p) != NUL) { + p = (char_u *)skipwhite(skiptowhite((char *)p)); } if (fword_ends && !can_compound(slang, p, compflags + sp->ts_compsplit)) { @@ -1590,8 +1590,8 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so break; } p = preword; - while (*skiptowhite(p) != NUL) { - p = (char_u *)skipwhite((char *)skiptowhite(p)); + while (*skiptowhite((char *)p) != NUL) { + p = (char_u *)skipwhite(skiptowhite((char *)p)); } if (sp->ts_complen > sp->ts_compsplit && !can_compound(slang, p, @@ -2636,8 +2636,8 @@ static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u * // removing the space. Don't do it when the good word also contains a // space. if (ascii_iswhite(su->su_badptr[su->su_badlen]) - && *skiptowhite(stp->st_word) == NUL) { - for (p = fword; *(p = skiptowhite(p)) != NUL;) { + && *skiptowhite((char *)stp->st_word) == NUL) { + for (p = fword; *(p = (char_u *)skiptowhite((char *)p)) != NUL;) { STRMOVE(p, p + 1); } } diff --git a/src/nvim/strings.c b/src/nvim/strings.c index bd0f122f99..16691d0ded 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -503,7 +503,7 @@ static int sort_compare(const void *s1, const void *s2) void sort_strings(char **files, int count) { - qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare); + qsort((void *)files, (size_t)count, sizeof(char *), sort_compare); } /* @@ -540,14 +540,12 @@ bool has_non_ascii_len(const char *const s, const size_t len) return false; } -/* - * Concatenate two strings and return the result in allocated memory. - */ -char_u *concat_str(const char_u *restrict str1, const char_u *restrict str2) +/// Concatenate two strings and return the result in allocated memory. +char *concat_str(const char *restrict str1, const char *restrict str2) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { size_t l = STRLEN(str1); - char_u *dest = xmalloc(l + STRLEN(str2) + 1); + char *dest = xmalloc(l + STRLEN(str2) + 1); STRCPY(dest, str1); STRCPY(dest + l, str2); return dest; @@ -1511,15 +1509,15 @@ int kv_do_printf(StringBuilder *str, const char *fmt, ...) /// Reverse text into allocated memory. /// /// @return the allocated string. -char_u *reverse_text(char_u *s) +char *reverse_text(char *s) FUNC_ATTR_NONNULL_RET { // Reverse the pattern. size_t len = STRLEN(s); - char_u *rev = xmalloc(len + 1); + char *rev = xmalloc(len + 1); size_t rev_i = len; for (size_t s_i = 0; s_i < len; s_i++) { - const int mb_len = utfc_ptr2len((char *)s + s_i); + const int mb_len = utfc_ptr2len(s + s_i); rev_i -= (size_t)mb_len; memmove(rev + rev_i, s + s_i, (size_t)mb_len); s_i += (size_t)mb_len - 1; diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index e88b1b17f6..f055cc9b0e 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -3013,7 +3013,7 @@ static void syn_cmd_conceal(exarg_T *eap, int syncing) return; } - next = skiptowhite(arg); + next = (char_u *)skiptowhite((char *)arg); if (*arg == NUL) { if (curwin->w_s->b_syn_conceal) { msg("syntax conceal on"); @@ -3042,7 +3042,7 @@ static void syn_cmd_case(exarg_T *eap, int syncing) return; } - next = skiptowhite(arg); + next = (char_u *)skiptowhite((char *)arg); if (*arg == NUL) { if (curwin->w_s->b_syn_ic) { msg("syntax case ignore"); @@ -3081,7 +3081,7 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) return; } - arg_end = skiptowhite(arg); + arg_end = (char_u *)skiptowhite((char *)arg); if (STRNICMP(arg, "start", 5) == 0 && arg_end - arg == 5) { curwin->w_s->b_syn_foldlevel = SYNFLD_START; } else if (STRNICMP(arg, "minimum", 7) == 0 && arg_end - arg == 7) { @@ -3110,7 +3110,7 @@ static void syn_cmd_spell(exarg_T *eap, int syncing) return; } - next = skiptowhite(arg); + next = (char_u *)skiptowhite((char *)arg); if (*arg == NUL) { if (curwin->w_s->b_syn_spell == SYNSPL_TOP) { msg("syntax spell toplevel"); @@ -3345,7 +3345,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) * Clear the group IDs that are in the argument. */ while (!ends_excmd(*arg)) { - arg_end = skiptowhite(arg); + arg_end = (char_u *)skiptowhite((char *)arg); if (*arg == '@') { id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { @@ -3522,7 +3522,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing) * List the group IDs and syntax clusters that are in the argument. */ while (!ends_excmd(*arg) && !got_int) { - arg_end = skiptowhite(arg); + arg_end = (char_u *)skiptowhite((char *)arg); if (*arg == '@') { int id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { @@ -4029,7 +4029,7 @@ static void add_keyword(char_u *const name, const int id, const int flags, /// Return NULL if the end of the command was found instead of further args. static char *get_group_name(char *arg, char **name_end) { - *name_end = (char *)skiptowhite((char_u *)arg); + *name_end = skiptowhite(arg); char *rest = skipwhite(*name_end); // Check if there are enough arguments. The first argument may be a @@ -4163,7 +4163,7 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i return NULL; } gname_start = (char_u *)arg; - arg = (char *)skiptowhite((char_u *)arg); + arg = skiptowhite(arg); if (gname_start == (char_u *)arg) { return NULL; } @@ -4600,7 +4600,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) } if (item == ITEM_MATCHGROUP) { - p = (char *)skiptowhite((char_u *)rest); + p = skiptowhite(rest); if ((p - rest == 4 && STRNCMP(rest, "NONE", 4) == 0) || eap->skip) { matchgroup_id = 0; } else { @@ -5141,7 +5141,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) } while (!ends_excmd(*arg_start)) { - arg_end = (char *)skiptowhite(arg_start); + arg_end = skiptowhite((char *)arg_start); next_arg = (char_u *)skipwhite(arg_end); xfree(key); key = vim_strnsave_up(arg_start, (size_t)(arg_end - (char *)arg_start)); @@ -5150,7 +5150,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT; } if (!ends_excmd(*next_arg)) { - arg_end = (char *)skiptowhite(next_arg); + arg_end = skiptowhite((char *)next_arg); if (!eap->skip) { curwin->w_s->b_syn_sync_id = (int16_t)syn_check_group((char *)next_arg, (size_t)(arg_end - (char *)next_arg)); @@ -5693,10 +5693,10 @@ void set_context_in_syntax_cmd(expand_T *xp, const char *arg) // (part of) subcommand already typed if (*arg != NUL) { - const char *p = (const char *)skiptowhite((const char_u *)arg); + const char *p = (const char *)skiptowhite(arg); if (*p != NUL) { // Past first word. xp->xp_pattern = skipwhite(p); - if (*skiptowhite((char_u *)xp->xp_pattern) != NUL) { + if (*skiptowhite(xp->xp_pattern) != NUL) { xp->xp_context = EXPAND_NOTHING; } else if (STRNICMP(arg, "case", p - arg) == 0) { expand_what = EXP_CASE; @@ -6028,7 +6028,7 @@ static void syntime_report(void) if (len > (int)STRLEN(p->pattern)) { len = (int)STRLEN(p->pattern); } - msg_outtrans_len(p->pattern, len); + msg_outtrans_len((char *)p->pattern, len); msg_puts("\n"); } ga_clear(&ga); diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 11825ce1c4..5270412382 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -738,7 +738,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char mt_names[matches[i][0] & MT_MASK]); msg_puts((char *)IObuff); if (tagp.tagkind != NULL) { - msg_outtrans_len(tagp.tagkind, + msg_outtrans_len((char *)tagp.tagkind, (int)(tagp.tagkind_end - tagp.tagkind)); } msg_advance(13); @@ -752,7 +752,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char // it and put "..." in the middle p = tag_full_fname(&tagp); if (p != NULL) { - msg_outtrans_attr(p, HL_ATTR(HLF_D)); + msg_outtrans_attr((char *)p, HL_ATTR(HLF_D)); XFREE_CLEAR(p); } if (msg_col > 0) { @@ -794,7 +794,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char } msg_advance(15); } - p = msg_outtrans_one(p, attr); + p = (char_u *)msg_outtrans_one((char *)p, attr); if (*p == TAB) { msg_puts_attr(" ", attr); break; @@ -852,7 +852,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char msg_putchar(' '); p++; } else { - p = msg_outtrans_one(p, 0); + p = (char_u *)msg_outtrans_one((char *)p, 0); } // don't display the "$/;\"" and "$?;\"" @@ -1052,7 +1052,7 @@ void do_tags(exarg_T *eap) tagstack[i].tagname, tagstack[i].fmark.mark.lnum); msg_outtrans((char *)IObuff); - msg_outtrans_attr(name, tagstack[i].fmark.fnum == curbuf->b_fnum + msg_outtrans_attr((char *)name, tagstack[i].fmark.fnum == curbuf->b_fnum ? HL_ATTR(HLF_D) : 0); xfree(name); } @@ -1561,7 +1561,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc // Try tag file names from tags option one by one. for (first_file = true; - use_cscope || get_tagfname(&tn, first_file, tag_fname) == OK; + use_cscope || get_tagfname(&tn, first_file, (char *)tag_fname) == OK; first_file = false) { // A file that doesn't exist is silently ignored. Only when not a // single file is found, an error message is given (further on). @@ -1705,7 +1705,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc eof = vim_fgets(lbuf, lbuf_size, fp); } // skip empty and blank lines - while (!eof && vim_isblankline(lbuf)) { + while (!eof && vim_isblankline((char *)lbuf)) { search_info.curr_offset = vim_ftell(fp); eof = vim_fgets(lbuf, lbuf_size, fp); } @@ -1726,7 +1726,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc eof = use_cscope ? cs_fgets(lbuf, lbuf_size) : vim_fgets(lbuf, lbuf_size, fp); - } while (!eof && vim_isblankline(lbuf)); + } while (!eof && vim_isblankline((char *)lbuf)); if (eof) { break; // end of file @@ -1741,7 +1741,7 @@ line_read_in: // Convert every line. Converting the pattern from 'enc' to // the tags file encoding doesn't work, because characters are // not recognized. - conv_line = string_convert(&vimconv, lbuf, NULL); + conv_line = (char_u *)string_convert(&vimconv, (char *)lbuf, NULL); if (conv_line != NULL) { // Copy or swap lbuf and conv_line. len = (int)STRLEN(conv_line) + 1; @@ -2340,10 +2340,10 @@ void free_tag_stuff(void) /// @param buf pointer to buffer of MAXPATHL chars /// /// @return FAIL if no more tag file names, OK otherwise. -int get_tagfname(tagname_T *tnp, int first, char_u *buf) +int get_tagfname(tagname_T *tnp, int first, char *buf) { - char_u *fname = NULL; - char_u *r_ptr; + char *fname = NULL; + char *r_ptr; if (first) { CLEAR_POINTER(tnp); @@ -2374,7 +2374,7 @@ int get_tagfname(tagname_T *tnp, int first, char_u *buf) #ifdef BACKSLASH_IN_FILENAME slash_adjust(buf); #endif - simplify_filename(buf); + simplify_filename((char_u *)buf); for (int i = 0; i < tag_fnames.ga_len; i++) { if (STRCMP(buf, ((char **)(tag_fnames.ga_data))[i]) == 0) { @@ -2402,7 +2402,7 @@ int get_tagfname(tagname_T *tnp, int first, char_u *buf) */ for (;;) { if (tnp->tn_did_filefind_init) { - fname = vim_findfile(tnp->tn_search_ctx); + fname = (char *)vim_findfile(tnp->tn_search_ctx); if (fname != NULL) { break; } @@ -2422,17 +2422,17 @@ int get_tagfname(tagname_T *tnp, int first, char_u *buf) * Copy next file name into buf. */ buf[0] = NUL; - (void)copy_option_part(&tnp->tn_np, (char *)buf, MAXPATHL - 1, " ,"); + (void)copy_option_part(&tnp->tn_np, buf, MAXPATHL - 1, " ,"); - r_ptr = vim_findfile_stopdir(buf); + r_ptr = (char *)vim_findfile_stopdir((char_u *)buf); // move the filename one char forward and truncate the // filepath with a NUL - filename = (char_u *)path_tail((char *)buf); + filename = (char_u *)path_tail(buf); STRMOVE(filename + 1, filename); *filename++ = NUL; - tnp->tn_search_ctx = vim_findfile_init(buf, filename, - r_ptr, 100, + tnp->tn_search_ctx = vim_findfile_init((char_u *)buf, filename, + (char_u *)r_ptr, 100, false, // don't free visited list FINDFILE_FILE, // we search for a file tnp->tn_search_ctx, true, (char_u *)curbuf->b_ffname); diff --git a/src/nvim/undo.c b/src/nvim/undo.c index ac52bce2f9..97a925f3ad 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -685,7 +685,7 @@ char *u_get_undo_file_name(const char *const buf_ffname, const bool reading) *p-- = NUL; } - bool has_directory = os_isdir((char_u *)dir_name); + bool has_directory = os_isdir(dir_name); if (!has_directory && *dirp == NUL && !reading) { // Last directory in the list does not exist, create it. int ret; diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index ae312de61a..5b2101587f 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -216,7 +216,7 @@ const char *set_context_in_user_cmd(expand_T *xp, const char *arg_in) // Check for attributes while (*arg == '-') { arg++; // Skip "-". - p = (const char *)skiptowhite((const char_u *)arg); + p = (const char *)skiptowhite(arg); if (*p == NUL) { // Cursor is still in the attribute. p = strchr(arg, '='); @@ -248,7 +248,7 @@ const char *set_context_in_user_cmd(expand_T *xp, const char *arg_in) } // After the attributes comes the new command name. - p = (const char *)skiptowhite((const char_u *)arg); + p = (const char *)skiptowhite(arg); if (*p == NUL) { xp->xp_context = EXPAND_USER_COMMANDS; xp->xp_pattern = (char *)arg; @@ -434,7 +434,7 @@ static void uc_list(char *name, size_t name_len) msg_putchar(' '); } - msg_outtrans_attr((char_u *)cmd->uc_name, HL_ATTR(HLF_D)); + msg_outtrans_attr(cmd->uc_name, HL_ATTR(HLF_D)); len = (int)STRLEN(cmd->uc_name) + 4; do { @@ -930,7 +930,7 @@ void ex_command(exarg_T *eap) // Check for attributes while (*p == '-') { p++; - end = (char *)skiptowhite((char_u *)p); + end = skiptowhite(p); if (uc_scan_attr(p, (size_t)(end - p), &argt, &def, &flags, &compl, (char_u **)&compl_arg, &addr_type_arg) == FAIL) { return; diff --git a/src/nvim/vim.h b/src/nvim/vim.h index 3e12d8b0b4..ec8d6ab153 100644 --- a/src/nvim/vim.h +++ b/src/nvim/vim.h @@ -230,10 +230,7 @@ enum { FOLD_TEXT_LEN = 51, }; //!< buffer size for get_foldtext() # endif #endif -#define STRRCHR(s, c) (char_u *)strrchr((const char *)(s), (c)) - -#define STRCAT(d, s) strcat((char *)(d), (char *)(s)) -#define STRNCAT(d, s, n) strncat((char *)(d), (char *)(s), (size_t)(n)) +#define STRCAT(d, s) strcat((char *)(d), (char *)(s)) // NOLINT(runtime/printf) #define STRLCAT(d, s, n) xstrlcat((char *)(d), (char *)(s), (size_t)(n)) // Character used as separated in autoload function/variable names. diff --git a/src/nvim/viml/parser/parser.h b/src/nvim/viml/parser/parser.h index b8835127e7..55f54cedbe 100644 --- a/src/nvim/viml/parser/parser.h +++ b/src/nvim/viml/parser/parser.h @@ -142,9 +142,7 @@ static inline void viml_preader_get_line(ParserInputReader *const preader, .allocated = true, .size = pline.size, }; - cpline.data = (char *)string_convert(&preader->conv, - (char_u *)pline.data, - &cpline.size); + cpline.data = string_convert(&preader->conv, (char *)pline.data, &cpline.size); if (pline.allocated) { xfree((void *)pline.data); } diff --git a/src/nvim/window.c b/src/nvim/window.c index 832cb82bda..5adc8db088 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -730,7 +730,7 @@ void win_set_minimal_style(win_T *wp) char_u *old = (char_u *)wp->w_p_fcs; wp->w_p_fcs = ((*old == NUL) ? xstrdup("eob: ") - : (char *)concat_str(old, (char_u *)",eob: ")); + : concat_str((char *)old, ",eob: ")); free_string_option((char *)old); } @@ -739,7 +739,7 @@ void win_set_minimal_style(win_T *wp) char_u *old = (char_u *)wp->w_p_winhl; wp->w_p_winhl = ((*old == NUL) ? xstrdup("EndOfBuffer:") - : (char *)concat_str(old, (char_u *)",EndOfBuffer:")); + : concat_str((char *)old, ",EndOfBuffer:")); free_string_option((char *)old); parse_winhl_opt(wp); -- cgit From 6b7eed1884c3b022cc15568c39f80f8f4da0780b Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 30 Aug 2022 21:16:03 +0200 Subject: Vim 9.0.{0314,0319}: some filetypes are not recognized (#20005) * vim-patch:9.0.0314: VDM files are not recognized Problem: VDM files are not recognized. Solution: Add patterns for VDM files. (Alessandro Pezzoni, closes vim/vim#11004) https://github.com/vim/vim/commit/bf26941f40923d331169a4ecb7341608f5d1ca38 * vim-patch:9.0.0319: Godot shader files are not recognized Problem: Godot shader files are not recognized. Solution: Add patterns for "gdshader". (Maxim Kim, closes vim/vim#11006) https://github.com/vim/vim/commit/d5c8f11905abc1bdf3b8864dbc40187855ed9374 --- runtime/filetype.vim | 10 +++++++++- runtime/lua/vim/filetype.lua | 9 ++++++++- src/nvim/testdir/test_filetype.vim | 4 ++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 52a20d5c10..98d9df8b5c 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -697,7 +697,10 @@ au BufNewFile,BufRead *.mo,*.gdmo setf gdmo au BufNewFile,BufRead *.gd setf gdscript " Godot resource -au BufRead,BufNewFile *.tscn,*.tres setf gdresource +au BufRead,BufNewFile *.tscn,*.tres setf gdresource + +" Godot shader +au BufRead,BufNewFile *.gdshader,*.shader setf gdshader " Gedcom au BufNewFile,BufRead *.ged,lltxxxxx.txt setf gedcom @@ -2095,6 +2098,11 @@ au BufNewFile,BufRead */.config/upstart/*.override setf upstart " Vala au BufNewFile,BufRead *.vala setf vala +" VDM +au BufRead,BufNewFile *.vdmpp,*.vpp setf vdmpp +au BufRead,BufNewFile *.vdmrt setf vdmrt +au BufRead,BufNewFile *.vdmsl,*.vdm setf vdmsl + " Vera au BufNewFile,BufRead *.vr,*.vri,*.vrh setf vera diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 99c98764dd..fcd697a7c1 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -422,9 +422,11 @@ local extension = { gdb = 'gdb', gdmo = 'gdmo', mo = 'gdmo', - tres = 'gdresource', tscn = 'gdresource', + tres = 'gdresource', gd = 'gdscript', + gdshader = 'gdshader', + shader = 'gdshader', ged = 'gedcom', gmi = 'gemtext', gemini = 'gemtext', @@ -1011,6 +1013,11 @@ local extension = { dsm = 'vb', ctl = 'vb', vbs = 'vb', + vdmpp = 'vdmpp', + vpp = 'vdmpp', + vdmrt = 'vdmrt', + vdmsl = 'vdmsl', + vdm = 'vdmsl', vr = 'vera', vri = 'vera', vrh = 'vera', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index e3a8370661..68ce9148a4 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -209,6 +209,7 @@ let s:filename_checks = { \ 'gdmo': ['file.mo', 'file.gdmo'], \ 'gdresource': ['file.tscn', 'file.tres'], \ 'gdscript': ['file.gd'], + \ 'gdshader': ['file.gdshader', 'file.shader'], \ 'gedcom': ['file.ged', 'lltxxxxx.txt', '/tmp/lltmp', '/tmp/lltmp-file', 'any/tmp/lltmp', 'any/tmp/lltmp-file'], \ 'gemtext': ['file.gmi', 'file.gemini'], \ 'gift': ['file.gift'], @@ -588,6 +589,9 @@ let s:filename_checks = { \ 'usw2kagtlog': ['usw2kagt.log', 'USW2KAGT.LOG', 'usw2kagt.file.log', 'USW2KAGT.FILE.LOG', 'file.usw2kagt.log', 'FILE.USW2KAGT.LOG'], \ 'vala': ['file.vala'], \ 'vb': ['file.sba', 'file.vb', 'file.vbs', 'file.dsm', 'file.ctl'], + \ 'vdmpp': ['file.vpp', 'file.vdmpp'], + \ 'vdmrt': ['file.vdmrt'], + \ 'vdmsl': ['file.vdm', 'file.vdmsl'], \ 'vera': ['file.vr', 'file.vri', 'file.vrh'], \ 'verilog': ['file.v'], \ 'verilogams': ['file.va', 'file.vams'], -- cgit From 813476bf7291dfaf9fc0ef77c9f53a07258a3801 Mon Sep 17 00:00:00 2001 From: Sean Dewar Date: Tue, 30 Aug 2022 23:13:52 +0100 Subject: fix(exceptions): restore `did_throw` (#20000) `!did_throw` doesn't exactly imply `!current_exception`, as `did_throw = false` is sometimes used to defer exception handling for later (without forgetting the exception). E.g: uncaught exception handling in `do_cmdline()` may be deferred to a different call (e.g: when `try_level > 0`). In #7881, `current_exception = NULL` in `do_cmdline()` is used as an analogue of `did_throw = false`, but also causes the pending exception to be lost, which also leaks as `discard_exception()` wasn't used. It may be possible to fix this by saving/restoring `current_exception`, but handling all of `did_throw`'s edge cases seems messier. Maybe not worth diverging over. This fix also uncovers a `man_spec.lua` bug on Windows: exceptions are thrown due to Windows missing `man`, but they're lost; skip these tests if `man` isn't executable. --- src/nvim/api/private/helpers.c | 8 +- src/nvim/api/private/helpers.h | 1 + src/nvim/api/vimscript.c | 4 +- src/nvim/eval.c | 2 +- src/nvim/eval/userfunc.c | 2 +- src/nvim/ex_docmd.c | 32 ++++--- src/nvim/ex_eval.c | 163 +++++++++++++++----------------- src/nvim/globals.h | 6 +- src/nvim/lua/executor.c | 2 +- test/functional/plugin/man_spec.lua | 6 ++ test/functional/vimscript/eval_spec.lua | 28 ++++++ 11 files changed, 143 insertions(+), 111 deletions(-) diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c index e35c58bf1b..ebcf6cca6d 100644 --- a/src/nvim/api/private/helpers.c +++ b/src/nvim/api/private/helpers.c @@ -58,6 +58,7 @@ void try_enter(TryState *const tstate) .private_msg_list = NULL, .trylevel = trylevel, .got_int = got_int, + .did_throw = did_throw, .need_rethrow = need_rethrow, .did_emsg = did_emsg, }; @@ -65,6 +66,7 @@ void try_enter(TryState *const tstate) current_exception = NULL; trylevel = 1; got_int = false; + did_throw = false; need_rethrow = false; did_emsg = false; } @@ -85,6 +87,7 @@ bool try_leave(const TryState *const tstate, Error *const err) assert(trylevel == 0); assert(!need_rethrow); assert(!got_int); + assert(!did_throw); assert(!did_emsg); assert(msg_list == &tstate->private_msg_list); assert(*msg_list == NULL); @@ -93,6 +96,7 @@ bool try_leave(const TryState *const tstate, Error *const err) current_exception = tstate->current_exception; trylevel = tstate->trylevel; got_int = tstate->got_int; + did_throw = tstate->did_throw; need_rethrow = tstate->need_rethrow; did_emsg = tstate->did_emsg; return ret; @@ -127,7 +131,7 @@ bool try_end(Error *err) force_abort = false; if (got_int) { - if (current_exception) { + if (did_throw) { // If we got an interrupt, discard the current exception discard_current_exception(); } @@ -146,7 +150,7 @@ bool try_end(Error *err) if (should_free) { xfree(msg); } - } else if (current_exception) { + } else if (did_throw) { api_set_error(err, kErrorTypeException, "%s", current_exception->value); discard_current_exception(); } diff --git a/src/nvim/api/private/helpers.h b/src/nvim/api/private/helpers.h index 4608554448..2157ad0ec2 100644 --- a/src/nvim/api/private/helpers.h +++ b/src/nvim/api/private/helpers.h @@ -134,6 +134,7 @@ typedef struct { const msglist_T *const *msg_list; int trylevel; int got_int; + bool did_throw; int need_rethrow; int did_emsg; } TryState; diff --git a/src/nvim/api/vimscript.c b/src/nvim/api/vimscript.c index a28bfd2ab9..f6d0e39327 100644 --- a/src/nvim/api/vimscript.c +++ b/src/nvim/api/vimscript.c @@ -137,7 +137,7 @@ Object nvim_eval(String expr, Error *err) if (!recursive) { force_abort = false; suppress_errthrow = false; - current_exception = NULL; + did_throw = false; // `did_emsg` is set by emsg(), which cancels execution. did_emsg = false; } @@ -196,7 +196,7 @@ static Object _call_function(String fn, Array args, dict_T *self, Error *err) if (!recursive) { force_abort = false; suppress_errthrow = false; - current_exception = NULL; + did_throw = false; // `did_emsg` is set by emsg(), which cancels execution. did_emsg = false; } diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 508d7cf491..2dbaa2f8ac 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -5985,7 +5985,7 @@ void timer_due_cb(TimeWatcher *tw, void *data) // Handle error message if (called_emsg > called_emsg_before && did_emsg) { timer->emsg_count++; - if (current_exception != NULL) { + if (did_throw) { discard_current_exception(); } } diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index b9a94a971b..1f94f9c2b7 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -3010,7 +3010,7 @@ void ex_call(exarg_T *eap) // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. - if ((!aborting() || current_exception != NULL) && (!failed || eap->cstack->cs_trylevel > 0)) { + if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. if (!ends_excmd(*arg)) { if (!failed && !aborting()) { diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 1fa14f4e4f..bf518f3849 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -134,6 +134,7 @@ struct dbg_stuff { char *vv_throwpoint; int did_emsg; int got_int; + bool did_throw; int need_rethrow; int check_cstack; except_T *current_exception; @@ -165,6 +166,7 @@ static void save_dbg_stuff(struct dbg_stuff *dsp) // Necessary for debugging an inactive ":catch", ":finally", ":endtry". dsp->did_emsg = did_emsg; did_emsg = false; dsp->got_int = got_int; got_int = false; + dsp->did_throw = did_throw; did_throw = false; dsp->need_rethrow = need_rethrow; need_rethrow = false; dsp->check_cstack = check_cstack; check_cstack = false; dsp->current_exception = current_exception; current_exception = NULL; @@ -180,6 +182,7 @@ static void restore_dbg_stuff(struct dbg_stuff *dsp) (void)v_throwpoint(dsp->vv_throwpoint); did_emsg = dsp->did_emsg; got_int = dsp->got_int; + did_throw = dsp->did_throw; need_rethrow = dsp->need_rethrow; check_cstack = dsp->check_cstack; current_exception = dsp->current_exception; @@ -397,7 +400,8 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) initial_trylevel = trylevel; - current_exception = NULL; + // "did_throw" will be set to true when an exception is being thrown. + did_throw = false; // "did_emsg" will be set to true when emsg() is used, in which case we // cancel the whole command line, and any if/endif or loop. // If force_abort is set, we cancel everything. @@ -625,7 +629,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // not to use a cs_line[] from an entry that isn't a ":while" // or ":for": It would make "current_line" invalid and can // cause a crash. - if (!did_emsg && !got_int && !current_exception + if (!did_emsg && !got_int && !did_throw && cstack.cs_idx >= 0 && (cstack.cs_flags[cstack.cs_idx] & (CSF_WHILE | CSF_FOR)) @@ -666,7 +670,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) current_line = 0; } - // A ":finally" makes did_emsg, got_int and current_exception pending for + // A ":finally" makes did_emsg, got_int and did_throw pending for // being restored at the ":endtry". Reset them here and set the // ACTIVE and FINALLY flags, so that the finally clause gets executed. // This includes the case where a missing ":endif", ":endwhile" or @@ -675,9 +679,8 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) cstack.cs_lflags &= ~CSL_HAD_FINA; report_make_pending((cstack.cs_pending[cstack.cs_idx] & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW)), - current_exception); - did_emsg = got_int = false; - current_exception = NULL; + did_throw ? current_exception : NULL); + did_emsg = got_int = did_throw = false; cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY; } @@ -690,7 +693,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // exception, cancel everything. If it is left normally, reset // force_abort to get the non-EH compatible abortion behavior for // the rest of the script. - if (trylevel == 0 && !did_emsg && !got_int && !current_exception) { + if (trylevel == 0 && !did_emsg && !got_int && !did_throw) { force_abort = false; } @@ -704,7 +707,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // - didn't get an error message or lines are not typed // - there is a command after '|', inside a :if, :while, :for or :try, or // looping for ":source" command or function call. - } while (!((got_int || (did_emsg && force_abort) || current_exception) + } while (!((got_int || (did_emsg && force_abort) || did_throw) && cstack.cs_trylevel == 0) && !(did_emsg // Keep going when inside try/catch, so that the error can be @@ -724,7 +727,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) if (cstack.cs_idx >= 0) { // If a sourced file or executed function ran to its end, report the // unclosed conditional. - if (!got_int && !current_exception + if (!got_int && !did_throw && ((getline_equal(fgetline, cookie, getsourceline) && !source_finished(fgetline, cookie)) || (getline_equal(fgetline, cookie, get_func_line) @@ -767,7 +770,8 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // conditional, discard the uncaught exception, disable the conversion // of interrupts or errors to exceptions, and ensure that no more // commands are executed. - if (current_exception) { + if (did_throw) { + assert(current_exception != NULL); char *p = NULL; msglist_T *messages = NULL; msglist_T *next; @@ -829,14 +833,14 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // cstack belongs to the same function or, respectively, script file, it // will have to be checked for finally clauses to be executed due to the // ":return" or ":finish". This is done in do_one_cmd(). - if (current_exception) { + if (did_throw) { need_rethrow = true; } if ((getline_equal(fgetline, cookie, getsourceline) && ex_nesting_level > source_level(real_cookie)) || (getline_equal(fgetline, cookie, get_func_line) && ex_nesting_level > func_level(real_cookie) + 1)) { - if (!current_exception) { + if (!did_throw) { check_cstack = true; } } else { @@ -1675,7 +1679,7 @@ static void profile_cmd(const exarg_T *eap, cstack_T *cstack, LineGetter fgetlin && (!eap->skip || cstack->cs_idx == 0 || (cstack->cs_idx > 0 && (cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)))) { - int skip = did_emsg || got_int || current_exception; + bool skip = did_emsg || got_int || did_throw; if (eap->cmdidx == CMD_catch) { skip = !skip && !(cstack->cs_idx >= 0 @@ -1872,7 +1876,7 @@ static char *do_one_cmd(char **cmdlinep, int flags, cstack_T *cstack, LineGetter ea.skip = (did_emsg || got_int - || current_exception + || did_throw || (cstack->cs_idx >= 0 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE))); diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c index 11795684cf..6dddafcfcb 100644 --- a/src/nvim/ex_eval.c +++ b/src/nvim/ex_eval.c @@ -49,16 +49,15 @@ // interrupt (got_int) under an active try conditional terminates the script // after the non-active finally clauses of all active try conditionals have been // executed. Otherwise, errors and/or interrupts are converted into catchable -// exceptions, which terminate the script only if not caught. For user -// exceptions, only current_exception is set. (Note: got_int can be set -// asynchronously afterwards by a SIGINT, so current_exception && got_int is not +// exceptions (did_throw additionally set), which terminate the script only if +// not caught. For user exceptions, only did_throw is set. (Note: got_int can +// be set asynchronously afterwards by a SIGINT, so did_throw && got_int is not // a reliant test that the exception currently being thrown is an interrupt // exception. Similarly, did_emsg can be set afterwards on an error in an -// (unskipped) conditional command inside an inactive conditional, so -// current_exception && did_emsg is not a reliant test that the exception -// currently being thrown is an error exception.) - The macros can be defined -// as expressions checking for a variable that is allowed to be changed during -// execution of a script. +// (unskipped) conditional command inside an inactive conditional, so did_throw +// && did_emsg is not a reliant test that the exception currently being thrown +// is an error exception.) - The macros can be defined as expressions checking +// for a variable that is allowed to be changed during execution of a script. // Values used for the Vim release. #define THROW_ON_ERROR true @@ -71,7 +70,7 @@ #define CHECK_SKIP \ (did_emsg \ || got_int \ - || current_exception \ + || did_throw \ || (cstack->cs_idx > 0 \ && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE))) @@ -104,7 +103,7 @@ static int cause_abort = false; /// value. "got_int" is also set by calling interrupt(). int aborting(void) { - return (did_emsg && force_abort) || got_int || current_exception; + return (did_emsg && force_abort) || got_int || did_throw; } /// The value of "force_abort" is temporarily reset by the first emsg() call @@ -186,7 +185,7 @@ bool cause_errthrow(const char *mesg, bool severe, bool *ignore) * currently throwing an exception, do nothing. The message text will * then be stored to v:errmsg by emsg() without displaying it. */ - if (((trylevel == 0 && !cause_abort) || emsg_silent) && !current_exception) { + if (((trylevel == 0 && !cause_abort) || emsg_silent) && !did_throw) { return false; } @@ -217,7 +216,7 @@ bool cause_errthrow(const char *mesg, bool severe, bool *ignore) * exception currently being thrown to prevent it from being caught. Just * execute finally clauses and terminate. */ - if (current_exception) { + if (did_throw) { // When discarding an interrupt exception, reset got_int to prevent the // same interrupt being converted to an exception again and discarding // the error exception we are about to throw here. @@ -349,7 +348,7 @@ int do_intthrow(cstack_T *cstack) { // If no interrupt occurred or no try conditional is active and no exception // is being thrown, do nothing (for compatibility of non-EH scripts). - if (!got_int || (trylevel == 0 && !current_exception)) { + if (!got_int || (trylevel == 0 && !did_throw)) { return false; } @@ -358,7 +357,7 @@ int do_intthrow(cstack_T *cstack) // The interrupt aborts everything except for executing finally clauses. // Discard any user or error or interrupt exception currently being // thrown. - if (current_exception) { + if (did_throw) { discard_current_exception(); } } else { @@ -369,7 +368,7 @@ int do_intthrow(cstack_T *cstack) // will be terminated then. - If an interrupt exception is already // being thrown, do nothing. - if (current_exception) { + if (did_throw) { if (current_exception->type == ET_INTERRUPT) { return false; } @@ -596,6 +595,7 @@ void discard_current_exception(void) } // Note: all globals manipulated here should be saved/restored in // try_enter/try_leave. + did_throw = false; need_rethrow = false; } @@ -1237,6 +1237,8 @@ void do_throw(cstack_T *cstack) cstack->cs_flags[idx] &= ~CSF_ACTIVE; cstack->cs_exception[idx] = current_exception; } + + did_throw = true; } /// Handle ":try" @@ -1345,7 +1347,7 @@ void ex_catch(exarg_T *eap) * corresponding try block never got active (because of an inactive * surrounding conditional or after an error or interrupt or throw). */ - if (!current_exception || !(cstack->cs_flags[idx] & CSF_TRUE)) { + if (!did_throw || !(cstack->cs_flags[idx] & CSF_TRUE)) { skip = true; } @@ -1406,10 +1408,10 @@ void ex_catch(exarg_T *eap) } if (caught) { - // Make this ":catch" clause active and reset did_emsg and got_int. - // Put the exception on the caught stack. + // Make this ":catch" clause active and reset did_emsg, got_int, + // and did_throw. Put the exception on the caught stack. cstack->cs_flags[idx] |= CSF_ACTIVE | CSF_CAUGHT; - did_emsg = got_int = false; + did_emsg = got_int = did_throw = false; catch_exception((except_T *)cstack->cs_exception[idx]); // It's mandatory that the current exception is stored in the cstack // so that it can be discarded at the next ":catch", ":finally", or @@ -1419,10 +1421,6 @@ void ex_catch(exarg_T *eap) if (cstack->cs_exception[cstack->cs_idx] != current_exception) { internal_error("ex_catch()"); } - // Discarding current_exceptions happens based on what is stored in - // cstack->cs_exception, *all* calls to discard_current_exception() are - // (and must be) guarded by current_exception check. - current_exception = NULL; } else { /* * If there is a preceding catch clause and it caught the exception, @@ -1477,14 +1475,12 @@ void ex_finally(exarg_T *eap) rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR, &cstack->cs_looplevel); - /* - * Don't do something when the corresponding try block never got active - * (because of an inactive surrounding conditional or after an error or - * interrupt or throw) or for a ":finally" without ":try" or a multiple - * ":finally". After every other error (did_emsg or the conditional - * errors detected above) or after an interrupt (got_int) or an - * exception (current_exception), the finally clause must be executed. - */ + // Don't do something when the corresponding try block never got active + // (because of an inactive surrounding conditional or after an error or + // interrupt or throw) or for a ":finally" without ":try" or a multiple + // ":finally". After every other error (did_emsg or the conditional + // errors detected above) or after an interrupt (got_int) or an + // exception (did_throw), the finally clause must be executed. skip = !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE); if (!skip) { @@ -1509,22 +1505,20 @@ void ex_finally(exarg_T *eap) */ cleanup_conditionals(cstack, CSF_TRY, false); - /* - * Make did_emsg, got_int, current_exception pending. If set, they - * overrule a pending ":continue", ":break", ":return", or ":finish". - * Then we have particularly to discard a pending return value (as done - * by the call to cleanup_conditionals() above when did_emsg or - * got_int is set). The pending values are restored by the - * ":endtry", except if there is a new error, interrupt, exception, - * ":continue", ":break", ":return", or ":finish" in the following - * finally clause. A missing ":endwhile", ":endfor" or ":endif" - * detected here is treated as if did_emsg and current_exception had - * already been set, respectively in case that the error is not - * converted to an exception, current_exception had already been unset. - * We must not set did_emsg here since that would suppress the - * error message. - */ - if (pending == CSTP_ERROR || did_emsg || got_int || current_exception) { + // Make did_emsg, got_int, did_throw pending. If set, they overrule + // a pending ":continue", ":break", ":return", or ":finish". Then + // we have particularly to discard a pending return value (as done + // by the call to cleanup_conditionals() above when did_emsg or + // got_int is set). The pending values are restored by the + // ":endtry", except if there is a new error, interrupt, exception, + // ":continue", ":break", ":return", or ":finish" in the following + // finally clause. A missing ":endwhile", ":endfor" or ":endif" + // detected here is treated as if did_emsg and did_throw had + // already been set, respectively in case that the error is not + // converted to an exception, did_throw had already been unset. + // We must not set did_emsg here since that would suppress the + // error message. + if (pending == CSTP_ERROR || did_emsg || got_int || did_throw) { if (cstack->cs_pending[cstack->cs_idx] == CSTP_RETURN) { report_discard_pending(CSTP_RETURN, cstack->cs_rettv[cstack->cs_idx]); @@ -1533,7 +1527,7 @@ void ex_finally(exarg_T *eap) if (pending == CSTP_ERROR && !did_emsg) { pending |= (THROW_ON_ERROR ? CSTP_THROW : 0); } else { - pending |= (current_exception ? CSTP_THROW : 0); + pending |= (did_throw ? CSTP_THROW : 0); } pending |= did_emsg ? CSTP_ERROR : 0; pending |= got_int ? CSTP_INTERRUPT : 0; @@ -1547,19 +1541,16 @@ void ex_finally(exarg_T *eap) // exception. When emsg() is called for a missing ":endif" or // a missing ":endwhile"/":endfor" detected here, the // exception will be discarded. - if (current_exception - && cstack->cs_exception[cstack->cs_idx] != current_exception) { + if (did_throw && cstack->cs_exception[cstack->cs_idx] != current_exception) { internal_error("ex_finally()"); } } - /* - * Set CSL_HAD_FINA, so do_cmdline() will reset did_emsg, - * got_int, and current_exception and make the finally clause active. - * This will happen after emsg() has been called for a missing - * ":endif" or a missing ":endwhile"/":endfor" detected here, so - * that the following finally clause will be executed even then. - */ + // Set CSL_HAD_FINA, so do_cmdline() will reset did_emsg, + // got_int, and did_throw and make the finally clause active. + // This will happen after emsg() has been called for a missing + // ":endif" or a missing ":endwhile"/":endfor" detected here, so + // that the following finally clause will be executed even then. cstack->cs_lflags |= CSL_HAD_FINA; } } @@ -1587,8 +1578,7 @@ void ex_endtry(exarg_T *eap) // made inactive by a ":continue", ":break", ":return", or ":finish" in // the finally clause. The latter case need not be tested since then // anything pending has already been discarded. - bool skip = did_emsg || got_int || current_exception - || !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE); + bool skip = did_emsg || got_int || did_throw || !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE); if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { eap->errmsg = get_end_emsg(cstack); @@ -1602,14 +1592,12 @@ void ex_endtry(exarg_T *eap) &cstack->cs_looplevel); skip = true; - /* - * If an exception is being thrown, discard it to prevent it from - * being rethrown at the end of this function. It would be - * discarded by the error message, anyway. Resets current_exception. - * This does not affect the script termination due to the error - * since "trylevel" is decremented after emsg() has been called. - */ - if (current_exception) { + // If an exception is being thrown, discard it to prevent it from + // being rethrown at the end of this function. It would be + // discarded by the error message, anyway. Resets did_throw. + // This does not affect the script termination due to the error + // since "trylevel" is decremented after emsg() has been called. + if (did_throw) { discard_current_exception(); } @@ -1624,7 +1612,7 @@ void ex_endtry(exarg_T *eap) * a finally clause, we need to rethrow it after closing the try * conditional. */ - if (current_exception + if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE) && !(cstack->cs_flags[idx] & CSF_FINALLY)) { rethrow = true; @@ -1648,10 +1636,10 @@ void ex_endtry(exarg_T *eap) if (got_int) { skip = true; (void)do_intthrow(cstack); - // The do_intthrow() call may have reset current_exception or + // The do_intthrow() call may have reset did_throw or // cstack->cs_pending[idx]. rethrow = false; - if (current_exception && !(cstack->cs_flags[idx] & CSF_FINALLY)) { + if (did_throw && !(cstack->cs_flags[idx] & CSF_FINALLY)) { rethrow = true; } } @@ -1721,7 +1709,7 @@ void ex_endtry(exarg_T *eap) // When the finally clause was entered due to an error, // interrupt or throw (as opposed to a ":continue", ":break", // ":return", or ":finish"), restore the pending values of - // did_emsg, got_int, and current_exception. This is skipped, if there + // did_emsg, got_int, and did_throw. This is skipped, if there // was a new error, interrupt, throw, ":continue", ":break", // ":return", or ":finish". in the finally clause. default: @@ -1768,24 +1756,22 @@ void enter_cleanup(cleanup_T *csp) { int pending = CSTP_NONE; - /* - * Postpone did_emsg, got_int, current_exception. The pending values will be - * restored by leave_cleanup() except if there was an aborting error, - * interrupt, or uncaught exception after this function ends. - */ - if (did_emsg || got_int || current_exception || need_rethrow) { + // Postpone did_emsg, got_int, did_throw. The pending values will be + // restored by leave_cleanup() except if there was an aborting error, + // interrupt, or uncaught exception after this function ends. + if (did_emsg || got_int || did_throw || need_rethrow) { csp->pending = (did_emsg ? CSTP_ERROR : 0) | (got_int ? CSTP_INTERRUPT : 0) - | (current_exception ? CSTP_THROW : 0) + | (did_throw ? CSTP_THROW : 0) | (need_rethrow ? CSTP_THROW : 0); - // If we are currently throwing an exception, save it as well. On an error - // not yet converted to an exception, update "force_abort" and reset - // "cause_abort" (as do_errthrow() would do). This is needed for the - // do_cmdline() call that is going to be made for autocommand execution. We - // need not save *msg_list because there is an extra instance for every call - // of do_cmdline(), anyway. - if (current_exception || need_rethrow) { + // If we are currently throwing an exception (did_throw), save it as + // well. On an error not yet converted to an exception, update + // "force_abort" and reset "cause_abort" (as do_errthrow() would do). + // This is needed for the do_cmdline() call that is going to be made + // for autocommand execution. We need not save *msg_list because + // there is an extra instance for every call of do_cmdline(), anyway. + if (did_throw || need_rethrow) { csp->exception = current_exception; current_exception = NULL; } else { @@ -1795,8 +1781,7 @@ void enter_cleanup(cleanup_T *csp) cause_abort = false; } } - did_emsg = got_int = need_rethrow = false; - current_exception = NULL; + did_emsg = got_int = did_throw = need_rethrow = false; // Report if required by the 'verbose' option or when debugging. report_make_pending(pending, csp->exception); @@ -1866,7 +1851,7 @@ void leave_cleanup(cleanup_T *csp) force_abort = false; } - // Restore the pending values of did_emsg, got_int, and current_exception. + // Restore the pending values of did_emsg, got_int, and did_throw. if (pending & CSTP_ERROR) { did_emsg = true; } @@ -1874,7 +1859,7 @@ void leave_cleanup(cleanup_T *csp) got_int = true; } if (pending & CSTP_THROW) { - need_rethrow = true; // current_exception will be set by do_one_cmd() + need_rethrow = true; // did_throw will be set by do_one_cmd() } // Report if required by the 'verbose' option or when debugging. diff --git a/src/nvim/globals.h b/src/nvim/globals.h index ddbe727db9..060db3b3b1 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -241,9 +241,13 @@ EXTERN int do_profiling INIT(= PROF_NONE); ///< PROF_ values /// Exception currently being thrown. Used to pass an exception to a different /// cstack. Also used for discarding an exception before it is caught or made -/// pending. +/// pending. Only valid when did_throw is true. EXTERN except_T *current_exception; +/// An exception is being thrown. Reset when the exception is caught or as +/// long as it is pending in a finally clause. +EXTERN bool did_throw INIT(= false); + /// Set when a throw that cannot be handled in do_cmdline() must be propagated /// to the cstack of the previously called do_cmdline(). EXTERN bool need_rethrow INIT(= false); diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 39585ac182..42aa13cfc1 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -1027,7 +1027,7 @@ int nlua_call(lua_State *lstate) // TODO(bfredl): this should be simplified in error handling refactor force_abort = false; suppress_errthrow = false; - current_exception = NULL; + did_throw = false; did_emsg = false; try_start(); diff --git a/test/functional/plugin/man_spec.lua b/test/functional/plugin/man_spec.lua index c8da5a711f..9304aa6da9 100644 --- a/test/functional/plugin/man_spec.lua +++ b/test/functional/plugin/man_spec.lua @@ -6,6 +6,12 @@ local funcs = helpers.funcs local nvim_prog = helpers.nvim_prog local matches = helpers.matches +clear() +if funcs.executable('man') == 0 then + pending('missing "man" command', function() end) + return +end + describe(':Man', function() before_each(function() clear() diff --git a/test/functional/vimscript/eval_spec.lua b/test/functional/vimscript/eval_spec.lua index 65ac5b8c80..d4fa7afe89 100644 --- a/test/functional/vimscript/eval_spec.lua +++ b/test/functional/vimscript/eval_spec.lua @@ -219,3 +219,31 @@ it('Error when if/for/while/try/function is nested too deep',function() feed(':call Test5()') screen:expect({any = 'E1058: '}) end) + +describe("uncaught exception", function() + before_each(clear) + after_each(function() + os.remove('throw1.vim') + os.remove('throw2.vim') + os.remove('throw3.vim') + end) + + it('is not forgotten #13490', function() + command('autocmd BufWinEnter * throw "i am error"') + eq('i am error', exc_exec('try | new | endtry')) + + -- Like Vim, throwing here aborts the processing of the script, but does not stop :runtime! + -- from processing the others. + -- Only the first thrown exception should be rethrown from the :try below, though. + for i = 1, 3 do + write_file('throw' .. i .. '.vim', ([[ + let result ..= '%d' + throw 'throw%d' + let result ..= 'X' + ]]):format(i, i)) + end + command('set runtimepath+=. | let result = ""') + eq('throw1', exc_exec('try | runtime! throw*.vim | endtry')) + eq('123', eval('result')) + end) +end) -- cgit From 94a2bc594020f2bb1f41d5e2e92d05ce9c293254 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 31 Aug 2022 06:27:39 +0800 Subject: vim-patch:9.0.0332: overwrite check may block BufWriteCmd (#20014) Problem: Overwrite check may block BufWriteCmd. Solution: Do not use overwrite check when 'buftype' is "acwrite". (closes vim/vim#11011) https://github.com/vim/vim/commit/9c8f94636b3610b898ffbbd07f6b75866d16cbca --- src/nvim/ex_cmds.c | 13 +++++++++---- src/nvim/testdir/test_autocmd.vim | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index fc753cf65c..e672b80d69 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -1996,11 +1996,16 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char *fname, char *ffname, int oth { // Write to another file or b_flags set or not writing the whole file: // overwriting only allowed with '!' + // If "other" is false and bt_nofilename(buf) is true, this must be + // writing an "acwrite" buffer to the same file as its b_ffname, and + // buf_write() will only allow writing with BufWriteCmd autocommands, + // so there is no need for an overwrite check. if ((other - || (buf->b_flags & BF_NOTEDITED) - || ((buf->b_flags & BF_NEW) - && vim_strchr(p_cpo, CPO_OVERNEW) == NULL) - || (buf->b_flags & BF_READERR)) + || (!bt_nofilename(buf) + && ((buf->b_flags & BF_NOTEDITED) + || ((buf->b_flags & BF_NEW) + && vim_strchr(p_cpo, CPO_OVERNEW) == NULL) + || (buf->b_flags & BF_READERR)))) && !p_wa && os_path_exists((char_u *)ffname)) { if (!eap->forceit && !eap->append) { diff --git a/src/nvim/testdir/test_autocmd.vim b/src/nvim/testdir/test_autocmd.vim index 27bc6303cf..3064b199d9 100644 --- a/src/nvim/testdir/test_autocmd.vim +++ b/src/nvim/testdir/test_autocmd.vim @@ -1836,6 +1836,21 @@ func Test_BufReadCmd() au! BufWriteCmd endfunc +func Test_BufWriteCmd() + autocmd BufWriteCmd Xbufwritecmd let g:written = 1 + new + file Xbufwritecmd + set buftype=acwrite + call mkdir('Xbufwritecmd') + write + " BufWriteCmd should be triggered even if a directory has the same name + call assert_equal(1, g:written) + call delete('Xbufwritecmd', 'd') + unlet g:written + au! BufWriteCmd + bwipe! +endfunc + func SetChangeMarks(start, end) exe a:start .. 'mark [' exe a:end .. 'mark ]' -- cgit From 518b5c65b0c6f5ee75718048fc661e629a01429b Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 31 Aug 2022 06:58:28 +0800 Subject: vim-patch:8.1.2037: can call win_gotoid() in cmdline window (#20015) Problem: Can call win_gotoid() in cmdline window. Solution: Disallow switching windows. (Yasuhiro Matsumoto, closes vim/vim#4940) https://github.com/vim/vim/commit/a046b37c22bcabdea5f0fd6d21ca4bd0aa4c768e --- src/nvim/eval/funcs.c | 14 +++++++++++++- src/nvim/testdir/test_cmdline.vim | 10 ++++++++++ src/nvim/window.c | 13 ------------- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index f21011d22b..aa328d50ef 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -9659,7 +9659,19 @@ static void f_win_gettype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// "win_gotoid()" function static void f_win_gotoid(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { - rettv->vval.v_number = win_gotoid(argvars); + int id = (int)tv_get_number(&argvars[0]); + + if (cmdwin_type != 0) { + emsg(_(e_cmdwin)); + return; + } + FOR_ALL_TAB_WINDOWS(tp, wp) { + if (wp->handle == id) { + goto_tabpage_win(tp, wp); + rettv->vval.v_number = 1; + return; + } + } } /// "win_id2tabwin()" function diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index 045504b8bf..4bfd22cb6c 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -1260,6 +1260,16 @@ func Test_cmdline_overstrike() let &encoding = encoding_save endfunc +func Test_cmdwin_bug() + let winid = win_getid() + sp + try + call feedkeys("q::call win_gotoid(" .. winid .. ")\:q\", 'x!') + catch /^Vim\%((\a\+)\)\=:E11/ + endtry + bw! +endfunc + func Test_cmdwin_restore() CheckScreendump diff --git a/src/nvim/window.c b/src/nvim/window.c index 5adc8db088..74ea1172ee 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -7396,19 +7396,6 @@ int win_getid(typval_T *argvars) return 0; } -int win_gotoid(typval_T *argvars) -{ - int id = (int)tv_get_number(&argvars[0]); - - FOR_ALL_TAB_WINDOWS(tp, wp) { - if (wp->handle == id) { - goto_tabpage_win(tp, wp); - return 1; - } - } - return 0; -} - void win_get_tabwin(handle_T id, int *tabnr, int *winnr) { *tabnr = 0; -- cgit From 5ff2ea66873dc0bcd1921158a93e363f009b245d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 31 Aug 2022 07:24:16 +0800 Subject: vim-patch:8.2.0301: insufficient testing for exception handling (#20016) Problem: Insufficient testing for exception handling and the "attention" prompt. Solution: Add test cases. (Yegappan Lakshmanan, closes vim/vim#5681) https://github.com/vim/vim/commit/b654103ad1e379348616f354272db86804ab4bdb Fix memory leak from last char_u refactor. --- src/nvim/eval/userfunc.c | 3 +- src/nvim/testdir/test_swap.vim | 1 + src/nvim/testdir/test_trycatch.vim | 175 +++++++++++++++++++++++++++++++++++-- 3 files changed, 171 insertions(+), 8 deletions(-) diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 1f94f9c2b7..4be922a055 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -3111,8 +3111,7 @@ char *get_return_cmd(void *rettv) char *tofree = NULL; if (rettv != NULL) { - tofree = encode_tv2echo((typval_T *)rettv, NULL); - s = encode_tv2echo((typval_T *)rettv, NULL); + tofree = s = encode_tv2echo((typval_T *)rettv, NULL); } if (s == NULL) { s = ""; diff --git a/src/nvim/testdir/test_swap.vim b/src/nvim/testdir/test_swap.vim index 923e1cbf50..5c9e39f1f4 100644 --- a/src/nvim/testdir/test_swap.vim +++ b/src/nvim/testdir/test_swap.vim @@ -2,6 +2,7 @@ source check.vim source shared.vim +source term_util.vim func s:swapname() return trim(execute('swapname')) diff --git a/src/nvim/testdir/test_trycatch.vim b/src/nvim/testdir/test_trycatch.vim index 646594e482..d71bb5bbb8 100644 --- a/src/nvim/testdir/test_trycatch.vim +++ b/src/nvim/testdir/test_trycatch.vim @@ -2027,16 +2027,179 @@ func Test_try_catch_verbose() endtry redir END let expected = [ - \ 'Exception thrown: Vim(echo):E121: Undefined variable: i', - \ '', - \ 'Exception caught: Vim(echo):E121: Undefined variable: i', - \ '', - \ 'Exception finished: Vim(echo):E121: Undefined variable: i' - \ ] + \ 'Exception thrown: Vim(echo):E121: Undefined variable: i', '', + \ 'Exception caught: Vim(echo):E121: Undefined variable: i', '', + \ 'Exception finished: Vim(echo):E121: Undefined variable: i'] call assert_equal(expected, split(msg, "\n")) + + " Test for verbose messages displayed when an exception is discarded + redir => msg + try + try + throw 'abc' + finally + throw 'xyz' + endtry + catch + endtry + redir END + let expected = [ + \ 'Exception thrown: abc', '', + \ 'Exception made pending: abc', '', + \ 'Exception thrown: xyz', '', + \ 'Exception discarded: abc', '', + \ 'Exception caught: xyz', '', + \ 'Exception finished: xyz'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :throw is resumed after :finally + redir => msg + try + try + throw 'abc' + finally + endtry + catch + endtry + redir END + let expected = [ + \ 'Exception thrown: abc', '', + \ 'Exception made pending: abc', '', + \ 'Exception resumed: abc', '', + \ 'Exception caught: abc', '', + \ 'Exception finished: abc'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :break is resumed after :finally + redir => msg + for i in range(1) + try + break + finally + endtry + endfor + redir END + let expected = [':break made pending', '', ':break resumed'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :continue is resumed after :finally + redir => msg + for i in range(1) + try + continue + finally + endtry + endfor + redir END + let expected = [':continue made pending', '', ':continue resumed'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :return is resumed after :finally + func Xtest() + try + return 'vim' + finally + endtry + endfunc + redir => msg + call Xtest() + redir END + let expected = [ + \ 'calling Xtest()', '', + \ ':return vim made pending', '', + \ ':return vim resumed', '', + \ 'Xtest returning ''vim''', '', + \ 'continuing in Test_try_catch_verbose'] + call assert_equal(expected, split(msg, "\n")) + delfunc Xtest + + " Test for messages displayed when :finish is resumed after :finally + call writefile(['try', 'finish', 'finally', 'endtry'], 'Xscript') + redir => msg + source Xscript + redir END + let expected = [ + \ ':finish made pending', '', + \ ':finish resumed', '', + \ 'finished sourcing Xscript', + \ 'continuing in Test_try_catch_verbose'] + call assert_equal(expected, split(msg, "\n")[1:]) + call delete('Xscript') + + " Test for messages displayed when a pending :continue is discarded by an + " exception in a finally handler + redir => msg + try + for i in range(1) + try + continue + finally + throw 'abc' + endtry + endfor + catch + endtry + redir END + let expected = [ + \ ':continue made pending', '', + \ 'Exception thrown: abc', '', + \ ':continue discarded', '', + \ 'Exception caught: abc', '', + \ 'Exception finished: abc'] + call assert_equal(expected, split(msg, "\n")) + set verbose& endfunc +" Test for throwing an exception from a BufEnter autocmd {{{1 +func Test_BufEnter_exception() + augroup bufenter_exception + au! + autocmd BufEnter Xfile1 throw 'abc' + augroup END + + let caught_abc = 0 + try + sp Xfile1 + catch /^abc/ + let caught_abc = 1 + endtry + call assert_equal(1, caught_abc) + call assert_equal(1, winnr('$')) + + augroup bufenter_exception + au! + augroup END + augroup! bufenter_exception + %bwipe! + + " Test for recursively throwing exceptions in autocmds + augroup bufenter_exception + au! + autocmd BufEnter Xfile1 throw 'bufenter' + autocmd BufLeave Xfile1 throw 'bufleave' + augroup END + + let ex_count = 0 + try + try + sp Xfile1 + catch /^bufenter/ + let ex_count += 1 + endtry + catch /^bufleave/ + let ex_count += 10 + endtry + call assert_equal(10, ex_count) + call assert_equal(2, winnr('$')) + + augroup bufenter_exception + au! + augroup END + augroup! bufenter_exception + %bwipe! +endfunc + " Test for using throw in a called function with following error {{{1 func Test_user_command_throw_in_function_call() let lines =<< trim END -- cgit From f4274d0f62625683486d3912dcd6e8e45877c6a4 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 31 Aug 2022 09:41:00 +0800 Subject: vim-patch:8.2.3102: test for crash fix does not fail without the fix (#20018) Problem: Test for crash fix does not fail without the fix. Solution: Adjust the test sequence. (closes vim/vim#8506) https://github.com/vim/vim/commit/3777d6e32b22f0a70b774760c24160079e303bad Cherry-pick CheckUnix from patch 8.2.1432. --- src/nvim/testdir/test_swap.vim | 24 ++-- .../ex_cmds/swapfile_preserve_recover_spec.lua | 124 +++++++++++++++++---- test/functional/legacy/cmdline_spec.lua | 3 +- 3 files changed, 120 insertions(+), 31 deletions(-) diff --git a/src/nvim/testdir/test_swap.vim b/src/nvim/testdir/test_swap.vim index 5c9e39f1f4..34d1d585ce 100644 --- a/src/nvim/testdir/test_swap.vim +++ b/src/nvim/testdir/test_swap.vim @@ -375,24 +375,26 @@ func Test_swap_prompt_splitwin() call WaitForAssert({-> assert_match('^1$', term_getline(buf, 20))}) call StopVimInTerminal(buf) - " This caused Vim to crash when typing "q". - " TODO: it does not actually reproduce the crash. - call writefile(['au BufAdd * set virtualedit=all'], 'Xvimrc') - - let buf = RunVimInTerminal('-u Xvimrc Xfile1', {'rows': 20, 'wait_for_ruler': 0}) - call TermWait(buf) - call WaitForAssert({-> assert_match('^\[O\]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:', term_getline(buf, 20))}) + " This caused Vim to crash when typing "q" at the swap file prompt. + let buf = RunVimInTerminal('-c "au bufadd * let foo_w = wincol()"', {'rows': 18}) + call term_sendkeys(buf, ":e Xfile1\") + call WaitForAssert({-> assert_match('More', term_getline(buf, 18))}) + call term_sendkeys(buf, " ") + call WaitForAssert({-> assert_match('^\[O\]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:', term_getline(buf, 18))}) call term_sendkeys(buf, "q") + call TermWait(buf) + " check that Vim is still running + call term_sendkeys(buf, ":echo 'hello'\") + call WaitForAssert({-> assert_match('^hello', term_getline(buf, 18))}) + call term_sendkeys(buf, ":%bwipe!\") + call StopVimInTerminal(buf) %bwipe! call delete('Xfile1') - call delete('Xvimrc') endfunc func Test_swap_symlink() - if !has("unix") - return - endif + CheckUnix call writefile(['text'], 'Xtestfile') silent !ln -s -f Xtestfile Xtestlink diff --git a/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua b/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua index 4d984af41e..69404039ff 100644 --- a/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua +++ b/test/functional/ex_cmds/swapfile_preserve_recover_spec.lua @@ -1,8 +1,8 @@ local Screen = require('test.functional.ui.screen') local helpers = require('test.functional.helpers')(after_each) local lfs = require('lfs') -local eq, eval, expect, source = - helpers.eq, helpers.eval, helpers.expect, helpers.source +local eq, eval, expect, exec = + helpers.eq, helpers.eval, helpers.expect, helpers.exec local assert_alive = helpers.assert_alive local clear = helpers.clear local command = helpers.command @@ -10,6 +10,8 @@ local feed = helpers.feed local nvim_prog = helpers.nvim_prog local ok = helpers.ok local rmdir = helpers.rmdir +local new_argv = helpers.new_argv +local pesc = helpers.pesc local os_kill = helpers.os_kill local set_session = helpers.set_session local spawn = helpers.spawn @@ -55,11 +57,11 @@ describe(':preserve', function() set swapfile fileformat=unix undolevels=-1 ]] - source(init) + exec(init) command('edit! '..testfile) feed('isometext') command('preserve') - source('redir => g:swapname | silent swapname | redir END') + exec('redir => g:swapname | silent swapname | redir END') local swappath1 = eval('g:swapname') @@ -69,12 +71,12 @@ describe(':preserve', function() true) set_session(nvim2) - source(init) + exec(init) -- Use the "SwapExists" event to choose the (R)ecover choice at the dialog. command('autocmd SwapExists * let v:swapchoice = "r"') command('silent edit! '..testfile) - source('redir => g:swapname | silent swapname | redir END') + exec('redir => g:swapname | silent swapname | redir END') local swappath2 = eval('g:swapname') @@ -92,25 +94,28 @@ end) describe('swapfile detection', function() local swapdir = lfs.currentdir()..'/Xtest_swapdialog_dir' + local nvim0 + -- Put swapdir at the start of the 'directory' list. #1836 + -- Note: `set swapfile` *must* go after `set directory`: otherwise it may + -- attempt to create a swapfile in different directory. + local init = [[ + set directory^=]]..swapdir:gsub([[\]], [[\\]])..[[// + set swapfile fileformat=unix undolevels=-1 hidden + ]] before_each(function() - clear() + nvim0 = spawn(new_argv()) + set_session(nvim0) rmdir(swapdir) lfs.mkdir(swapdir) end) after_each(function() + set_session(nvim0) command('%bwipeout!') rmdir(swapdir) end) it('always show swapfile dialog #8840 #9027', function() local testfile = 'Xtest_swapdialog_file1' - -- Put swapdir at the start of the 'directory' list. #1836 - -- Note: `set swapfile` *must* go after `set directory`: otherwise it may - -- attempt to create a swapfile in different directory. - local init = [[ - set directory^=]]..swapdir:gsub([[\]], [[\\]])..[[// - set swapfile fileformat=unix undolevels=-1 hidden - ]] local expected_no_dialog = '^'..(' '):rep(256)..'|\n' for _=1,37 do @@ -119,19 +124,17 @@ describe('swapfile detection', function() expected_no_dialog = expected_no_dialog..testfile..(' '):rep(216)..'0,0-1 All|\n' expected_no_dialog = expected_no_dialog..(' '):rep(256)..'|\n' - source(init) + exec(init) command('edit! '..testfile) feed('isometext') command('preserve') - os_kill(eval('getpid()')) -- Start another Nvim instance. - local nvim2 = spawn({nvim_prog, '-u', 'NONE', '-i', 'NONE', '--embed'}, - true) + local nvim2 = spawn({nvim_prog, '-u', 'NONE', '-i', 'NONE', '--embed'}, true, nil, true) set_session(nvim2) local screen2 = Screen.new(256, 40) screen2:attach() - source(init) + exec(init) -- With shortmess+=F command('set shortmess+=F') @@ -176,5 +179,88 @@ describe('swapfile detection', function() } }) feed('') + + nvim2:close() + end) + + -- oldtest: Test_swap_prompt_splitwin() + it('selecting "q" in the attention prompt', function() + exec(init) + command('edit Xfile1') + command('preserve') -- should help to make sure the swap file exists + + local screen = Screen.new(75, 18) + screen:set_default_attr_ids({ + [0] = {bold = true, foreground = Screen.colors.Blue}, -- NonText + [1] = {bold = true, foreground = Screen.colors.SeaGreen}, -- MoreMsg + }) + + local nvim1 = spawn(new_argv(), true, nil, true) + set_session(nvim1) + screen:attach() + exec(init) + feed(':split Xfile1\n') + screen:expect({ + any = pesc('{1:[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: }^') + }) + feed('q') + feed(':') + screen:expect([[ + ^ | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + : | + ]]) + nvim1:close() + + local nvim2 = spawn(new_argv(), true, nil, true) + set_session(nvim2) + screen:attach() + exec(init) + command('set more') + command('au bufadd * let foo_w = wincol()') + feed(':e Xfile1') + screen:expect({any = pesc('{1:-- More --}^')}) + feed('') + screen:expect({ + any = pesc('{1:[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: }^') + }) + feed('q') + command([[echo 'hello']]) + screen:expect([[ + ^ | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + hello | + ]]) + nvim2:close() end) end) diff --git a/test/functional/legacy/cmdline_spec.lua b/test/functional/legacy/cmdline_spec.lua index 65b46f793d..99d2d0f30e 100644 --- a/test/functional/legacy/cmdline_spec.lua +++ b/test/functional/legacy/cmdline_spec.lua @@ -5,6 +5,7 @@ local command = helpers.command local feed = helpers.feed local feed_command = helpers.feed_command local exec = helpers.exec +local pesc = helpers.pesc describe('cmdline', function() before_each(clear) @@ -158,7 +159,7 @@ describe('cmdwin', function() command('set more') command('autocmd WinNew * highlight') feed('q:') - screen:expect({any = '{3:%-%- More %-%-}^'}) + screen:expect({any = pesc('{3:-- More --}^')}) feed('q') screen:expect([[ | -- cgit From 0903702634d8e5714749ea599a2f1042b3377525 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Wed, 31 Aug 2022 08:08:51 +0200 Subject: vim-patch:9b03d3e75b42 (#20013) Update runtime files https://github.com/vim/vim/commit/9b03d3e75b4274493bbe76772d7b92238791964c --- runtime/compiler/raco.vim | 14 + runtime/compiler/racomake.vim | 14 + runtime/compiler/racosetup.vim | 14 + runtime/compiler/racotest.vim | 14 + runtime/doc/eval.txt | 3 + runtime/ftplugin/racket.vim | 82 ++++++ runtime/indent/racket.vim | 60 ++++ runtime/syntax/gdresource.vim | 64 ++++ runtime/syntax/gdscript.vim | 104 +++++++ runtime/syntax/gdshader.vim | 57 ++++ runtime/syntax/racket.vim | 656 +++++++++++++++++++++++++++++++++++++++++ 11 files changed, 1082 insertions(+) create mode 100644 runtime/compiler/raco.vim create mode 100644 runtime/compiler/racomake.vim create mode 100644 runtime/compiler/racosetup.vim create mode 100644 runtime/compiler/racotest.vim create mode 100644 runtime/ftplugin/racket.vim create mode 100644 runtime/indent/racket.vim create mode 100644 runtime/syntax/gdresource.vim create mode 100644 runtime/syntax/gdscript.vim create mode 100644 runtime/syntax/gdshader.vim create mode 100644 runtime/syntax/racket.vim diff --git a/runtime/compiler/raco.vim b/runtime/compiler/raco.vim new file mode 100644 index 0000000000..bd10859aa9 --- /dev/null +++ b/runtime/compiler/raco.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco (Racket command-line tools) +" Maintainer: D. Ben Knoble +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'raco' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal +endif + +CompilerSet makeprg=raco +CompilerSet errorformat=%f:%l:%c:%m diff --git a/runtime/compiler/racomake.vim b/runtime/compiler/racomake.vim new file mode 100644 index 0000000000..dae95fec42 --- /dev/null +++ b/runtime/compiler/racomake.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco make (Racket command-line tools) +" Maintainer: D. Ben Knoble +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'racomake' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal +endif + +CompilerSet makeprg=raco\ make\ --\ % +CompilerSet errorformat=%f:%l:%c:%m diff --git a/runtime/compiler/racosetup.vim b/runtime/compiler/racosetup.vim new file mode 100644 index 0000000000..1efe8a15a2 --- /dev/null +++ b/runtime/compiler/racosetup.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco setup (Racket command-line tools) +" Maintainer: D. Ben Knoble +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'racosetup' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal +endif + +CompilerSet makeprg=raco\ setup +CompilerSet errorformat=%f:%l:%c:%m diff --git a/runtime/compiler/racotest.vim b/runtime/compiler/racotest.vim new file mode 100644 index 0000000000..d2a1a3c0f3 --- /dev/null +++ b/runtime/compiler/racotest.vim @@ -0,0 +1,14 @@ +" Vim compiler file +" Compiler: raco test (Racket command-line tools) +" Maintainer: D. Ben Knoble +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +let current_compiler = 'racotest' + +if exists(":CompilerSet") != 2 + command -nargs=* CompilerSet setlocal +endif + +CompilerSet makeprg=raco\ test\ % +CompilerSet errorformat=location:%f:%l:%c diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index 376adfec7f..3fbf1ee136 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -3167,6 +3167,9 @@ text... iterate over. Unlike with |List|, modifying the |Blob| does not affect the iteration. + When {object} is a |String| each item is a string with + one character, plus any combining characters. + :for [{var1}, {var2}, ...] in {listlist} :endfo[r] Like `:for` above, but each item in {listlist} must be diff --git a/runtime/ftplugin/racket.vim b/runtime/ftplugin/racket.vim new file mode 100644 index 0000000000..3aa413397e --- /dev/null +++ b/runtime/ftplugin/racket.vim @@ -0,0 +1,82 @@ +" Vim filetype plugin +" Language: Racket +" Maintainer: D. Ben Knoble +" Previous Maintainer: Will Langstroth +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 29 + +if exists("b:did_ftplugin") + finish +endif +let b:did_ftplugin = 1 + +let s:cpo_save = &cpo +set cpo&vim + +" quick hack to allow adding values +setlocal iskeyword=@,!,#-',*-:,<-Z,a-z,~,_,94 + +" Enable auto begin new comment line when continuing from an old comment line +setlocal comments=:;;;;,:;;;,:;;,:; +setlocal formatoptions+=r + +"setlocal commentstring=;;%s +setlocal commentstring=#\|\ %s\ \|# + +setlocal formatprg=raco\ fmt + +" Undo our settings when the filetype changes away from Racket +" (this should be amended if settings/mappings are added above!) +let b:undo_ftplugin = + \ "setlocal iskeyword< lispwords< lisp< comments< formatoptions< formatprg<" + \. " | setlocal commentstring<" + +if !exists("no_plugin_maps") && !exists("no_racket_maps") + " Simply setting keywordprg like this works: + " setlocal keywordprg=raco\ docs + " but then vim says: + " "press ENTER or type a command to continue" + " We avoid the annoyance of having to hit enter by remapping K directly. + function s:RacketDoc(word) abort + execute 'silent !raco docs --' shellescape(a:word) + redraw! + endfunction + nnoremap RacketDoc :call RacketDoc(expand('')) + nmap K RacketDoc + + " For the visual mode K mapping, it's slightly more convoluted to get the + " selected text: + function! s:Racket_visual_doc() + try + let l:old_a = @a + normal! gv"ay + call system("raco docs '". @a . "'") + redraw! + return @a + finally + let @a = l:old_a + endtry + endfunction + + xnoremap RacketDoc :call Racket_visual_doc() + xmap K RacketDoc + + let b:undo_ftplugin .= + \ " | silent! execute 'nunmap K'" + \. " | silent! execute 'xunmap K'" +endif + +if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter") + let b:browsefilter = + \ "Racket Source Files (*.rkt *.rktl)\t*.rkt;*.rktl\n" + \. "All Files (*.*)\t*.*\n" + let b:undo_ftplugin .= " | unlet! b:browsefilter" +endif + +if exists("loaded_matchit") && !exists("b:match_words") + let b:match_words = '#|:|#' + let b:undo_ftplugin .= " | unlet! b:match_words" +endif + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/indent/racket.vim b/runtime/indent/racket.vim new file mode 100644 index 0000000000..93bd38fbff --- /dev/null +++ b/runtime/indent/racket.vim @@ -0,0 +1,60 @@ +" Vim indent file +" Language: Racket +" Maintainer: D. Ben Knoble +" Previous Maintainer: Will Langstroth +" URL: https://github.com/benknoble/vim-racket +" Last Change: 2022 Aug 12 + +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +setlocal lisp autoindent nosmartindent + +setlocal lispwords+=module,module*,module+,parameterize,let-values,let*-values,letrec-values,local +setlocal lispwords+=define/contract +setlocal lispwords+=λ +setlocal lispwords+=with-handlers +setlocal lispwords+=define-values,opt-lambda,case-lambda,syntax-rules,with-syntax,syntax-case,syntax-parse +setlocal lispwords+=define-for-syntax,define-syntax-parser,define-syntax-parse-rule,define-syntax-class,define-splicing-syntax-class +setlocal lispwords+=define-signature,unit,unit/sig,compund-unit/sig,define-values/invoke-unit/sig +setlocal lispwords+=define-opt/c,define-syntax-rule +setlocal lispwords+=define-test-suite +setlocal lispwords+=struct +setlocal lispwords+=with-input-from-file,with-output-to-file + +" Racket OOP +" TODO missing a lot of define-like forms here (e.g., define/augment, etc.) +setlocal lispwords+=class,class*,mixin,interface,class/derived +setlocal lispwords+=define/public,define/pubment,define/public-final +setlocal lispwords+=define/override,define/overment,define/override-final +setlocal lispwords+=define/augment,define/augride,define/augment-final +setlocal lispwords+=define/private + +" kanren +setlocal lispwords+=fresh,run,run*,project,conde,condu + +" loops +setlocal lispwords+=for,for/list,for/fold,for*,for*/list,for*/fold,for/or,for/and,for*/or,for*/and +setlocal lispwords+=for/hash,for/hasheq,for/hasheqv,for/sum,for/flvector,for*/flvector,for/vector,for*/vector,for*/sum,for*/hash,for*/hasheq,for*/hasheqv +setlocal lispwords+=for/async +setlocal lispwords+=for/set,for*/set +setlocal lispwords+=for/first,for*/first + +setlocal lispwords+=match,match*,match/values,define/match,match-lambda,match-lambda*,match-lambda** +setlocal lispwords+=match-let,match-let*,match-let-values,match-let*-values +setlocal lispwords+=match-letrec,match-define,match-define-values + +setlocal lispwords+=let/cc,let/ec + +" qi +setlocal lispwords+=define-flow,define-switch,flow-lambda,switch-lambda,on,switch,π,λ01 +setlocal lispwords+=define-qi-syntax,define-qi-syntax-parser,define-qi-syntax-rule + +" gui-easy +setlocal lispwords+=if-view,case-view,cond-view,list-view,dyn-view +setlocal lispwords+=case/dep +setlocal lispwords+=define/obs + +let b:undo_indent = "setlocal lisp< ai< si< lw<" diff --git a/runtime/syntax/gdresource.vim b/runtime/syntax/gdresource.vim new file mode 100644 index 0000000000..eb500aa6c2 --- /dev/null +++ b/runtime/syntax/gdresource.vim @@ -0,0 +1,64 @@ +" Vim syntax file for Godot resource (scenes) +" Language: gdresource +" Maintainer: Maxim Kim +" Filenames: *.tscn, *.tres + +if exists("b:current_syntax") + finish +endif + +let s:keepcpo= &cpo +set cpo&vim + +syn match gdResourceNumber "\<0x\%(_\=\x\)\+\>" +syn match gdResourceNumber "\<0b\%(_\=[01]\)\+\>" +syn match gdResourceNumber "\<\d\%(_\=\d\)*\>" +syn match gdResourceNumber "\<\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" +syn match gdResourceNumber "\<\d\%(_\=\d\)*\.\%(e[+-]\=\d\%(_\=\d\)*\)\=\%(\W\|$\)\@=" +syn match gdResourceNumber "\%(^\|\W\)\@1<=\%(\d\%(_\=\d\)*\)\=\.\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" + +syn keyword gdResourceKeyword true false + +syn region gdResourceString + \ start=+[uU]\="+ end='"' skip='\\\\\|\\"' + \ contains=@Spell keepend + +" Section +syn region gdResourceSection matchgroup=gdResourceSectionDelimiter + \ start='^\[' end=']\s*$' + \ oneline keepend + \ contains=gdResourceSectionName,gdResourceSectionAttribute + +syn match gdResourceSectionName '\[\@<=\S\+' contained skipwhite +syn match gdResourceSectionAttribute '\S\+\s*=\s*\S\+' + \ skipwhite keepend contained + \ contains=gdResourceSectionAttributeName,gdResourceSectionAttributeValue +syn match gdResourceSectionAttributeName '\S\+\ze\(\s*=\)' skipwhite contained +syn match gdResourceSectionAttributeValue '\(=\s*\)\zs\S\+\ze' skipwhite + \ contained + \ contains=gdResourceString,gdResourceNumber,gdResourceKeyword + + +" Section body +syn match gdResourceAttribute '^\s*\S\+\s*=.*$' + \ skipwhite keepend + \ contains=gdResourceAttributeName,gdResourceAttributeValue + +syn match gdResourceAttributeName '\S\+\ze\(\s*=\)' skipwhite contained +syn match gdResourceAttributeValue '\(=\s*\)\zs.*$' skipwhite + \ contained + \ contains=gdResourceString,gdResourceNumber,gdResourceKeyword + + +hi def link gdResourceNumber Constant +hi def link gdResourceKeyword Constant +hi def link gdResourceSectionName Statement +hi def link gdResourceSectionDelimiter Delimiter +hi def link gdResourceSectionAttributeName Type +hi def link gdResourceAttributeName Identifier +hi def link gdResourceString String + +let b:current_syntax = "gdresource" + +let &cpo = s:keepcpo +unlet s:keepcpo diff --git a/runtime/syntax/gdscript.vim b/runtime/syntax/gdscript.vim new file mode 100644 index 0000000000..bf6d47c60d --- /dev/null +++ b/runtime/syntax/gdscript.vim @@ -0,0 +1,104 @@ +" Vim syntax file for Godot gdscript +" Language: gdscript +" Maintainer: Maxim Kim +" Filenames: *.gd + +if exists("b:current_syntax") + finish +endif + +let s:keepcpo= &cpo +set cpo&vim + +syntax sync maxlines=100 + +syn keyword gdscriptConditional if else elif match +syn keyword gdscriptRepeat for while break continue + +syn keyword gdscriptOperator is as not and or in + +syn match gdscriptClass "\v<\u\w+>" +syn match gdscriptConstant "\<[_A-Z]\+[0-9_A-Z]*\>" +syn match gdscriptBlockStart ":\s*$" + +syn keyword gdscriptKeyword null self owner parent tool +syn keyword gdscriptBoolean false true + +syn keyword gdscriptStatement remote master puppet remotesync mastersync puppetsync sync +syn keyword gdscriptStatement return pass +syn keyword gdscriptStatement static const enum +syn keyword gdscriptStatement breakpoint assert +syn keyword gdscriptStatement onready +syn keyword gdscriptStatement class_name extends + +syn keyword gdscriptType void bool int float String contained + +syn keyword gdscriptStatement var nextgroup=gdscriptTypeDecl skipwhite +syn keyword gdscriptStatement const nextgroup=gdscriptTypeDecl skipwhite +syn match gdscriptTypeDecl "\h\w*\s*:\s*\h\w*" contains=gdscriptOperator,gdscriptType,gdscriptClass contained skipwhite +syn match gdscriptTypeDecl "->\s*\h\w*" contains=gdscriptOperator,gdscriptType,gdscriptClass skipwhite + +syn keyword gdscriptStatement export nextgroup=gdscriptExportTypeDecl skipwhite +syn match gdscriptExportTypeDecl "(.\{-}[,)]" contains=gdscriptOperator,gdscriptType,gdscriptClass contained skipwhite + +syn keyword gdscriptStatement setget nextgroup=gdscriptSetGet,gdscriptSetGetSeparator skipwhite +syn match gdscriptSetGet "\h\w*" nextgroup=gdscriptSetGetSeparator display contained skipwhite +syn match gdscriptSetGetSeparator "," nextgroup=gdscriptSetGet display contained skipwhite + +syn keyword gdscriptStatement class func signal nextgroup=gdscriptFunctionName skipwhite +syn match gdscriptFunctionName "\h\w*" nextgroup=gdscriptFunctionParams display contained skipwhite +syn match gdscriptFunctionParams "(.*)" contains=gdscriptTypeDecl display contained skipwhite + +syn match gdscriptNode "\$\h\w*\%(/\h\w*\)*" + +syn match gdscriptComment "#.*$" contains=@Spell,gdscriptTodo + +syn region gdscriptString matchgroup=gdscriptQuotes + \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1" + \ contains=gdscriptEscape,@Spell + +syn region gdscriptString matchgroup=gdscriptTripleQuotes + \ start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend + \ contains=gdscriptEscape,@Spell + +syn match gdscriptEscape +\\[abfnrtv'"\\]+ contained +syn match gdscriptEscape "\\$" + +" Numbers +syn match gdscriptNumber "\<0x\%(_\=\x\)\+\>" +syn match gdscriptNumber "\<0b\%(_\=[01]\)\+\>" +syn match gdscriptNumber "\<\d\%(_\=\d\)*\>" +syn match gdscriptNumber "\<\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" +syn match gdscriptNumber "\<\d\%(_\=\d\)*\.\%(e[+-]\=\d\%(_\=\d\)*\)\=\%(\W\|$\)\@=" +syn match gdscriptNumber "\%(^\|\W\)\@1<=\%(\d\%(_\=\d\)*\)\=\.\d\%(_\=\d\)*\%(e[+-]\=\d\%(_\=\d\)*\)\=\>" + +" XXX, TODO, etc +syn keyword gdscriptTodo TODO XXX FIXME HACK NOTE BUG contained + +hi def link gdscriptStatement Statement +hi def link gdscriptKeyword Keyword +hi def link gdscriptConditional Conditional +hi def link gdscriptBoolean Boolean +hi def link gdscriptOperator Operator +hi def link gdscriptRepeat Repeat +hi def link gdscriptSetGet Function +hi def link gdscriptFunctionName Function +hi def link gdscriptClass Type +hi def link gdscriptConstant Constant +hi def link gdscriptBuiltinStruct Typedef +hi def link gdscriptComment Comment +hi def link gdscriptString String +hi def link gdscriptQuotes String +hi def link gdscriptTripleQuotes String +hi def link gdscriptEscape Special +hi def link gdscriptNode PreProc +hi def link gdscriptType Type +hi def link gdscriptNumber Number +hi def link gdscriptBlockStart Special +hi def link gdscriptTodo Todo + + +let b:current_syntax = "gdscript" + +let &cpo = s:keepcpo +unlet s:keepcpo diff --git a/runtime/syntax/gdshader.vim b/runtime/syntax/gdshader.vim new file mode 100644 index 0000000000..f0d9f7edd9 --- /dev/null +++ b/runtime/syntax/gdshader.vim @@ -0,0 +1,57 @@ +" Vim syntax file for Godot shading language +" Language: gdshader +" Maintainer: Maxim Kim +" Filenames: *.gdshader + +if exists("b:current_syntax") + finish +endif + +syn keyword gdshaderConditional if else switch case default +syn keyword gdshaderRepeat for while do +syn keyword gdshaderStatement return discard +syn keyword gdshaderBoolean true false + +syn keyword gdshaderKeyword shader_type render_mode +syn keyword gdshaderKeyword in out inout +syn keyword gdshaderKeyword lowp mediump highp +syn keyword gdshaderKeyword uniform varying const +syn keyword gdshaderKeyword flat smooth + +syn keyword gdshaderType float vec2 vec3 vec4 +syn keyword gdshaderType uint uvec2 uvec3 uvec4 +syn keyword gdshaderType int ivec2 ivec3 ivec4 +syn keyword gdshaderType void bool +syn keyword gdshaderType bvec2 bvec3 bvec4 +syn keyword gdshaderType mat2 mat3 mat4 +syn keyword gdshaderType sampler2D isampler2D usampler2D samplerCube + +syn match gdshaderMember "\v<(\.)@<=[a-z_]+\w*>" +syn match gdshaderBuiltin "\v<[A-Z_]+[A-Z0-9_]*>" +syn match gdshaderFunction "\v<\w*>(\()@=" + +syn match gdshaderNumber "\v<\d+(\.)@!>" +syn match gdshaderFloat "\v<\d*\.\d+(\.)@!>" +syn match gdshaderFloat "\v<\d*\.=\d+(e-=\d+)@=" +syn match gdshaderExponent "\v(\d*\.=\d+)@<=e-=\d+>" + +syn match gdshaderComment "\v//.*$" contains=@Spell +syn region gdshaderComment start="/\*" end="\*/" contains=@Spell +syn keyword gdshaderTodo TODO FIXME XXX NOTE BUG HACK OPTIMIZE containedin=gdshaderComment + +hi def link gdshaderConditional Conditional +hi def link gdshaderRepeat Repeat +hi def link gdshaderStatement Statement +hi def link gdshaderBoolean Boolean +hi def link gdshaderKeyword Keyword +hi def link gdshaderMember Identifier +hi def link gdshaderBuiltin Identifier +hi def link gdshaderFunction Function +hi def link gdshaderType Type +hi def link gdshaderNumber Number +hi def link gdshaderFloat Float +hi def link gdshaderExponent Special +hi def link gdshaderComment Comment +hi def link gdshaderTodo Todo + +let b:current_syntax = "gdshader" diff --git a/runtime/syntax/racket.vim b/runtime/syntax/racket.vim new file mode 100644 index 0000000000..b1ed2b454c --- /dev/null +++ b/runtime/syntax/racket.vim @@ -0,0 +1,656 @@ +" Vim syntax file +" Language: Racket +" Maintainer: D. Ben Knoble +" Previous Maintainer: Will Langstroth +" URL: https://github.com/benknoble/vim-racket +" Description: Contains all of the keywords in #lang racket +" Last Change: 2022 Aug 12 + +" Initializing: +if exists("b:current_syntax") + finish +endif + +" Highlight unmatched parens +syntax match racketError ,[]})], + +if version < 800 + set iskeyword=33,35-39,42-58,60-90,94,95,97-122,126,_ +else + " syntax iskeyword 33,35-39,42-58,60-90,94,95,97-122,126,_ + " converted from decimal to char + " :s/\d\+/\=submatch(0)->str2nr()->nr2char()/g + " but corrected to remove duplicate _, move ^ to end + syntax iskeyword @,!,#-',*-:,<-Z,a-z,~,_,^ + " expanded + " syntax iskeyword !,#,$,%,&,',*,+,,,-,.,/,0-9,:,<,=,>,?,@,A-Z,_,a-z,~,^ +endif + +" Forms in order of appearance at +" http://docs.racket-lang.org/reference/index.html +" +syntax keyword racketSyntax module module* module+ require provide quote +syntax keyword racketSyntax #%datum #%expression #%top #%variable-reference #%app +syntax keyword racketSyntax lambda case-lambda let let* letrec +syntax keyword racketSyntax let-values let*-values let-syntax letrec-syntax +syntax keyword racketSyntax let-syntaxes letrec-syntaxes letrec-syntaxes+values +syntax keyword racketSyntax local shared +syntax keyword racketSyntax if cond and or case define else => +syntax keyword racketSyntax define define-values define-syntax define-syntaxes +syntax keyword racketSyntax define-for-syntax define-require-syntax define-provide-syntax +syntax keyword racketSyntax define-syntax-rule +syntax keyword racketSyntax define-record-type +syntax keyword racketSyntax begin begin0 +syntax keyword racketSyntax begin-for-syntax +syntax keyword racketSyntax when unless +syntax keyword racketSyntax set! set!-values +syntax keyword racketSyntax for for/list for/vector for/hash for/hasheq for/hasheqv +syntax keyword racketSyntax for/and for/or for/lists for/first +syntax keyword racketSyntax for/last for/fold +syntax keyword racketSyntax for* for*/list for*/vector for*/hash for*/hasheq for*/hasheqv +syntax keyword racketSyntax for*/and for*/or for*/lists for*/first +syntax keyword racketSyntax for*/last for*/fold +syntax keyword racketSyntax for/fold/derived for*/fold/derived +syntax keyword racketSyntax define-sequence-syntax :do-in do +syntax keyword racketSyntax with-continuation-mark +syntax keyword racketSyntax quasiquote unquote unquote-splicing quote-syntax +syntax keyword racketSyntax #%top-interaction +syntax keyword racketSyntax define-package open-package package-begin +syntax keyword racketSyntax define* define*-values define*-syntax define*-syntaxes open*-package +syntax keyword racketSyntax package? package-exported-identifiers package-original-identifiers +syntax keyword racketSyntax block #%stratified-body + +" 8 Contracts +" 8.2 Function contracts +syntax keyword racketSyntax -> ->* ->i ->d case-> dynamic->* unconstrained-domain-> + +" 8.6.1 Nested Contract Boundaries +syntax keyword racketSyntax with-contract define/contract define-struct/contract +syntax keyword racketSyntax invariant-assertion current-contract-region + +" 9 Pattern Matching +syntax keyword racketSyntax match match* match/values define/match +syntax keyword racketSyntax match-lambda match-lambda* match-lambda** +syntax keyword racketSyntax match-let match-let* match-let-values match-let*-values +syntax keyword racketSyntax match-letrec match-define match-define-values + +" 10.2.3 Handling Exceptions +syntax keyword racketSyntax with-handlers with-handlers* + +" 10.4 Continuations +syntax keyword racketSyntax let/cc let/ec + +" 10.4.1 Additional Control Operators +syntax keyword racketSyntax % prompt control prompt-at control-at reset shift +syntax keyword racketSyntax reset-at shift-at prompt0 reset0 control0 shift0 +syntax keyword racketSyntax prompt0-at reset0-at control0-at shift0-at +syntax keyword racketSyntax set cupto + +" 11.3.2 Parameters +syntax keyword racketSyntax parameterize parameterize* + +" 12.5 Writing +syntax keyword racketSyntax write display displayln print +syntax keyword racketSyntax fprintf printf eprintf format +syntax keyword racketSyntax print-pair-curly-braces print-mpair-curly-braces print-unreadable +syntax keyword racketSyntax print-graph print-struct print-box print-vector-length print-hash-table +syntax keyword racketSyntax print-boolean-long-form print-reader-abbreviations print-as-expression print-syntax-width +syntax keyword racketSyntax current-write-relative-directory port-write-handler port-display-handler +syntax keyword racketSyntax port-print-handler global-port-print-handler + +" 13.7 Custodians +syntax keyword racketSyntax custodian? custodian-memory-accounting-available? custodian-box? +syntax keyword racketSyntax make-custodian custodian-shutdown-all current-custodian custodian-managed-list +syntax keyword racketSyntax custodian-require-memory custodian-limit-memory +syntax keyword racketSyntax make-custodian-box custodian-box-value + +" lambda sign +syntax match racketSyntax /\<[\u03bb]\>/ + + +" Functions ================================================================== + +syntax keyword racketFunc boolean? not equal? eqv? eq? equal?/recur immutable? +syntax keyword racketFunc true false symbol=? boolean=? false? +syntax keyword racketFunc number? complex? real? rational? integer? +syntax keyword racketFunc exact-integer? exact-nonnegative-integer? +syntax keyword racketFunc exact-positive-integer? inexact-real? +syntax keyword racketFunc fixnum? flonum? zero? positive? negative? +syntax keyword racketFunc even? odd? exact? inexact? +syntax keyword racketFunc inexact->exact exact->inexact + +" 3.2.2 General Arithmetic + +" 3.2.2.1 Arithmetic +syntax keyword racketFunc + - * / quotient remainder quotient/remainder modulo +syntax keyword racketFunc add1 sub1 abs max min gcd lcm round exact-round floor +syntax keyword racketFunc ceiling truncate numerator denominator rationalize + +" 3.2.2.2 Number Comparison +syntax keyword racketFunc = < <= > >= + +" 3.2.2.3 Powers and Roots +syntax keyword racketFunc sqrt integer-sqrt integer-sqrt/remainder +syntax keyword racketFunc expt exp log + +" 3.2.2.3 Trigonometric Functions +syntax keyword racketFunc sin cos tan asin acos atan + +" 3.2.2.4 Complex Numbers +syntax keyword racketFunc make-rectangular make-polar +syntax keyword racketFunc real-part imag-part magnitude angle +syntax keyword racketFunc bitwise-ior bitwise-and bitwise-xor bitwise-not +syntax keyword racketFunc bitwise-bit-set? bitwise-bit-field arithmetic-shift +syntax keyword racketFunc integer-length + +" 3.2.2.5 Random Numbers +syntax keyword racketFunc random random-seed +syntax keyword racketFunc make-pseudo-random-generator pseudo-random-generator? +syntax keyword racketFunc current-pseudo-random-generator pseudo-random-generator->vector +syntax keyword racketFunc vector->pseudo-random-generator vector->pseudo-random-generator! + +" 3.2.2.8 Number-String Conversions +syntax keyword racketFunc number->string string->number real->decimal-string +syntax keyword racketFunc integer->integer-bytes +syntax keyword racketFunc floating-point-bytes->real real->floating-point-bytes +syntax keyword racketFunc system-big-endian? + +" 3.2.2.9 Extra Constants and Functions +syntax keyword racketFunc pi sqr sgn conjugate sinh cosh tanh order-of-magnitude + +" 3.2.3 Flonums + +" 3.2.3.1 Flonum Arithmetic +syntax keyword racketFunc fl+ fl- fl* fl/ flabs +syntax keyword racketFunc fl= fl< fl> fl<= fl>= flmin flmax +syntax keyword racketFunc flround flfloor flceiling fltruncate +syntax keyword racketFunc flsin flcos fltan flasin flacos flatan +syntax keyword racketFunc fllog flexp flsqrt +syntax keyword racketFunc ->fl fl->exact-integer make-flrectangular +syntax keyword racketFunc flreal-part flimag-part + +" 3.2.3.2 Flonum Vectors +syntax keyword racketFunc flvector? flvector make-flvector flvector-length +syntax keyword racketFunc flvector-ref flvector-set! flvector-copy in-flvector +syntax keyword racketFunc shared-flvector make-shared-flvector +syntax keyword racketSyntax for/flvector for*/flvector + +" 3.2.4 Fixnums +syntax keyword racketFunc fx+ fx- fx* fxquotient fxremainder fxmodulo fxabs +syntax keyword racketFunc fxand fxior fxxor fxnot fxlshift fxrshift +syntax keyword racketFunc fx= fx< fx> fx<= fx>= fxmin fxmax fx->fl fl->fx + +" 3.2.4.2 Fixnum Vectors +syntax keyword racketFunc fxvector? fxvector make-fxvector fxvector-length +syntax keyword racketFunc fxvector-ref fxvector-set! fxvector-copy in-fxvector +syntax keyword racketFunc for/fxvector for*/fxvector +syntax keyword racketFunc shared-fxvector make-shared-fxvector + +" 3.3 Strings +syntax keyword racketFunc string? make-string string string->immutable-string string-length +syntax keyword racketFunc string-ref string-set! substring string-copy string-copy! +syntax keyword racketFunc string-fill! string-append string->list list->string +syntax keyword racketFunc build-string string=? string? string>=? +syntax keyword racketFunc string-ci=? string-ci? string-ci>=? +syntax keyword racketFunc string-upcase string-downcase string-titlecase string-foldcase +syntax keyword racketFunc string-normalize-nfd string-normalize-nfc string-normalize-nfkc +syntax keyword racketFunc string-normalize-spaces string-trim +syntax keyword racketFunc string-locale=? string-locale>? string-localeimmutable-bytes byte? +syntax keyword racketFunc bytes-length bytes-ref bytes-set! subbytes bytes-copy +syntax keyword racketFunc bytes-copy! bytes-fill! bytes-append bytes->list list->bytes +syntax keyword racketFunc make-shared-bytes shared-bytes +syntax keyword racketFunc bytes=? bytes? +syntax keyword racketFunc bytes->string/utf-8 bytes->string/latin-1 +syntax keyword racketFunc string->bytes/locale string->bytes/latin-1 string->bytes/utf-8 +syntax keyword racketFunc string-utf-8-length bytes-utf8-ref bytes-utf-8-index +syntax keyword racketFunc bytes-open-converter bytes-close-converter +syntax keyword racketFunc bytes-convert bytes-convert-end bytes-converter? +syntax keyword racketFunc locale-string-encoding + +" 3.5 Characters +syntax keyword racketFunc char? char->integer integer->char +syntax keyword racketFunc char=? char? char>=? +syntax keyword racketFunc char-ci=? char-ci? char-ci>=? +syntax keyword racketFunc char-alphabetic? char-lower-case? char-upper-case? char-title-case? +syntax keyword racketFunc char-numeric? char-symbolic? char-punctuation? char-graphic? +syntax keyword racketFunc char-whitespace? char-blank? +syntax keyword racketFunc char-iso-control? char-general-category +syntax keyword racketFunc make-known-char-range-list +syntax keyword racketFunc char-upcase char-downcase char-titlecase char-foldcase + +" 3.6 Symbols +syntax keyword racketFunc symbol? symbol-interned? symbol-unreadable? +syntax keyword racketFunc symbol->string string->symbol +syntax keyword racketFunc string->uninterned-symbol string->unreadable-symbol +syntax keyword racketFunc gensym + +" 3.7 Regular Expressions +syntax keyword racketFunc regexp? pregexp? byte-regexp? byte-pregexp? +syntax keyword racketFunc regexp pregexp byte-regexp byte-pregexp +syntax keyword racketFunc regexp-quote regexp-match regexp-match* +syntax keyword racketFunc regexp-try-match regexp-match-positions +syntax keyword racketFunc regexp-match-positions* regexp-match? +syntax keyword racketFunc regexp-match-peek-positions regexp-match-peek-immediate +syntax keyword racketFunc regexp-match-peek regexp-match-peek-positions* +syntax keyword racketFunc regexp-match/end regexp-match-positions/end +syntax keyword racketFunc regexp-match-peek-positions-immediat/end +syntax keyword racketFunc regexp-split regexp-replace regexp-replace* +syntax keyword racketFunc regexp-replace-quote + +" 3.8 Keywords +syntax keyword racketFunc keyword? keyword->string string->keyword keywordlist list->vector +syntax keyword racketFunc vector->immutable-vector vector-fill! vector-copy! +syntax keyword racketFunc vector->values build-vector vector-set*! vector-map +syntax keyword racketFunc vector-map! vector-append vector-take vector-take-right +syntax keyword racketFunc vector-drop vector-drop-right vector-split-at +syntax keyword racketFunc vector-split-at-right vector-copy vector-filter +syntax keyword racketFunc vector-filter-not vector-count vector-argmin vector-argmax +syntax keyword racketFunc vector-member vector-memv vector-memq + +" 3.12 Boxes +syntax keyword racketFunc box? box box-immutable unbox set-box! + +" 3.13 Hash Tables +syntax keyword racketFunc hash? hash-equal? hash-eqv? hash-eq? hash-weak? hash +syntax keyword racketFunc hasheq hasheqv +syntax keyword racketFunc make-hash make-hasheqv make-hasheq make-weak-hash make-weak-hasheqv +syntax keyword racketFunc make-weak-hasheq make-immutable-hash make-immutable-hasheqv +syntax keyword racketFunc make-immutable-hasheq +syntax keyword racketFunc hash-set! hash-set*! hash-set hash-set* hash-ref hash-ref! +syntax keyword racketFunc hash-has-key? hash-update! hash-update hash-remove! +syntax keyword racketFunc hash-remove hash-map hash-keys hash-values +syntax keyword racketFunc hash->list hash-for-each hash-count +syntax keyword racketFunc hash-iterate-first hash-iterate-next hash-iterate-key +syntax keyword racketFunc hash-iterate-value hash-copy eq-hash-code eqv-hash-code +syntax keyword racketFunc equal-hash-code equal-secondary-hash-code + +" 3.15 Dictionaries +syntax keyword racketFunc dict? dict-mutable? dict-can-remove-keys? dict-can-functional-set? +syntax keyword racketFunc dict-set! dict-set*! dict-set dict-set* dict-has-key? dict-ref +syntax keyword racketFunc dict-ref! dict-update! dict-update dict-remove! dict-remove +syntax keyword racketFunc dict-map dict-for-each dict-count dict-iterate-first dict-iterate-next +syntax keyword racketFunc dict-iterate-key dict-iterate-value in-dict in-dict-keys +syntax keyword racketFunc in-dict-values in-dict-pairs dict-keys dict-values +syntax keyword racketFunc dict->list prop: dict prop: dict/contract dict-key-contract +syntax keyword racketFunc dict-value-contract dict-iter-contract make-custom-hash +syntax keyword racketFunc make-immutable-custom-hash make-weak-custom-hash + +" 3.16 Sets +syntax keyword racketFunc set seteqv seteq set-empty? set-count set-member? +syntax keyword racketFunc set-add set-remove set-union set-intersect set-subtract +syntax keyword racketFunc set-symmetric-difference set=? subset? proper-subset? +syntax keyword racketFunc set-map set-for-each set? set-equal? set-eqv? set-eq? +syntax keyword racketFunc set/c in-set for/set for/seteq for/seteqv for*/set +syntax keyword racketFunc for*/seteq for*/seteqv list->set list->seteq +syntax keyword racketFunc list->seteqv set->list + +" 3.17 Procedures +syntax keyword racketFunc procedure? apply compose compose1 procedure-rename procedure->method +syntax keyword racketFunc keyword-apply procedure-arity procedure-arity? +syntax keyword racketFunc procedure-arity-includes? procedure-reduce-arity +syntax keyword racketFunc procedure-keywords make-keyword-procedure +syntax keyword racketFunc procedure-reduce-keyword-arity procedure-struct-type? +syntax keyword racketFunc procedure-extract-target checked-procedure-check-and-extract +syntax keyword racketFunc primitive? primitive-closure? primitive-result-arity +syntax keyword racketFunc identity const thunk thunk* negate curry curryr + +" 3.18 Void +syntax keyword racketFunc void void? + +" 4.1 Defining Structure Types +syntax keyword racketFunc struct struct-field-index define-struct define-struct define-struct/derived + +" 4.2 Creating Structure Types +syntax keyword racketFunc make-struct-type make-struct-field-accessor make-struct-field-mutator + +" 4.3 Structure Type Properties +syntax keyword racketFunc make-struct-type-property struct-type-property? struct-type-property-accessor-procedure? + +" 4.4 Copying and Updating Structures +syntax keyword racketFunc struct-copy + +" 4.5 Structure Utilities +syntax keyword racketFunc struct->vector struct? struct-type? +syntax keyword racketFunc struct-constructor-procedure? struct-predicate-procedure? struct-accessor-procedure? struct-mutator-procedure? +syntax keyword racketFunc prefab-struct-key make-prefab-struct prefab-key->struct-type + +" 4.6 Structure Type Transformer Binding +syntax keyword racketFunc struct-info? check-struct-info? make-struct-info extract-struct-info +syntax keyword racketFunc struct-auto-info? struct-auto-info-lists + +" 5.1 Creating Interfaces +syntax keyword racketFunc interface interface* + +" 5.2 Creating Classes +syntax keyword racketFunc class* class inspect +syntax keyword racketFunc init init-field field inherit field init-rest +syntax keyword racketFunc public public* pubment pubment* public-final public-final* +syntax keyword racketFunc override override* overment overment* override-final override-final* +syntax keyword racketFunc augride augride* augment augment* augment-final augment-final* +syntax keyword racketFunc abstract inherit inherit/super inherit/inner +syntax keyword racketFunc rename-inner rename-super +syntax keyword racketFunc define/public define/pubment define/public-final +syntax keyword racketFunc define/override define/overment define/override-final +syntax keyword racketFunc define/augride define/augment define/augment-final +syntax keyword racketFunc private* define/private + +" 5.2.3 Methods +syntax keyword racketFunc class/derived +syntax keyword racketFunc super inner define-local-member-name define-member-name +syntax keyword racketFunc member-name-key generate-member-key member-name-key? +syntax keyword racketFunc member-name-key=? member-name-key-hash-code + +" 5.3 Creating Objects +syntax keyword racketFunc make-object instantiate new +syntax keyword racketFunc super-make-object super-instantiate super-new + +"5.4 Field and Method Access +syntax keyword racketFunc method-id send send/apply send/keyword-apply dynamic-send send* +syntax keyword racketFunc get-field set-field! field-bound? +syntax keyword racketFunc class-field-accessor class-field-mutator + +"5.4.3 Generics +syntax keyword racketFunc generic send-generic make-generic + +" 8.1 Data-strucure contracts +syntax keyword racketFunc flat-contract-with-explanation flat-named-contract +" TODO where do any/c and none/c `value`s go? +syntax keyword racketFunc or/c first-or/c and/c not/c =/c /c <=/c >=/c +syntax keyword racketFunc between/c real-in integer-in char-in natural-number/c +syntax keyword racketFunc string-len/c printable/c one-of/c symbols vectorof +syntax keyword racketFunc vector-immutableof vector/c box/c box-immutable/c listof +syntax keyword racketFunc non-empty-listof list*of cons/c cons/dc list/c *list/c +syntax keyword racketFunc syntax/c struct/c struct/dc parameter/c +syntax keyword racketFunc procedure-arity-includes/c hash/c hash/dc channel/c +syntax keyword racketFunc prompt-tag/c continuation-mark-key/c evt/c promise/c +syntax keyword racketFunc flat-contract flat-contract-predicate suggest/c + +" 9.1 Multiple Values +syntax keyword racketFunc values call-with-values + +" 10.2.2 Raising Exceptions +syntax keyword racketFunc raise error raise-user-error raise-argument-error +syntax keyword racketFunc raise-result-error raise-argument-error raise-range-error +syntax keyword racketFunc raise-type-error raise-mismatch-error raise-arity-error +syntax keyword racketFunc raise-syntax-error + +" 10.2.3 Handling Exceptions +syntax keyword racketFunc call-with-exception-handler uncaught-exception-handler + +" 10.2.4 Configuring Default Handlers +syntax keyword racketFunc error-escape-handler error-display-handler error-print-width +syntax keyword racketFunc error-print-context-length error-values->string-handler +syntax keyword racketFunc error-print-source-location + +" 10.2.5 Built-in Exception Types +syntax keyword racketFunc exn exn:fail exn:fail:contract exn:fail:contract:arity +syntax keyword racketFunc exn:fail:contract:divide-by-zero exn:fail:contract:non-fixnum-result +syntax keyword racketFunc exn:fail:contract:continuation exn:fail:contract:variable +syntax keyword racketFunc exn:fail:syntax exn:fail:syntax:unbound exn:fail:syntax:missing-module +syntax keyword racketFunc exn:fail:read exn:fail:read:eof exn:fail:read:non-char +syntax keyword racketFunc exn:fail:filesystem exn:fail:filesystem:exists +syntax keyword racketFunc exn:fail:filesystem:version exn:fail:filesystem:errno +syntax keyword racketFunc exn:fail:filesystem:missing-module +syntax keyword racketFunc exn:fail:network exn:fail:network:errno exn:fail:out-of-memory +syntax keyword racketFunc exn:fail:unsupported exn:fail:user +syntax keyword racketFunc exn:break exn:break:hang-up exn:break:terminate + +" 10.3 Delayed Evaluation +syntax keyword racketFunc promise? delay lazy force promise-forced? promise-running? + +" 10.3.1 Additional Promise Kinds +syntax keyword racketFunc delay/name promise/name delay/strict delay/sync delay/thread delay/idle + +" 10.4 Continuations +syntax keyword racketFunc call-with-continuation-prompt abort-current-continuation make-continuation-prompt-tag +syntax keyword racketFunc default-continuation-prompt-tag call-with-current-continuation call/cc +syntax keyword racketFunc call-with-composable-continuation call-with-escape-continuation call/ec +syntax keyword racketFunc call-with-continuation-barrier continuation-prompt-available +syntax keyword racketFunc continuation? continuation-prompt-tag dynamic-wind + +" 10.4.1 Additional Control Operators +syntax keyword racketFunc call/prompt abort/cc call/comp abort fcontrol spawn splitter new-prompt + +" 11.3.2 Parameters +syntax keyword racketFunc make-parameter make-derived-parameter parameter? +syntax keyword racketFunc parameter-procedure=? current-parameterization +syntax keyword racketFunc call-with-parameterization parameterization? + +" 14.1.1 Manipulating Paths +syntax keyword racketFunc path? path-string? path-for-some-system? string->path path->string path->bytes +syntax keyword racketFunc string->path-element bytes->path-element path-element->string path-element->bytes +syntax keyword racketFunc path-convention-type system-path-convention-type build-type +syntax keyword racketFunc build-type/convention-type +syntax keyword racketFunc absolute-path? relative-path? complete-path? +syntax keyword racketFunc path->complete-path path->directory-path +syntax keyword racketFunc resolve-path cleanse-path expand-user-path simplify-path normal-case-path split-path +syntax keyword racketFunc path-replace-suffix path-add-suffix + +" 14.1.2 More Path Utilities +syntax keyword racketFunc explode-path file-name-from-path filename-extension find-relative-path normalize-path +syntax keyword racketFunc path-element? path-only simple-form-path some-simple-path->string string->some-system-path + +" 15.6 Time +syntax keyword racketFunc current-seconds current-inexact-milliseconds +syntax keyword racketFunc seconds->date current-milliseconds + + +syntax match racketDelimiter !\<\.\>! + +syntax cluster racketTop contains=racketSyntax,racketFunc,racketDelimiter + +syntax match racketConstant ,\<\*\k\+\*\>, +syntax match racketConstant ,\<<\k\+>\>, + +" Non-quoted lists, and strings +syntax region racketStruc matchgroup=racketParen start="("rs=s+1 end=")"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="#("rs=s+2 end=")"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="{"rs=s+1 end="}"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="#{"rs=s+2 end="}"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="\["rs=s+1 end="\]"re=e-1 contains=@racketTop +syntax region racketStruc matchgroup=racketParen start="#\["rs=s+2 end="\]"re=e-1 contains=@racketTop + +for lit in ['hash', 'hasheq', 'hasheqv'] + execute printf('syntax match racketLit "\<%s\>" nextgroup=@racketParen containedin=ALLBUT,.*String,.*Comment', '#'.lit) +endfor + +for lit in ['rx', 'rx#', 'px', 'px#'] + execute printf('syntax match racketRe "\<%s\>" nextgroup=@racketString containedin=ALLBUT,.*String,.*Comment,', '#'.lit) +endfor + +unlet lit + +" Simple literals + +" Strings + +syntax match racketStringEscapeError "\\." contained display + +syntax match racketStringEscape "\\[abtnvfre'"\\]" contained display +syntax match racketStringEscape "\\$" contained display +syntax match racketStringEscape "\\\o\{1,3}\|\\x\x\{1,2}" contained display + +syntax match racketUStringEscape "\\u\x\{1,4}\|\\U\x\{1,8}" contained display +syntax match racketUStringEscape "\\u\x\{4}\\u\x\{4}" contained display + +syntax region racketString start=/\%(\\\)\@" +syntax match racketContainedNumberError "\<#b\k*[^-+01delfinas#./@]\>" +syntax match racketContainedNumberError "\<#[ei]#[ei]" +syntax match racketContainedNumberError "\<#[xdob]#[xdob]" + +" start with the simpler sorts +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\d\+/\d\+\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\d\+/\d\+[-+]\d\+\(/\d\+\)\?i\>" contains=racketContainedNumberError + +" different possible ways of expressing complex values +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?[-+]\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f][-+]\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?[-+]\(inf\|nan\)\.[0f]i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?@[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f]@[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[dobie]\)\{0,2}[-+]\?\(\d\+\|\d\+#*\.\|\d*\.\d\+\)#*\(/\d\+#*\)\?\([sdlef][-+]\?\d\+#*\)\?@[-+]\(inf\|nan\)\.[0f]\>" contains=racketContainedNumberError + +" hex versions of the above (separate because of the different possible exponent markers) +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\x\+/\x\+\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\x\+/\x\+[-+]\x\+\(/\x\+\)\?i\>" + +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?[-+]\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\(inf\|nan\)\.[0f][-+]\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?[-+]\(inf\|nan\)\.[0f]i\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?@[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\(inf\|nan\)\.[0f]@[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?\>" +syntax match racketNumber "\<\(#x\|#[ei]#x\|#x#[ei]\)[-+]\?\(\x\+\|\x\+#*\.\|\x*\.\x\+\)#*\(/\x\+#*\)\?\([sl][-+]\?\x\+#*\)\?@[-+]\(inf\|nan\)\.[0f]\>" + +" these work for any radix +syntax match racketNumber "\<\(#[xdobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f]i\?\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[xdobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f][-+]\(inf\|nan\)\.[0f]i\>" contains=racketContainedNumberError +syntax match racketNumber "\<\(#[xdobie]\)\{0,2}[-+]\(inf\|nan\)\.[0f]@[-+]\(inf\|nan\)\.[0f]\>" contains=racketContainedNumberError + +syntax keyword racketBoolean #t #f #true #false #T #F + +syntax match racketError "\<#\\\k*\>" + +syntax match racketChar "\<#\\.\w\@!" +syntax match racketChar "\<#\\space\>" +syntax match racketChar "\<#\\newline\>" +syntax match racketChar "\<#\\return\>" +syntax match racketChar "\<#\\null\?\>" +syntax match racketChar "\<#\\backspace\>" +syntax match racketChar "\<#\\tab\>" +syntax match racketChar "\<#\\linefeed\>" +syntax match racketChar "\<#\\vtab\>" +syntax match racketChar "\<#\\page\>" +syntax match racketChar "\<#\\rubout\>" +syntax match racketChar "\<#\\\o\{1,3}\>" +syntax match racketChar "\<#\\x\x\{1,2}\>" +syntax match racketChar "\<#\\u\x\{1,6}\>" + +syntax cluster racketTop add=racketNumber,racketBoolean,racketChar + +" Command-line parsing +syntax keyword racketExtFunc command-line current-command-line-arguments once-any help-labels multi once-each + +syntax match racketSyntax "#lang " +syntax match racketExtSyntax "#:\k\+" + +syntax cluster racketTop add=racketExtFunc,racketExtSyntax + +" syntax quoting, unquoting and quasiquotation +syntax match racketQuote "#\?['`]" + +syntax match racketUnquote "#," +syntax match racketUnquote "#,@" +syntax match racketUnquote "," +syntax match racketUnquote ",@" + +" Comments +syntax match racketSharpBang "\%^#![ /].*" display +syntax match racketComment /;.*$/ contains=racketTodo,racketNote,@Spell +syntax region racketMultilineComment start=/#|/ end=/|#/ contains=racketMultilineComment,racketTodo,racketNote,@Spell +syntax match racketFormComment "#;" nextgroup=@racketTop + +syntax match racketTodo /\C\<\(FIXME\|TODO\|XXX\)\ze:\?\>/ contained +syntax match racketNote /\CNOTE\ze:\?/ contained + +syntax cluster racketTop add=racketQuote,racketUnquote,racketComment,racketMultilineComment,racketFormComment + +" Synchronization and the wrapping up... +syntax sync match matchPlace grouphere NONE "^[^ \t]" +" ... i.e. synchronize on a line that starts at the left margin + +" Define the default highlighting. +highlight default link racketSyntax Statement +highlight default link racketFunc Function + +highlight default link racketString String +highlight default link racketStringEscape Special +highlight default link racketUStringEscape Special +highlight default link racketStringEscapeError Error +highlight default link racketChar Character +highlight default link racketBoolean Boolean + +highlight default link racketNumber Number +highlight default link racketNumberError Error +highlight default link racketContainedNumberError Error + +highlight default link racketQuote SpecialChar +highlight default link racketUnquote SpecialChar + +highlight default link racketDelimiter Delimiter +highlight default link racketParen Delimiter +highlight default link racketConstant Constant + +highlight default link racketLit Type +highlight default link racketRe Type + +highlight default link racketComment Comment +highlight default link racketMultilineComment Comment +highlight default link racketFormComment SpecialChar +highlight default link racketSharpBang Comment +highlight default link racketTodo Todo +highlight default link racketNote SpecialComment +highlight default link racketError Error + +highlight default link racketExtSyntax Type +highlight default link racketExtFunc PreProc + +let b:current_syntax = "racket" -- cgit From fa747d004a1e91b30066020f2f592e4dc5d94084 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 31 Aug 2022 19:47:10 +0800 Subject: fix(api): nvim_set_hl bail out on invalid group name (#20021) --- src/nvim/api/vim.c | 10 ++++++---- test/functional/api/highlight_spec.lua | 5 +++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index b164106cef..a1721d433f 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -86,8 +86,7 @@ Dictionary nvim_get_hl_by_name(String name, Boolean rgb, Error *err) int id = syn_name2id(name.data); if (id == 0) { - api_set_error(err, kErrorTypeException, "Invalid highlight name: %s", - name.data); + api_set_error(err, kErrorTypeException, "Invalid highlight name: %s", name.data); return result; } result = nvim_get_hl_by_id(id, rgb, err); @@ -105,8 +104,7 @@ Dictionary nvim_get_hl_by_id(Integer hl_id, Boolean rgb, Error *err) { Dictionary dic = ARRAY_DICT_INIT; if (syn_get_final_id((int)hl_id) == 0) { - api_set_error(err, kErrorTypeException, - "Invalid highlight id: %" PRId64, hl_id); + api_set_error(err, kErrorTypeException, "Invalid highlight id: %" PRId64, hl_id); return dic; } int attrcode = syn_id2attr((int)hl_id); @@ -175,6 +173,10 @@ void nvim_set_hl(Integer ns_id, String name, Dict(highlight) *val, Error *err) FUNC_API_SINCE(7) { int hl_id = syn_check_group(name.data, name.size); + if (hl_id == 0) { + api_set_error(err, kErrorTypeException, "Invalid highlight name: %s", name.data); + return; + } int link_id = -1; HlAttrs attrs = dict2hlattrs(val, true, &link_id, err); diff --git a/test/functional/api/highlight_spec.lua b/test/functional/api/highlight_spec.lua index 2730f7e23d..3b36563d21 100644 --- a/test/functional/api/highlight_spec.lua +++ b/test/functional/api/highlight_spec.lua @@ -354,4 +354,9 @@ describe("API: set highlight", function() meths.set_hl(0, 'Normal', {fg='#000083', bg='#0000F3'}) eq({foreground = 131, background = 243}, nvim("get_hl_by_name", 'Normal', true)) end) + + it('does not segfault on invalid group name #20009', function() + eq('Invalid highlight name: foo bar', pcall_err(meths.set_hl, 0, 'foo bar', {bold = true})) + assert_alive() + end) end) -- cgit From fb1edb2f5728d74ae811c6ab32395598cea5609b Mon Sep 17 00:00:00 2001 From: Dundar Göc Date: Fri, 26 Aug 2022 23:11:25 +0200 Subject: refactor: replace char_u with char Work on https://github.com/neovim/neovim/issues/459 --- src/nvim/buffer.c | 2 +- src/nvim/change.c | 20 ++--- src/nvim/charset.c | 4 +- src/nvim/cmdexpand.c | 6 +- src/nvim/cursor.c | 2 +- src/nvim/diff.c | 8 +- src/nvim/drawline.c | 6 +- src/nvim/edit.c | 16 ++-- src/nvim/eval.c | 4 +- src/nvim/eval/funcs.c | 12 +-- src/nvim/eval/userfunc.c | 14 ++-- src/nvim/eval/vars.c | 3 +- src/nvim/event/socket.c | 2 +- src/nvim/ex_cmds.c | 36 ++++----- src/nvim/ex_cmds2.c | 6 +- src/nvim/ex_docmd.c | 17 ++-- src/nvim/ex_getln.c | 12 +-- src/nvim/file_search.c | 4 +- src/nvim/fileio.c | 26 +++--- src/nvim/fold.c | 12 +-- src/nvim/getchar.c | 4 +- src/nvim/hardcopy.c | 4 +- src/nvim/if_cscope.c | 8 +- src/nvim/indent.c | 14 ++-- src/nvim/indent_c.c | 66 +++++++-------- src/nvim/insexpand.c | 16 ++-- src/nvim/macros.h | 2 +- src/nvim/main.c | 4 +- src/nvim/mapping.c | 4 +- src/nvim/mark.c | 4 +- src/nvim/mbyte.c | 15 ++-- src/nvim/memline.c | 68 ++++++++-------- src/nvim/menu.c | 2 +- src/nvim/message.c | 204 +++++++++++++++++++++++------------------------ src/nvim/mouse.c | 6 +- src/nvim/normal.c | 10 +-- src/nvim/ops.c | 203 +++++++++++++++++++++++----------------------- src/nvim/os/fs.c | 4 +- src/nvim/os/shell.c | 8 +- src/nvim/path.c | 13 +-- src/nvim/plines.c | 14 ++-- src/nvim/quickfix.c | 12 +-- src/nvim/regexp.c | 2 +- src/nvim/regexp_bt.c | 4 +- src/nvim/regexp_nfa.c | 2 +- src/nvim/runtime.c | 2 +- src/nvim/search.c | 42 +++++----- src/nvim/spell.c | 4 +- src/nvim/spellfile.c | 12 +-- src/nvim/syntax.c | 4 +- src/nvim/tag.c | 18 ++--- src/nvim/textformat.c | 10 +-- src/nvim/textobject.c | 8 +- src/nvim/tui/terminfo.c | 4 +- src/nvim/undo.c | 6 +- src/nvim/usercmd.c | 2 +- src/nvim/window.c | 2 +- 57 files changed, 511 insertions(+), 508 deletions(-) diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index 514be4c56b..8f23102e2e 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -3701,7 +3701,7 @@ static int chk_modeline(linenr_T lnum, int flags) int retval = OK; prev = -1; - for (s = (char *)ml_get(lnum); *s != NUL; s++) { + for (s = ml_get(lnum); *s != NUL; s++) { if (prev == -1 || ascii_isspace(prev)) { if ((prev != -1 && STRNCMP(s, "ex:", (size_t)3) == 0) || STRNCMP(s, "vi:", (size_t)3) == 0) { diff --git a/src/nvim/change.c b/src/nvim/change.c index 85ab92e49b..5bea388f28 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -631,7 +631,7 @@ void ins_char_bytes(char *buf, size_t charlen) size_t col = (size_t)curwin->w_cursor.col; linenr_T lnum = curwin->w_cursor.lnum; - char *oldp = (char *)ml_get(lnum); + char *oldp = ml_get(lnum); size_t linelen = STRLEN(oldp) + 1; // length of old line including NUL // The lengths default to the values for when not replacing. @@ -739,7 +739,7 @@ void ins_str(char *s) } colnr_T col = curwin->w_cursor.col; - char *oldp = (char *)ml_get(lnum); + char *oldp = ml_get(lnum); int oldlen = (int)STRLEN(oldp); char *newp = xmalloc((size_t)oldlen + (size_t)newlen + 1); @@ -797,7 +797,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) linenr_T lnum = curwin->w_cursor.lnum; colnr_T col = curwin->w_cursor.col; bool fixpos = fixpos_arg; - char *oldp = (char *)ml_get(lnum); + char *oldp = ml_get(lnum); colnr_T oldlen = (colnr_T)STRLEN(oldp); // Can't do anything when the cursor is on the NUL after the line. @@ -843,7 +843,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) && (get_ve_flags() & VE_ONEMORE) == 0) { curwin->w_cursor.col--; curwin->w_cursor.coladd = 0; - curwin->w_cursor.col -= utf_head_off((char_u *)oldp, (char_u *)oldp + curwin->w_cursor.col); + curwin->w_cursor.col -= utf_head_off(oldp, oldp + curwin->w_cursor.col); } count = oldlen - col; movelen = 1; @@ -854,7 +854,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) bool was_alloced = ml_line_alloced(); // check if oldp was allocated char *newp; if (was_alloced) { - ml_add_deleted_len(curbuf->b_ml.ml_line_ptr, oldlen); + ml_add_deleted_len((char *)curbuf->b_ml.ml_line_ptr, oldlen); newp = oldp; // use same allocated memory } else { // need to allocate a new line newp = xmalloc((size_t)(oldlen + 1 - count)); @@ -1047,7 +1047,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // the line, replacing what was there before and pushing the right // stuff onto the replace stack. -- webb. if (curwin->w_cursor.lnum < orig_line_count) { - next_line = (char *)vim_strsave(ml_get(curwin->w_cursor.lnum + 1)); + next_line = xstrdup(ml_get(curwin->w_cursor.lnum + 1)); } else { next_line = xstrdup(""); } @@ -1119,7 +1119,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // Skip preprocessor directives, unless they are recognised as comments. if (lead_len == 0 && ptr[0] == '#') { while (ptr[0] == '#' && curwin->w_cursor.lnum > 1) { - ptr = (char *)ml_get(--curwin->w_cursor.lnum); + ptr = ml_get(--curwin->w_cursor.lnum); } newindent = get_indent(); } @@ -1210,7 +1210,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) } else { was_backslashed = false; } - ptr = (char *)ml_get(++curwin->w_cursor.lnum); + ptr = ml_get(++curwin->w_cursor.lnum); } if (was_backslashed) { newindent = 0; // Got to end of file @@ -1465,7 +1465,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // blank-out any other chars from the old leader. while (--p >= leader) { - int l = utf_head_off((char_u *)leader, (char_u *)p); + int l = utf_head_off(leader, p); if (l > 1) { p -= l; @@ -1872,7 +1872,7 @@ void truncate_line(int fixpos) if (col == 0) { newp = xstrdup(""); } else { - newp = (char *)vim_strnsave(ml_get(lnum), (size_t)col); + newp = xstrnsave(ml_get(lnum), (size_t)col); } ml_replace(lnum, newp, false); diff --git a/src/nvim/charset.c b/src/nvim/charset.c index 4efd8a4ad1..4604bf7716 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -927,11 +927,11 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en } } posptr = ptr + pos->col; - posptr -= utf_head_off(line, posptr); + posptr -= utf_head_off((char *)line, (char *)posptr); } chartabsize_T cts; - init_chartabsize_arg(&cts, wp, pos->lnum, 0, line, line); + init_chartabsize_arg(&cts, wp, pos->lnum, 0, (char *)line, (char *)line); // This function is used very often, do some speed optimizations. // When 'list', 'linebreak', 'showbreak' and 'breakindent' are not set diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 5c54404aab..1c35f28301 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -675,7 +675,7 @@ int showmatches(expand_T *xp, int wildmenu) msg_advance(maxlen + 1); msg_puts((const char *)p); msg_advance(maxlen + 3); - msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D)); + msg_outtrans_long_attr((char *)p + 2, HL_ATTR(HLF_D)); break; } for (j = maxlen - lastlen; --j >= 0;) { @@ -2720,7 +2720,7 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) int j = cclp->cmdpos; int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); while (--j > i) { - j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); + j -= utf_head_off((char *)cclp->cmdbuff, (char *)cclp->cmdbuff + j); if (vim_ispathsep(cclp->cmdbuff[j])) { found = true; break; @@ -2741,7 +2741,7 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) int j = cclp->cmdpos - 1; int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); while (--j > i) { - j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); + j -= utf_head_off((char *)cclp->cmdbuff, (char *)cclp->cmdbuff + j); if (vim_ispathsep(cclp->cmdbuff[j]) #ifdef BACKSLASH_IN_FILENAME && vim_strchr((const char_u *)" *?[{`$%#", cclp->cmdbuff[j + 1]) diff --git a/src/nvim/cursor.c b/src/nvim/cursor.c index ed0488cf76..54e5ffff37 100644 --- a/src/nvim/cursor.c +++ b/src/nvim/cursor.c @@ -138,7 +138,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a } chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, pos->lnum, 0, line, line); + init_chartabsize_arg(&cts, curwin, pos->lnum, 0, (char *)line, (char *)line); while (cts.cts_vcol <= wcol && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) csize = win_lbr_chartabsize(&cts, &head); diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 1cfb535fe8..a3046bb7d7 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -2348,8 +2348,8 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) // Move back to first byte of character in both lines (may // have "nn^" in line_org and "n^ in line_new). - si_org -= utf_head_off((char_u *)line_org, (char_u *)line_org + si_org); - si_new -= utf_head_off((char_u *)line_new, (char_u *)line_new + si_new); + si_org -= utf_head_off(line_org, line_org + si_org); + si_new -= utf_head_off(line_new, line_new + si_new); if (*startp > si_org) { *startp = si_org; @@ -2381,8 +2381,8 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp) const char_u *p1 = (char_u *)line_org + ei_org; const char_u *p2 = (char_u *)line_new + ei_new; - p1 -= utf_head_off((char_u *)line_org, p1); - p2 -= utf_head_off((char_u *)line_new, p2); + p1 -= utf_head_off(line_org, (char *)p1); + p2 -= utf_head_off(line_new, (char *)p2); if (!diff_equal_char(p1, p2, &l)) { break; diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index b6c4400c60..66d8a1fb32 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -943,7 +943,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, chartabsize_T cts; int charsize; - init_chartabsize_arg(&cts, wp, lnum, (colnr_T)vcol, line, ptr); + init_chartabsize_arg(&cts, wp, lnum, (colnr_T)vcol, (char *)line, (char *)ptr); while (cts.cts_vcol < v && *cts.cts_ptr != NUL) { charsize = win_lbr_chartabsize(&cts, NULL); cts.cts_vcol += charsize; @@ -1803,11 +1803,11 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, // Found last space before word: check for line break. if (wp->w_p_lbr && c0 == c && vim_isbreak(c) && !vim_isbreak((int)(*ptr))) { - int mb_off = utf_head_off(line, ptr - 1); + int mb_off = utf_head_off((char *)line, (char *)ptr - 1); char_u *p = ptr - (mb_off + 1); chartabsize_T cts; - init_chartabsize_arg(&cts, wp, lnum, (colnr_T)vcol, line, p); + init_chartabsize_arg(&cts, wp, lnum, (colnr_T)vcol, (char *)line, (char *)p); n_extra = win_lbr_chartabsize(&cts, NULL) - 1; // We have just drawn the showbreak value, no need to add diff --git a/src/nvim/edit.c b/src/nvim/edit.c index aee8389900..642162284c 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1545,7 +1545,7 @@ void display_dollar(colnr_T col) // If on the last byte of a multi-byte move to the first byte. char_u *p = get_cursor_line_ptr(); - curwin->w_cursor.col -= utf_head_off(p, p + col); + curwin->w_cursor.col -= utf_head_off((char *)p, (char *)p + col); curs_columns(curwin, false); // Recompute w_wrow and w_wcol if (curwin->w_wcol < curwin->w_grid.cols) { edit_putchar('$', false); @@ -1672,7 +1672,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang last_vcol = 0; ptr = get_cursor_line_ptr(); chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, 0, 0, ptr, ptr); + init_chartabsize_arg(&cts, curwin, 0, 0, (char *)ptr, (char *)ptr); while (cts.cts_vcol <= (int)curwin->w_virtcol) { last_vcol = cts.cts_vcol; if (cts.cts_vcol > 0) { @@ -4642,7 +4642,7 @@ static bool ins_tab(void) char_u *tab = (char_u *)"\t"; chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, 0, vcol, tab, tab); + init_chartabsize_arg(&cts, curwin, 0, vcol, (char *)tab, (char *)tab); // Use as many TABs as possible. Beware of 'breakindent', 'showbreak' // and 'linebreak' adding extra virtual columns. @@ -4671,7 +4671,7 @@ static bool ins_tab(void) if (change_col >= 0) { int repl_off = 0; // Skip over the spaces we need. - init_chartabsize_arg(&cts, curwin, 0, vcol, ptr, ptr); + init_chartabsize_arg(&cts, curwin, 0, vcol, (char *)ptr, (char *)ptr); while (cts.cts_vcol < want_vcol && *cts.cts_ptr == ' ') { cts.cts_vcol += lbr_chartabsize(&cts); cts.cts_ptr++; @@ -4869,12 +4869,12 @@ int ins_copychar(linenr_T lnum) } // try to advance to the cursor column - line = ml_get(lnum); + line = (char_u *)ml_get(lnum); prev_ptr = line; validate_virtcol(); chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, lnum, 0, line, line); + init_chartabsize_arg(&cts, curwin, lnum, 0, (char *)line, (char *)line); while (cts.cts_vcol < curwin->w_virtcol && *cts.cts_ptr != NUL) { prev_ptr = (char_u *)cts.cts_ptr; cts.cts_vcol += lbr_chartabsize_adv(&cts); @@ -4958,7 +4958,7 @@ static void ins_try_si(int c) * case where an "if (..\n..) {" statement continues over multiple * lines -- webb */ - ptr = ml_get(pos->lnum); + ptr = (char_u *)ml_get(pos->lnum); i = pos->col; if (i > 0) { // skip blanks before '{' while (--i > 0 && ascii_iswhite(ptr[i])) {} @@ -4983,7 +4983,7 @@ static void ins_try_si(int c) old_pos = curwin->w_cursor; i = get_indent(); while (curwin->w_cursor.lnum > 1) { - ptr = (char_u *)skipwhite((char *)ml_get(--(curwin->w_cursor.lnum))); + ptr = (char_u *)skipwhite(ml_get(--(curwin->w_cursor.lnum))); // ignore empty lines and lines starting with '#'. if (*ptr != '#' && *ptr != NUL) { diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 2dbaa2f8ac..2ade64df3f 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -6369,7 +6369,7 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret } int len; if (charcol) { - len = mb_charlen(ml_get(pos.lnum)); + len = mb_charlen((char_u *)ml_get(pos.lnum)); } else { len = (int)STRLEN(ml_get(pos.lnum)); } @@ -8630,7 +8630,7 @@ void invoke_prompt_callback(void) if (curbuf->b_prompt_callback.type == kCallbackNone) { return; } - char *text = (char *)ml_get(lnum); + char *text = ml_get(lnum); char *prompt = (char *)prompt_text(); if (STRLEN(text) >= STRLEN(prompt)) { text += STRLEN(prompt); diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index aa328d50ef..6593a34f4a 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -1034,7 +1034,7 @@ static void f_confirm(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } if (!error) { - rettv->vval.v_number = do_dialog(type, NULL, (char_u *)message, (char_u *)buttons, def, NULL, + rettv->vval.v_number = do_dialog(type, NULL, (char *)message, (char *)buttons, def, NULL, false); } } @@ -3849,7 +3849,7 @@ static void f_hostname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) os_get_hostname(hostname, 256); rettv->v_type = VAR_STRING; - rettv->vval.v_string = (char *)vim_strsave((char_u *)hostname); + rettv->vval.v_string = xstrdup(hostname); } /// iconv() function @@ -5385,7 +5385,7 @@ static void f_nextnonblank(typval_T *argvars, typval_T *rettv, EvalFuncData fptr lnum = 0; break; } - if (*skipwhite((char *)ml_get(lnum)) != NUL) { + if (*skipwhite(ml_get(lnum)) != NUL) { break; } } @@ -5473,7 +5473,7 @@ static void f_prevnonblank(typval_T *argvars, typval_T *rettv, EvalFuncData fptr if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) { lnum = 0; } else { - while (lnum >= 1 && *skipwhite((char *)ml_get(lnum)) == NUL) { + while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL) { lnum--; } } @@ -7810,7 +7810,7 @@ free_lstval: if (strval == NULL) { return; } - write_reg_contents_ex(regname, (const char_u *)strval, (ssize_t)STRLEN(strval), + write_reg_contents_ex(regname, strval, (ssize_t)STRLEN(strval), append, yank_type, (colnr_T)block_len); } if (pointreg != 0) { @@ -9639,7 +9639,7 @@ static void f_win_gettype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (argvars[0].v_type != VAR_UNKNOWN) { wp = find_win_by_nr_or_id(&argvars[0]); if (wp == NULL) { - rettv->vval.v_string = (char *)vim_strsave((char_u *)"unknown"); + rettv->vval.v_string = xstrdup("unknown"); return; } } diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 4be922a055..21bd662db5 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -378,7 +378,7 @@ char_u *deref_func_name(const char *name, int *lenp, partial_T **const partialp, *lenp = 0; return (char_u *)""; } - *lenp = (int)STRLEN(v->di_tv.vval.v_string); + *lenp = (int)strlen(v->di_tv.vval.v_string); return (char_u *)v->di_tv.vval.v_string; } @@ -970,11 +970,11 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rett snprintf((char *)numbuf, sizeof(numbuf), "%d", ai + 1); name = (char *)numbuf; } - if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { + if (fixvar_idx < FIXVAR_CNT && strlen(name) <= VAR_SHORT_LEN) { v = (dictitem_T *)&fc->fixvar[fixvar_idx++]; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; } else { - v = xmalloc(sizeof(dictitem_T) + STRLEN(name)); + v = xmalloc(sizeof(dictitem_T) + strlen(name)); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX | DI_FLAGS_ALLOC; } STRCPY(v->di_key, name); @@ -1455,7 +1455,7 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t rettv->v_type = VAR_UNKNOWN; if (len <= 0) { - len = (int)STRLEN(funcname); + len = (int)strlen(funcname); } if (partial != NULL) { fp = partial->pt_func; @@ -2054,7 +2054,7 @@ void ex_function(exarg_T *eap) msg_putchar(' '); } } - msg_prt_line((char_u *)FUNCLINE(fp, j), false); + msg_prt_line(FUNCLINE(fp, j), false); ui_flush(); // show a line at a time os_breakcheck(); } @@ -2270,8 +2270,8 @@ void ex_function(exarg_T *eap) } else if (line_arg != NULL && *skipwhite((char *)line_arg) != NUL) { nextcmd = line_arg; } else if (*p != NUL && *p != '"' && p_verbose > 0) { - give_warning2((char_u *)_("W22: Text found after :endfunction: %s"), - p, true); + give_warning2(_("W22: Text found after :endfunction: %s"), + (char *)p, true); } if (nextcmd != NULL) { // Another command follows. If the line came from "eap" we diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index 75410d40d8..dbbb03b1b8 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -710,8 +710,7 @@ static char *ex_let_one(char *arg, typval_T *const tv, const bool copy, const bo } } if (p != NULL) { - write_reg_contents(*arg == '@' ? '"' : *arg, - (const char_u *)p, (ssize_t)STRLEN(p), false); + write_reg_contents(*arg == '@' ? '"' : *arg, p, (ssize_t)STRLEN(p), false); arg_end = arg + 1; } xfree(ptofree); diff --git a/src/nvim/event/socket.c b/src/nvim/event/socket.c index 9496a568b9..9ca3dcc276 100644 --- a/src/nvim/event/socket.c +++ b/src/nvim/event/socket.c @@ -125,7 +125,7 @@ int socket_watcher_start(SocketWatcher *watcher, int backlog, socket_cb cb) // Libuv converts ENOENT to EACCES for Windows compatibility, but if // the parent directory does not exist, ENOENT would be more accurate. *path_tail(watcher->addr) = NUL; - if (!os_path_exists((char_u *)watcher->addr)) { + if (!os_path_exists(watcher->addr)) { result = UV_ENOENT; } } diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index e672b80d69..17d45f207e 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -557,7 +557,7 @@ void ex_sort(exarg_T *eap) // matching and number conversion only has to be done once per line. // Also get the longest line length for allocating "sortbuf". for (lnum = eap->line1; lnum <= eap->line2; lnum++) { - s = (char *)ml_get(lnum); + s = ml_get(lnum); len = (int)STRLEN(s); if (maxlen < len) { maxlen = len; @@ -658,7 +658,7 @@ void ex_sort(exarg_T *eap) change_occurred = true; } - s = (char *)ml_get(get_lnum); + s = ml_get(get_lnum); size_t bytelen = STRLEN(s) + 1; // include EOL in bytelen old_count += (bcount_t)bytelen; if (!unique || i == 0 || string_compare(s, sortbuf1) != 0) { @@ -760,7 +760,7 @@ void ex_retab(exarg_T *eap) new_ts_str = xstrnsave(new_ts_str, (size_t)(eap->arg - new_ts_str)); } for (lnum = eap->line1; !got_int && lnum <= eap->line2; lnum++) { - ptr = (char *)ml_get(lnum); + ptr = ml_get(lnum); col = 0; vcol = 0; did_undo = false; @@ -941,7 +941,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) return FAIL; } for (extra = 0, l = line1; l <= line2; l++) { - str = (char *)vim_strsave(ml_get(l + extra)); + str = xstrdup(ml_get(l + extra)); ml_append(dest + l - line1, str, (colnr_T)0, false); xfree(str); if (dest < line1) { @@ -1088,7 +1088,7 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) while (line1 <= line2) { // need to use vim_strsave() because the line will be unlocked within // ml_append() - p = (char *)vim_strsave(ml_get(line1)); + p = xstrdup(ml_get(line1)); ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, false); xfree(p); @@ -1710,7 +1710,7 @@ void print_line(linenr_T lnum, int use_number, int list) int save_silent = silent_mode; // apply :filter /pat/ - if (message_filtered((char *)ml_get(lnum))) { + if (message_filtered(ml_get(lnum))) { return; } @@ -1897,7 +1897,7 @@ int do_write(exarg_T *eap) && !p_wa) { if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) { if (vim_dialog_yesno(VIM_QUESTION, NULL, - (char_u *)_("Write partial file?"), 2) != VIM_YES) { + _("Write partial file?"), 2) != VIM_YES) { goto theend; } eap->forceit = true; @@ -2007,7 +2007,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char *fname, char *ffname, int oth && vim_strchr(p_cpo, CPO_OVERNEW) == NULL) || (buf->b_flags & BF_READERR)))) && !p_wa - && os_path_exists((char_u *)ffname)) { + && os_path_exists(ffname)) { if (!eap->forceit && !eap->append) { #ifdef UNIX // It is possible to open a directory on Unix. @@ -2020,7 +2020,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char *fname, char *ffname, int oth char buff[DIALOG_MSG_SIZE]; dialog_msg((char *)buff, _("Overwrite existing file \"%s\"?"), fname); - if (vim_dialog_yesno(VIM_QUESTION, NULL, (char_u *)buff, 2) != VIM_YES) { + if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES) { return FAIL; } eap->forceit = true; @@ -2051,14 +2051,14 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char *fname, char *ffname, int oth } swapname = (char *)makeswapname((char_u *)fname, (char_u *)ffname, curbuf, (char_u *)dir); xfree(dir); - if (os_path_exists((char_u *)swapname)) { + if (os_path_exists(swapname)) { if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) { char buff[DIALOG_MSG_SIZE]; dialog_msg((char *)buff, _("Swap file \"%s\" exists, overwrite anyway?"), swapname); - if (vim_dialog_yesno(VIM_QUESTION, NULL, (char_u *)buff, 2) + if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES) { xfree(swapname); return FAIL; @@ -2171,7 +2171,7 @@ static int check_readonly(int *forceit, buf_T *buf) // Handle a file being readonly when the 'readonly' option is set or when // the file exists and permissions are read-only. if (!*forceit && (buf->b_p_ro - || (os_path_exists((char_u *)buf->b_ffname) + || (os_path_exists(buf->b_ffname) && !os_file_is_writable(buf->b_ffname)))) { if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && buf->b_fname != NULL) { char buff[DIALOG_MSG_SIZE]; @@ -2187,7 +2187,7 @@ static int check_readonly(int *forceit, buf_T *buf) buf->b_fname); } - if (vim_dialog_yesno(VIM_QUESTION, NULL, (char_u *)buff, 2) == VIM_YES) { + if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES) { // Set forceit, to force the writing of a readonly file *forceit = true; return false; @@ -2678,7 +2678,7 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum } buf = curbuf; if (buf->b_fname != NULL) { - new_name = (char *)vim_strsave((char_u *)buf->b_fname); + new_name = xstrdup(buf->b_fname); } else { new_name = NULL; } @@ -3803,7 +3803,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T break; } if (sub_firstline == NULL) { - sub_firstline = (char *)vim_strsave(ml_get(sub_firstlnum)); + sub_firstline = xstrdup(ml_get(sub_firstlnum)); } // Save the line number of the last change for the final @@ -3944,7 +3944,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T // really update the line, it would change // what matches. Temporarily replace the line // and change it back afterwards. - orig_line = (char *)vim_strsave(ml_get(lnum)); + orig_line = xstrdup(ml_get(lnum)); char *new_line = concat_str(new_start, sub_firstline + copycol); // Position the cursor relative to the end of the line, the @@ -4072,7 +4072,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T if (nmatch > 1) { \ sub_firstlnum += (linenr_T)nmatch - 1; \ xfree(sub_firstline); \ - sub_firstline = (char *)vim_strsave(ml_get(sub_firstlnum)); \ + sub_firstline = xstrdup(ml_get(sub_firstlnum)); \ /* When going beyond the last line, stop substituting. */ \ if (sub_firstlnum <= line2) { \ do_again = true; \ @@ -4148,7 +4148,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T if (nmatch == 1) { p1 = sub_firstline; } else { - p1 = (char *)ml_get(sub_firstlnum + (linenr_T)nmatch - 1); + p1 = ml_get(sub_firstlnum + (linenr_T)nmatch - 1); nmatch_tl += nmatch - 1; } size_t copy_len = (size_t)(regmatch.startpos[0].col - copycol); diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c index 11280eecbb..e551cbee0b 100644 --- a/src/nvim/ex_cmds2.c +++ b/src/nvim/ex_cmds2.c @@ -200,9 +200,9 @@ void dialog_changed(buf_T *buf, bool checkall) dialog_msg((char *)buff, _("Save changes to \"%s\"?"), buf->b_fname); if (checkall) { - ret = vim_dialog_yesnoallcancel(VIM_QUESTION, NULL, (char_u *)buff, 1); + ret = vim_dialog_yesnoallcancel(VIM_QUESTION, NULL, buff, 1); } else { - ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, (char_u *)buff, 1); + ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1); } if (ret == VIM_YES) { @@ -252,7 +252,7 @@ bool dialog_close_terminal(buf_T *buf) dialog_msg(buff, _("Close \"%s\"?"), (buf->b_fname != NULL) ? buf->b_fname : "?"); - int ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, (char_u *)buff, 1); + int ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1); return ret == VIM_YES; } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index bf518f3849..8f72ba0e23 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -535,7 +535,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) if (flags & DOCMD_KEEPLINE) { xfree(repeat_cmdline); if (count == 0) { - repeat_cmdline = (char *)vim_strsave((char_u *)next_cmdline); + repeat_cmdline = xstrdup(next_cmdline); } else { repeat_cmdline = NULL; } @@ -2826,7 +2826,7 @@ static void append_command(char *cmd) if (len > IOSIZE - 100) { // Not enough space, truncate and put in "...". d = (char *)IObuff + IOSIZE - 100; - d -= utf_head_off(IObuff, (const char_u *)d); + d -= utf_head_off((char *)IObuff, d); STRCPY(d, "..."); } STRCAT(IObuff, ": "); @@ -3081,10 +3081,9 @@ void f_fullcommand(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) return; } - rettv->vval.v_string = (char *)vim_strsave(IS_USER_CMDIDX(ea.cmdidx) - ? (char_u *)get_user_command_name(ea.useridx, - ea.cmdidx) - : (char_u *)cmdnames[ea.cmdidx].cmd_name); + rettv->vval.v_string = xstrdup(IS_USER_CMDIDX(ea.cmdidx) + ? get_user_command_name(ea.useridx, ea.cmdidx) + : cmdnames[ea.cmdidx].cmd_name); } cmdidx_T excmd_get_cmdidx(const char *cmd, size_t len) @@ -4344,7 +4343,7 @@ static int check_more(int message, bool forceit) vim_snprintf((char *)buff, DIALOG_MSG_SIZE, NGETTEXT("%d more file to edit. Quit anyway?", "%d more files to edit. Quit anyway?", (unsigned long)n), n); - if (vim_dialog_yesno(VIM_QUESTION, NULL, (char_u *)buff, 1) == VIM_YES) { + if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES) { return OK; } return FAIL; @@ -6007,7 +6006,7 @@ static void ex_redir(exarg_T *eap) // Make register empty when not using @A-@Z and the // command is valid. if (*arg == NUL && !isupper(redir_reg)) { - write_reg_contents(redir_reg, (char_u *)"", 0, false); + write_reg_contents(redir_reg, "", 0, false); } } } @@ -6162,7 +6161,7 @@ FILE *open_exfile(char_u *fname, int forceit, char *mode) return NULL; } #endif - if (!forceit && *mode != 'a' && os_path_exists(fname)) { + if (!forceit && *mode != 'a' && os_path_exists((char *)fname)) { semsg(_("E189: \"%s\" exists (add ! to override)"), fname); return NULL; } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 0998bdd867..e8af99805d 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -1704,8 +1704,8 @@ static int command_line_handle_key(CommandLineState *s) do { ccline.cmdpos--; // Move to first byte of possibly multibyte char. - ccline.cmdpos -= utf_head_off(ccline.cmdbuff, - ccline.cmdbuff + ccline.cmdpos); + ccline.cmdpos -= utf_head_off((char *)ccline.cmdbuff, + (char *)ccline.cmdbuff + ccline.cmdpos); ccline.cmdspos -= cmdline_charsize(ccline.cmdpos); } while (ccline.cmdpos > 0 && (s->c == K_S_LEFT || s->c == K_C_LEFT @@ -3208,7 +3208,7 @@ draw_cmdline_no_arabicshape: continue; } const int chunk_start = MAX(chunk.start, start); - msg_outtrans_len_attr(ccline.cmdbuff + chunk_start, + msg_outtrans_len_attr((char *)ccline.cmdbuff + chunk_start, chunk.end - chunk_start, chunk.attr); } @@ -3442,14 +3442,14 @@ void put_on_cmdline(char_u *str, int len, int redraw) i = 0; c = utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos); while (ccline.cmdpos > 0 && utf_iscomposing(c)) { - i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos - 1) + 1; + i = utf_head_off((char *)ccline.cmdbuff, (char *)ccline.cmdbuff + ccline.cmdpos - 1) + 1; ccline.cmdpos -= i; len += i; c = utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos); } if (i == 0 && ccline.cmdpos > 0 && arabic_maycombine(c)) { // Check the previous character for Arabic combining pair. - i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos - 1) + 1; + i = utf_head_off((char *)ccline.cmdbuff, (char *)ccline.cmdbuff + ccline.cmdpos - 1) + 1; if (arabic_combine(utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos - i), c)) { ccline.cmdpos -= i; len += i; @@ -3581,7 +3581,7 @@ static bool cmdline_paste(int regname, bool literally, bool remcr) // Locate start of last word in the cmd buffer. for (w = ccline.cmdbuff + ccline.cmdpos; w > ccline.cmdbuff;) { - len = utf_head_off(ccline.cmdbuff, w - 1) + 1; + len = utf_head_off((char *)ccline.cmdbuff, (char *)w - 1) + 1; if (!vim_iswordc(utf_ptr2char((char *)w - len))) { break; } diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index bbc6e53aa8..e87e0853f3 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -825,7 +825,7 @@ char_u *vim_findfile(void *search_ctx_arg) for (;;) { // if file exists and we didn't already find it if ((path_with_url((char *)file_path) - || (os_path_exists(file_path) + || (os_path_exists((char *)file_path) && (search_ctx->ffsc_find_what == FINDFILE_BOTH || ((search_ctx->ffsc_find_what == FINDFILE_DIR) == os_isdir((char *)file_path))))) @@ -1473,7 +1473,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first buf = (char *)suffixes; for (;;) { if ( - (os_path_exists((char_u *)NameBuff) + (os_path_exists(NameBuff) && (find_what == FINDFILE_BOTH || ((find_what == FINDFILE_DIR) == os_isdir(NameBuff))))) { diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index d67cd36a85..517424f4c1 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -143,7 +143,7 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr) msg_scroll = msg_scroll_save; msg_scrolled_ign = true; // may truncate the message to avoid a hit-return prompt - msg_outtrans_attr((char *)msg_may_trunc(false, IObuff), attr); + msg_outtrans_attr(msg_may_trunc(false, (char *)IObuff), attr); msg_clr_eos(); ui_flush(); msg_scrolled_ign = false; @@ -1011,7 +1011,7 @@ retry: tlen = 0; for (;;) { - p = ml_get(read_buf_lnum) + read_buf_col; + p = (char_u *)ml_get(read_buf_lnum) + read_buf_col; n = (int)STRLEN(p); if ((int)tlen + n + 1 > size) { // Filled up to "size", append partial line. @@ -1371,7 +1371,7 @@ retry: if (*--p < 0x80) { u8c = *p; } else { - len = utf_head_off((char_u *)ptr, p); + len = utf_head_off(ptr, (char *)p); p -= len; u8c = (unsigned)utf_ptr2char((char *)p); if (len == 0) { @@ -2970,13 +2970,13 @@ nobackup: * delete an existing one, try to use another name. * Change one character, just before the extension. */ - if (!p_bk && os_path_exists((char_u *)backup)) { + if (!p_bk && os_path_exists(backup)) { p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext); if (p < backup) { // empty file name ??? p = backup; } *p = 'z'; - while (*p > 'a' && os_path_exists((char_u *)backup)) { + while (*p > 'a' && os_path_exists(backup)) { (*p)--; } // They all exist??? Must be something wrong! @@ -3211,11 +3211,11 @@ restore_backup: // This may not work if the vim_rename() fails. // In that case we leave the copy around. // If file does not exist, put the copy in its place - if (!os_path_exists((char_u *)fname)) { + if (!os_path_exists(fname)) { vim_rename((char_u *)backup, (char_u *)fname); } // if original file does exist throw away the copy - if (os_path_exists((char_u *)fname)) { + if (os_path_exists(fname)) { os_remove(backup); } } else { @@ -3225,7 +3225,7 @@ restore_backup: } // if original file no longer exists give an extra warning - if (!newfile && !os_path_exists((char_u *)fname)) { + if (!newfile && !os_path_exists(fname)) { end = 0; } } @@ -3588,7 +3588,7 @@ restore_backup: */ if (org == NULL) { emsg(_("E205: Patchmode: can't save original file")); - } else if (!os_path_exists((char_u *)org)) { + } else if (!os_path_exists(org)) { vim_rename((char_u *)backup, (char_u *)org); XFREE_CLEAR(backup); // don't delete the file #ifdef UNIX @@ -4677,7 +4677,7 @@ int vim_rename(const char_u *from, const char_u *to) char *tail = path_tail((char *)tempname); snprintf(tail, (size_t)((MAXPATHL + 1) - (tail - (char *)tempname - 1)), "%d", n); - if (!os_path_exists(tempname)) { + if (!os_path_exists((char *)tempname)) { if (os_rename(from, tempname) == OK) { if (os_rename(tempname, to) == OK) { return 0; @@ -5028,7 +5028,7 @@ int buf_check_timestamp(buf_T *buf) } } } else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W) - && os_path_exists((char_u *)buf->b_ffname)) { + && os_path_exists(buf->b_ffname)) { retval = 1; mesg = _("W13: Warning: File \"%s\" has been created after editing started"); buf->b_flags |= BF_NEW_W; @@ -5051,8 +5051,8 @@ int buf_check_timestamp(buf_T *buf) xstrlcat(tbuf, "\n", tbuf_len - 1); xstrlcat(tbuf, mesg2, tbuf_len - 1); } - switch (do_dialog(VIM_WARNING, (char_u *)_("Warning"), (char_u *)tbuf, - (char_u *)_("&OK\n&Load File\nLoad File &and Options"), + switch (do_dialog(VIM_WARNING, _("Warning"), tbuf, + _("&OK\n&Load File\nLoad File &and Options"), 1, NULL, true)) { case 2: reload = RELOAD_NORMAL; diff --git a/src/nvim/fold.c b/src/nvim/fold.c index b4ddb3ec08..d8c864df5b 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -995,7 +995,7 @@ void foldAdjustVisual(void) start->col = 0; } if (hasFolding(end->lnum, NULL, &end->lnum)) { - ptr = ml_get(end->lnum); + ptr = (char_u *)ml_get(end->lnum); end->col = (colnr_T)STRLEN(ptr); if (end->col > 0 && *p_sel == 'o') { end->col--; @@ -1588,7 +1588,7 @@ static void foldAddMarker(buf_T *buf, pos_T pos, const char_u *marker, size_t ma if (u_save(lnum - 1, lnum + 1) == OK) { // Check if the line ends with an unclosed comment - skip_comment(line, false, false, &line_is_comment); + skip_comment((char *)line, false, false, &line_is_comment); newline = xmalloc(line_len + markerlen + STRLEN(cms) + 1); STRCPY(newline, line); // Append the marker to the end of the line @@ -1601,7 +1601,7 @@ static void foldAddMarker(buf_T *buf, pos_T pos, const char_u *marker, size_t ma STRCPY(newline + line_len + (p - cms) + markerlen, p + 2); added = markerlen + STRLEN(cms) - 2; } - ml_replace_buf(buf, lnum, newline, false); + ml_replace_buf(buf, lnum, (char *)newline, false); if (added) { extmark_splice_cols(buf, (int)lnum - 1, (int)line_len, 0, (int)added, kExtmarkUndo); @@ -1666,7 +1666,7 @@ static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t mark assert(p >= line); memcpy(newline, line, (size_t)(p - line)); STRCPY(newline + (p - line), p + len); - ml_replace_buf(buf, lnum, newline, false); + ml_replace_buf(buf, lnum, (char *)newline, false); extmark_splice_cols(buf, (int)lnum - 1, (int)(p - line), (int)len, 0, kExtmarkUndo); } @@ -3251,12 +3251,12 @@ void f_foldtext(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } // Find interesting text in this line. - char_u *s = (char_u *)skipwhite((char *)ml_get(lnum)); + char_u *s = (char_u *)skipwhite(ml_get(lnum)); // skip C comment-start if (s[0] == '/' && (s[1] == '*' || s[1] == '/')) { s = (char_u *)skipwhite((char *)s + 2); if (*skipwhite((char *)s) == NUL && lnum + 1 < foldend) { - s = (char_u *)skipwhite((char *)ml_get(lnum + 1)); + s = (char_u *)skipwhite(ml_get(lnum + 1)); if (*s == '*') { s = (char_u *)skipwhite((char *)s + 1); } diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index 0a9457ef35..4d7339f3b5 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -2569,7 +2569,7 @@ static int vgetorpeek(bool advance) ptr = get_cursor_line_ptr(); chartabsize_T cts; init_chartabsize_arg(&cts, curwin, - curwin->w_cursor.lnum, 0, ptr, ptr); + curwin->w_cursor.lnum, 0, (char *)ptr, (char *)ptr); while ((char_u *)cts.cts_ptr < ptr + curwin->w_cursor.col) { if (!ascii_iswhite(*cts.cts_ptr)) { curwin->w_wcol = cts.cts_vcol; @@ -2597,7 +2597,7 @@ static int vgetorpeek(bool advance) // Correct when the cursor is on the right halve // of a double-wide character. ptr = get_cursor_line_ptr(); - col -= utf_head_off(ptr, ptr + col); + col -= utf_head_off((char *)ptr, (char *)ptr + col); if (utf_ptr2cells((char *)ptr + col) > 1) { curwin->w_wcol--; } diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c index 602fa8b71d..d7f5730943 100644 --- a/src/nvim/hardcopy.c +++ b/src/nvim/hardcopy.c @@ -879,7 +879,7 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T } mch_print_start_line(false, page_line); - line = ml_get(ppos->file_line); + line = (char_u *)ml_get(ppos->file_line); /* * Loop over the columns until the end of the file line or right margin. @@ -897,7 +897,7 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T id = 0; } // Get the line again, a multi-line regexp may invalidate it. - line = ml_get(ppos->file_line); + line = (char_u *)ml_get(ppos->file_line); if (id != current_syn_id) { current_syn_id = id; diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index 9413abb2e1..e54bffb587 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -446,7 +446,7 @@ staterr: if (arg2 != NULL) { ppath = xmalloc(MAXPATHL + 1); expand_env(arg2, ppath, MAXPATHL); - if (!os_path_exists((char_u *)ppath)) { + if (!os_path_exists(ppath)) { goto staterr; } } @@ -1651,7 +1651,7 @@ static void cs_print_tags_priv(char **matches, char **cntxts, } (void)snprintf(buf, bufsize, csfmt_str, i + 1, lno); msg_puts_attr(buf, HL_ATTR(HLF_CM)); - msg_outtrans_long_attr((char_u *)cs_pathcomponents(fname), HL_ATTR(HLF_CM)); + msg_outtrans_long_attr(cs_pathcomponents(fname), HL_ATTR(HLF_CM)); // compute the required space for the context char *context = cntxts[i] ? cntxts[i] : globalcntx; @@ -1673,11 +1673,11 @@ static void cs_print_tags_priv(char **matches, char **cntxts, msg_putchar('\n'); } msg_advance(12); - msg_outtrans_long_attr((char_u *)buf, 0); + msg_outtrans_long_attr(buf, 0); msg_putchar('\n'); if (extra != NULL) { msg_advance(13); - msg_outtrans_long_attr((char_u *)extra, 0); + msg_outtrans_long_attr(extra, 0); } // restore matches[i] diff --git a/src/nvim/indent.c b/src/nvim/indent.c index 792f4d93c4..da4bcf6934 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -352,7 +352,7 @@ int get_indent(void) // Count the size (in window cells) of the indent in line "lnum". int get_indent_lnum(linenr_T lnum) { - return get_indent_str_vtab((char *)ml_get(lnum), + return get_indent_str_vtab(ml_get(lnum), curbuf->b_p_ts, curbuf->b_p_vts_array, false); @@ -710,7 +710,7 @@ int get_number_indent(linenr_T lnum) // In format_lines() (i.e. not insert mode), fo+=q is needed too... if ((State & MODE_INSERT) || has_format_option(FO_Q_COMS)) { - lead_len = get_leader_len((char *)ml_get(lnum), NULL, false, true); + lead_len = get_leader_len(ml_get(lnum), NULL, false, true); } regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC); @@ -719,9 +719,9 @@ int get_number_indent(linenr_T lnum) // vim_regexec() expects a pointer to a line. This lets us // start matching for the flp beyond any comment leader... - if (vim_regexec(®match, (char *)ml_get(lnum) + lead_len, (colnr_T)0)) { + if (vim_regexec(®match, ml_get(lnum) + lead_len, (colnr_T)0)) { pos.lnum = lnum; - pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum)); + pos.col = (colnr_T)(*regmatch.endp - (char_u *)ml_get(lnum)); pos.coladd = 0; } vim_regfree(regmatch.regprog); @@ -1036,7 +1036,7 @@ int get_lisp_indent(void) } else { char_u *line = that; chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, pos->lnum, 0, line, line); + init_chartabsize_arg(&cts, curwin, pos->lnum, 0, (char *)line, (char *)line); while (*cts.cts_ptr != NUL && col > 0) { cts.cts_vcol += lbr_chartabsize_adv(&cts); col--; @@ -1060,7 +1060,7 @@ int get_lisp_indent(void) firsttry = amount; init_chartabsize_arg(&cts, curwin, (colnr_T)(that - line), - amount, line, that); + amount, (char *)line, (char *)that); while (ascii_iswhite(*cts.cts_ptr)) { cts.cts_vcol += lbr_chartabsize(&cts); cts.cts_ptr++; @@ -1081,7 +1081,7 @@ int get_lisp_indent(void) quotecount = 0; init_chartabsize_arg(&cts, curwin, - (colnr_T)(that - line), amount, line, that); + (colnr_T)(that - line), amount, (char *)line, (char *)that); if (vi_lisp || ((*that != '"') && (*that != '\'') && (*that != '#') && ((*that < '0') || (*that > '9')))) { while (*cts.cts_ptr diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c index 166695ef5b..ccee4dd48a 100644 --- a/src/nvim/indent_c.c +++ b/src/nvim/indent_c.c @@ -52,7 +52,7 @@ pos_T *find_start_comment(int ind_maxcomment) // XXX * Check if the comment start we found is inside a string. * If it is then restrict the search to below this line and try again. */ - if (!is_pos_in_string(ml_get(pos->lnum), pos->col)) { + if (!is_pos_in_string((char_u *)ml_get(pos->lnum), pos->col)) { break; } cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1; @@ -115,7 +115,7 @@ static pos_T *find_start_rawstring(int ind_maxcomment) // XXX // Check if the raw string start we found is inside a string. // If it is then restrict the search to below this line and try again. - if (!is_pos_in_string(ml_get(pos->lnum), pos->col)) { + if (!is_pos_in_string((char_u *)ml_get(pos->lnum), pos->col)) { break; } cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1; @@ -291,7 +291,7 @@ static pos_T *find_line_comment(void) // XXX pos = curwin->w_cursor; while (--pos.lnum > 0) { - line = ml_get(pos.lnum); + line = (char_u *)ml_get(pos.lnum); p = (char_u *)skipwhite((char *)line); if (cin_islinecomment(p)) { pos.col = (int)(p - line); @@ -616,7 +616,7 @@ static int get_indent_nolabel(linenr_T lnum) // XXX colnr_T col; const char_u *p; - l = ml_get(lnum); + l = (char_u *)ml_get(lnum); p = after_label(l); if (p == NULL) { return 0; @@ -724,13 +724,14 @@ static int cin_get_equal_amount(linenr_T lnum) pos_T fp; if (lnum > 1) { - line = ml_get(lnum - 1); + line = (char_u *)ml_get(lnum - 1); if (*line != NUL && line[STRLEN(line) - 1] == '\\') { return -1; } } - line = s = ml_get(lnum); + s = (char_u *)ml_get(lnum); + line = s; while (*s != NUL && vim_strchr("=;{}\"'", *s) == NULL) { if (cin_iscomment(s)) { // ignore comments s = cin_skipcomment(s); @@ -792,14 +793,14 @@ static int cin_ispreproc_cont(const char_u **pp, linenr_T *lnump, int *amount) if (lnum == 1) { break; } - line = ml_get(--lnum); + line = (char_u *)ml_get(--lnum); if (*line == NUL || line[STRLEN(line) - 1] != '\\') { break; } } if (lnum != *lnump) { - *pp = ml_get(*lnump); + *pp = (char_u *)ml_get(*lnump); } if (retval) { *amount = candidate_amount; @@ -895,7 +896,7 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l int just_started = true; if (sp == NULL) { - s = ml_get(lnum); + s = (char_u *)ml_get(lnum); } else { s = *sp; } @@ -908,7 +909,7 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l curwin->w_cursor.lnum = save_lnum; return false; } - s = ml_get(lnum); + s = (char_u *)ml_get(lnum); } curwin->w_cursor.lnum = save_lnum; @@ -947,7 +948,7 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l // #if defined(x) && {backslash} // defined(y) lnum = first_lnum - 1; - s = ml_get(lnum); + s = (char_u *)ml_get(lnum); if (*s == NUL || s[STRLEN(s) - 1] != '\\') { retval = true; } @@ -964,7 +965,7 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l if (lnum >= curbuf->b_ml.ml_line_count) { break; } - s = ml_get(++lnum); + s = (char_u *)ml_get(++lnum); if (!cin_ispreproc(s)) { break; } @@ -989,7 +990,7 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l done: if (lnum != first_lnum && sp != NULL) { - *sp = ml_get(first_lnum); + *sp = (char_u *)ml_get(first_lnum); } return retval; @@ -1121,7 +1122,7 @@ static int cin_iswhileofdo_end(int terminated) curwin->w_cursor.col = i; trypos = find_match_paren(curbuf->b_ind_maxparen); if (trypos != NULL) { - s = cin_skipcomment(ml_get(trypos->lnum)); + s = cin_skipcomment((char_u *)ml_get(trypos->lnum)); if (*s == '}') { // accept "} while (cond);" s = cin_skipcomment(s + 1); } @@ -1200,7 +1201,7 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) * {} */ while (lnum > 1) { - line = ml_get(lnum - 1); + line = (char_u *)ml_get(lnum - 1); s = (char_u *)skipwhite((char *)line); if (*s == '#' || *s == NUL) { break; @@ -1222,7 +1223,7 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) } pos->lnum = lnum; - line = ml_get(lnum); + line = (char_u *)ml_get(lnum); s = line; for (;;) { if (*s == NUL) { @@ -1230,7 +1231,7 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) break; } // Continue in the cursor line. - line = ml_get(++lnum); + line = (char_u *)ml_get(++lnum); s = line; } if (s == line) { @@ -1420,7 +1421,8 @@ static int cin_skip2pos(pos_T *trypos) const char_u *p; const char_u *new_p; - p = line = ml_get(trypos->lnum); + line = (char_u *)ml_get(trypos->lnum); + p = line; while (*p && (colnr_T)(p - line) < trypos->col) { if (cin_iscomment(p)) { p = cin_skipcomment(p); @@ -1952,7 +1954,7 @@ int get_c_indent(void) /* Get a copy of the current contents of the line. * This is required, because only the most recent line obtained with * ml_get is valid! */ - linecopy = vim_strsave(ml_get(cur_curpos.lnum)); + linecopy = vim_strsave((char_u *)ml_get(cur_curpos.lnum)); /* * In insert mode and the cursor is on a ')' truncate the line at the @@ -2019,7 +2021,7 @@ int get_c_indent(void) if (trypos == NULL && curwin->w_cursor.lnum > 1) { // There may be a statement before the comment, search from the end // of the line for a comment start. - linecomment_pos.col = check_linecomment((char *)ml_get(curwin->w_cursor.lnum - 1)); + linecomment_pos.col = check_linecomment(ml_get(curwin->w_cursor.lnum - 1)); if (linecomment_pos.col != MAXCOL) { trypos = &linecomment_pos; trypos->lnum = curwin->w_cursor.lnum - 1; @@ -2094,7 +2096,7 @@ int get_c_indent(void) * line, use the indent of that line plus offset. If * the middle comment string matches in the previous * line, use the indent of that line. XXX */ - look = (char_u *)skipwhite((char *)ml_get(curwin->w_cursor.lnum - 1)); + look = (char_u *)skipwhite(ml_get(curwin->w_cursor.lnum - 1)); if (STRNCMP(look, lead_start, lead_start_len) == 0) { amount = get_indent_lnum(curwin->w_cursor.lnum - 1); } else if (STRNCMP(look, lead_middle, lead_middle_len) == 0) { @@ -2156,7 +2158,7 @@ int get_c_indent(void) } if (amount == -1) { // use the comment opener if (!curbuf->b_ind_in_comment2) { - start = ml_get(comment_pos->lnum); + start = (char_u *)ml_get(comment_pos->lnum); look = start + comment_pos->col + 2; // skip / and * if (*look != NUL) { // if something after it comment_pos->col = (colnr_T)((char_u *)skipwhite((char *)look) - start); @@ -2208,7 +2210,7 @@ int get_c_indent(void) } else { amount = -1; for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; lnum--) { - l = (char_u *)skipwhite((char *)ml_get(lnum)); + l = (char_u *)skipwhite(ml_get(lnum)); if (cin_nocode(l)) { // skip comment lines continue; } @@ -2269,7 +2271,7 @@ int get_c_indent(void) curwin->w_cursor = cursor_save; - line = ml_get(outermost.lnum); + line = (char_u *)ml_get(outermost.lnum); is_if_for_while = cin_is_if_for_while_before_offset(line, &outermost.col); @@ -2297,7 +2299,7 @@ int get_c_indent(void) } curwin->w_cursor.lnum = save_lnum; - look = ml_get(our_paren_pos.lnum) + look_col; + look = (char_u *)ml_get(our_paren_pos.lnum) + look_col; } if (theline[0] == ')' || (curbuf->b_ind_unclosed == 0 && is_if_for_while == 0) @@ -2314,7 +2316,7 @@ int get_c_indent(void) */ if (theline[0] != ')') { cur_amount = MAXCOL; - l = ml_get(our_paren_pos.lnum); + l = (char_u *)ml_get(our_paren_pos.lnum); if (curbuf->b_ind_unclosed_wrapped && cin_ends_in(l, (char_u *)"(", NULL)) { /* look for opening unmatched paren, indent one level @@ -2435,7 +2437,7 @@ int get_c_indent(void) tryposBrace = &tryposCopy; trypos = tryposBrace; ourscope = trypos->lnum; - start = ml_get(ourscope); + start = (char_u *)ml_get(ourscope); /* * Now figure out how indented the line is in general. @@ -3054,7 +3056,7 @@ int get_c_indent(void) */ if (terminated == ',') { while (curwin->w_cursor.lnum > 1) { - l = ml_get(curwin->w_cursor.lnum - 1); + l = (char_u *)ml_get(curwin->w_cursor.lnum - 1); if (*l == NUL || l[STRLEN(l) - 1] != '\\') { break; } @@ -3607,7 +3609,7 @@ term_again: * here; */ while (n == 0 && curwin->w_cursor.lnum > 1) { - l = ml_get(curwin->w_cursor.lnum - 1); + l = (char_u *)ml_get(curwin->w_cursor.lnum - 1); if (*l == NUL || l[STRLEN(l) - 1] != '\\') { break; } @@ -3670,7 +3672,7 @@ term_again: pos_T curpos_save = curwin->w_cursor; while (curwin->w_cursor.lnum > 1) { - look = ml_get(--curwin->w_cursor.lnum); + look = (char_u *)ml_get(--curwin->w_cursor.lnum); if (!(cin_nocode(look) || cin_ispreproc_cont(&look, &curwin->w_cursor.lnum, &amount))) { break; @@ -3702,7 +3704,7 @@ term_again: * indent_to_0 here; */ if (cin_ends_in(l, (char_u *)";", NULL)) { - l = ml_get(curwin->w_cursor.lnum - 1); + l = (char_u *)ml_get(curwin->w_cursor.lnum - 1); if (cin_ends_in(l, (char_u *)",", NULL) || (*l != NUL && l[STRLEN(l) - 1] == '\\')) { break; @@ -3737,7 +3739,7 @@ term_again: // char *foo = "asdf{backslash} // here"; if (cur_curpos.lnum > 1) { - l = ml_get(cur_curpos.lnum - 1); + l = (char_u *)ml_get(cur_curpos.lnum - 1); if (*l != NUL && l[STRLEN(l) - 1] == '\\') { cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1); if (cur_amount > 0) { diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index ba0a36cafe..a530061280 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2177,7 +2177,7 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) p = compl_orig_text; for (len = 0; p[len] != NUL && p[len] == ptr[len]; len++) {} if (len > 0) { - len -= utf_head_off(p, p + len); + len -= utf_head_off((char *)p, (char *)p + len); } for (p += len; *p != NUL; MB_PTR_ADV(p)) { AppendCharToRedobuff(K_BS); @@ -3726,16 +3726,16 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) } else if (--startcol < 0 || !vim_iswordp(mb_prevptr(line, line + startcol + 1))) { // Match any word of at least two chars - compl_pattern = (char *)vim_strsave((char_u *)"\\<\\k\\k"); + compl_pattern = xstrdup("\\<\\k\\k"); compl_col += curs_col; compl_length = 0; } else { // Search the point of change class of multibyte character // or not a word single byte character backward. - startcol -= utf_head_off(line, line + startcol); + startcol -= utf_head_off((char *)line, (char *)line + startcol); int base_class = mb_get_class(line + startcol); while (--startcol >= 0) { - int head_off = utf_head_off(line, line + startcol); + int head_off = utf_head_off((char *)line, (char *)line + startcol); if (base_class != mb_get_class(line + startcol - head_off)) { break; } @@ -3893,7 +3893,7 @@ static int get_userdefined_compl_info(colnr_T curs_col) // Setup variables for completion. Need to obtain "line" again, // it may have become invalid. - char_u *line = ml_get(curwin->w_cursor.lnum); + char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum); compl_length = curs_col - compl_col; compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length); @@ -3919,7 +3919,7 @@ static int get_spell_compl_info(int startcol, colnr_T curs_col) compl_length = (int)curs_col - compl_col; } // Need to obtain "line" again, it may have become invalid. - char_u *line = ml_get(curwin->w_cursor.lnum); + char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum); compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length); return OK; @@ -4036,7 +4036,7 @@ static int ins_compl_start(void) return FAIL; } - char_u *line = ml_get(curwin->w_cursor.lnum); + char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum); colnr_T curs_col = curwin->w_cursor.col; compl_pending = 0; @@ -4074,7 +4074,7 @@ static int ins_compl_start(void) } // If "line" was changed while getting completion info get it again. if (line_invalid) { - line = ml_get(curwin->w_cursor.lnum); + line = (char_u *)ml_get(curwin->w_cursor.lnum); } if (compl_status_adding()) { diff --git a/src/nvim/macros.h b/src/nvim/macros.h index 5601db274b..b84539852f 100644 --- a/src/nvim/macros.h +++ b/src/nvim/macros.h @@ -104,7 +104,7 @@ // MB_PTR_BACK(): backup a pointer to the previous character, taking care of // multi-byte characters if needed. Only use with "p" > "s" ! #define MB_PTR_BACK(s, p) \ - (p -= utf_head_off((char_u *)(s), (char_u *)(p) - 1) + 1) + (p -= utf_head_off((char *)(s), (char *)(p) - 1) + 1) // MB_CHAR2BYTES(): convert character to bytes and advance pointer to bytes #define MB_CHAR2BYTES(c, b) ((b) += utf_char2bytes((c), ((char *)b))) diff --git a/src/nvim/main.c b/src/nvim/main.c index 883f946cad..1c7cfea768 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1914,9 +1914,9 @@ static bool do_user_initialization(void) char_u *user_vimrc = (char_u *)stdpaths_user_conf_subpath("init.vim"); // init.lua - if (os_path_exists(init_lua_path) + if (os_path_exists((char *)init_lua_path) && do_source((char *)init_lua_path, true, DOSO_VIMRC)) { - if (os_path_exists(user_vimrc)) { + if (os_path_exists((char *)user_vimrc)) { semsg(_("E5422: Conflicting configs: \"%s\" \"%s\""), init_lua_path, user_vimrc); } diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 333fb847f6..d740a0eb77 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -174,7 +174,7 @@ static void showmap(mapblock_T *mp, bool local) } // Display the LHS. Get length of what we write. - len = (size_t)msg_outtrans_special(mp->m_keys, true, 0); + len = (size_t)msg_outtrans_special((char *)mp->m_keys, true, 0); do { msg_putchar(' '); // padd with blanks len++; @@ -203,7 +203,7 @@ static void showmap(mapblock_T *mp, bool local) } else if (mp->m_str[0] == NUL) { msg_puts_attr("", HL_ATTR(HLF_8)); } else { - msg_outtrans_special((char_u *)mp->m_str, false, 0); + msg_outtrans_special(mp->m_str, false, 0); } if (mp->m_desc != NULL) { diff --git a/src/nvim/mark.c b/src/nvim/mark.c index 9df4d416ff..816599271d 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -819,7 +819,7 @@ static char_u *mark_line(pos_T *mp, int lead_len) } assert(Columns >= 0); // Allow for up to 5 bytes per character. - s = vim_strnsave((char_u *)skipwhite((char *)ml_get(mp->lnum)), (size_t)Columns * 5); + s = vim_strnsave((char_u *)skipwhite(ml_get(mp->lnum)), (size_t)Columns * 5); // Truncate the line to fit it in the window len = 0; @@ -1758,7 +1758,7 @@ void mark_mb_adjustpos(buf_T *buf, pos_T *lp) if (*p == NUL || (int)STRLEN(p) < lp->col) { lp->col = 0; } else { - lp->col -= utf_head_off(p, p + lp->col); + lp->col -= utf_head_off((char *)p, (char *)p + lp->col); } // Reset "coladd" when the cursor would be on the right half of a // double-wide character. diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index b874f0dc94..f592b54f67 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -1618,21 +1618,24 @@ void show_utf8(void) /// "base" must be the start of the string, which must be NUL terminated. /// If "p" points to the NUL at the end of the string return 0. /// Returns 0 when already at the first byte of a character. -int utf_head_off(const char_u *base, const char_u *p) +int utf_head_off(const char *base_in, const char *p_in) { int c; int len; - if (*p < 0x80) { // be quick for ASCII + if ((uint8_t)(*p_in) < 0x80) { // be quick for ASCII return 0; } + const uint8_t *base = (uint8_t *)base_in; + const uint8_t *p = (uint8_t *)p_in; + // Skip backwards over trailing bytes: 10xx.xxxx // Skip backwards again if on a composing char. - const char_u *q; + const uint8_t *q; for (q = p;; q--) { // Move s to the last byte of this char. - const char_u *s; + const uint8_t *s; for (s = q; (s[1] & 0xc0) == 0x80; s++) {} // Move q to the first byte of this char. @@ -1657,7 +1660,7 @@ int utf_head_off(const char_u *base, const char_u *p) if (arabic_maycombine(c)) { // Advance to get a sneak-peak at the next char - const char_u *j = q; + const uint8_t *j = q; j--; // Move j to the first byte of this char. while (j > base && (*j & 0xc0) == 0x80) { @@ -2042,7 +2045,7 @@ void mb_check_adjust_col(void *win_) win->w_cursor.col = len - 1; } // Move the cursor to the head byte. - win->w_cursor.col -= utf_head_off((char_u *)p, (char_u *)p + win->w_cursor.col); + win->w_cursor.col -= utf_head_off(p, p + win->w_cursor.col); } // Reset `coladd` when the cursor would be on the right half of a diff --git a/src/nvim/memline.c b/src/nvim/memline.c index b0b6b675cb..a30a98d6e9 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -1177,7 +1177,7 @@ void ml_recover(bool checkext) } else { for (idx = 1; idx <= lnum; idx++) { // Need to copy one line, fetching the other one may flush it. - p = vim_strsave(ml_get(idx)); + p = vim_strsave((char_u *)ml_get(idx)); i = STRCMP(p, ml_get(idx + lnum)); xfree(p); if (i != 0) { @@ -1276,7 +1276,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) #ifdef HAVE_READLINK // Expand symlink in the file name, because the swap file is created // with the actual file instead of with the symlink. - if (resolve_symlink(fname, fname_buf) == OK) { + if (resolve_symlink((char *)fname, (char *)fname_buf) == OK) { fname_res = fname_buf; } else #endif @@ -1351,7 +1351,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) if (*dirp == NUL && file_count + num_files == 0 && fname != NULL) { char_u *swapname = (char_u *)modname((char *)fname_res, ".swp", true); if (swapname != NULL) { - if (os_path_exists(swapname)) { + if (os_path_exists((char *)swapname)) { files = xmalloc(sizeof(char_u *)); files[0] = (char *)swapname; swapname = NULL; @@ -1399,7 +1399,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) } } else { msg_puts(_(" In directory ")); - msg_home_replace(dir_name); + msg_home_replace((char *)dir_name); msg_puts(":\n"); } @@ -1592,7 +1592,7 @@ static bool swapfile_unchanged(char *fname) int ret = true; // Swap file must exist. - if (!os_path_exists((char_u *)fname)) { + if (!os_path_exists(fname)) { return false; } @@ -1793,9 +1793,9 @@ theend: /// /// On failure an error message is given and IObuff is returned (to avoid /// having to check for error everywhere). -char_u *ml_get(linenr_T lnum) +char *ml_get(linenr_T lnum) { - return ml_get_buf(curbuf, lnum, false); + return (char *)ml_get_buf(curbuf, lnum, false); } /// @return pointer to position "pos". @@ -2414,9 +2414,9 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b return OK; } -void ml_add_deleted_len(char_u *ptr, ssize_t len) +void ml_add_deleted_len(char *ptr, ssize_t len) { - ml_add_deleted_len_buf(curbuf, ptr, len); + ml_add_deleted_len_buf(curbuf, (char_u *)ptr, len); } void ml_add_deleted_len_buf(buf_T *buf, char_u *ptr, ssize_t len) @@ -2439,7 +2439,7 @@ void ml_add_deleted_len_buf(buf_T *buf, char_u *ptr, ssize_t len) int ml_replace(linenr_T lnum, char *line, bool copy) { - return ml_replace_buf(curbuf, lnum, (char_u *)line, copy); + return ml_replace_buf(curbuf, lnum, line, copy); } /// Replace line "lnum", with buffering, in current buffer. @@ -2454,7 +2454,7 @@ int ml_replace(linenr_T lnum, char *line, bool copy) /// changed_lines(), unless update_screen(UPD_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) +int ml_replace_buf(buf_T *buf, linenr_T lnum, char *line, bool copy) { if (line == NULL) { // just checking... return FAIL; @@ -2468,7 +2468,7 @@ int ml_replace_buf(buf_T *buf, linenr_T lnum, char_u *line, bool copy) bool readlen = true; if (copy) { - line = vim_strsave(line); + line = xstrdup(line); } if (buf->b_ml.ml_line_lnum != lnum) { // other line buffered ml_flush_line(buf); // flush it @@ -2483,7 +2483,7 @@ int ml_replace_buf(buf_T *buf, linenr_T lnum, char_u *line, bool copy) ml_add_deleted_len_buf(buf, ml_get_buf(buf, lnum, false), -1); } - buf->b_ml.ml_line_ptr = line; + buf->b_ml.ml_line_ptr = (char_u *)line; buf->b_ml.ml_line_lnum = lnum; buf->b_ml.ml_flags = (buf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY; @@ -3142,9 +3142,9 @@ static void ml_lineadd(buf_T *buf, int count) /// /// @return OK if it worked and the resolved link in "buf[MAXPATHL]", /// FAIL otherwise -int resolve_symlink(const char_u *fname, char_u *buf) +int resolve_symlink(const char *fname, char *buf) { - char_u tmp[MAXPATHL]; + char tmp[MAXPATHL]; int ret; int depth = 0; @@ -3162,7 +3162,7 @@ int resolve_symlink(const char_u *fname, char_u *buf) return FAIL; } - ret = (int)readlink((char *)tmp, (char *)buf, MAXPATHL - 1); + ret = (int)readlink(tmp, buf, MAXPATHL - 1); if (ret <= 0) { if (errno == EINVAL || errno == ENOENT) { // Found non-symlink or not existing file, stop here. @@ -3185,10 +3185,10 @@ int resolve_symlink(const char_u *fname, char_u *buf) // If it's relative, build a new path based on the directory // portion of the filename (if any) and the path the symlink // points to. - if (path_is_absolute(buf)) { + if (path_is_absolute((char_u *)buf)) { STRCPY(tmp, buf); } else { - char_u *tail = (char_u *)path_tail((char *)tmp); + char_u *tail = (char_u *)path_tail(tmp); if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL) { return FAIL; } @@ -3201,7 +3201,7 @@ int resolve_symlink(const char_u *fname, char_u *buf) * be consistent even when opening a relative symlink from different * working directories. */ - return vim_FullName((char *)tmp, (char *)buf, MAXPATHL, true); + return vim_FullName(tmp, buf, MAXPATHL, true); } #endif @@ -3217,7 +3217,7 @@ char_u *makeswapname(char_u *fname, char_u *ffname, buf_T *buf, char_u *dir_name // 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) { + if (resolve_symlink((char *)fname, (char *)fname_buf) == OK) { fname_res = fname_buf; } #endif @@ -3300,7 +3300,7 @@ static void attention_message(buf_T *buf, char_u *fname) no_wait_return++; (void)emsg(_("E325: ATTENTION")); msg_puts(_("\nFound a swap file by the name \"")); - msg_home_replace(fname); + msg_home_replace((char *)fname); msg_puts("\"\n"); const time_t swap_mtime = swapfile_info(fname); msg_puts(_("While opening file \"")); @@ -3499,7 +3499,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ // It's safe to delete the swap file if all these are true: // - the edited file exists // - the swap file has no changes and looks OK - if (os_path_exists((char_u *)buf->b_fname) && swapfile_unchanged(fname)) { + if (os_path_exists(buf->b_fname) && swapfile_unchanged(fname)) { choice = 4; if (p_verbose > 0) { verb_msg(_("Found a swap file that is not useful, deleting it")); @@ -3541,13 +3541,13 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ memcpy(name, sw_msg_1, sw_msg_1_len + 1); home_replace(NULL, fname, &name[sw_msg_1_len], fname_len, true); xstrlcat(name, sw_msg_2, name_len); - choice = do_dialog(VIM_WARNING, (char_u *)_("VIM - ATTENTION"), - (char_u *)name, + choice = do_dialog(VIM_WARNING, _("VIM - ATTENTION"), + name, process_still_running - ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover" - "\n&Quit\n&Abort") : - (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover" - "\n&Delete it\n&Quit\n&Abort"), + ? _("&Open Read-Only\n&Edit anyway\n&Recover" + "\n&Quit\n&Abort") : + _("&Open Read-Only\n&Edit anyway\n&Recover" + "\n&Delete it\n&Quit\n&Abort"), 1, NULL, false); if (process_still_running && choice >= 4) { @@ -3582,7 +3582,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ } // If the file was deleted this fname can be used. - if (!os_path_exists((char_u *)fname)) { + if (!os_path_exists(fname)) { break; } } else { @@ -4212,8 +4212,8 @@ int dec(pos_T *lp) lp->coladd = 0; if (lp->col == MAXCOL) { // past end of line - char_u *p = ml_get(lp->lnum); - lp->col = (colnr_T)STRLEN(p); + char *p = ml_get(lp->lnum); + lp->col = (colnr_T)strlen(p); lp->col -= utf_head_off(p, p + lp->col); return 0; } @@ -4221,15 +4221,15 @@ int dec(pos_T *lp) if (lp->col > 0) { // still within line lp->col--; - char_u *p = ml_get(lp->lnum); + char *p = ml_get(lp->lnum); lp->col -= utf_head_off(p, p + lp->col); return 0; } if (lp->lnum > 1) { // there is a prior line lp->lnum--; - char_u *p = ml_get(lp->lnum); - lp->col = (colnr_T)STRLEN(p); + char *p = ml_get(lp->lnum); + lp->col = (colnr_T)strlen(p); lp->col -= utf_head_off(p, p + lp->col); return 1; } diff --git a/src/nvim/menu.c b/src/nvim/menu.c index cb6918cd27..84a1defbe0 100644 --- a/src/nvim/menu.c +++ b/src/nvim/menu.c @@ -888,7 +888,7 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth) if (*menu->strings[bit] == NUL) { msg_puts_attr("", HL_ATTR(HLF_8)); } else { - msg_outtrans_special((char_u *)menu->strings[bit], false, 0); + msg_outtrans_special(menu->strings[bit], false, 0); } } } diff --git a/src/nvim/message.c b/src/nvim/message.c index 80b5f53f4e..e7959c73c6 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -59,7 +59,7 @@ struct msgchunk_S { char sb_eol; // true when line ends after this text int sb_msg_col; // column in which text starts int sb_attr; // text attributes - char_u sb_text[1]; // text to be displayed, actually longer + char sb_text[1]; // text to be displayed, actually longer }; // Magic chars used in confirm dialog strings @@ -70,8 +70,8 @@ static int confirm_msg_used = false; // displaying confirm_msg #ifdef INCLUDE_GENERATED_DECLARATIONS # include "message.c.generated.h" #endif -static char_u *confirm_msg = NULL; // ":confirm" message -static char_u *confirm_msg_tail; // tail of confirm_msg +static char *confirm_msg = NULL; // ":confirm" message +static char *confirm_msg_tail; // tail of confirm_msg MessageHistoryEntry *first_msg_hist = NULL; MessageHistoryEntry *last_msg_hist = NULL; @@ -251,7 +251,7 @@ void msg_multiline_attr(const char *s, int attr, bool check_int, bool *need_clea if (next_spec != NULL) { // Printing all char that are before the char found by strpbrk - msg_outtrans_len_attr((const char_u *)s, (int)(next_spec - s), attr); + msg_outtrans_len_attr(s, (int)(next_spec - s), attr); if (*next_spec != TAB && *need_clear) { msg_clr_eos(); @@ -294,7 +294,7 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) { static int entered = 0; int retval; - char_u *buf = NULL; + char *buf = NULL; if (keep && multiline) { // Not implemented. 'multiline' is only used by nvim-added messages, @@ -335,9 +335,9 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) // Truncate the message if needed. msg_start(); - buf = msg_strtrunc((char_u *)s, false); + buf = msg_strtrunc((char *)s, false); if (buf != NULL) { - s = (const char *)buf; + s = buf; } bool need_clear = true; @@ -367,9 +367,9 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) /// @return an allocated string or NULL when no truncating is done. /// /// @param force always truncate -char_u *msg_strtrunc(char_u *s, int force) +char *msg_strtrunc(char *s, int force) { - char_u *buf = NULL; + char *buf = NULL; int len; int room; @@ -377,7 +377,7 @@ char_u *msg_strtrunc(char_u *s, int force) if ((!msg_scroll && !need_wait_return && shortmess(SHM_TRUNCALL) && !exmode_active && msg_silent == 0 && !ui_has(kUIMessages)) || force) { - len = vim_strsize((char *)s); + len = vim_strsize(s); if (msg_scrolled != 0) { // Use all the columns. room = (Rows - msg_row) * Columns - 1; @@ -390,7 +390,7 @@ char_u *msg_strtrunc(char_u *s, int force) // composing chars) len = (room + 2) * 18; buf = xmalloc((size_t)len); - trunc_string((char *)s, (char *)buf, room, len); + trunc_string(s, buf, room, len); } } return buf; @@ -444,7 +444,7 @@ void trunc_string(char *s, char *buf, int room_in, int buflen) half = i = (int)STRLEN(s); for (;;) { do { - half = half - utf_head_off((char_u *)s, (char_u *)s + half - 1) - 1; + half = half - utf_head_off(s, s + half - 1) - 1; } while (half > 0 && utf_iscomposing(utf_ptr2char(s + half))); n = ptr2cells(s + half); if (len + n > room || half == 0) { @@ -900,7 +900,7 @@ char *msg_trunc_attr(char *s, bool force, int attr) // Add message to history before truncating. add_msg_hist(s, -1, attr, false); - char *ts = (char *)msg_may_trunc(force, (char_u *)s); + char *ts = msg_may_trunc(force, s); msg_hist_off = true; n = msg_attr(ts, attr); @@ -917,14 +917,14 @@ char *msg_trunc_attr(char *s, bool force, int attr) /// @return a pointer to where the truncated message starts. /// /// @note: May change the message by replacing a character with '<'. -char_u *msg_may_trunc(bool force, char_u *s) +char *msg_may_trunc(bool force, char *s) { int room; room = (Rows - cmdline_row - 1) * Columns + sc_col - 1; if ((force || (shortmess(SHM_TRUNC) && !exmode_active)) && (int)STRLEN(s) - room > 0 && p_ch > 0) { - int size = vim_strsize((char *)s); + int size = vim_strsize(s); // There may be room anyway when there are multibyte chars. if (size <= room) { @@ -932,8 +932,8 @@ char_u *msg_may_trunc(bool force, char_u *s) } int n; for (n = 0; size >= room;) { - size -= utf_ptr2cells((char *)s + n); - n += utfc_ptr2len((char *)s + n); + size -= utf_ptr2cells(s + n); + n += utfc_ptr2len(s + n); } n--; s += n; @@ -1497,19 +1497,19 @@ void msg_outnum(long n) msg_puts(buf); } -void msg_home_replace(char_u *fname) +void msg_home_replace(char *fname) { msg_home_replace_attr(fname, 0); } -void msg_home_replace_hl(char_u *fname) +void msg_home_replace_hl(char *fname) { msg_home_replace_attr(fname, HL_ATTR(HLF_D)); } -static void msg_home_replace_attr(char_u *fname, int attr) +static void msg_home_replace_attr(char *fname, int attr) { - char *name = home_replace_save(NULL, (char *)fname); + char *name = home_replace_save(NULL, fname); msg_outtrans_attr(name, attr); xfree(name); } @@ -1526,12 +1526,12 @@ int msg_outtrans(char *str) int msg_outtrans_attr(const char *str, int attr) { - return msg_outtrans_len_attr((char_u *)str, (int)STRLEN(str), attr); + return msg_outtrans_len_attr(str, (int)STRLEN(str), attr); } int msg_outtrans_len(const char *str, int len) { - return msg_outtrans_len_attr((char_u *)str, len, 0); + return msg_outtrans_len_attr(str, len, 0); } /// Output one character at "p". @@ -1543,19 +1543,19 @@ char *msg_outtrans_one(char *p, int attr) int l; if ((l = utfc_ptr2len(p)) > 1) { - msg_outtrans_len_attr((char_u *)p, l, attr); + msg_outtrans_len_attr(p, l, attr); return p + l; } msg_puts_attr((const char *)transchar_byte(*p), attr); return p + 1; } -int msg_outtrans_len_attr(const char_u *msgstr, int len, int attr) +int msg_outtrans_len_attr(const char *msgstr, int len, int attr) { int retval = 0; - const char *str = (const char *)msgstr; - const char *plain_start = (const char *)msgstr; - char_u *s; + const char *str = msgstr; + const char *plain_start = msgstr; + char *s; int mb_l; int c; int save_got_int = got_int; @@ -1601,7 +1601,7 @@ int msg_outtrans_len_attr(const char_u *msgstr, int len, int attr) len -= mb_l - 1; str += mb_l; } else { - s = transchar_byte((uint8_t)(*str)); + s = (char *)transchar_byte((uint8_t)(*str)); if (s[1] != NUL) { // Unprintable char: print the printable chars so far and the // translation of the unprintable char. @@ -1663,12 +1663,12 @@ void msg_make(char *arg) /// /// @param from true for LHS of a mapping /// @param maxlen screen columns, 0 for unlimited -int msg_outtrans_special(const char_u *strstart, bool from, int maxlen) +int msg_outtrans_special(const char *strstart, bool from, int maxlen) { if (strstart == NULL) { return 0; // Do nothing. } - const char_u *str = strstart; + const char *str = strstart; int retval = 0; int attr = HL_ATTR(HLF_8); @@ -1679,7 +1679,7 @@ int msg_outtrans_special(const char_u *strstart, bool from, int maxlen) text = ""; str++; } else { - text = str2special((const char **)&str, from, false); + text = str2special(&str, from, false); } if (text[0] != NUL && text[1] == NUL) { // single-byte character or illegal byte @@ -1818,20 +1818,20 @@ void str2specialbuf(const char *sp, char *buf, size_t len) } /// print line for :print or :list command -void msg_prt_line(char_u *s, int list) +void msg_prt_line(char *s, int list) { int c; int col = 0; int n_extra = 0; int c_extra = 0; int c_final = 0; - char_u *p_extra = NULL; // init to make SASC shut up + char *p_extra = NULL; // init to make SASC shut up int n; int attr = 0; - char_u *lead = NULL; + char *lead = NULL; bool in_multispace = false; int multispace_pos = 0; - char_u *trail = NULL; + char *trail = NULL; int l; if (curwin->w_p_list) { @@ -1873,16 +1873,16 @@ void msg_prt_line(char_u *s, int list) c = c_extra; } else { assert(p_extra != NULL); - c = *p_extra++; + c = (unsigned char)(*p_extra++); } - } else if ((l = utfc_ptr2len((char *)s)) > 1) { - col += utf_ptr2cells((char *)s); + } else if ((l = utfc_ptr2len(s)) > 1) { + col += utf_ptr2cells(s); char buf[MB_MAXBYTES + 1]; if (l >= MB_MAXBYTES) { xstrlcpy(buf, "?", sizeof(buf)); } else if (curwin->w_p_lcs_chars.nbsp != NUL && list - && (utf_ptr2char((char *)s) == 160 - || utf_ptr2char((char *)s) == 0x202f)) { + && (utf_ptr2char(s) == 160 + || utf_ptr2char(s) == 0x202f)) { int len = utf_char2bytes(curwin->w_p_lcs_chars.nbsp, buf); buf[len] = NUL; } else { @@ -1894,7 +1894,7 @@ void msg_prt_line(char_u *s, int list) continue; } else { attr = 0; - c = *s++; + c = (unsigned char)(*s++); in_multispace = c == ' ' && ((col > 0 && s[-2] == ' ') || *s == ' '); if (!in_multispace) { multispace_pos = 0; @@ -1920,7 +1920,7 @@ void msg_prt_line(char_u *s, int list) c = curwin->w_p_lcs_chars.nbsp; attr = HL_ATTR(HLF_0); } else if (c == NUL && list && curwin->w_p_lcs_chars.eol != NUL) { - p_extra = (char_u *)""; + p_extra = ""; c_extra = NUL; c_final = NUL; n_extra = 1; @@ -1929,10 +1929,10 @@ void msg_prt_line(char_u *s, int list) s--; } else if (c != NUL && (n = byte2cells(c)) > 1) { n_extra = n - 1; - p_extra = transchar_byte(c); + p_extra = (char *)transchar_byte(c); c_extra = NUL; c_final = NUL; - c = *p_extra++; + c = (unsigned char)(*p_extra++); // Use special coloring to be able to distinguish from // the same in plain text. attr = HL_ATTR(HLF_0); @@ -2023,12 +2023,12 @@ void msg_puts_title(const char *s) /// Show a message in such a way that it always fits in the line. Cut out a /// part in the middle and replace it with "..." when necessary. /// Does not handle multi-byte characters! -void msg_outtrans_long_attr(char_u *longstr, int attr) +void msg_outtrans_long_attr(char *longstr, int attr) { msg_outtrans_long_len_attr(longstr, (int)STRLEN(longstr), attr); } -void msg_outtrans_long_len_attr(char_u *longstr, int len, int attr) +void msg_outtrans_long_len_attr(char *longstr, int len, int attr) { int slen = len; int room; @@ -2105,7 +2105,7 @@ void msg_puts_attr_len(const char *const str, const ptrdiff_t len, int attr) } } if (!msg_use_printf() || (headless_mode && default_grid.chars)) { - msg_puts_display((const char_u *)str, (int)len, attr, false); + msg_puts_display(str, (int)len, attr, false); } need_fileinfo = false; @@ -2148,10 +2148,10 @@ static void msg_ext_emit_chunk(void) /// The display part of msg_puts_attr_len(). /// May be called recursively to display scroll-back text. -static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurse) +static void msg_puts_display(const char *str, int maxlen, int attr, int recurse) { - const char_u *s = str; - const char_u *t_s = str; // String from "t_s" to "s" is still todo. + const char *s = str; + const char *t_s = str; // String from "t_s" to "s" is still todo. int t_col = 0; // Screen cells todo, 0 when "t_s" not used. int l; int cw; @@ -2186,19 +2186,19 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs && (*s == '\n' || (cmdmsg_rl ? (msg_col <= 1 || (*s == TAB && msg_col <= 7) - || (utf_ptr2cells((char *)s) > 1 + || (utf_ptr2cells(s) > 1 && msg_col <= 2)) : ((*s != '\r' && msg_col + t_col >= Columns - 1) || (*s == TAB && msg_col + t_col >= ((Columns - 1) & ~7)) - || (utf_ptr2cells((char *)s) > 1 + || (utf_ptr2cells(s) > 1 && msg_col + t_col >= Columns - 2))))) { // The screen is scrolled up when at the last row (some terminals // scroll automatically, some don't. To avoid problems we scroll // ourselves). if (t_col > 0) { // output postponed text - t_puts(&t_col, (char *)t_s, (char *)s, attr); + t_puts(&t_col, t_s, s, attr); } // When no more prompt and no more room, truncate here @@ -2207,7 +2207,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs } // Scroll the screen up one line. - bool has_last_char = (*s >= ' ' && !cmdmsg_rl); + bool has_last_char = ((uint8_t)(*s) >= ' ' && !cmdmsg_rl); msg_scroll_up(!has_last_char); msg_row = Rows - 2; @@ -2219,11 +2219,11 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs if (has_last_char) { if (maxlen >= 0) { // Avoid including composing chars after the end. - l = utfc_ptr2len_len(s, (int)((str + maxlen) - s)); + l = utfc_ptr2len_len((char_u *)s, (int)((str + maxlen) - s)); } else { - l = utfc_ptr2len((char *)s); + l = utfc_ptr2len(s); } - s = (char_u *)screen_puts_mbyte((char *)s, l, attr); + s = screen_puts_mbyte((char *)s, l, attr); did_last_char = true; } else { did_last_char = false; @@ -2276,13 +2276,13 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs wrap = *s == '\n' || msg_col + t_col >= Columns - || (utf_ptr2cells((char *)s) > 1 + || (utf_ptr2cells(s) > 1 && msg_col + t_col >= Columns - 1) ; if (t_col > 0 && (wrap || *s == '\r' || *s == '\b' || *s == '\t' || *s == BELL)) { // Output any postponed text. - t_puts(&t_col, (char *)t_s, (char *)s, attr); + t_puts(&t_col, t_s, s, attr); } if (wrap && p_more && !recurse) { @@ -2312,20 +2312,20 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs } while (msg_col & 7); } else if (*s == BELL) { // beep (from ":sh") vim_beep(BO_SH); - } else if (*s >= 0x20) { // printable char - cw = utf_ptr2cells((char *)s); + } else if ((uint8_t)(*s) >= 0x20) { // printable char + cw = utf_ptr2cells(s); if (maxlen >= 0) { // avoid including composing chars after the end - l = utfc_ptr2len_len(s, (int)((str + maxlen) - s)); + l = utfc_ptr2len_len((char_u *)s, (int)((str + maxlen) - s)); } else { - l = utfc_ptr2len((char *)s); + l = utfc_ptr2len(s); } // When drawing from right to left or when a double-wide character // doesn't fit, draw a single character here. Otherwise collect // characters and draw them all at once later. if (cmdmsg_rl || (cw > 1 && msg_col + t_col >= Columns - 1)) { if (l > 1) { - s = (char_u *)screen_puts_mbyte((char *)s, l, attr) - 1; + s = screen_puts_mbyte((char *)s, l, attr) - 1; } else { msg_screen_putchar(*s, attr); } @@ -2343,7 +2343,7 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs // Output any postponed text. if (t_col > 0) { - t_puts(&t_col, (char *)t_s, (char *)s, attr); + t_puts(&t_col, t_s, s, attr); } if (p_more && !recurse) { store_sb_text((char **)&sb_str, (char *)s, attr, &sb_col, false); @@ -2679,7 +2679,7 @@ void msg_sb_eol(void) static msgchunk_T *disp_sb_line(int row, msgchunk_T *smp) { msgchunk_T *mp = smp; - char_u *p; + char *p; for (;;) { msg_row = row; @@ -3080,13 +3080,13 @@ static void msg_screen_putchar(int c, int attr) void msg_moremsg(int full) { int attr; - char_u *s = (char_u *)_("-- More --"); + char *s = _("-- More --"); attr = hl_combine_attr(HL_ATTR(HLF_MSG), HL_ATTR(HLF_M)); - grid_puts(&msg_grid_adj, (char *)s, Rows - 1, 0, attr); + grid_puts(&msg_grid_adj, s, Rows - 1, 0, attr); if (full) { grid_puts(&msg_grid_adj, _(" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit "), - Rows - 1, vim_strsize((char *)s), attr); + Rows - 1, vim_strsize(s), attr); } } @@ -3281,7 +3281,7 @@ void msg_check(void) /// @param maxlen if -1, write the whole string, otherwise up to "maxlen" bytes. static void redir_write(const char *const str, const ptrdiff_t maxlen) { - const char_u *s = (char_u *)str; + const char *s = str; static int cur_col = 0; if (maxlen == 0) { @@ -3306,7 +3306,7 @@ static void redir_write(const char *const str, const ptrdiff_t maxlen) ga_concat_len(capture_ga, " ", 1); } if (redir_reg) { - write_reg_contents(redir_reg, (char_u *)" ", 1, true); + write_reg_contents(redir_reg, " ", 1, true); } else if (redir_vname) { var_redir_str(" ", -1); } else if (redir_fd != NULL) { @@ -3332,7 +3332,7 @@ static void redir_write(const char *const str, const ptrdiff_t maxlen) // Write and adjust the current column. while (*s != NUL - && (maxlen < 0 || (int)(s - (const char_u *)str) < maxlen)) { + && (maxlen < 0 || (int)(s - str) < maxlen)) { if (!redir_reg && !redir_vname && !capture_ga) { if (redir_fd != NULL) { putc(*s, redir_fd); @@ -3469,9 +3469,9 @@ void give_warning(char *message, bool hl) no_wait_return--; } -void give_warning2(char_u *const message, char_u *const a1, bool hl) +void give_warning2(char *const message, char *const a1, bool hl) { - vim_snprintf((char *)IObuff, IOSIZE, (char *)message, a1); + vim_snprintf((char *)IObuff, IOSIZE, message, a1); give_warning((char *)IObuff, hl); } @@ -3524,11 +3524,11 @@ void msg_advance(int col) /// @param textfiel IObuff for inputdialog(), NULL otherwise /// @param ex_cmd when true pressing : accepts default and starts Ex command /// @returns 0 if cancelled, otherwise the nth button (1-indexed). -int do_dialog(int type, char_u *title, char_u *message, char_u *buttons, int dfltbutton, - char_u *textfield, int ex_cmd) +int do_dialog(int type, char *title, char *message, char *buttons, int dfltbutton, char *textfield, + int ex_cmd) { int retval = 0; - char_u *hotkeys; + char *hotkeys; int c; int i; @@ -3578,10 +3578,10 @@ int do_dialog(int type, char_u *title, char_u *message, char_u *buttons, int dfl c = mb_tolower(c); retval = 1; for (i = 0; hotkeys[i]; i++) { - if (utf_ptr2char((char *)hotkeys + i) == c) { + if (utf_ptr2char(hotkeys + i) == c) { break; } - i += utfc_ptr2len((char *)hotkeys + i) - 1; + i += utfc_ptr2len(hotkeys + i) - 1; retval++; } if (hotkeys[i]) { @@ -3608,14 +3608,14 @@ int do_dialog(int type, char_u *title, char_u *message, char_u *buttons, int dfl /// characters. Return the length of the character in bytes. /// /// @param lowercase make character lower case -static int copy_char(const char_u *from, char_u *to, bool lowercase) +static int copy_char(const char *from, char *to, bool lowercase) FUNC_ATTR_NONNULL_ALL { if (lowercase) { - int c = mb_tolower(utf_ptr2char((char *)from)); - return utf_char2bytes(c, (char *)to); + int c = mb_tolower(utf_ptr2char(from)); + return utf_char2bytes(c, to); } - int len = utfc_ptr2len((char *)from); + int len = utfc_ptr2len(from); memmove(to, from, (size_t)len); return len; } @@ -3635,7 +3635,7 @@ static int copy_char(const char_u *from, char_u *to, bool lowercase) /// corresponding button has a hotkey /// /// @return Pointer to memory allocated for storing hotkeys -static char_u *console_dialog_alloc(const char_u *message, char_u *buttons, bool has_hotkey[]) +static char *console_dialog_alloc(const char *message, char *buttons, bool has_hotkey[]) { int lenhotkey = HOTK_LEN; // count first button has_hotkey[0] = false; @@ -3643,7 +3643,7 @@ static char_u *console_dialog_alloc(const char_u *message, char_u *buttons, bool // Compute the size of memory to allocate. int len = 0; int idx = 0; - char_u *r = buttons; + char *r = buttons; while (*r) { if (*r == DLG_BUTTON_SEP) { len += 3; // '\n' -> ', '; 'x' -> '(x)' @@ -3689,11 +3689,11 @@ static char_u *console_dialog_alloc(const char_u *message, char_u *buttons, bool /// The hotkeys can be multi-byte characters, but without combining chars. /// /// @return an allocated string with hotkeys. -static char_u *msg_show_console_dialog(char_u *message, char_u *buttons, int dfltbutton) +static char *msg_show_console_dialog(char *message, char *buttons, int dfltbutton) FUNC_ATTR_NONNULL_RET { bool has_hotkey[HAS_HOTKEY_LEN] = { false }; - char_u *hotk = console_dialog_alloc(message, buttons, has_hotkey); + char *hotk = console_dialog_alloc(message, buttons, has_hotkey); copy_hotkeys_and_msg(message, buttons, dfltbutton, has_hotkey, hotk); @@ -3709,13 +3709,13 @@ static char_u *msg_show_console_dialog(char_u *message, char_u *buttons, int dfl /// @param has_hotkey An element in this array is true if corresponding button /// has a hotkey /// @param[out] hotkeys_ptr Pointer to the memory location where hotkeys will be copied -static void copy_hotkeys_and_msg(const char_u *message, char_u *buttons, int default_button_idx, - const bool has_hotkey[], char_u *hotkeys_ptr) +static void copy_hotkeys_and_msg(const char *message, char *buttons, int default_button_idx, + const bool has_hotkey[], char *hotkeys_ptr) { *confirm_msg = '\n'; STRCPY(confirm_msg + 1, message); - char_u *msgp = confirm_msg + 1 + STRLEN(message); + char *msgp = confirm_msg + 1 + STRLEN(message); // Define first default hotkey. Keep the hotkey string NUL // terminated to avoid reading past the end. @@ -3732,7 +3732,7 @@ static void copy_hotkeys_and_msg(const char_u *message, char_u *buttons, int def } int idx = 0; - char_u *r = buttons; + char *r = buttons; while (*r) { if (*r == DLG_BUTTON_SEP) { *msgp++ = ','; @@ -3788,28 +3788,28 @@ void display_confirm_msg(void) confirm_msg_used++; if (confirm_msg != NULL) { msg_ext_set_kind("confirm"); - msg_puts_attr((const char *)confirm_msg, HL_ATTR(HLF_M)); + msg_puts_attr(confirm_msg, HL_ATTR(HLF_M)); } confirm_msg_used--; } -int vim_dialog_yesno(int type, char_u *title, char_u *message, int dflt) +int vim_dialog_yesno(int type, char *title, char *message, int dflt) { if (do_dialog(type, - title == NULL ? (char_u *)_("Question") : title, + title == NULL ? _("Question") : title, message, - (char_u *)_("&Yes\n&No"), dflt, NULL, false) == 1) { + _("&Yes\n&No"), dflt, NULL, false) == 1) { return VIM_YES; } return VIM_NO; } -int vim_dialog_yesnocancel(int type, char_u *title, char_u *message, int dflt) +int vim_dialog_yesnocancel(int type, char *title, char *message, int dflt) { switch (do_dialog(type, - title == NULL ? (char_u *)_("Question") : title, + title == NULL ? _("Question") : title, message, - (char_u *)_("&Yes\n&No\n&Cancel"), dflt, NULL, false)) { + _("&Yes\n&No\n&Cancel"), dflt, NULL, false)) { case 1: return VIM_YES; case 2: @@ -3818,12 +3818,12 @@ int vim_dialog_yesnocancel(int type, char_u *title, char_u *message, int dflt) return VIM_CANCEL; } -int vim_dialog_yesnoallcancel(int type, char_u *title, char_u *message, int dflt) +int vim_dialog_yesnoallcancel(int type, char *title, char *message, int dflt) { switch (do_dialog(type, - title == NULL ? (char_u *)"Question" : title, + title == NULL ? "Question" : title, message, - (char_u *)_("&Yes\n&No\nSave &All\n&Discard All\n&Cancel"), + _("&Yes\n&No\nSave &All\n&Discard All\n&Cancel"), dflt, NULL, false)) { case 1: return VIM_YES; diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index 73147204a1..90084bde17 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -633,7 +633,7 @@ colnr_T vcol2col(win_T *const wp, const linenr_T lnum, const colnr_T vcol) // try to advance to the specified column char_u *line = ml_get_buf(wp->w_buffer, lnum, false); chartabsize_T cts; - init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + init_chartabsize_arg(&cts, wp, lnum, 0, (char *)line, (char *)line); while (cts.cts_vcol < vcol && *cts.cts_ptr != NUL) { cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); MB_PTR_ADV(cts.cts_ptr); @@ -666,7 +666,7 @@ void set_mouse_topline(win_T *wp) static colnr_T scroll_line_len(linenr_T lnum) { colnr_T col = 0; - char_u *line = ml_get(lnum); + char_u *line = (char_u *)ml_get(lnum); if (*line != NUL) { for (;;) { int numchar = win_chartabsize(curwin, (char *)line, col); @@ -771,7 +771,7 @@ static int mouse_adjust_click(win_T *wp, int row, int col) // highlighting the second byte, not the ninth. linenr_T lnum = wp->w_cursor.lnum; - char_u *line = ml_get(lnum); + char_u *line = (char_u *)ml_get(lnum); char_u *ptr = line; char_u *ptr_end; char_u *ptr_row_offset = line; // Where we begin adjusting `ptr_end` diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 47ad000385..17b79e27c1 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -2215,12 +2215,12 @@ static void find_start_of_word(pos_T *pos) int cclass; int col; - line = ml_get(pos->lnum); + line = (char_u *)ml_get(pos->lnum); cclass = get_mouse_class(line + pos->col); while (pos->col > 0) { col = pos->col - 1; - col -= utf_head_off(line, line + col); + col -= utf_head_off((char *)line, (char *)line + col); if (get_mouse_class(line + col) != cclass) { break; } @@ -2236,10 +2236,10 @@ static void find_end_of_word(pos_T *pos) int cclass; int col; - line = ml_get(pos->lnum); + line = (char_u *)ml_get(pos->lnum); if (*p_sel == 'e' && pos->col > 0) { pos->col--; - pos->col -= utf_head_off(line, line + pos->col); + pos->col -= utf_head_off((char *)line, (char *)line + pos->col); } cclass = get_mouse_class(line + pos->col); while (line[pos->col] != NUL) { @@ -2445,7 +2445,7 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text this_class = mb_get_class(ptr + col); } while (col > 0 && this_class != 0) { - prevcol = col - 1 - utf_head_off(ptr, ptr + col - 1); + prevcol = col - 1 - utf_head_off((char *)ptr, (char *)ptr + col - 1); prev_class = mb_get_class(ptr + prevcol); if (this_class != prev_class && (i == 0 diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 4f2b84d20f..adb071b754 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -272,7 +272,7 @@ void op_shift(oparg_T *oap, int curs_top, int amount) // Set "'[" and "']" marks. curbuf->b_op_start = oap->start; curbuf->b_op_end.lnum = oap->end.lnum; - curbuf->b_op_end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); + curbuf->b_op_end.col = (colnr_T)strlen(ml_get(oap->end.lnum)); if (curbuf->b_op_end.col > 0) { curbuf->b_op_end.col--; } @@ -382,7 +382,7 @@ static void shift_block(oparg_T *oap, int amount) // TODO(vim): is passing bd.textstart for start of the line OK? chartabsize_T cts; init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, - bd.start_vcol, bd.textstart, bd.textstart); + bd.start_vcol, (char *)bd.textstart, (char *)bd.textstart); while (ascii_iswhite(*cts.cts_ptr)) { incr = lbr_chartabsize_adv(&cts); total += incr; @@ -448,7 +448,7 @@ static void shift_block(oparg_T *oap, int amount) chartabsize_T cts; init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, - non_white_col, bd.textstart, non_white); + non_white_col, (char *)bd.textstart, (char *)non_white); while (ascii_iswhite(*cts.cts_ptr)) { incr = lbr_chartabsize_adv(&cts); cts.cts_vcol += incr; @@ -477,7 +477,7 @@ static void shift_block(oparg_T *oap, int amount) verbatim_copy_width -= bd.start_char_vcols; } init_chartabsize_arg(&cts, curwin, 0, verbatim_copy_width, - bd.textstart, verbatim_copy_end); + (char *)bd.textstart, (char *)verbatim_copy_end); while (cts.cts_vcol < destination_col) { incr = lbr_chartabsize(&cts); if (cts.cts_vcol + incr > destination_col) { @@ -543,7 +543,7 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def continue; // OP_INSERT, line ends before block start } - oldp = ml_get(lnum); + oldp = (char_u *)ml_get(lnum); if (b_insert) { ts_val = bdp->start_char_vcols; @@ -572,7 +572,7 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def if (spaces > 0) { // avoid copying part of a multi-byte character - offset -= utf_head_off(oldp, oldp + offset); + offset -= utf_head_off((char *)oldp, (char *)oldp + offset); } if (spaces < 0) { // can happen when the cursor was moved spaces = 0; @@ -1014,7 +1014,7 @@ static int stuff_yank(int regname, char_u *p) yankreg_T *reg = get_yank_register(regname, YREG_YANK); if (is_append_register(regname) && reg->y_array != NULL) { char **pp = &(reg->y_array[reg->y_size - 1]); - char_u *lp = xmalloc(STRLEN(*pp) + STRLEN(p) + 1); + char_u *lp = xmalloc(strlen(*pp) + STRLEN(p) + 1); STRCPY(lp, *pp); // TODO(philix): use xstpcpy() in stuff_yank() STRCAT(lp, p); @@ -1513,7 +1513,7 @@ int op_delete(oparg_T *oap) && oap->line_count > 1 && oap->motion_force == NUL && oap->op_type == OP_DELETE) { - ptr = ml_get(oap->end.lnum) + oap->end.col; + ptr = (char_u *)ml_get(oap->end.lnum) + oap->end.col; if (*ptr != NUL) { ptr += oap->inclusive; } @@ -1617,7 +1617,7 @@ int op_delete(oparg_T *oap) // If we delete a TAB, it may be replaced by several characters. // Thus the number of characters may increase! n = bd.textlen - bd.startspaces - bd.endspaces; - oldp = ml_get(lnum); + oldp = (char_u *)ml_get(lnum); newp = (char_u *)xmalloc(STRLEN(oldp) - (size_t)n + 1); // copy up to deleted part memmove(newp, oldp, (size_t)bd.textcol); @@ -1662,7 +1662,7 @@ int op_delete(oparg_T *oap) beginline(0); // cursor in column 0 } - int old_len = (int)STRLEN(ml_get(curwin->w_cursor.lnum)); + int old_len = (int)strlen(ml_get(curwin->w_cursor.lnum)); truncate_line(false); // delete the rest of the line extmark_splice_cols(curbuf, @@ -1816,7 +1816,7 @@ setmarks: static void mb_adjust_opend(oparg_T *oap) { if (oap->inclusive) { - char *p = (char *)ml_get(oap->end.lnum); + char *p = ml_get(oap->end.lnum); oap->end.col += utf_cp_tail_off(p, p + oap->end.col); } } @@ -1990,7 +1990,7 @@ static int op_replace(oparg_T *oap, int c) if (oap->motion_type == kMTLineWise) { oap->start.col = 0; curwin->w_cursor.col = 0; - oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); + oap->end.col = (colnr_T)strlen(ml_get(oap->end.lnum)); if (oap->end.col) { oap->end.col--; } @@ -2104,7 +2104,7 @@ void op_tilde(oparg_T *oap) if (oap->motion_type == kMTLineWise) { oap->start.col = 0; pos.col = 0; - oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); + oap->end.col = (colnr_T)strlen(ml_get(oap->end.lnum)); if (oap->end.col) { oap->end.col--; } @@ -2281,7 +2281,7 @@ void op_insert(oparg_T *oap, long count1) // Get indent information ind_pre_col = (colnr_T)getwhitecols_curline(); ind_pre_vcol = get_indent(); - firstline = ml_get(oap->start.lnum) + bd.textcol; + firstline = (char_u *)ml_get(oap->start.lnum) + bd.textcol; if (oap->op_type == OP_APPEND) { firstline += bd.textlen; @@ -2413,7 +2413,7 @@ void op_insert(oparg_T *oap, long count1) * Subsequent calls to ml_get() flush the firstline data - take a * copy of the required string. */ - firstline = ml_get(oap->start.lnum); + firstline = (char_u *)ml_get(oap->start.lnum); const size_t len = STRLEN(firstline); colnr_T add = bd.textcol; colnr_T offset = 0; // offset when cursor was moved in insert mode @@ -2498,7 +2498,7 @@ int op_change(oparg_T *oap) || gchar_cursor() == NUL)) { coladvance_force(getviscol()); } - firstline = ml_get(oap->start.lnum); + firstline = (char_u *)ml_get(oap->start.lnum); pre_textlen = (long)STRLEN(firstline); pre_indent = (long)getwhitecols((char *)firstline); bd.textcol = curwin->w_cursor.col; @@ -2519,7 +2519,7 @@ int op_change(oparg_T *oap) && oap->start.lnum != oap->end.lnum && !got_int) { // Auto-indenting may have changed the indent. If the cursor was past // the indent, exclude that indent change from the inserted text. - firstline = ml_get(oap->start.lnum); + firstline = (char_u *)ml_get(oap->start.lnum); if (bd.textcol > (colnr_T)pre_indent) { long new_indent = (long)getwhitecols((char *)firstline); @@ -2547,7 +2547,7 @@ int op_change(oparg_T *oap) } else { vpos.coladd = 0; } - oldp = ml_get(linenr); + oldp = (char_u *)ml_get(linenr); newp = xmalloc(STRLEN(oldp) + (size_t)vpos.coladd + (size_t)ins_len + 1); // copy up to block start @@ -2691,14 +2691,14 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) break; case kMTLineWise: - reg->y_array[y_idx] = (char *)vim_strsave(ml_get(lnum)); + reg->y_array[y_idx] = xstrdup(ml_get(lnum)); break; case kMTCharWise: { colnr_T startcol = 0, endcol = MAXCOL; int is_oneChar = false; colnr_T cs, ce; - p = ml_get(lnum); + p = (char_u *)ml_get(lnum); bd.startspaces = 0; bd.endspaces = 0; @@ -2724,7 +2724,7 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) // Don't add space for double-wide // char; endcol will be on last byte // of multi-byte char. - && utf_head_off(p, p + endcol) == 0)) { + && utf_head_off((char *)p, (char *)p + endcol) == 0)) { if (oap->start.lnum == oap->end.lnum && oap->start.col == oap->end.col) { // Special case: inside a single char @@ -2776,8 +2776,8 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) // the new block, unless being Vi compatible. if (curr->y_type == kMTCharWise && vim_strchr(p_cpo, CPO_REGAPPEND) == NULL) { - pnew = xmalloc(STRLEN(curr->y_array[curr->y_size - 1]) - + STRLEN(reg->y_array[0]) + 1); + pnew = xmalloc(strlen(curr->y_array[curr->y_size - 1]) + + strlen(reg->y_array[0]) + 1); STRCPY(pnew, curr->y_array[--j]); STRCAT(pnew, reg->y_array[0]); xfree(curr->y_array[j]); @@ -2857,7 +2857,7 @@ static void yank_copy_line(yankreg_T *reg, struct block_def *bd, size_t y_idx, int s = bd->textlen + bd->endspaces; while (s > 0 && ascii_iswhite(*(bd->textstart + s - 1))) { - s = s - utf_head_off(bd->textstart, bd->textstart + s - 1) - 1; + s = s - utf_head_off((char *)bd->textstart, (char *)bd->textstart + s - 1) - 1; pnew--; } } @@ -3299,7 +3299,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) oldlen = STRLEN(oldp); chartabsize_T cts; init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0, - oldp, oldp); + (char *)oldp, (char *)oldp); while (cts.cts_vcol < col && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) @@ -3320,7 +3320,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) bd.startspaces = incr - bd.endspaces; bd.textcol--; delcount = 1; - bd.textcol -= utf_head_off(oldp, oldp + bd.textcol); + bd.textcol -= utf_head_off((char *)oldp, (char *)oldp + bd.textcol); if (oldp[bd.textcol] != TAB) { /* Only a Tab can be split into spaces. Other * characters will have to be moved to after the @@ -3336,8 +3336,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) // calculate number of spaces required to fill right side of // block spaces = y_width + 1; - init_chartabsize_arg(&cts, curwin, 0, 0, - (char_u *)y_array[i], (char_u *)y_array[i]); + init_chartabsize_arg(&cts, curwin, 0, 0, y_array[i], y_array[i]); for (int j = 0; j < yanklen; j++) { spaces -= lbr_chartabsize(&cts); cts.cts_ptr++; @@ -3483,7 +3482,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) } else { totlen = (size_t)(count * yanklen); do { - oldp = ml_get(lnum); + oldp = (char_u *)ml_get(lnum); oldlen = STRLEN(oldp); if (lnum > start_lnum) { pos_T pos = { @@ -3510,7 +3509,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) ml_replace(lnum, (char *)newp, false); // compute the byte offset for the last character - first_byte_off = utf_head_off(newp, ptr - 1); + first_byte_off = utf_head_off((char *)newp, (char *)ptr - 1); // Place cursor on last putted char. if (lnum == curwin->w_cursor.lnum) { @@ -3554,7 +3553,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) // First insert y_array[size - 1] in front of second line. // Then append y_array[0] to first line. lnum = new_cursor.lnum; - ptr = ml_get(lnum) + col; + ptr = (char_u *)ml_get(lnum) + col; totlen = STRLEN(y_array[y_size - 1]); newp = (char_u *)xmalloc((size_t)(STRLEN(ptr) + totlen + 1)); STRCPY(newp, y_array[y_size - 1]); @@ -3564,7 +3563,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) new_lnum++; xfree(newp); - oldp = ml_get(lnum); + oldp = (char_u *)ml_get(lnum); newp = (char_u *)xmalloc((size_t)col + (size_t)yanklen + 1); // copy first part of line memmove(newp, oldp, (size_t)col); @@ -3588,7 +3587,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) if (flags & PUT_FIXINDENT) { old_pos = curwin->w_cursor; curwin->w_cursor.lnum = lnum; - ptr = ml_get(lnum); + ptr = (char_u *)ml_get(lnum); if (cnt == count && i == y_size - 1) { lendiff = (int)STRLEN(ptr); } @@ -3668,8 +3667,8 @@ error: if (col > 1) { curbuf->b_op_end.col = col - 1; if (len > 0) { - curbuf->b_op_end.col -= utf_head_off((char_u *)y_array[y_size - 1], - (char_u *)y_array[y_size - 1] + len - 1); + curbuf->b_op_end.col -= utf_head_off(y_array[y_size - 1], + y_array[y_size - 1] + len - 1); } } else { curbuf->b_op_end.col = 0; @@ -3878,14 +3877,14 @@ void ex_display(exarg_T *eap) && (arg == NULL || vim_strchr((char *)arg, '.') != NULL) && !got_int && !message_filtered((char *)p)) { msg_puts("\n c \". "); - dis_msg(p, true); + dis_msg((char *)p, true); } // display last command line if (last_cmdline != NULL && (arg == NULL || vim_strchr((char *)arg, ':') != NULL) && !got_int && !message_filtered(last_cmdline)) { msg_puts("\n c \": "); - dis_msg((char_u *)last_cmdline, false); + dis_msg(last_cmdline, false); } // display current file name @@ -3893,7 +3892,7 @@ void ex_display(exarg_T *eap) && (arg == NULL || vim_strchr((char *)arg, '%') != NULL) && !got_int && !message_filtered(curbuf->b_fname)) { msg_puts("\n c \"% "); - dis_msg((char_u *)curbuf->b_fname, false); + dis_msg(curbuf->b_fname, false); } // display alternate file name @@ -3903,7 +3902,7 @@ void ex_display(exarg_T *eap) if (buflist_name_nr(0, &fname, &dummy) != FAIL && !message_filtered(fname)) { msg_puts("\n c \"# "); - dis_msg((char_u *)fname, false); + dis_msg(fname, false); } } @@ -3912,14 +3911,14 @@ void ex_display(exarg_T *eap) && (arg == NULL || vim_strchr((char *)arg, '/') != NULL) && !got_int && !message_filtered((char *)last_search_pat())) { msg_puts("\n c \"/ "); - dis_msg(last_search_pat(), false); + dis_msg((char *)last_search_pat(), false); } // display last used expression if (expr_line != NULL && (arg == NULL || vim_strchr((char *)arg, '=') != NULL) && !got_int && !message_filtered((char *)expr_line)) { msg_puts("\n c \"= "); - dis_msg(expr_line, false); + dis_msg((char *)expr_line, false); } } @@ -3927,7 +3926,7 @@ void ex_display(exarg_T *eap) /// truncate at end of screen line /// /// @param skip_esc if true, ignore trailing ESC -static void dis_msg(const char_u *p, bool skip_esc) +static void dis_msg(const char *p, bool skip_esc) FUNC_ATTR_NONNULL_ALL { int n; @@ -3936,12 +3935,12 @@ static void dis_msg(const char_u *p, bool skip_esc) n = Columns - 6; while (*p != NUL && !(*p == ESC && skip_esc && *(p + 1) == NUL) - && (n -= ptr2cells((char *)p)) >= 0) { - if ((l = utfc_ptr2len((char *)p)) > 1) { - msg_outtrans_len((char *)p, l); + && (n -= ptr2cells(p)) >= 0) { + if ((l = utfc_ptr2len(p)) > 1) { + msg_outtrans_len(p, l); p += l; } else { - msg_outtrans_len((char *)p++, 1); + msg_outtrans_len(p++, 1); } } os_breakcheck(); @@ -3958,11 +3957,11 @@ static void dis_msg(const char_u *p, bool skip_esc) /// @param include_space - whether to skip space following the comment leader /// @param[out] is_comment - whether the current line ends with an unclosed /// comment. -char_u *skip_comment(char_u *line, bool process, bool include_space, bool *is_comment) +char *skip_comment(char *line, bool process, bool include_space, bool *is_comment) { char *comment_flags = NULL; int lead_len; - int leader_offset = get_last_leader_offset((char *)line, &comment_flags); + int leader_offset = get_last_leader_offset(line, &comment_flags); *is_comment = false; if (leader_offset != -1) { @@ -3984,7 +3983,7 @@ char_u *skip_comment(char_u *line, bool process, bool include_space, bool *is_co return line; } - lead_len = get_leader_len((char *)line, &comment_flags, false, include_space); + lead_len = get_leader_len(line, &comment_flags, false, include_space); if (lead_len == 0) { return line; @@ -4022,11 +4021,11 @@ char_u *skip_comment(char_u *line, bool process, bool include_space, bool *is_co /// @return FAIL for failure, OK otherwise int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions, bool setmark) { - char_u *curr = NULL; - char_u *curr_start = NULL; - char_u *cend; - char_u *newp; - char_u *spaces; // number of spaces inserted before a line + char *curr = NULL; + char *curr_start = NULL; + char *cend; + char *newp; + char *spaces; // number of spaces inserted before a line int endcurr1 = NUL; int endcurr2 = NUL; int currsize = 0; // size of the current line @@ -4055,7 +4054,8 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions // Don't move anything, just compute the final line length // and setup the array of space strings lengths for (t = 0; t < (linenr_T)count; t++) { - curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t)); + curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t)); + curr = curr_start; if (t == 0 && setmark && (cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '[ mark. curwin->w_buffer->b_op_start.lnum = curwin->w_cursor.lnum; @@ -4065,8 +4065,7 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions // We don't want to remove the comment leader if the // previous line is not a comment. if (t > 0 && prev_was_comment) { - char_u *new_curr = skip_comment(curr, true, insert_space, - &prev_was_comment); + char *new_curr = skip_comment(curr, true, insert_space, &prev_was_comment); comments[t] = (int)(new_curr - curr); curr = new_curr; } else { @@ -4075,17 +4074,17 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions } if (insert_space && t > 0) { - curr = (char_u *)skipwhite((char *)curr); + curr = skipwhite(curr); if (*curr != NUL && *curr != ')' && sumsize != 0 && endcurr1 != TAB && (!has_format_option(FO_MBYTE_JOIN) - || (utf_ptr2char((char *)curr) < 0x100 && endcurr1 < 0x100)) + || (utf_ptr2char(curr) < 0x100 && endcurr1 < 0x100)) && (!has_format_option(FO_MBYTE_JOIN2) - || (utf_ptr2char((char *)curr) < 0x100 && !utf_eat_space(endcurr1)) + || (utf_ptr2char(curr) < 0x100 && !utf_eat_space(endcurr1)) || (endcurr1 < 0x100 - && !utf_eat_space(utf_ptr2char((char *)curr))))) { + && !utf_eat_space(utf_ptr2char(curr))))) { // don't add a space if the line is ending in a space if (endcurr1 == ' ') { endcurr1 = endcurr2; @@ -4112,10 +4111,10 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions if (insert_space && currsize > 0) { cend = curr + currsize; MB_PTR_BACK(curr, cend); - endcurr1 = utf_ptr2char((char *)cend); + endcurr1 = utf_ptr2char(cend); if (cend > curr) { MB_PTR_BACK(curr, cend); - endcurr2 = utf_ptr2char((char *)cend); + endcurr2 = utf_ptr2char(cend); } } line_breakcheck(); @@ -4129,7 +4128,7 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions col = sumsize - currsize - spaces[count - 1]; // allocate the space for the new line - newp = (char_u *)xmalloc((size_t)sumsize + 1); + newp = xmalloc((size_t)sumsize + 1); cend = newp + sumsize; *cend = 0; @@ -4165,17 +4164,18 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions break; } - curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1)); + curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1)); + curr = curr_start; if (remove_comments) { curr += comments[t - 1]; } if (insert_space && t > 1) { - curr = (char_u *)skipwhite((char *)curr); + curr = skipwhite(curr); } currsize = (int)STRLEN(curr); } - ml_replace(curwin->w_cursor.lnum, (char *)newp, false); + ml_replace(curwin->w_cursor.lnum, newp, false); if (setmark && (cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '] mark. @@ -4234,11 +4234,11 @@ theend: static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool is_del) { int incr = 0; - char_u *pend; - char_u *pstart; - char_u *line; - char_u *prev_pstart; - char_u *prev_pend; + char *pend; + char *pstart; + char *line; + char *prev_pstart; + char *prev_pend; const int lbr_saved = curwin->w_p_lbr; // Avoid a problem with unwanted linebreaks in block mode. @@ -4271,11 +4271,11 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool bdp->pre_whitesp = 0; bdp->pre_whitesp_c = 0; } - prev_pstart = (char_u *)cts.cts_ptr; + prev_pstart = cts.cts_ptr; MB_PTR_ADV(cts.cts_ptr); } bdp->start_vcol = cts.cts_vcol; - pstart = (char_u *)cts.cts_ptr; + pstart = cts.cts_ptr; clear_chartabsize_arg(&cts); bdp->start_char_vcols = incr; @@ -4313,17 +4313,16 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool } } } else { - init_chartabsize_arg(&cts, curwin, lnum, bdp->end_vcol, - line, pend); + init_chartabsize_arg(&cts, curwin, lnum, bdp->end_vcol, line, pend); prev_pend = pend; while (cts.cts_vcol <= oap->end_vcol && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) - prev_pend = (char_u *)cts.cts_ptr; + prev_pend = cts.cts_ptr; incr = lbr_chartabsize_adv(&cts); cts.cts_vcol += incr; } bdp->end_vcol = cts.cts_vcol; - pend = (char_u *)cts.cts_ptr; + pend = cts.cts_ptr; clear_chartabsize_arg(&cts); if (bdp->end_vcol <= oap->end_vcol @@ -4356,7 +4355,7 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bool bdp->textlen = (int)(pend - pstart); } bdp->textcol = (colnr_T)(pstart - line); - bdp->textstart = pstart; + bdp->textstart = (char_u *)pstart; curwin->w_p_lbr = lbr_saved; } @@ -4511,7 +4510,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) } curwin->w_cursor = *pos; - ptr = ml_get(pos->lnum); + ptr = (char_u *)ml_get(pos->lnum); col = pos->col; if (*ptr == NUL || col + !!save_coladd >= (int)STRLEN(ptr)) { @@ -4523,14 +4522,14 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) if (do_bin) { while (col > 0 && ascii_isbdigit(ptr[col])) { col--; - col -= utf_head_off(ptr, ptr + col); + col -= utf_head_off((char *)ptr, (char *)ptr + col); } } if (do_hex) { while (col > 0 && ascii_isxdigit(ptr[col])) { col--; - col -= utf_head_off(ptr, ptr + col); + col -= utf_head_off((char *)ptr, (char *)ptr + col); } } if (do_bin @@ -4538,7 +4537,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) && !((col > 0 && (ptr[col] == 'X' || ptr[col] == 'x') && ptr[col - 1] == '0' - && !utf_head_off(ptr, ptr + col - 1) + && !utf_head_off((char *)ptr, (char *)ptr + col - 1) && ascii_isxdigit(ptr[col + 1])))) { // In case of binary/hexadecimal pattern overlap match, rescan @@ -4546,7 +4545,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) while (col > 0 && ascii_isdigit(ptr[col])) { col--; - col -= utf_head_off(ptr, ptr + col); + col -= utf_head_off((char *)ptr, (char *)ptr + col); } } @@ -4554,17 +4553,17 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) && col > 0 && (ptr[col] == 'X' || ptr[col] == 'x') && ptr[col - 1] == '0' - && !utf_head_off(ptr, ptr + col - 1) + && !utf_head_off((char *)ptr, (char *)ptr + col - 1) && ascii_isxdigit(ptr[col + 1])) || (do_bin && col > 0 && (ptr[col] == 'B' || ptr[col] == 'b') && ptr[col - 1] == '0' - && !utf_head_off(ptr, ptr + col - 1) + && !utf_head_off((char *)ptr, (char *)ptr + col - 1) && ascii_isbdigit(ptr[col + 1]))) { // Found hexadecimal or binary number, move to its start. col--; - col -= utf_head_off(ptr, ptr + col); + col -= utf_head_off((char *)ptr, (char *)ptr + col); } else { // Search forward and then backward to find the start of number. col = pos->col; @@ -4597,7 +4596,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) } if (col > pos->col && ptr[col - 1] == '-' - && !utf_head_off(ptr, ptr + col - 1) + && !utf_head_off((char *)ptr, (char *)ptr + col - 1) && !do_unsigned) { negative = true; was_positive = false; @@ -4643,7 +4642,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) curwin->w_cursor.col = col; } else { if (col > 0 && ptr[col - 1] == '-' - && !utf_head_off(ptr, ptr + col - 1) + && !utf_head_off((char *)ptr, (char *)ptr + col - 1) && !visual && !do_unsigned) { // negative number @@ -5036,7 +5035,7 @@ static void finish_write_reg(int name, yankreg_T *reg, yankreg_T *old_y_previous /// store `str` in register `name` /// /// @see write_reg_contents_ex -void write_reg_contents(int name, const char_u *str, ssize_t len, int must_append) +void write_reg_contents(int name, const char *str, ssize_t len, int must_append) { write_reg_contents_ex(name, str, len, must_append, kMTUnknown, 0L); } @@ -5045,9 +5044,9 @@ void write_reg_contents_lst(int name, char **strings, bool must_append, MotionTy colnr_T block_len) { if (name == '/' || name == '=') { - char_u *s = (char_u *)strings[0]; + char *s = strings[0]; if (strings[0] == NULL) { - s = (char_u *)""; + s = ""; } else if (strings[1] != NULL) { emsg(_("E883: search pattern and expression register may not " "contain two or more lines")); @@ -5067,7 +5066,7 @@ void write_reg_contents_lst(int name, char **strings, bool must_append, MotionTy return; } - str_to_reg(reg, yank_type, (char *)strings, STRLEN((char_u *)strings), + str_to_reg(reg, yank_type, (char *)strings, STRLEN(strings), block_len, true); finish_write_reg(name, reg, old_y_previous); } @@ -5090,7 +5089,7 @@ void write_reg_contents_lst(int name, char **strings, bool must_append, MotionTy /// is an uppercase letter. /// @param yank_type The motion type (kMTUnknown to auto detect) /// @param block_len width of visual block -void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_append, +void write_reg_contents_ex(int name, const char *str, ssize_t len, bool must_append, MotionType yank_type, colnr_T block_len) { if (len < 0) { @@ -5099,7 +5098,7 @@ void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_a // Special case: '/' search pattern if (name == '/') { - set_last_search_pat(str, RE_SEARCH, true, true); + set_last_search_pat((char_u *)str, RE_SEARCH, true, true); return; } @@ -5107,14 +5106,14 @@ void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_a buf_T *buf; if (ascii_isdigit(*str)) { - int num = atoi((char *)str); + int num = atoi(str); buf = buflist_findnr(num); if (buf == NULL) { semsg(_(e_nobufnr), (int64_t)num); } } else { - buf = buflist_findnr(buflist_findpat((char *)str, (char *)str + STRLEN(str), + buf = buflist_findnr(buflist_findpat(str, str + STRLEN(str), true, false, false)); } if (buf == NULL) { @@ -5155,7 +5154,7 @@ void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_a if (!(reg = init_write_reg(name, &old_y_previous, must_append))) { return; } - str_to_reg(reg, yank_type, (char *)str, (size_t)len, block_len, false); + str_to_reg(reg, yank_type, str, (size_t)len, block_len, false); finish_write_reg(name, reg, old_y_previous); } @@ -5425,7 +5424,7 @@ void cursor_pos_info(dict_T *dict) len = (long)bd.textlen; break; case 'V': - s = ml_get(lnum); + s = (char_u *)ml_get(lnum); len = MAXCOL; break; case 'v': { @@ -5434,7 +5433,7 @@ void cursor_pos_info(dict_T *dict) colnr_T end_col = (lnum == max_pos.lnum) ? max_pos.col - start_col + 1 : MAXCOL; - s = ml_get(lnum) + start_col; + s = (char_u *)ml_get(lnum) + start_col; len = end_col; } break; @@ -5455,14 +5454,14 @@ void cursor_pos_info(dict_T *dict) word_count_cursor += word_count; char_count_cursor += char_count; byte_count_cursor = byte_count - + line_count_info(ml_get(lnum), &word_count_cursor, + + line_count_info((char_u *)ml_get(lnum), &word_count_cursor, &char_count_cursor, (varnumber_T)curwin->w_cursor.col + 1, eol_size); } } // Add to the running totals - byte_count += line_count_info(ml_get(lnum), &word_count, &char_count, + byte_count += line_count_info((char_u *)ml_get(lnum), &word_count, &char_count, (varnumber_T)MAXCOL, eol_size); } diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c index c0d5616666..158c22efaf 100644 --- a/src/nvim/os/fs.c +++ b/src/nvim/os/fs.c @@ -821,10 +821,10 @@ int os_fchown(int fd, uv_uid_t owner, uv_gid_t group) /// Check if a path exists. /// /// @return `true` if `path` exists -bool os_path_exists(const char_u *path) +bool os_path_exists(const char *path) { uv_stat_t statbuf; - return os_stat((char *)path, &statbuf) == kLibuvSuccess; + return os_stat(path, &statbuf) == kLibuvSuccess; } /// Sets file access and modification times. diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index 461a79c37b..35390e3dc1 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -503,7 +503,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in // Move the file names to allocated memory. for (j = 0, i = 0; i < *num_file; i++) { // Require the files to exist. Helps when using /bin/sh - if (!(flags & EW_NOTFOUND) && !os_path_exists((char_u *)(*file)[i])) { + if (!(flags & EW_NOTFOUND) && !os_path_exists((*file)[i])) { continue; } @@ -1112,7 +1112,7 @@ static void out_data_append_to_screen(char *output, size_t *count, bool eof) goto end; } - (void)msg_outtrans_len_attr((char_u *)p, i, 0); + (void)msg_outtrans_len_attr(p, i, 0); p += i; } } @@ -1208,7 +1208,7 @@ static void read_input(DynamicBuffer *buf) { size_t written = 0, l = 0, len = 0; linenr_T lnum = curbuf->b_op_start.lnum; - char_u *lp = ml_get(lnum); + char_u *lp = (char_u *)ml_get(lnum); for (;;) { l = strlen((char *)lp + written); @@ -1240,7 +1240,7 @@ static void read_input(DynamicBuffer *buf) if (lnum > curbuf->b_op_end.lnum) { break; } - lp = ml_get(lnum); + lp = (char_u *)ml_get(lnum); written = 0; } else if (len > 0) { written += len; diff --git a/src/nvim/path.c b/src/nvim/path.c index a5cec6772f..5bbcbc7144 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -755,8 +755,9 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, backslash_halve((char *)buf + len + 1); } // add existing file or symbolic link - if ((flags & EW_ALLLINKS) ? os_fileinfo_link((char *)buf, &file_info) - : os_path_exists(buf)) { + if ((flags & EW_ALLLINKS) + ? os_fileinfo_link((char *)buf, &file_info) + : os_path_exists((char *)buf)) { addfile(gap, buf, flags); } } @@ -1461,7 +1462,7 @@ void addfile(garray_T *gap, char_u *f, int flags) if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS) ? !os_fileinfo_link((char *)f, &file_info) - : !os_path_exists(f))) { + : !os_path_exists((char *)f))) { return; } @@ -1926,7 +1927,7 @@ void path_fix_case(char *name) while ((entry = (char *)os_scandir_next(&dir))) { // Only accept names that differ in case and are the same byte // length. TODO: accept different length name. - if (STRICMP(tail, entry) == 0 && STRLEN(tail) == STRLEN(entry)) { + if (STRICMP(tail, entry) == 0 && strlen(tail) == strlen(entry)) { char_u newname[MAXPATHL + 1]; // Verify the inode is equal. @@ -1951,7 +1952,7 @@ void path_fix_case(char *name) int after_pathsep(const char *b, const char *p) { return p > b && vim_ispathsep(p[-1]) - && utf_head_off((char_u *)b, (char_u *)p - 1) == 0; + && utf_head_off(b, p - 1) == 0; } /// Return true if file names "f1" and "f2" are in the same directory. @@ -2272,7 +2273,7 @@ int path_full_dir_name(char *directory, char *buffer, size_t len) int SUCCESS = 0; int retval = OK; - if (STRLEN(directory) == 0) { + if (strlen(directory) == 0) { return os_dirname((char_u *)buffer, len); } diff --git a/src/nvim/plines.c b/src/nvim/plines.c index cc730ba307..3ba09b45a1 100644 --- a/src/nvim/plines.c +++ b/src/nvim/plines.c @@ -149,7 +149,7 @@ int plines_win_col(win_T *wp, linenr_T lnum, long column) colnr_T col = 0; chartabsize_T cts; - init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + init_chartabsize_arg(&cts, wp, lnum, 0, (char *)line, (char *)line); while (*cts.cts_ptr != NUL && --column >= 0) { cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); MB_PTR_ADV(cts.cts_ptr); @@ -257,7 +257,7 @@ int linetabsize(char_u *s) int linetabsize_col(int startcol, char *s) { chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, 0, startcol, (char_u *)s, (char_u *)s); + init_chartabsize_arg(&cts, curwin, 0, startcol, s, s); while (*cts.cts_ptr != NUL) { cts.cts_vcol += lbr_chartabsize_adv(&cts); } @@ -275,7 +275,7 @@ int linetabsize_col(int startcol, char *s) unsigned int win_linetabsize(win_T *wp, linenr_T lnum, char_u *line, colnr_T len) { chartabsize_T cts; - init_chartabsize_arg(&cts, wp, lnum, 0, line, line); + init_chartabsize_arg(&cts, wp, lnum, 0, (char *)line, (char *)line); for (; *cts.cts_ptr != NUL && (len == MAXCOL || cts.cts_ptr < (char *)line + len); MB_PTR_ADV(cts.cts_ptr)) { cts.cts_vcol += win_lbr_chartabsize(&cts, NULL); @@ -288,14 +288,14 @@ unsigned int win_linetabsize(win_T *wp, linenr_T lnum, char_u *line, colnr_T len /// /// "line" is the start of the line, "ptr" is the first relevant character. /// When "lnum" is zero do not use text properties that insert text. -void init_chartabsize_arg(chartabsize_T *cts, win_T *wp, linenr_T lnum, colnr_T col, char_u *line, - char_u *ptr) +void init_chartabsize_arg(chartabsize_T *cts, win_T *wp, linenr_T lnum, colnr_T col, char *line, + char *ptr) { cts->cts_win = wp; cts->cts_lnum = lnum; cts->cts_vcol = col; - cts->cts_line = (char *)line; - cts->cts_ptr = (char *)ptr; + cts->cts_line = line; + cts->cts_ptr = ptr; cts->cts_cur_text_width = 0; // TODO(bfredl): actually lookup inline virtual text here cts->cts_has_virt_text = false; diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index f9c4892b91..f1fc48ef40 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -1250,7 +1250,7 @@ static int qf_parse_fmt_f(regmatch_T *rmp, int midx, qffields_T *fields, int pre // For separate filename patterns (%O, %P and %Q), the specified file // should exist. if (vim_strchr("OPQ", prefix) != NULL - && !os_path_exists((char_u *)fields->namebuf)) { + && !os_path_exists(fields->namebuf)) { return QF_FAIL; } @@ -1564,7 +1564,7 @@ static int qf_parse_dir_pfx(int idx, qffields_T *fields, qf_list_T *qfl) static int qf_parse_file_pfx(int idx, qffields_T *fields, qf_list_T *qfl, char *tail) { fields->valid = false; - if (*fields->namebuf == NUL || os_path_exists((char_u *)fields->namebuf)) { + if (*fields->namebuf == NUL || os_path_exists(fields->namebuf)) { if (*fields->namebuf && idx == 'P') { qfl->qf_currfile = qf_push_dir(fields->namebuf, &qfl->qf_file_stack, true); } else if (idx == 'Q') { @@ -2069,7 +2069,7 @@ static int qf_get_fnum(qf_list_T *qfl, char *directory, char *fname) // This should normally be true, but if make works without // "leaving directory"-messages we might have missed a // directory change. - if (!os_path_exists((char_u *)ptr)) { + if (!os_path_exists(ptr)) { xfree(ptr); directory = qf_guess_filepath(qfl, fname); if (directory) { @@ -2223,7 +2223,7 @@ static char *qf_guess_filepath(qf_list_T *qfl, char *filename) xfree(fullname); fullname = concat_fnames(ds_ptr->dirname, filename, true); - if (os_path_exists((char_u *)fullname)) { + if (os_path_exists(fullname)) { break; } @@ -3089,7 +3089,7 @@ static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel) qf_fmt_text((fname != NULL || qfp->qf_lnum != 0) ? skipwhite(qfp->qf_text) : qfp->qf_text, (char *)tbuf, (int)tbuflen); - msg_prt_line(tbuf, false); + msg_prt_line((char *)tbuf, false); if (tbuf != IObuff) { xfree(tbuf); @@ -5075,7 +5075,7 @@ static void vgr_init_regmatch(regmmatch_T *regmatch, char *s) static void vgr_display_fname(char *fname) { msg_start(); - char *p = (char *)msg_strtrunc((char_u *)fname, true); + char *p = msg_strtrunc(fname, true); if (p == NULL) { msg_outtrans(fname); } else { diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index a52343e28b..f471f1c8e0 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -1093,7 +1093,7 @@ void unref_extmatch(reg_extmatch_T *em) static int reg_prev_class(void) { if (rex.input > rex.line) { - return mb_get_class_tab(rex.input - 1 - utf_head_off(rex.line, rex.input - 1), + return mb_get_class_tab(rex.input - 1 - utf_head_off((char *)rex.line, (char *)rex.input - 1), rex.reg_buf->b_chartab); } return -1; diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c index 88f0d781af..b951df69d6 100644 --- a/src/nvim/regexp_bt.c +++ b/src/nvim/regexp_bt.c @@ -4765,8 +4765,8 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) reg_getline(rp->rs_un.regsave.rs_u.pos.lnum); rp->rs_un.regsave.rs_u.pos.col -= - utf_head_off(line, - line + rp->rs_un.regsave.rs_u.pos.col - 1) + utf_head_off((char *)line, + (char *)line + rp->rs_un.regsave.rs_u.pos.col - 1) + 1; } } else { diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c index d4db710d93..e1327ce155 100644 --- a/src/nvim/regexp_nfa.c +++ b/src/nvim/regexp_nfa.c @@ -5595,7 +5595,7 @@ static int recursive_regmatch(nfa_state_T *state, nfa_pim_T *pim, nfa_regprog_T } if ((int)(rex.input - rex.line) >= state->val) { rex.input -= state->val; - rex.input -= utf_head_off(rex.line, rex.input); + rex.input -= utf_head_off((char *)rex.line, (char *)rex.input); } else { rex.input = rex.line; } diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index e85167f8fd..a38f743081 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -1822,7 +1822,7 @@ static void cmd_source_buffer(const exarg_T *const eap) if (ga.ga_len > 400) { ga_set_growsize(&ga, MIN(ga.ga_len, 8000)); } - ga_concat(&ga, (char *)ml_get(curr_lnum)); + ga_concat(&ga, ml_get(curr_lnum)); ga_append(&ga, NL); } ((char *)ga.ga_data)[ga.ga_len - 1] = NUL; diff --git a/src/nvim/search.c b/src/nvim/search.c index e995081df8..d7f8d4e1cd 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -853,7 +853,7 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, pos->col--; if (pos->lnum <= buf->b_ml.ml_line_count) { ptr = ml_get_buf(buf, pos->lnum, false); - pos->col -= utf_head_off(ptr, ptr + pos->col); + pos->col -= utf_head_off((char *)ptr, (char *)ptr + pos->col); } } if (end_pos != NULL) { @@ -1250,7 +1250,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, memmove(msgbuf + STRLEN(p) + 1, off_buf, off_len); } - trunc = msg_strtrunc(msgbuf, true); + trunc = (char_u *)msg_strtrunc((char *)msgbuf, true); if (trunc != NULL) { xfree(msgbuf); msgbuf = trunc; @@ -1589,7 +1589,7 @@ int searchc(cmdarg_T *cap, int t_cmd) if (col == 0) { return FAIL; } - col -= utf_head_off(p, p + col - 1) + 1; + col -= utf_head_off((char *)p, (char *)p + col - 1) + 1; } if (lastc_bytelen == 1) { if (p[col] == c && stop) { @@ -1610,7 +1610,7 @@ int searchc(cmdarg_T *cap, int t_cmd) col += lastc_bytelen - 1; } else { // To previous char, which may be multi-byte. - col -= utf_head_off(p, p + col); + col -= utf_head_off((char *)p, (char *)p + col); } } curwin->w_cursor.col = col; @@ -1641,7 +1641,7 @@ static bool check_prevcol(char_u *linep, int col, int ch, int *prevcol) { col--; if (col > 0) { - col -= utf_head_off(linep, linep + col); + col -= utf_head_off((char *)linep, (char *)linep + col); } if (prevcol) { *prevcol = col; @@ -1664,7 +1664,7 @@ static bool find_rawstring_end(char_u *linep, pos_T *startpos, pos_T *endpos) char_u *delim_copy = vim_strnsave(linep + startpos->col + 1, delim_len); bool found = false; for (lnum = startpos->lnum; lnum <= endpos->lnum; lnum++) { - char_u *line = ml_get(lnum); + char_u *line = (char_u *)ml_get(lnum); for (p = line + (lnum == startpos->lnum ? startpos->col + 1 : 0); *p; p++) { if (lnum == endpos->lnum && (colnr_T)(p - line) >= endpos->col) { @@ -1768,7 +1768,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos = curwin->w_cursor; pos.coladd = 0; - char_u *linep = ml_get(pos.lnum); // pointer to current line + char_u *linep = (char_u *)ml_get(pos.lnum); // pointer to current line // vi compatible matching bool cpo_match = (vim_strchr(p_cpo, CPO_MATCH) != NULL); @@ -1923,7 +1923,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) break; } pos.lnum += hash_dir; - linep = ml_get(pos.lnum); + linep = (char_u *)ml_get(pos.lnum); line_breakcheck(); // check for CTRL-C typed ptr = (char_u *)skipwhite((char *)linep); if (*ptr != '#') { @@ -2003,7 +2003,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) break; } - linep = ml_get(pos.lnum); + linep = (char_u *)ml_get(pos.lnum); pos.col = (colnr_T)STRLEN(linep); // pos.col on trailing NUL do_quotes = -1; line_breakcheck(); @@ -2018,7 +2018,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } } else { pos.col--; - pos.col -= utf_head_off(linep, linep + pos.col); + pos.col -= utf_head_off((char *)linep, (char *)linep + pos.col); } } else { // forward search if (linep[pos.col] == NUL @@ -2038,7 +2038,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) break; } - linep = ml_get(pos.lnum); + linep = (char_u *)ml_get(pos.lnum); pos.col = 0; do_quotes = -1; line_breakcheck(); @@ -2088,7 +2088,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) match_pos = pos; match_pos.col--; } - linep = ml_get(pos.lnum); // may have been released + linep = (char_u *)ml_get(pos.lnum); // may have been released } } else if (linep[pos.col - 1] == '/' && linep[pos.col] == '*' @@ -2158,7 +2158,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } } if (pos.lnum > 1) { - ptr = ml_get(pos.lnum - 1); + ptr = (char_u *)ml_get(pos.lnum - 1); if (*ptr && *(ptr + STRLEN(ptr) - 1) == '\\') { do_quotes = 1; if (start_in_quotes == kNone) { @@ -2172,7 +2172,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } // ml_get() only keeps one line, need to get linep again - linep = ml_get(pos.lnum); + linep = (char_u *)ml_get(pos.lnum); } } } @@ -2648,7 +2648,7 @@ int linewhite(linenr_T lnum) { char_u *p; - p = (char_u *)skipwhite((char *)ml_get(lnum)); + p = (char_u *)skipwhite(ml_get(lnum)); return *p == NUL; } @@ -3488,7 +3488,7 @@ void f_matchfuzzypos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// mark. static char_u *get_line_and_copy(linenr_T lnum, char_u *buf) { - char_u *line = ml_get(lnum); + char_u *line = (char_u *)ml_get(lnum); STRLCPY(buf, line, LSIZE); return buf; } @@ -3625,7 +3625,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo msg_putchar('\n'); // cursor below last one */ if (!got_int) { // don't display if 'q' typed at "--more--" // message - msg_home_replace_hl(new_fname); + msg_home_replace_hl((char *)new_fname); msg_puts(_(" (includes previously listed match)")); prev_fname = NULL; } @@ -3655,7 +3655,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo for (i = 0; i < depth_displayed; i++) { msg_puts(" "); } - msg_home_replace(files[depth_displayed].name); + msg_home_replace((char *)files[depth_displayed].name); msg_puts(" -->\n"); } if (!got_int) { // don't display if 'q' typed @@ -3937,7 +3937,7 @@ search_line: } if (!got_int) { // don't display if 'q' typed // at "--more--" message - msg_home_replace_hl(curr_fname); + msg_home_replace_hl((char *)curr_fname); } prev_fname = curr_fname; } @@ -4146,7 +4146,7 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, msg_puts_attr((const char *)IObuff, HL_ATTR(HLF_N)); msg_puts(" "); } - msg_prt_line(line, false); + msg_prt_line((char *)line, false); ui_flush(); // show one line at a time // Definition continues until line that doesn't end with '\' @@ -4163,7 +4163,7 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, if (++*lnum > curbuf->b_ml.ml_line_count) { break; } - line = ml_get(*lnum); + line = (char_u *)ml_get(*lnum); } msg_putchar('\n'); } diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 1259736e0e..d8bc4b22c2 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -571,7 +571,7 @@ static void find_word(matchinf_T *mip, int mode) arridx = endidx[endidxcnt]; wlen = endlen[endidxcnt]; - if (utf_head_off(ptr, ptr + wlen) > 0) { + if (utf_head_off((char *)ptr, (char *)ptr + wlen) > 0) { continue; // not at first byte of character } if (spell_iswordp(ptr + wlen, mip->mi_win)) { @@ -2479,7 +2479,7 @@ bool check_need_cap(linenr_T lnum, colnr_T col) if (lnum == 1) { need_cap = true; } else { - line = ml_get(lnum - 1); + line = (char_u *)ml_get(lnum - 1); if (*skipwhite((char *)line) == NUL) { need_cap = true; } else { diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index 0f8034312e..c472cac27d 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -3197,7 +3197,7 @@ static int spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile) _("line %6d, word %6ld - %s"), lnum, spin->si_foldwcount + spin->si_keepwcount, w); msg_start(); - msg_outtrans_long_attr(message, 0); + msg_outtrans_long_attr((char *)message, 0); msg_clr_eos(); msg_didout = false; msg_col = 0; @@ -5339,7 +5339,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool } else { // Check for overwriting before doing things that may take a lot of // time. - if (!over_write && os_path_exists((char_u *)wfname)) { + if (!over_write && os_path_exists(wfname)) { emsg(_(e_exists)); goto theend; } @@ -5389,7 +5389,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool spin.si_region = 1 << i; vim_snprintf((char *)fname, MAXPATHL, "%s.aff", innames[i]); - if (os_path_exists(fname)) { + if (os_path_exists((char *)fname)) { // Read the .aff file. Will init "spin->si_conv" based on the // "SET" line. afile[i] = spell_read_aff(&spin, fname); @@ -5500,7 +5500,7 @@ static void spell_message(const spellinfo_T *spin, char *str) // ":[count]spellrare {word}" void ex_spell(exarg_T *eap) { - spell_add_word((char_u *)eap->arg, (int)STRLEN(eap->arg), + spell_add_word((char_u *)eap->arg, (int)strlen(eap->arg), eap->cmdidx == CMD_spellwrong ? SPELL_ADD_BAD : eap->cmdidx == CMD_spellrare ? SPELL_ADD_RARE : SPELL_ADD_GOOD, eap->forceit ? 0 : (int)eap->line2, @@ -5810,7 +5810,7 @@ static int write_spell_prefcond(FILE *fd, garray_T *gap, size_t *fwv) // : char *p = ((char **)gap->ga_data)[i]; if (p != NULL) { - size_t len = STRLEN(p); + size_t len = strlen(p); if (fd != NULL) { assert(len <= INT_MAX); fputc((int)len, fd); @@ -5873,7 +5873,7 @@ static void set_map_str(slang_T *lp, char_u *map) utf_char2bytes(headc, b + cl + 1); b[cl + 1 + headcl] = NUL; hash = hash_hash((char_u *)b); - hi = hash_lookup(&lp->sl_map_hash, (const char *)b, STRLEN(b), hash); + hi = hash_lookup(&lp->sl_map_hash, (const char *)b, strlen(b), hash); if (HASHITEM_EMPTY(hi)) { hash_add_item(&lp->sl_map_hash, hi, (char_u *)b, hash); } else { diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index f055cc9b0e..1319894226 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -610,7 +610,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) * Skip lines that end in a backslash. */ for (; start_lnum > 1; start_lnum--) { - line = ml_get(start_lnum - 1); + line = (char_u *)ml_get(start_lnum - 1); if (*line == NUL || *(line + STRLEN(line) - 1) != '\\') { break; } @@ -1711,7 +1711,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con const char_u *cur_pos = line + current_col; if (vim_iswordp_buf(cur_pos, syn_buf) && (current_col == 0 - || !vim_iswordp_buf(cur_pos - 1 - utf_head_off(line, cur_pos - 1), + || !vim_iswordp_buf(cur_pos - 1 - utf_head_off((char *)line, (char *)cur_pos - 1), syn_buf))) { syn_id = check_keyword_id(line, (int)current_col, &endcol, &flags, &next_list, cur_si, &cchar); diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 5270412382..4fd99b058b 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -742,7 +742,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char (int)(tagp.tagkind_end - tagp.tagkind)); } msg_advance(13); - msg_outtrans_len_attr(tagp.tagname, + msg_outtrans_len_attr((char *)tagp.tagname, (int)(tagp.tagname_end - tagp.tagname), HL_ATTR(HLF_T)); msg_putchar(' '); @@ -1230,7 +1230,7 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl continue; } - len += STRLEN(tv->vval.v_string) + 1; // Space for "\tVALUE" + len += strlen(tv->vval.v_string) + 1; // Space for "\tVALUE" if (!STRCMP(dict_key, "name")) { res_name = (char_u *)tv->vval.v_string; continue; @@ -1497,7 +1497,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc curbuf->b_help = false; } - orgpat.len = (int)STRLEN(pat); + orgpat.len = (int)strlen(pat); if (curbuf->b_help) { // When "@ab" is specified use only the "ab" language, otherwise // search all languages. @@ -1550,7 +1550,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc if ((flags & TAG_KEEP_LANG) && help_lang_find == NULL && curbuf->b_fname != NULL - && (i = (int)STRLEN(curbuf->b_fname)) > 4 + && (i = (int)strlen(curbuf->b_fname)) > 4 && STRICMP(curbuf->b_fname + i - 4, ".txt") == 0) { is_txt = true; } @@ -1595,7 +1595,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc if ((flags & TAG_KEEP_LANG) && help_lang_find == NULL && curbuf->b_fname != NULL - && (i = (int)STRLEN(curbuf->b_fname)) > 4 + && (i = (int)strlen(curbuf->b_fname)) > 4 && curbuf->b_fname[i - 1] == 'x' && curbuf->b_fname[i - 4] == '.' && STRNICMP(curbuf->b_fname + i - 3, help_lang, 2) == 0) { @@ -2174,7 +2174,7 @@ parse_line: hash = hash_hash((char_u *)mfp); } hi = hash_lookup(&ht_match[mtt], (const char *)mfp, - STRLEN(mfp), hash); + strlen(mfp), hash); if (HASHITEM_EMPTY(hi)) { hash_add_item(&ht_match[mtt], hi, (char_u *)mfp, hash); ga_grow(&ga_match[mtt], 1); @@ -2713,7 +2713,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) * file. Also accept a file name for which there is a matching BufReadCmd * autocommand event (e.g., http://sys/file). */ - if (!os_path_exists(fname) + if (!os_path_exists((char *)fname) && !has_autocmd(EVENT_BUFREADCMD, (char *)fname, NULL)) { retval = NOTAGFILE; @@ -3168,7 +3168,7 @@ static int add_tag_field(dict_T *dict, const char *field_name, const char *start char_u *buf = xmalloc(MAXPATHL); if (start != NULL) { if (end == NULL) { - end = start + STRLEN(start); + end = start + strlen(start); while (end > start && (end[-1] == '\r' || end[-1] == '\n')) { end--; } @@ -3180,7 +3180,7 @@ static int add_tag_field(dict_T *dict, const char *field_name, const char *start STRLCPY(buf, start, len + 1); } buf[len] = NUL; - retval = tv_dict_add_str(dict, field_name, STRLEN(field_name), + retval = tv_dict_add_str(dict, field_name, strlen(field_name), (const char *)buf); xfree(buf); return retval; diff --git a/src/nvim/textformat.c b/src/nvim/textformat.c index 125146f712..5ded0c9ab2 100644 --- a/src/nvim/textformat.c +++ b/src/nvim/textformat.c @@ -470,7 +470,7 @@ static int fmt_check_par(linenr_T lnum, int *leader_len, char_u **leader_flags, char_u *flags = NULL; // init for GCC char_u *ptr; - ptr = ml_get(lnum); + ptr = (char_u *)ml_get(lnum); if (do_comments) { *leader_len = get_leader_len((char *)ptr, (char **)leader_flags, false, true); } else { @@ -493,7 +493,7 @@ static int fmt_check_par(linenr_T lnum, int *leader_len, char_u **leader_flags, /// @return true if line "lnum" ends in a white character. static bool ends_in_white(linenr_T lnum) { - char_u *s = ml_get(lnum); + char_u *s = (char_u *)ml_get(lnum); size_t l; if (*s == NUL) { @@ -552,9 +552,9 @@ static bool same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, i // Get current line and next line, compare the leaders. // The first line has to be saved, only one line can be locked at a time. - line1 = vim_strsave(ml_get(lnum)); + line1 = vim_strsave((char_u *)ml_get(lnum)); for (idx1 = 0; ascii_iswhite(line1[idx1]); idx1++) {} - line2 = ml_get(lnum + 1); + line2 = (char_u *)ml_get(lnum + 1); for (idx2 = 0; idx2 < leader2_len; idx2++) { if (!ascii_iswhite(line2[idx2])) { if (line1[idx1++] != line2[idx2]) { @@ -586,7 +586,7 @@ static bool paragraph_start(linenr_T lnum) if (lnum <= 1) { return true; // start of the file } - p = ml_get(lnum - 1); + p = (char_u *)ml_get(lnum - 1); if (*p == NUL) { return true; // after empty line } diff --git a/src/nvim/textobject.c b/src/nvim/textobject.c index 02174edeb1..a8f4cc7aeb 100644 --- a/src/nvim/textobject.c +++ b/src/nvim/textobject.c @@ -213,13 +213,13 @@ bool findpar(bool *pincl, int dir, long count, int what, bool both) } curwin->w_cursor.lnum = curr; if (curr == curbuf->b_ml.ml_line_count && what != '}') { - char_u *line = ml_get(curr); + char_u *line = (char_u *)ml_get(curr); // Put the cursor on the last character in the last line and make the // motion inclusive. if ((curwin->w_cursor.col = (colnr_T)STRLEN(line)) != 0) { curwin->w_cursor.col--; - curwin->w_cursor.col -= utf_head_off(line, line + curwin->w_cursor.col); + curwin->w_cursor.col -= utf_head_off((char *)line, (char *)line + curwin->w_cursor.col); *pincl = true; } } else { @@ -260,7 +260,7 @@ bool startPS(linenr_T lnum, int para, bool both) { char_u *s; - s = ml_get(lnum); + s = (char_u *)ml_get(lnum); if (*s == para || *s == '\f' || (both && *s == '}')) { return true; } @@ -1467,7 +1467,7 @@ static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *e while (col_start > 0) { col_start--; - col_start -= utf_head_off(line, line + col_start); + col_start -= utf_head_off((char *)line, (char *)line + col_start); n = 0; if (escape != NULL) { while (col_start - n > 0 && vim_strchr((char *)escape, diff --git a/src/nvim/tui/terminfo.c b/src/nvim/tui/terminfo.c index ce48059b94..229e340dc3 100644 --- a/src/nvim/tui/terminfo.c +++ b/src/nvim/tui/terminfo.c @@ -189,7 +189,7 @@ void terminfo_info_msg(const unibi_term *const ut) msg_printf_attr(0, " %-25s %-10s = ", unibi_name_str(i), unibi_short_name_str(i)); // Most of these strings will contain escape sequences. - msg_outtrans_special((char_u *)s, false, 0); + msg_outtrans_special(s, false, 0); msg_putchar('\n'); } } @@ -216,7 +216,7 @@ void terminfo_info_msg(const unibi_term *const ut) msg_puts("Extended string capabilities:\n"); for (size_t i = 0; i < unibi_count_ext_str(ut); i++) { msg_printf_attr(0, " %-25s = ", unibi_get_ext_str_name(ut, i)); - msg_outtrans_special((char_u *)unibi_get_ext_str(ut, i), false, 0); + msg_outtrans_special(unibi_get_ext_str(ut, i), false, 0); msg_putchar('\n'); } } diff --git a/src/nvim/undo.c b/src/nvim/undo.c index 97a925f3ad..5f086df4e9 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -651,7 +651,7 @@ char *u_get_undo_file_name(const char *const buf_ffname, const bool reading) char fname_buf[MAXPATHL]; // Expand symlink in the file name, so that we put the undo file with the // actual file instead of with the symlink. - if (resolve_symlink((const char_u *)ffname, (char_u *)fname_buf) == OK) { + if (resolve_symlink(ffname, fname_buf) == OK) { ffname = fname_buf; } #endif @@ -713,7 +713,7 @@ char *u_get_undo_file_name(const char *const buf_ffname, const bool reading) // When reading check if the file exists. if (undo_file_name != NULL - && (!reading || os_path_exists((char_u *)undo_file_name))) { + && (!reading || os_path_exists(undo_file_name))) { break; } XFREE_CLEAR(undo_file_name); @@ -1177,7 +1177,7 @@ void u_write_undo(const char *const name, const bool forceit, buf_T *const buf, // If the undo file already exists, verify that it actually is an undo // file, and delete it. - if (os_path_exists((char_u *)file_name)) { + if (os_path_exists(file_name)) { if (name == NULL || !forceit) { // Check we can read it and it's an undo file. fd = os_open(file_name, O_RDONLY, 0); diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index 5b2101587f..9cc9fb5588 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -531,7 +531,7 @@ static void uc_list(char *name, size_t name_len) } } - msg_outtrans_special((char_u *)cmd->uc_rep, false, + msg_outtrans_special(cmd->uc_rep, false, name_len == 0 ? Columns - 47 : 0); if (p_verbose > 0) { last_set_msg(cmd->uc_script_ctx); diff --git a/src/nvim/window.c b/src/nvim/window.c index 74ea1172ee..c11484d1b8 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -6578,7 +6578,7 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u * Go one char back to ":" before "//" even when ':' is not in 'isfname'. */ while ((char_u *)ptr > line) { - if ((len = (size_t)(utf_head_off(line, (char_u *)ptr - 1))) > 0) { + if ((len = (size_t)(utf_head_off((char *)line, ptr - 1))) > 0) { ptr -= len + 1; } else if (vim_isfilec(ptr[-1]) || ((options & FNAME_HYP) && path_is_url(ptr - 1))) { ptr--; -- cgit From 933c80e8f9d7ff4ab634c14d370440702c7c8ed7 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 31 Aug 2022 21:14:14 +0800 Subject: refactor(mappings)!: mapblock_fill_dict() use API Dictionary (#20020) This introduces the following breaking changes: - nvim_get_keymap now always returns a LuaRef object as "callback" for a Lua mapping regardless of how it is called. The LuaRef object can be called from Lua and Vim script, but is lost over RPC. - maparg() now returns a Funcref instead of a ref number as "callback" for a Lua mapping. The Funcref can be called from Lua and Vim script, but is lost over RPC. This may also make nvim_get_keymap faster, but make maparg() slower. --- src/nvim/api/buffer.c | 4 +- src/nvim/api/vim.c | 4 +- src/nvim/mapping.c | 87 ++++++++++++++++--------------------- test/functional/api/keymap_spec.lua | 42 +++++++++++++----- 4 files changed, 71 insertions(+), 66 deletions(-) diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c index 199650fc55..16f574f46d 100644 --- a/src/nvim/api/buffer.c +++ b/src/nvim/api/buffer.c @@ -945,7 +945,7 @@ Integer nvim_buf_get_changedtick(Buffer buffer, Error *err) /// @param[out] err Error details, if any /// @returns Array of |maparg()|-like dictionaries describing mappings. /// The "buffer" key holds the associated buffer handle. -ArrayOf(Dictionary) nvim_buf_get_keymap(uint64_t channel_id, Buffer buffer, String mode, Error *err) +ArrayOf(Dictionary) nvim_buf_get_keymap(Buffer buffer, String mode, Error *err) FUNC_API_SINCE(3) { buf_T *buf = find_buffer_by_handle(buffer, err); @@ -954,7 +954,7 @@ ArrayOf(Dictionary) nvim_buf_get_keymap(uint64_t channel_id, Buffer buffer, Stri return (Array)ARRAY_DICT_INIT; } - return keymap_array(mode, buf, channel_id == LUA_INTERNAL_CALL); + return keymap_array(mode, buf); } /// Sets a buffer-local |mapping| for the given mode. diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index a1721d433f..9e1f2dd631 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -1421,10 +1421,10 @@ Dictionary nvim_get_mode(void) /// @param mode Mode short-name ("n", "i", "v", ...) /// @returns Array of |maparg()|-like dictionaries describing mappings. /// The "buffer" key is always zero. -ArrayOf(Dictionary) nvim_get_keymap(uint64_t channel_id, String mode) +ArrayOf(Dictionary) nvim_get_keymap(String mode) FUNC_API_SINCE(3) { - return keymap_array(mode, NULL, channel_id == LUA_INTERNAL_CALL); + return keymap_array(mode, NULL); } /// Sets a global |mapping| for the given mode. diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 333fb847f6..caa040e79b 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -1989,16 +1989,18 @@ void f_hasmapto(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } } -/// Fill a dictionary with all applicable maparg() like dictionaries +/// Fill a Dictionary with all applicable maparg() like dictionaries /// -/// @param dict The dictionary to be filled /// @param mp The maphash that contains the mapping information /// @param buffer_value The "buffer" value /// @param compatible True for compatible with old maparg() dict -static void mapblock_fill_dict(dict_T *const dict, const mapblock_T *const mp, - const char *lhsrawalt, long buffer_value, bool compatible) - FUNC_ATTR_NONNULL_ARG(1, 2) +/// +/// @return A Dictionary. +static Dictionary mapblock_fill_dict(const mapblock_T *const mp, const char *lhsrawalt, + const long buffer_value, const bool compatible) + FUNC_ATTR_NONNULL_ARG(1) { + Dictionary dict = ARRAY_DICT_INIT; char *const lhs = str2special_save((const char *)mp->m_keys, compatible, !compatible); char *const mapmode = map_mode_to_chars(mp->m_mode); @@ -2015,37 +2017,35 @@ static void mapblock_fill_dict(dict_T *const dict, const mapblock_T *const mp, } if (mp->m_luaref != LUA_NOREF) { - tv_dict_add_nr(dict, S_LEN("callback"), mp->m_luaref); + PUT(dict, "callback", LUAREF_OBJ(api_new_luaref(mp->m_luaref))); } else { - if (compatible) { - tv_dict_add_str(dict, S_LEN("rhs"), (const char *)mp->m_orig_str); - } else { - tv_dict_add_allocated_str(dict, S_LEN("rhs"), - str2special_save((const char *)mp->m_str, false, - true)); - } + PUT(dict, "rhs", STRING_OBJ(compatible + ? cstr_to_string(mp->m_orig_str) + : cstr_as_string(str2special_save(mp->m_str, false, true)))); } if (mp->m_desc != NULL) { - tv_dict_add_allocated_str(dict, S_LEN("desc"), xstrdup(mp->m_desc)); + PUT(dict, "desc", STRING_OBJ(cstr_to_string(mp->m_desc))); } - tv_dict_add_allocated_str(dict, S_LEN("lhs"), lhs); - tv_dict_add_str(dict, S_LEN("lhsraw"), (const char *)mp->m_keys); + PUT(dict, "lhs", STRING_OBJ(cstr_as_string(lhs))); + PUT(dict, "lhsraw", STRING_OBJ(cstr_to_string((const char *)mp->m_keys))); if (lhsrawalt != NULL) { // Also add the value for the simplified entry. - tv_dict_add_str(dict, S_LEN("lhsrawalt"), lhsrawalt); - } - tv_dict_add_nr(dict, S_LEN("noremap"), noremap_value); - tv_dict_add_nr(dict, S_LEN("script"), mp->m_noremap == REMAP_SCRIPT ? 1 : 0); - tv_dict_add_nr(dict, S_LEN("expr"), mp->m_expr ? 1 : 0); - tv_dict_add_nr(dict, S_LEN("silent"), mp->m_silent ? 1 : 0); - tv_dict_add_nr(dict, S_LEN("sid"), (varnumber_T)mp->m_script_ctx.sc_sid); - tv_dict_add_nr(dict, S_LEN("lnum"), (varnumber_T)mp->m_script_ctx.sc_lnum); - tv_dict_add_nr(dict, S_LEN("buffer"), (varnumber_T)buffer_value); - tv_dict_add_nr(dict, S_LEN("nowait"), mp->m_nowait ? 1 : 0); + PUT(dict, "lhsrawalt", STRING_OBJ(cstr_to_string(lhsrawalt))); + } + PUT(dict, "noremap", INTEGER_OBJ(noremap_value)); + PUT(dict, "script", INTEGER_OBJ(mp->m_noremap == REMAP_SCRIPT ? 1 : 0)); + PUT(dict, "expr", INTEGER_OBJ(mp->m_expr ? 1 : 0)); + PUT(dict, "silent", INTEGER_OBJ(mp->m_silent ? 1 : 0)); + PUT(dict, "sid", INTEGER_OBJ((varnumber_T)mp->m_script_ctx.sc_sid)); + PUT(dict, "lnum", INTEGER_OBJ((varnumber_T)mp->m_script_ctx.sc_lnum)); + PUT(dict, "buffer", INTEGER_OBJ((varnumber_T)buffer_value)); + PUT(dict, "nowait", INTEGER_OBJ(mp->m_nowait ? 1 : 0)); if (mp->m_replace_keycodes) { - tv_dict_add_nr(dict, S_LEN("replace_keycodes"), 1); + PUT(dict, "replace_keycodes", INTEGER_OBJ(1)); } - tv_dict_add_allocated_str(dict, S_LEN("mode"), mapmode); + PUT(dict, "mode", STRING_OBJ(cstr_as_string(mapmode))); + + return dict; } static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) @@ -2114,11 +2114,14 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) rettv->vval.v_string = nlua_funcref_str(mp->m_luaref); } } else { + // Return a dictionary. tv_dict_alloc_ret(rettv); if (mp != NULL && (rhs != NULL || rhs_lua != LUA_NOREF)) { - // Return a dictionary. - mapblock_fill_dict(rettv->vval.v_dict, mp, did_simplify ? (char *)keys_simplified : NULL, - buffer_local, true); + Dictionary dict = mapblock_fill_dict(mp, + did_simplify ? (char *)keys_simplified : NULL, + buffer_local, true); + (void)object_to_vim(DICTIONARY_OBJ(dict), rettv, NULL); + api_free_dictionary(dict); } } @@ -2599,12 +2602,10 @@ fail_and_free: /// /// @param mode The abbreviation for the mode /// @param buf The buffer to get the mapping array. NULL for global -/// @param from_lua Whether it is called from internal Lua api. /// @returns Array of maparg()-like dictionaries describing mappings -ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf, bool from_lua) +ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf) { Array mappings = ARRAY_DICT_INIT; - dict_T *const dict = tv_dict_alloc(); // Convert the string mode to the integer mode // that is stored within each mapblock @@ -2623,25 +2624,11 @@ ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf, bool from_lua) } // Check for correct mode if (int_mode & current_maphash->m_mode) { - mapblock_fill_dict(dict, current_maphash, NULL, buffer_value, false); - Object api_dict = vim_to_object((typval_T[]) { { .v_type = VAR_DICT, - .vval.v_dict = dict } }); - if (from_lua) { - Dictionary d = api_dict.data.dictionary; - for (size_t j = 0; j < d.size; j++) { - if (strequal("callback", d.items[j].key.data)) { - d.items[j].value.type = kObjectTypeLuaRef; - d.items[j].value.data.luaref = api_new_luaref((LuaRef)d.items[j].value.data.integer); - break; - } - } - } - ADD(mappings, api_dict); - tv_dict_clear(dict); + ADD(mappings, + DICTIONARY_OBJ(mapblock_fill_dict(current_maphash, NULL, buffer_value, false))); } } } - tv_dict_free(dict); return mappings; } diff --git a/test/functional/api/keymap_spec.lua b/test/functional/api/keymap_spec.lua index a93a4544ff..fedcbfa76a 100644 --- a/test/functional/api/keymap_spec.lua +++ b/test/functional/api/keymap_spec.lua @@ -6,6 +6,7 @@ local command = helpers.command local curbufmeths = helpers.curbufmeths local eq, neq = helpers.eq, helpers.neq local exec_lua = helpers.exec_lua +local exec = helpers.exec local feed = helpers.feed local funcs = helpers.funcs local meths = helpers.meths @@ -336,21 +337,26 @@ describe('nvim_get_keymap', function() end) it('can handle lua mappings', function() - eq(0, exec_lua [[ + eq(0, exec_lua([[ GlobalCount = 0 - vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end }) + vim.api.nvim_set_keymap('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end }) return GlobalCount - ]]) + ]])) feed('asdf\n') - eq(1, exec_lua[[return GlobalCount]]) + eq(1, exec_lua([[return GlobalCount]])) - eq(2, exec_lua[[ + eq(2, exec_lua([[ vim.api.nvim_get_keymap('n')[1].callback() return GlobalCount + ]])) + + exec([[ + call nvim_get_keymap('n')[0].callback() ]]) + eq(3, exec_lua([[return GlobalCount]])) + local mapargs = meths.get_keymap('n') - assert(type(mapargs[1].callback) == 'number', 'callback is not luaref number') mapargs[1].callback = nil eq({ lhs='asdf', @@ -834,17 +840,29 @@ describe('nvim_set_keymap, nvim_del_keymap', function() end) it ('maparg() returns lua mapping correctly', function() - exec_lua [[ - vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() print('jkl;') end }) - ]] - assert.truthy(string.match(funcs.maparg('asdf', 'n'), - "^")) + eq(0, exec_lua([[ + GlobalCount = 0 + vim.api.nvim_set_keymap('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end }) + return GlobalCount + ]])) + + assert.truthy(string.match(funcs.maparg('asdf', 'n'), "^")) + local mapargs = funcs.maparg('asdf', 'n', false, true) - assert(type(mapargs.callback) == 'number', 'callback is not luaref number') mapargs.callback = nil mapargs.lhsraw = nil mapargs.lhsrawalt = nil eq(generate_mapargs('n', 'asdf', nil, {sid=sid_lua}), mapargs) + + eq(1, exec_lua([[ + vim.fn.maparg('asdf', 'n', false, true).callback() + return GlobalCount + ]])) + + exec([[ + call maparg('asdf', 'n', v:false, v:true).callback() + ]]) + eq(2, exec_lua([[return GlobalCount]])) end) it('can make lua expr mappings replacing keycodes', function() -- cgit From f31db30975479cb6b57247f124a65f4362f80bfe Mon Sep 17 00:00:00 2001 From: bfredl Date: Thu, 30 Jun 2022 13:26:31 +0600 Subject: feat(lua): vim.ui_attach to get ui events from lua Co-authored-by: Famiu Haque --- runtime/doc/lua.txt | 31 +++++++++ src/nvim/api/extmark.c | 2 +- src/nvim/api/ui.c | 1 + src/nvim/api/ui_events.in.h | 4 +- src/nvim/buffer_updates.c | 8 +-- src/nvim/eval.c | 9 +-- src/nvim/generators/gen_api_ui_events.lua | 2 + src/nvim/lua/executor.c | 89 +++++++++++++++++++++++-- src/nvim/map.c | 1 + src/nvim/map.h | 1 + src/nvim/memory.c | 2 + src/nvim/ui.c | 7 +- src/nvim/ui.h | 5 ++ src/nvim/ui_compositor.c | 87 +++++++++++++++++++++++- test/functional/lua/ui_event_spec.lua | 107 ++++++++++++++++++++++++++++++ 15 files changed, 334 insertions(+), 22 deletions(-) create mode 100644 test/functional/lua/ui_event_spec.lua diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 499b3f9a6f..a634cc1e93 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -967,6 +967,37 @@ vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()* end < +vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* + Attach to ui events, similar to |nvim_ui_attach()| but receive events + as lua callback. Can be used to implement screen elements like + popupmenu or message handling in lua. + + {options} should be a dictionary-like table, where `ext_...` options should + be set to true to receive events for the respective external element. + + {callback} receives event name plus additional parameters. See |ui-popupmenu| + and the sections below for event format for respective events. + + Example (stub for a |ui-popupmenu| implementation): > + + ns = vim.api.nvim_create_namespace('my_fancy_pum') + + vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...) + if event == "popupmenu_show" then + local items, selected, row, col, grid = ... + print("display pum ", #items) + elseif event == "popupmenu_select" then + local selected = ... + print("selected", selected) + elseif event == "popupmenu_hide" then + print("FIN") + end + end) + +vim.ui_detach({ns}) *vim.ui_detach()* + Detach a callback previously attached with |vim.ui_attach()| for the + given namespace {ns}. + vim.type_idx *vim.type_idx* Type index for use in |lua-special-tbl|. Specifying one of the values from |vim.types| allows typing the empty table (it is unclear whether empty Lua diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index 09b004637f..6ff0a2ed21 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -87,7 +87,7 @@ const char *describe_ns(NS ns_id) } // Is the Namespace in use? -static bool ns_initialized(uint32_t ns) +bool ns_initialized(uint32_t ns) { if (ns < 1) { return false; diff --git a/src/nvim/api/ui.c b/src/nvim/api/ui.c index e34dcbdb46..654eb19bec 100644 --- a/src/nvim/api/ui.c +++ b/src/nvim/api/ui.c @@ -223,6 +223,7 @@ void nvim_ui_attach(uint64_t channel_id, Integer width, Integer height, Dictiona ui->msg_set_pos = remote_ui_msg_set_pos; ui->event = remote_ui_event; ui->inspect = remote_ui_inspect; + ui->win_viewport = remote_ui_win_viewport; CLEAR_FIELD(ui->ui_ext); diff --git a/src/nvim/api/ui_events.in.h b/src/nvim/api/ui_events.in.h index 8b7e01e1c3..17930dca85 100644 --- a/src/nvim/api/ui_events.in.h +++ b/src/nvim/api/ui_events.in.h @@ -100,7 +100,7 @@ void raw_line(Integer grid, Integer row, Integer startcol, FUNC_API_NOEXPORT FUNC_API_COMPOSITOR_IMPL; void event(char *name, Array args) - FUNC_API_NOEXPORT; + FUNC_API_NOEXPORT FUNC_API_COMPOSITOR_IMPL; void win_pos(Integer grid, Window win, Integer startrow, Integer startcol, Integer width, Integer height) @@ -121,7 +121,7 @@ void msg_set_pos(Integer grid, Integer row, Boolean scrolled, String sep_char) void win_viewport(Integer grid, Window win, Integer topline, Integer botline, Integer curline, Integer curcol, Integer line_count) - FUNC_API_SINCE(7) FUNC_API_REMOTE_ONLY; + FUNC_API_SINCE(7) FUNC_API_BRIDGE_IMPL; void win_extmark(Integer grid, Window win, Integer ns_id, Integer mark_id, Integer row, Integer col) diff --git a/src/nvim/buffer_updates.c b/src/nvim/buffer_updates.c index 14973502ab..1b3c0bc28f 100644 --- a/src/nvim/buffer_updates.c +++ b/src/nvim/buffer_updates.c @@ -285,14 +285,13 @@ void buf_updates_send_changes(buf_T *buf, linenr_T firstline, int64_t num_added, args.items[7] = INTEGER_OBJ((Integer)deleted_codeunits); } textlock++; - Object res = nlua_call_ref(cb.on_lines, "lines", args, true, NULL); + Object res = nlua_call_ref(cb.on_lines, "lines", args, false, NULL); textlock--; if (res.type == kObjectTypeBoolean && res.data.boolean == true) { buffer_update_callbacks_free(cb); keep = false; } - api_free_object(res); } if (keep) { kv_A(buf->update_callbacks, j++) = kv_A(buf->update_callbacks, i); @@ -335,7 +334,7 @@ void buf_updates_send_splice(buf_T *buf, int start_row, colnr_T start_col, bcoun ADD_C(args, INTEGER_OBJ(new_byte)); textlock++; - Object res = nlua_call_ref(cb.on_bytes, "bytes", args, true, NULL); + Object res = nlua_call_ref(cb.on_bytes, "bytes", args, false, NULL); textlock--; if (res.type == kObjectTypeBoolean && res.data.boolean == true) { @@ -371,14 +370,13 @@ void buf_updates_changedtick(buf_T *buf) textlock++; Object res = nlua_call_ref(cb.on_changedtick, "changedtick", - args, true, NULL); + args, false, NULL); textlock--; if (res.type == kObjectTypeBoolean && res.data.boolean == true) { buffer_update_callbacks_free(cb); keep = false; } - api_free_object(res); } if (keep) { kv_A(buf->update_callbacks, j++) = kv_A(buf->update_callbacks, i); diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 2dbaa2f8ac..92082772e1 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -5858,13 +5858,8 @@ bool callback_call(Callback *const callback, const int argcount_in, typval_T *co break; case kCallbackLua: - rv = nlua_call_ref(callback->data.luaref, NULL, args, true, NULL); - switch (rv.type) { - case kObjectTypeBoolean: - return rv.data.boolean; - default: - return false; - } + rv = nlua_call_ref(callback->data.luaref, NULL, args, false, NULL); + return (rv.type == kObjectTypeBoolean && rv.data.boolean == true); case kCallbackNone: return false; diff --git a/src/nvim/generators/gen_api_ui_events.lua b/src/nvim/generators/gen_api_ui_events.lua index f9e888c20d..ea66be7ee8 100755 --- a/src/nvim/generators/gen_api_ui_events.lua +++ b/src/nvim/generators/gen_api_ui_events.lua @@ -75,6 +75,8 @@ local function call_ui_event_method(output, ev) hlattrs_args_count = hlattrs_args_count + 1 elseif kind == 'Object' then output:write('args.items['..(j-1)..'];\n') + elseif kind == 'Window' then + output:write('(Window)args.items['..(j-1)..'].data.integer;\n') else output:write('args.items['..(j-1)..'].data.'..string.lower(kind)..';\n') end diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 42aa13cfc1..f144e47c3a 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -7,6 +7,7 @@ #include #include "luv/luv.h" +#include "nvim/api/extmark.h" #include "nvim/api/private/defs.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" @@ -40,6 +41,9 @@ #include "nvim/os/os.h" #include "nvim/profile.h" #include "nvim/runtime.h" +#include "nvim/screen.h" +#include "nvim/ui.h" +#include "nvim/ui_compositor.h" #include "nvim/undo.h" #include "nvim/usercmd.h" #include "nvim/version.h" @@ -589,6 +593,71 @@ static bool nlua_init_packages(lua_State *lstate) return true; } +/// "vim.ui_attach(ns_id, {ext_foo=true}, cb)" function +static int nlua_ui_attach(lua_State *lstate) + FUNC_ATTR_NONNULL_ALL +{ + uint32_t ns_id = (uint32_t)luaL_checkinteger(lstate, 1); + + if (!ns_initialized(ns_id)) { + return luaL_error(lstate, "invalid ns_id"); + } + if (!lua_istable(lstate, 2)) { + return luaL_error(lstate, "ext_widgets must be a table"); + } + if (!lua_isfunction(lstate, 3)) { + return luaL_error(lstate, "callback must be a Lua function"); + } + + bool ext_widgets[kUIGlobalCount] = { false }; + bool tbl_has_true_val = false; + + lua_pushvalue(lstate, 2); + lua_pushnil(lstate); + while (lua_next(lstate, -2)) { + // [dict, key, val] + size_t len; + const char *s = lua_tolstring(lstate, -2, &len); + bool val = lua_toboolean(lstate, -1); + + for (size_t i = 0; i < kUIGlobalCount; i++) { + if (strequal(s, ui_ext_names[i])) { + if (val) { + tbl_has_true_val = true; + } + ext_widgets[i] = val; + goto ok; + } + } + + return luaL_error(lstate, "Unexpected key: %s", s); +ok: + lua_pop(lstate, 1); + } + + if (!tbl_has_true_val) { + return luaL_error(lstate, "ext_widgets table must contain at least one 'true' value"); + } + + LuaRef ui_event_cb = nlua_ref_global(lstate, 3); + ui_comp_add_cb(ns_id, ui_event_cb, ext_widgets); + return 0; +} + +/// "vim.ui_detach(ns_id)" function +static int nlua_ui_detach(lua_State *lstate) + FUNC_ATTR_NONNULL_ALL +{ + uint32_t ns_id = (uint32_t)luaL_checkinteger(lstate, 1); + + if (!ns_initialized(ns_id)) { + return luaL_error(lstate, "invalid ns_id"); + } + + ui_comp_remove_cb(ns_id); + return 0; +} + /// Initialize lua interpreter state /// /// Called by lua interpreter itself to initialize state. @@ -649,6 +718,14 @@ static bool nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL lua_pushcfunction(lstate, &nlua_wait); lua_setfield(lstate, -2, "wait"); + // ui_attach + lua_pushcfunction(lstate, &nlua_ui_attach); + lua_setfield(lstate, -2, "ui_attach"); + + // ui_detach + lua_pushcfunction(lstate, &nlua_ui_detach); + lua_setfield(lstate, -2, "ui_detach"); + nlua_common_vim_init(lstate, false); // patch require() (only for --startuptime) @@ -1422,9 +1499,10 @@ bool nlua_ref_is_function(LuaRef ref) /// @param name if non-NULL, sent to callback as first arg /// if NULL, only args are used /// @param retval if true, convert return value to Object -/// if false, discard return value +/// if false, only check if return value is truthy /// @param err Error details, if any (if NULL, errors are echoed) -/// @return Return value of function, if retval was set. Otherwise NIL. +/// @return Return value of function, if retval was set. Otherwise +/// BOOLEAN_OBJ(true) or NIL. Object nlua_call_ref(LuaRef ref, const char *name, Array args, bool retval, Error *err) { lua_State *const lstate = global_lstate; @@ -1438,7 +1516,7 @@ Object nlua_call_ref(LuaRef ref, const char *name, Array args, bool retval, Erro nlua_push_Object(lstate, args.items[i], false); } - if (nlua_pcall(lstate, nargs, retval ? 1 : 0)) { + if (nlua_pcall(lstate, nargs, 1)) { // if err is passed, the caller will deal with the error. if (err) { size_t len; @@ -1458,7 +1536,10 @@ Object nlua_call_ref(LuaRef ref, const char *name, Array args, bool retval, Erro } return nlua_pop_Object(lstate, false, err); } else { - return NIL; + bool value = lua_toboolean(lstate, -1); + lua_pop(lstate, 1); + + return value ? BOOLEAN_OBJ(true) : NIL; } } diff --git a/src/nvim/map.c b/src/nvim/map.c index d3058a5d52..1561b089a7 100644 --- a/src/nvim/map.c +++ b/src/nvim/map.c @@ -168,6 +168,7 @@ MAP_IMPL(int, cstr_t, DEFAULT_INITIALIZER) MAP_IMPL(cstr_t, ptr_t, DEFAULT_INITIALIZER) MAP_IMPL(cstr_t, int, DEFAULT_INITIALIZER) MAP_IMPL(ptr_t, ptr_t, DEFAULT_INITIALIZER) +MAP_IMPL(uint32_t, ptr_t, DEFAULT_INITIALIZER) MAP_IMPL(uint64_t, ptr_t, DEFAULT_INITIALIZER) MAP_IMPL(uint64_t, ssize_t, SSIZE_INITIALIZER) MAP_IMPL(uint64_t, uint64_t, DEFAULT_INITIALIZER) diff --git a/src/nvim/map.h b/src/nvim/map.h index 845daac3f7..f5f30f5a85 100644 --- a/src/nvim/map.h +++ b/src/nvim/map.h @@ -39,6 +39,7 @@ MAP_DECLS(int, cstr_t) MAP_DECLS(cstr_t, ptr_t) MAP_DECLS(cstr_t, int) MAP_DECLS(ptr_t, ptr_t) +MAP_DECLS(uint32_t, ptr_t) MAP_DECLS(uint64_t, ptr_t) MAP_DECLS(uint64_t, ssize_t) MAP_DECLS(uint64_t, uint64_t) diff --git a/src/nvim/memory.c b/src/nvim/memory.c index a9785fcb7c..acd2478c81 100644 --- a/src/nvim/memory.c +++ b/src/nvim/memory.c @@ -23,6 +23,7 @@ #include "nvim/message.h" #include "nvim/sign.h" #include "nvim/ui.h" +#include "nvim/ui_compositor.h" #include "nvim/vim.h" #ifdef UNIT_TESTING @@ -824,6 +825,7 @@ void free_all_mem(void) nlua_free_all_mem(); ui_free_all_mem(); + ui_comp_free_all_mem(); // should be last, in case earlier free functions deallocates arenas arena_free_reuse_blks(); diff --git a/src/nvim/ui.c b/src/nvim/ui.c index 46f4d137c4..06be5676c7 100644 --- a/src/nvim/ui.c +++ b/src/nvim/ui.c @@ -198,13 +198,16 @@ void ui_refresh(void) ext_widgets[i] = true; } + UI *compositor = uis[0]; + bool inclusive = ui_override(); - for (size_t i = 0; i < ui_count; i++) { + for (size_t i = 1; i < ui_count; i++) { UI *ui = uis[i]; width = MIN(ui->width, width); height = MIN(ui->height, height); for (UIExtension j = 0; (int)j < kUIExtCount; j++) { - ext_widgets[j] &= (ui->ui_ext[j] || inclusive); + bool in_compositor = ui->composed && compositor->ui_ext[j]; + ext_widgets[j] &= (ui->ui_ext[j] || in_compositor || inclusive); } } diff --git a/src/nvim/ui.h b/src/nvim/ui.h index 996b3467a6..9034e7b764 100644 --- a/src/nvim/ui.h +++ b/src/nvim/ui.h @@ -69,6 +69,11 @@ struct ui_t { void (*inspect)(UI *ui, Dictionary *info); }; +typedef struct ui_event_callback { + LuaRef cb; + bool ext_widgets[kUIGlobalCount]; +} UIEventCallback; + #ifdef INCLUDE_GENERATED_DECLARATIONS # include "ui.h.generated.h" diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c index 2216e25db9..5167f291c3 100644 --- a/src/nvim/ui_compositor.c +++ b/src/nvim/ui_compositor.c @@ -20,6 +20,7 @@ #include "nvim/log.h" #include "nvim/lua/executor.h" #include "nvim/main.h" +#include "nvim/map.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/os/os.h" @@ -54,6 +55,8 @@ static bool msg_was_scrolled = false; static int msg_sep_row = -1; static schar_T msg_sep_char = { ' ', NUL }; +static PMap(uint32_t) ui_event_cbs = MAP_INIT; + static int dbghl_normal, dbghl_clear, dbghl_composed, dbghl_recompose; void ui_comp_init(void) @@ -69,14 +72,18 @@ void ui_comp_init(void) compositor->grid_cursor_goto = ui_comp_grid_cursor_goto; compositor->raw_line = ui_comp_raw_line; compositor->msg_set_pos = ui_comp_msg_set_pos; + compositor->event = ui_comp_event; // Be unopinionated: will be attached together with a "real" ui anyway compositor->width = INT_MAX; compositor->height = INT_MAX; - for (UIExtension i = 0; (int)i < kUIExtCount; i++) { + for (UIExtension i = kUIGlobalCount; (int)i < kUIExtCount; i++) { compositor->ui_ext[i] = true; } + // TODO(bfredl): one day. in the future. + compositor->ui_ext[kUIMultigrid] = false; + // TODO(bfredl): this will be more complicated if we implement // hlstate per UI (i e reduce hl ids for non-hlstate UIs) compositor->ui_ext[kUIHlState] = false; @@ -87,6 +94,15 @@ void ui_comp_init(void) ui_attach_impl(compositor, 0); } +void ui_comp_free_all_mem(void) +{ + UIEventCallback *event_cb; + map_foreach_value(&ui_event_cbs, event_cb, { + xfree(event_cb); + }) + pmap_destroy(uint32_t)(&ui_event_cbs); +} + void ui_comp_syn_init(void) { dbghl_normal = syn_check_group(S_LEN("RedrawDebugNormal")); @@ -676,3 +692,72 @@ static void ui_comp_grid_resize(UI *ui, Integer grid, Integer width, Integer hei } } } + +static void ui_comp_event(UI *ui, char *name, Array args) +{ + Error err = ERROR_INIT; + UIEventCallback *event_cb; + bool handled = false; + + map_foreach_value(&ui_event_cbs, event_cb, { + Object res = nlua_call_ref(event_cb->cb, name, args, false, &err); + if (res.type == kObjectTypeBoolean && res.data.boolean == true) { + handled = true; + } + }) + + if (!handled) { + ui_composed_call_event(name, args); + } +} + +static void ui_comp_update_ext(void) +{ + memset(compositor->ui_ext, 0, ARRAY_SIZE(compositor->ui_ext)); + + for (size_t i = 0; i < kUIGlobalCount; i++) { + UIEventCallback *event_cb; + + map_foreach_value(&ui_event_cbs, event_cb, { + if (event_cb->ext_widgets[i]) { + compositor->ui_ext[i] = true; + break; + } + }) + } +} + +void free_ui_event_callback(UIEventCallback *event_cb) +{ + api_free_luaref(event_cb->cb); + xfree(event_cb); +} + +void ui_comp_add_cb(uint32_t ns_id, LuaRef cb, bool *ext_widgets) +{ + UIEventCallback *event_cb = xcalloc(1, sizeof(UIEventCallback)); + event_cb->cb = cb; + memcpy(event_cb->ext_widgets, ext_widgets, ARRAY_SIZE(event_cb->ext_widgets)); + if (event_cb->ext_widgets[kUIMessages]) { + event_cb->ext_widgets[kUICmdline] = true; + } + + UIEventCallback **item = (UIEventCallback **)pmap_ref(uint32_t)(&ui_event_cbs, ns_id, true); + if (*item) { + free_ui_event_callback(*item); + } + *item = event_cb; + + ui_comp_update_ext(); + ui_schedule_refresh(); +} + +void ui_comp_remove_cb(uint32_t ns_id) +{ + if (pmap_has(uint32_t)(&ui_event_cbs, ns_id)) { + free_ui_event_callback(pmap_get(uint32_t)(&ui_event_cbs, ns_id)); + pmap_del(uint32_t)(&ui_event_cbs, ns_id); + } + ui_comp_update_ext(); + ui_schedule_refresh(); +} diff --git a/test/functional/lua/ui_event_spec.lua b/test/functional/lua/ui_event_spec.lua new file mode 100644 index 0000000000..05322a0fdb --- /dev/null +++ b/test/functional/lua/ui_event_spec.lua @@ -0,0 +1,107 @@ +local helpers = require('test.functional.helpers')(after_each) +local Screen = require('test.functional.ui.screen') +local eq = helpers.eq +local exec_lua = helpers.exec_lua +local clear = helpers.clear +local feed = helpers.feed +local funcs = helpers.funcs +local inspect = require'vim.inspect' + +describe('vim.ui_attach', function() + local screen + before_each(function() + clear() + exec_lua [[ + ns = vim.api.nvim_create_namespace 'testspace' + events = {} + function on_event(event, ...) + events[#events+1] = {event, ...} + return true + end + + function get_events() + local ret_events = events + events = {} + return ret_events + end + ]] + + screen = Screen.new(40,5) + screen:set_default_attr_ids({ + [1] = {bold = true, foreground = Screen.colors.Blue1}; + [2] = {bold = true}; + [3] = {background = Screen.colors.Grey}; + [4] = {background = Screen.colors.LightMagenta}; + }) + screen:attach() + end) + + local function expect_events(expected) + local evs = exec_lua "return get_events(...)" + eq(expected, evs, inspect(evs)) + end + + it('can receive popupmenu events', function() + exec_lua [[ vim.ui_attach(ns, {ext_popupmenu=true}, on_event) ]] + feed('ifo') + screen:expect{grid=[[ + fo^ | + {1:~ }| + {1:~ }| + {1:~ }| + {2:-- INSERT --} | + ]]} + + funcs.complete(1, {'food', 'foobar', 'foo'}) + screen:expect{grid=[[ + food^ | + {1:~ }| + {1:~ }| + {1:~ }| + {2:-- INSERT --} | + ]]} + expect_events { + { "popupmenu_show", { { "food", "", "", "" }, { "foobar", "", "", "" }, { "foo", "", "", "" } }, 0, 0, 0, 1 }; + } + + feed '' + screen:expect{grid=[[ + foobar^ | + {1:~ }| + {1:~ }| + {1:~ }| + {2:-- INSERT --} | + ]]} + expect_events { + { "popupmenu_select", 1 }; + } + + feed '' + screen:expect{grid=[[ + foobar^ | + {1:~ }| + {1:~ }| + {1:~ }| + {2:-- INSERT --} | + ]], intermediate=true} + expect_events { + { "popupmenu_hide" }; + } + + -- ui_detach stops events, and reenables builtin pum + exec_lua [[ vim.ui_detach(ns) ]] + + funcs.complete(1, {'food', 'foobar', 'foo'}) + screen:expect{grid=[[ + food^ | + {3:food }{1: }| + {4:foobar }{1: }| + {4:foo }{1: }| + {2:-- INSERT --} | + ]]} + expect_events { + } + + + end) +end) -- cgit From ba8be7446d440053b24358046e8e4033e3447633 Mon Sep 17 00:00:00 2001 From: bfredl Date: Wed, 31 Aug 2022 14:49:15 +0200 Subject: refactor(highlight): make hlattrs2dict always use pre-allocated dict hlattrs2dict used to work with both allocated and unallocated dicts which was quite messy. Now always delegate allocation to caller. --- src/nvim/api/ui.c | 64 ++++++++++++++++++++++++---------------------- src/nvim/api/vim.c | 22 ++++++++-------- src/nvim/highlight.c | 30 ++++++++-------------- src/nvim/highlight.h | 2 ++ src/nvim/highlight_group.c | 16 +++++++----- 5 files changed, 66 insertions(+), 68 deletions(-) diff --git a/src/nvim/api/ui.c b/src/nvim/api/ui.c index e34dcbdb46..110bd6920e 100644 --- a/src/nvim/api/ui.c +++ b/src/nvim/api/ui.c @@ -748,10 +748,12 @@ static void remote_ui_hl_attr_define(UI *ui, Integer id, HlAttrs rgb_attrs, HlAt UIData *data = ui->data; Array args = data->call_buf; ADD_C(args, INTEGER_OBJ(id)); - MAXSIZE_TEMP_DICT(rgb, 16); - MAXSIZE_TEMP_DICT(cterm, 16); - ADD_C(args, DICTIONARY_OBJ(hlattrs2dict(&rgb, rgb_attrs, true))); - ADD_C(args, DICTIONARY_OBJ(hlattrs2dict(&cterm, cterm_attrs, false))); + MAXSIZE_TEMP_DICT(rgb, HLATTRS_DICT_SIZE); + MAXSIZE_TEMP_DICT(cterm, HLATTRS_DICT_SIZE); + hlattrs2dict(&rgb, rgb_attrs, true); + hlattrs2dict(&cterm, rgb_attrs, false); + ADD_C(args, DICTIONARY_OBJ(rgb)); + ADD_C(args, DICTIONARY_OBJ(cterm)); if (ui->ui_ext[kUIHlState]) { ADD_C(args, ARRAY_OBJ(info)); @@ -771,8 +773,9 @@ static void remote_ui_highlight_set(UI *ui, int id) return; } data->hl_id = id; - MAXSIZE_TEMP_DICT(dict, 16); - ADD_C(args, DICTIONARY_OBJ(hlattrs2dict(&dict, syn_attr2entry(id), ui->rgb))); + MAXSIZE_TEMP_DICT(dict, HLATTRS_DICT_SIZE); + hlattrs2dict(&dict, syn_attr2entry(id), ui->rgb); + ADD_C(args, DICTIONARY_OBJ(dict)); push_call(ui, "highlight_set", args); } @@ -952,65 +955,63 @@ static void remote_ui_flush(UI *ui) } } -static Array translate_contents(UI *ui, Array contents) +static Array translate_contents(UI *ui, Array contents, Arena *arena) { - Array new_contents = ARRAY_DICT_INIT; + Array new_contents = arena_array(arena, contents.size); for (size_t i = 0; i < contents.size; i++) { Array item = contents.items[i].data.array; - Array new_item = ARRAY_DICT_INIT; + Array new_item = arena_array(arena, 2); int attr = (int)item.items[0].data.integer; if (attr) { - Dictionary rgb_attrs = hlattrs2dict(NULL, syn_attr2entry(attr), ui->rgb); + Dictionary rgb_attrs = arena_dict(arena, HLATTRS_DICT_SIZE); + hlattrs2dict(&rgb_attrs, syn_attr2entry(attr), ui->rgb); ADD(new_item, DICTIONARY_OBJ(rgb_attrs)); } else { ADD(new_item, DICTIONARY_OBJ((Dictionary)ARRAY_DICT_INIT)); } - ADD(new_item, copy_object(item.items[1], NULL)); + ADD(new_item, item.items[1]); ADD(new_contents, ARRAY_OBJ(new_item)); } return new_contents; } -static Array translate_firstarg(UI *ui, Array args) +static Array translate_firstarg(UI *ui, Array args, Arena *arena) { - Array new_args = ARRAY_DICT_INIT; + Array new_args = arena_array(arena, args.size); Array contents = args.items[0].data.array; - ADD(new_args, ARRAY_OBJ(translate_contents(ui, contents))); + ADD_C(new_args, ARRAY_OBJ(translate_contents(ui, contents, arena))); for (size_t i = 1; i < args.size; i++) { - ADD(new_args, copy_object(args.items[i], NULL)); + ADD(new_args, args.items[i]); } return new_args; } static void remote_ui_event(UI *ui, char *name, Array args) { + Arena arena = ARENA_EMPTY; UIData *data = ui->data; if (!ui->ui_ext[kUILinegrid]) { // the representation of highlights in cmdline changed, translate back // never consumes args if (strequal(name, "cmdline_show")) { - Array new_args = translate_firstarg(ui, args); + Array new_args = translate_firstarg(ui, args, &arena); push_call(ui, name, new_args); - api_free_array(new_args); - return; + goto free_ret; } else if (strequal(name, "cmdline_block_show")) { Array new_args = data->call_buf; Array block = args.items[0].data.array; - Array new_block = ARRAY_DICT_INIT; + Array new_block = arena_array(&arena, block.size); for (size_t i = 0; i < block.size; i++) { - ADD(new_block, - ARRAY_OBJ(translate_contents(ui, block.items[i].data.array))); + ADD_C(new_block, ARRAY_OBJ(translate_contents(ui, block.items[i].data.array, &arena))); } ADD_C(new_args, ARRAY_OBJ(new_block)); push_call(ui, name, new_args); - api_free_array(new_block); - return; + goto free_ret; } else if (strequal(name, "cmdline_block_append")) { - Array new_args = translate_firstarg(ui, args); + Array new_args = translate_firstarg(ui, args, &arena); push_call(ui, name, new_args); - api_free_array(new_args); - return; + goto free_ret; } } @@ -1022,19 +1023,18 @@ static void remote_ui_event(UI *ui, char *name, Array args) if (data->wildmenu_active) { Array new_args = data->call_buf; Array items = args.items[0].data.array; - Array new_items = ARRAY_DICT_INIT; + Array new_items = arena_array(&arena, items.size); for (size_t i = 0; i < items.size; i++) { - ADD(new_items, copy_object(items.items[i].data.array.items[0], NULL)); + ADD_C(new_items, items.items[i].data.array.items[0]); } ADD_C(new_args, ARRAY_OBJ(new_items)); push_call(ui, "wildmenu_show", new_args); - api_free_array(new_items); if (args.items[1].data.integer != -1) { Array new_args2 = data->call_buf; ADD_C(new_args2, args.items[1]); push_call(ui, "wildmenu_select", new_args2); } - return; + goto free_ret; } } else if (strequal(name, "popupmenu_select")) { if (data->wildmenu_active) { @@ -1048,6 +1048,10 @@ static void remote_ui_event(UI *ui, char *name, Array args) } push_call(ui, name, args); + return; + +free_ret: + arena_mem_free(arena_finish(&arena)); } static void remote_ui_inspect(UI *ui, Dictionary *info) diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index 9e1f2dd631..83d6ba8dc7 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -79,7 +79,7 @@ /// @param[out] err Error details, if any /// @return Highlight definition map /// @see nvim_get_hl_by_id -Dictionary nvim_get_hl_by_name(String name, Boolean rgb, Error *err) +Dictionary nvim_get_hl_by_name(String name, Boolean rgb, Arena *arena, Error *err) FUNC_API_SINCE(3) { Dictionary result = ARRAY_DICT_INIT; @@ -89,8 +89,7 @@ Dictionary nvim_get_hl_by_name(String name, Boolean rgb, Error *err) api_set_error(err, kErrorTypeException, "Invalid highlight name: %s", name.data); return result; } - result = nvim_get_hl_by_id(id, rgb, err); - return result; + return nvim_get_hl_by_id(id, rgb, arena, err); } /// Gets a highlight definition by id. |hlID()| @@ -99,7 +98,7 @@ Dictionary nvim_get_hl_by_name(String name, Boolean rgb, Error *err) /// @param[out] err Error details, if any /// @return Highlight definition map /// @see nvim_get_hl_by_name -Dictionary nvim_get_hl_by_id(Integer hl_id, Boolean rgb, Error *err) +Dictionary nvim_get_hl_by_id(Integer hl_id, Boolean rgb, Arena *arena, Error *err) FUNC_API_SINCE(3) { Dictionary dic = ARRAY_DICT_INIT; @@ -108,7 +107,7 @@ Dictionary nvim_get_hl_by_id(Integer hl_id, Boolean rgb, Error *err) return dic; } int attrcode = syn_id2attr((int)hl_id); - return hl_get_attr_by_id(attrcode, rgb, err); + return hl_get_attr_by_id(attrcode, rgb, arena, err); } /// Gets a highlight group by name @@ -120,10 +119,10 @@ Integer nvim_get_hl_id_by_name(String name) return syn_check_group(name.data, name.size); } -Dictionary nvim__get_hl_defs(Integer ns_id, Error *err) +Dictionary nvim__get_hl_defs(Integer ns_id, Arena *arena, Error *err) { if (ns_id == 0) { - return get_global_hl_defs(); + return get_global_hl_defs(arena); } abort(); } @@ -1934,7 +1933,7 @@ void nvim_select_popupmenu_item(Integer item, Boolean insert, Boolean finish, Di } /// NB: if your UI doesn't use hlstate, this will not return hlstate first time -Array nvim__inspect_cell(Integer grid, Integer row, Integer col, Error *err) +Array nvim__inspect_cell(Integer grid, Integer row, Integer col, Arena *arena, Error *err) { Array ret = ARRAY_DICT_INIT; @@ -1958,13 +1957,14 @@ Array nvim__inspect_cell(Integer grid, Integer row, Integer col, Error *err) || col < 0 || col >= g->cols) { return ret; } + ret = arena_array(arena, 3); size_t off = g->line_offset[(size_t)row] + (size_t)col; - ADD(ret, STRING_OBJ(cstr_to_string((char *)g->chars[off]))); + ADD_C(ret, STRING_OBJ(cstr_as_string((char *)g->chars[off]))); int attr = g->attrs[off]; - ADD(ret, DICTIONARY_OBJ(hl_get_attr_by_id(attr, true, err))); + ADD_C(ret, DICTIONARY_OBJ(hl_get_attr_by_id(attr, true, arena, err))); // will not work first time if (!highlight_use_hlstate()) { - ADD(ret, ARRAY_OBJ(hl_inspect(attr))); + ADD_C(ret, ARRAY_OBJ(hl_inspect(attr))); } return ret; } diff --git a/src/nvim/highlight.c b/src/nvim/highlight.c index a78b933108..e42cb66422 100644 --- a/src/nvim/highlight.c +++ b/src/nvim/highlight.c @@ -788,7 +788,7 @@ HlAttrs syn_attr2entry(int attr) } /// Gets highlight description for id `attr_id` as a map. -Dictionary hl_get_attr_by_id(Integer attr_id, Boolean rgb, Error *err) +Dictionary hl_get_attr_by_id(Integer attr_id, Boolean rgb, Arena *arena, Error *err) { Dictionary dic = ARRAY_DICT_INIT; @@ -801,25 +801,21 @@ Dictionary hl_get_attr_by_id(Integer attr_id, Boolean rgb, Error *err) "Invalid attribute id: %" PRId64, attr_id); return dic; } - - return hlattrs2dict(NULL, syn_attr2entry((int)attr_id), rgb); + Dictionary retval = arena_dict(arena, HLATTRS_DICT_SIZE); + hlattrs2dict(&retval, syn_attr2entry((int)attr_id), rgb); + return retval; } /// Converts an HlAttrs into Dictionary /// -/// @param[out] hl optional pre-allocated dictionary for return value -/// if present, must be allocated with at least 16 elements! +/// @param[in/out] hl Dictionary with pre-allocated space for HLATTRS_DICT_SIZE elements /// @param[in] aep data to convert /// @param use_rgb use 'gui*' settings if true, else resorts to 'cterm*' -Dictionary hlattrs2dict(Dictionary *hl_alloc, HlAttrs ae, bool use_rgb) +void hlattrs2dict(Dictionary *dict, HlAttrs ae, bool use_rgb) { + assert(dict->capacity >= HLATTRS_DICT_SIZE); // at most 16 items + Dictionary hl = *dict; int mask = use_rgb ? ae.rgb_ae_attr : ae.cterm_ae_attr; - Dictionary hl = ARRAY_DICT_INIT; - if (hl_alloc) { - hl = *hl_alloc; - } else { - kv_ensure_space(hl, 16); - } if (mask & HL_BOLD) { PUT_C(hl, "bold", BOOLEAN_OBJ(true)); @@ -899,14 +895,7 @@ Dictionary hlattrs2dict(Dictionary *hl_alloc, HlAttrs ae, bool use_rgb) PUT_C(hl, "blend", INTEGER_OBJ(ae.hl_blend)); } - if (hl_alloc) { - *hl_alloc = hl; - return hl; - } else { - Dictionary allocated = copy_dictionary(hl, NULL); - kv_destroy(hl); - return allocated; - } + *dict = hl; } HlAttrs dict2hlattrs(Dict(highlight) *dict, bool use_rgb, int *link_id, Error *err) @@ -1086,6 +1075,7 @@ int object_to_color(Object val, char *key, bool rgb, Error *err) Array hl_inspect(int attr) { + // TODO(bfredl): use arena allocation Array ret = ARRAY_DICT_INIT; if (hlstate_active) { hl_inspect_impl(&ret, attr); diff --git a/src/nvim/highlight.h b/src/nvim/highlight.h index 50299bb91c..e85e3859e2 100644 --- a/src/nvim/highlight.h +++ b/src/nvim/highlight.h @@ -19,6 +19,8 @@ static inline int win_hl_attr(win_T *wp, int hlf) return ((wp->w_ns_hl_attr && ns_hl_fast < 0) ? wp->w_ns_hl_attr : hl_attr_active)[hlf]; } +#define HLATTRS_DICT_SIZE 16 + #define HL_SET_DEFAULT_COLORS(rgb_fg, rgb_bg, rgb_sp) \ do { \ bool dark_ = (*p_bg == 'd'); \ diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c index ed1f0185b7..97d4b421fe 100644 --- a/src/nvim/highlight_group.c +++ b/src/nvim/highlight_group.c @@ -1466,19 +1466,21 @@ static void highlight_list_one(const int id) } } -Dictionary get_global_hl_defs(void) +Dictionary get_global_hl_defs(Arena *arena) { - Dictionary rv = ARRAY_DICT_INIT; - for (int i = 1; i <= highlight_ga.ga_len && !got_int; i++) { + Dictionary rv = arena_dict(arena, (size_t)highlight_ga.ga_len); + for (int i = 1; i <= highlight_ga.ga_len; i++) { Dictionary attrs = ARRAY_DICT_INIT; HlGroup *h = &hl_table[i - 1]; if (h->sg_attr > 0) { - attrs = hlattrs2dict(NULL, syn_attr2entry(h->sg_attr), true); + attrs = arena_dict(arena, HLATTRS_DICT_SIZE); + hlattrs2dict(&attrs, syn_attr2entry(h->sg_attr), true); } else if (h->sg_link > 0) { - const char *link = (const char *)hl_table[h->sg_link - 1].sg_name; - PUT(attrs, "link", STRING_OBJ(cstr_to_string(link))); + attrs = arena_dict(arena, 1); + char *link = (char *)hl_table[h->sg_link - 1].sg_name; + PUT_C(attrs, "link", STRING_OBJ(cstr_as_string(link))); } - PUT(rv, (const char *)h->sg_name, DICTIONARY_OBJ(attrs)); + PUT_C(rv, (char *)h->sg_name, DICTIONARY_OBJ(attrs)); } return rv; -- cgit From bd51ac2a347c0a3efb64e4b09400b7314286844c Mon Sep 17 00:00:00 2001 From: Dundar Göc Date: Fri, 26 Aug 2022 23:11:25 +0200 Subject: refactor: replace char_u with char Work on https://github.com/neovim/neovim/issues/459 --- src/nvim/cmdexpand.c | 4 +- src/nvim/debugger.c | 50 ++++---- src/nvim/decoration.c | 2 +- src/nvim/drawline.c | 4 +- src/nvim/edit.c | 4 +- src/nvim/eval.c | 6 +- src/nvim/eval/funcs.c | 4 +- src/nvim/eval/userfunc.c | 16 +-- src/nvim/eval/vars.c | 4 +- src/nvim/ex_cmds.c | 6 +- src/nvim/ex_docmd.c | 14 +-- src/nvim/ex_getln.c | 21 ++-- src/nvim/fold.c | 104 ++++++++-------- src/nvim/mbyte.c | 21 ++-- src/nvim/path.c | 2 +- src/nvim/regexp.c | 53 ++++---- src/nvim/regexp_bt.c | 14 +-- src/nvim/regexp_nfa.c | 8 +- src/nvim/search.c | 4 +- src/nvim/shada.c | 2 +- src/nvim/sign.c | 317 +++++++++++++++++++++++------------------------ src/nvim/sign_defs.h | 2 +- src/nvim/spell.c | 4 +- src/nvim/syntax.c | 247 ++++++++++++++++++------------------ src/nvim/tag.c | 88 +++++++------ src/nvim/ui.c | 2 +- 26 files changed, 493 insertions(+), 510 deletions(-) diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 1c35f28301..7e2adf7f29 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -1424,7 +1424,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons set_context_in_cscope_cmd(xp, arg, cmdidx); break; case CMD_sign: - set_context_in_sign_cmd(xp, (char_u *)arg); + set_context_in_sign_cmd(xp, (char *)arg); break; case CMD_bdelete: case CMD_bwipeout: @@ -2890,7 +2890,7 @@ void f_getcompletion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } if (xpc.xp_context == EXPAND_SIGN) { - set_context_in_sign_cmd(&xpc, (char_u *)xpc.xp_pattern); + set_context_in_sign_cmd(&xpc, xpc.xp_pattern); xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); } diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c index 36df62b502..b720628e33 100644 --- a/src/nvim/debugger.c +++ b/src/nvim/debugger.c @@ -33,7 +33,7 @@ static char *debug_newval = NULL; struct debuggy { int dbg_nr; ///< breakpoint number int dbg_type; ///< DBG_FUNC or DBG_FILE or DBG_EXPR - char_u *dbg_name; ///< function, expression or file name + char *dbg_name; ///< function, expression or file name regprog_T *dbg_prog; ///< regexp program linenr_T dbg_lnum; ///< line number in function or file int dbg_forceit; ///< ! used @@ -60,7 +60,7 @@ void do_debug(char *cmd) bool typeahead_saved = false; int save_ignore_script = 0; int n; - char_u *cmdline = NULL; + char *cmdline = NULL; char *p; char *tail = NULL; static int last_cmd = 0; @@ -129,8 +129,8 @@ void do_debug(char *cmd) } xfree(cmdline); - cmdline = (char_u *)getcmdline_prompt('>', NULL, 0, EXPAND_NOTHING, NULL, - CALLBACK_NONE); + cmdline = getcmdline_prompt('>', NULL, 0, EXPAND_NOTHING, NULL, + CALLBACK_NONE); if (typeahead_saved) { restore_typeahead(&typeaheadbuf); @@ -144,7 +144,7 @@ void do_debug(char *cmd) // If this is a debug command, set "last_cmd". // If not, reset "last_cmd". // For a blank line use previous command. - p = skipwhite((char *)cmdline); + p = skipwhite(cmdline); if (*p != NUL) { switch (*p) { case 'c': @@ -239,14 +239,14 @@ void do_debug(char *cmd) last_cmd = CMD_STEP; break; case CMD_BACKTRACE: - do_showbacktrace((char_u *)cmd); + do_showbacktrace(cmd); continue; case CMD_FRAME: if (*p == NUL) { - do_showbacktrace((char_u *)cmd); + do_showbacktrace(cmd); } else { p = skipwhite(p); - do_setdebugtracelevel((char_u *)p); + do_setdebugtracelevel(p); } continue; case CMD_UP: @@ -266,7 +266,7 @@ void do_debug(char *cmd) // don't debug this command n = debug_break_level; debug_break_level = -1; - (void)do_cmdline((char *)cmdline, getexline, NULL, DOCMD_VERBOSE|DOCMD_EXCRESET); + (void)do_cmdline(cmdline, getexline, NULL, DOCMD_VERBOSE|DOCMD_EXCRESET); debug_break_level = n; } lines_left = Rows - 1; @@ -306,9 +306,9 @@ static int get_maxbacktrace_level(char *sname) return maxbacktrace; } -static void do_setdebugtracelevel(char_u *arg) +static void do_setdebugtracelevel(char *arg) { - int level = atoi((char *)arg); + int level = atoi(arg); if (*arg == '+' || level < 0) { debug_backtrace_level += level; } else { @@ -335,7 +335,7 @@ static void do_checkbacktracelevel(void) } } -static void do_showbacktrace(char_u *cmd) +static void do_showbacktrace(char *cmd) { char *sname = estack_sfile(ESTACK_NONE); int max = get_maxbacktrace_level(sname); @@ -470,7 +470,7 @@ static typval_T *eval_expr_no_emsg(struct debuggy *const bp) { // Disable error messages, a bad expression would make Vim unusable. emsg_off++; - typval_T *const tv = eval_expr((char *)bp->dbg_name); + typval_T *const tv = eval_expr(bp->dbg_name); emsg_off--; return tv; } @@ -482,9 +482,9 @@ static typval_T *eval_expr_no_emsg(struct debuggy *const bp) /// /// @param arg /// @param gap either &dbg_breakp or &prof_ga -static int dbg_parsearg(char_u *arg, garray_T *gap) +static int dbg_parsearg(char *arg, garray_T *gap) { - char *p = (char *)arg; + char *p = arg; char *q; bool here = false; @@ -531,11 +531,11 @@ static int dbg_parsearg(char_u *arg, garray_T *gap) } if (bp->dbg_type == DBG_FUNC) { - bp->dbg_name = vim_strsave((char_u *)p); + bp->dbg_name = xstrdup(p); } else if (here) { - bp->dbg_name = vim_strsave((char_u *)curbuf->b_ffname); + bp->dbg_name = xstrdup(curbuf->b_ffname); } else if (bp->dbg_type == DBG_EXPR) { - bp->dbg_name = vim_strsave((char_u *)p); + bp->dbg_name = xstrdup(p); bp->dbg_val = eval_expr_no_emsg(bp); } else { // Expand the file name in the same way as do_source(). This means @@ -551,10 +551,10 @@ static int dbg_parsearg(char_u *arg, garray_T *gap) return FAIL; } if (*p != '*') { - bp->dbg_name = (char_u *)fix_fname(p); + bp->dbg_name = fix_fname(p); xfree(p); } else { - bp->dbg_name = (char_u *)p; + bp->dbg_name = p; } } @@ -572,12 +572,12 @@ void ex_breakadd(exarg_T *eap) gap = &prof_ga; } - if (dbg_parsearg((char_u *)eap->arg, gap) == OK) { + if (dbg_parsearg(eap->arg, gap) == OK) { struct debuggy *bp = &DEBUGGY(gap, gap->ga_len); bp->dbg_forceit = eap->forceit; if (bp->dbg_type != DBG_EXPR) { - char *pat = file_pat_to_reg_pat((char *)bp->dbg_name, NULL, NULL, false); + char *pat = file_pat_to_reg_pat(bp->dbg_name, NULL, NULL, false); if (pat != NULL) { bp->dbg_prog = vim_regcomp(pat, RE_MAGIC + RE_STRING); xfree(pat); @@ -639,7 +639,7 @@ void ex_breakdel(exarg_T *eap) del_all = true; } else { // ":breakdel {func|file|expr} [lnum] {name}" - if (dbg_parsearg((char_u *)eap->arg, gap) == FAIL) { + if (dbg_parsearg(eap->arg, gap) == FAIL) { return; } bp = &DEBUGGY(gap, gap->ga_len); @@ -697,13 +697,13 @@ void ex_breaklist(exarg_T *eap) for (int i = 0; i < dbg_breakp.ga_len; i++) { struct debuggy *bp = &BREAKP(i); if (bp->dbg_type == DBG_FILE) { - home_replace(NULL, (char *)bp->dbg_name, (char *)NameBuff, MAXPATHL, true); + home_replace(NULL, bp->dbg_name, (char *)NameBuff, MAXPATHL, true); } if (bp->dbg_type != DBG_EXPR) { smsg(_("%3d %s %s line %" PRId64), bp->dbg_nr, bp->dbg_type == DBG_FUNC ? "func" : "file", - bp->dbg_type == DBG_FUNC ? bp->dbg_name : (char_u *)NameBuff, + bp->dbg_type == DBG_FUNC ? bp->dbg_name : NameBuff, (int64_t)bp->dbg_lnum); } else { smsg(_("%3d expr %s"), bp->dbg_nr, bp->dbg_name); diff --git a/src/nvim/decoration.c b/src/nvim/decoration.c index 9f3e5a8638..8955048f45 100644 --- a/src/nvim/decoration.c +++ b/src/nvim/decoration.c @@ -394,7 +394,7 @@ void decor_redraw_signs(buf_T *buf, int row, int *num_signs, SignTextAttrs sattr } if (j < SIGN_SHOW_MAX) { sattrs[j] = (SignTextAttrs) { - .text = decor->sign_text, + .text = (char *)decor->sign_text, .hl_attr_id = decor->sign_hl_id == 0 ? 0 : syn_id2attr(decor->sign_hl_id), .priority = decor->priority }; diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index 66d8a1fb32..85a0bf2f5f 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -306,7 +306,7 @@ static void get_sign_display_info(bool nrcol, win_T *wp, linenr_T lnum, SignText if (row == startrow + filler_lines && filler_todo <= 0) { SignTextAttrs *sattr = sign_get_attr(sign_idx, sattrs, wp->w_scwidth); if (sattr != NULL) { - *pp_extra = sattr->text; + *pp_extra = (char_u *)sattr->text; if (*pp_extra != NULL) { *c_extrap = NUL; *c_finalp = NUL; @@ -1349,7 +1349,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, linenr_T lnume = lnum + foldinfo.fi_lines - 1; memset(buf_fold, ' ', FOLD_TEXT_LEN); - p_extra = get_foldtext(wp, lnum, lnume, foldinfo, buf_fold); + p_extra = (char_u *)get_foldtext(wp, lnum, lnume, foldinfo, (char *)buf_fold); n_extra = (int)STRLEN(p_extra); if (p_extra != buf_fold) { diff --git a/src/nvim/edit.c b/src/nvim/edit.c index 642162284c..9144d055f7 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -3236,7 +3236,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) assert(p >= look && (uintmax_t)(p - look) <= SIZE_MAX); if (s + (p - look) <= line + curwin->w_cursor.col && (icase - ? mb_strnicmp(s, look, (size_t)(p - look)) + ? mb_strnicmp((char *)s, (char *)look, (size_t)(p - look)) : STRNCMP(s, look, p - look)) == 0) { match = true; } @@ -3250,7 +3250,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) if ((curwin->w_cursor.col == (colnr_T)(p - look) || !vim_iswordc(line[-(p - look) - 1])) && (icase - ? mb_strnicmp(line - (p - look), look, (size_t)(p - look)) + ? mb_strnicmp((char *)line - (p - look), (char *)look, (size_t)(p - look)) : STRNCMP(line - (p - look), look, p - look)) == 0) { match = true; } diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 2ade64df3f..0b03cf3011 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -2292,7 +2292,7 @@ int eval0(char *arg, typval_T *rettv, char **nextcmd, int evaluate) ret = FAIL; } if (nextcmd != NULL) { - *nextcmd = (char *)check_nextcmd((char_u *)p); + *nextcmd = check_nextcmd(p); } return ret; @@ -7639,7 +7639,7 @@ void ex_echo(exarg_T *eap) tv_clear(&rettv); arg = skipwhite(arg); } - eap->nextcmd = (char *)check_nextcmd((char_u *)arg); + eap->nextcmd = check_nextcmd(arg); if (eap->skip) { emsg_skip--; @@ -7736,7 +7736,7 @@ void ex_execute(exarg_T *eap) emsg_skip--; } - eap->nextcmd = (char *)check_nextcmd((char_u *)arg); + eap->nextcmd = check_nextcmd(arg); } /// Skip over the name of an option: "&option", "&g:option" or "&l:option". diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 6593a34f4a..5a5293780d 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -1065,7 +1065,7 @@ static void f_count(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) const size_t len = STRLEN(expr); while (*p != NUL) { - if (mb_strnicmp(p, expr, len) == 0) { + if (mb_strnicmp((char *)p, (char *)expr, len) == 0) { n++; p += len; } else { @@ -8687,7 +8687,7 @@ static void f_submatch(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) if (retList == 0) { rettv->v_type = VAR_STRING; - rettv->vval.v_string = (char *)reg_submatch(no); + rettv->vval.v_string = reg_submatch(no); } else { rettv->v_type = VAR_LIST; rettv->vval.v_list = reg_submatch_list(no); diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 21bd662db5..bcaca0ca13 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -1942,7 +1942,7 @@ void ex_function(exarg_T *eap) } } } - eap->nextcmd = (char *)check_nextcmd((char_u *)eap->arg); + eap->nextcmd = check_nextcmd(eap->arg); return; } @@ -1978,7 +1978,7 @@ void ex_function(exarg_T *eap) if (*p == '/') { p++; } - eap->nextcmd = (char *)check_nextcmd(p); + eap->nextcmd = check_nextcmd((char *)p); return; } @@ -2032,7 +2032,7 @@ void ex_function(exarg_T *eap) semsg(_(e_trailing_arg), p); goto ret_free; } - eap->nextcmd = (char *)check_nextcmd(p); + eap->nextcmd = check_nextcmd((char *)p); if (eap->nextcmd != NULL) { *p = NUL; } @@ -2590,8 +2590,8 @@ int eval_fname_script(const char *const p) // Use mb_strnicmp() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' - && (mb_strnicmp((char_u *)p + 1, (char_u *)"SID>", 4) == 0 - || mb_strnicmp((char_u *)p + 1, (char_u *)"SNR>", 4) == 0)) { + && (mb_strnicmp(p + 1, "SID>", 4) == 0 + || mb_strnicmp(p + 1, "SNR>", 4) == 0)) { return 5; } if (p[0] == 's' && p[1] == ':') { @@ -2700,7 +2700,7 @@ void ex_delfunction(exarg_T *eap) semsg(_(e_trailing_arg), p); return; } - eap->nextcmd = (char *)check_nextcmd(p); + eap->nextcmd = check_nextcmd((char *)p); if (eap->nextcmd != NULL) { *p = NUL; } @@ -2889,7 +2889,7 @@ void ex_return(exarg_T *eap) if (returning) { eap->nextcmd = NULL; } else if (eap->nextcmd == NULL) { // no argument - eap->nextcmd = (char *)check_nextcmd(arg); + eap->nextcmd = check_nextcmd((char *)arg); } if (eap->skip) { @@ -3018,7 +3018,7 @@ void ex_call(exarg_T *eap) semsg(_(e_trailing_arg), arg); } } else { - eap->nextcmd = (char *)check_nextcmd(arg); + eap->nextcmd = check_nextcmd((char *)arg); } } diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index dbbb03b1b8..ba58254bdd 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -207,7 +207,7 @@ static void ex_let_const(exarg_T *eap, const bool is_const) list_func_vars(&first); list_vim_vars(&first); } - eap->nextcmd = (char *)check_nextcmd((char_u *)arg); + eap->nextcmd = check_nextcmd(arg); } else if (expr[0] == '=' && expr[1] == '<' && expr[2] == '<') { // HERE document list_T *l = heredoc_get(eap, expr + 3); @@ -824,7 +824,7 @@ static void ex_unletlock(exarg_T *eap, char *argstart, int deep, ex_unletlock_ca arg = skipwhite(name_end); } while (!ends_excmd(*arg)); - eap->nextcmd = (char *)check_nextcmd((char_u *)arg); + eap->nextcmd = check_nextcmd(arg); } // TODO(ZyX-I): move to eval/ex_cmds diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 17d45f207e..d050562e4c 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -509,8 +509,8 @@ void ex_sort(exarg_T *eap) } else if (*p == '"') { // comment start break; - } else if (check_nextcmd((char_u *)p) != NULL) { - eap->nextcmd = (char *)check_nextcmd((char_u *)p); + } else if (check_nextcmd(p) != NULL) { + eap->nextcmd = check_nextcmd(p); break; } else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL) { s = skip_regexp(p + 1, *p, true, NULL); @@ -3625,7 +3625,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T */ cmd = skipwhite(cmd); if (*cmd && *cmd != '"') { // if not end-of-line or comment - eap->nextcmd = (char *)check_nextcmd((char_u *)cmd); + eap->nextcmd = check_nextcmd(cmd); if (eap->nextcmd == NULL) { semsg(_(e_trailing_arg), cmd); return 0; diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 8f72ba0e23..01d141e557 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -1929,7 +1929,7 @@ static char *do_one_cmd(char **cmdlinep, int flags, cstack_T *cstack, LineGetter // If we got a line, but no command, then go to the line. // If we find a '|' or '\n' we set ea.nextcmd. if (*ea.cmd == NUL || *ea.cmd == '"' - || (ea.nextcmd = (char *)check_nextcmd((char_u *)ea.cmd)) != NULL) { + || (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL) { // strange vi behaviour: // ":3" jumps to line 3 // ":3|..." prints line 3 @@ -3934,7 +3934,7 @@ void separate_nextcmd(exarg_T *eap) STRMOVE(p - 1, p); // remove the '\' p--; } else { - eap->nextcmd = (char *)check_nextcmd((char_u *)p); + eap->nextcmd = check_nextcmd(p); *p = NUL; break; } @@ -4311,12 +4311,12 @@ char *find_nextcmd(const char *p) /// Check if *p is a separator between Ex commands, skipping over white space. /// /// @return NULL if it isn't, the following character if it is. -char_u *check_nextcmd(char_u *p) +char *check_nextcmd(char *p) { - char *s = skipwhite((char *)p); + char *s = skipwhite(p); if (*s == '|' || *s == '\n') { - return (char_u *)(s + 1); + return s + 1; } else { return NULL; } @@ -5674,7 +5674,7 @@ static void ex_wincmd(exarg_T *eap) p = eap->arg + 1; } - eap->nextcmd = (char *)check_nextcmd((char_u *)p); + eap->nextcmd = check_nextcmd(p); p = skipwhite(p); if (*p != NUL && *p != '"' && eap->nextcmd == NULL) { emsg(_(e_invarg)); @@ -6465,7 +6465,7 @@ static void ex_findpat(exarg_T *eap) if (!ends_excmd(*p)) { eap->errmsg = ex_errmsg(e_trailing_arg, p); } else { - eap->nextcmd = (char *)check_nextcmd((char_u *)p); + eap->nextcmd = check_nextcmd(p); } } } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index e8af99805d..9d1cebd43e 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -328,7 +328,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s int empty; *end = NUL; - empty = empty_pattern((char_u *)p); + empty = empty_pattern(p); *end = c; if (empty) { goto theend; @@ -489,7 +489,7 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat if (!use_last_pat) { next_char = ccline.cmdbuff[skiplen + patlen]; ccline.cmdbuff[skiplen + patlen] = NUL; - if (empty_pattern(ccline.cmdbuff) && !no_hlsearch) { + if (empty_pattern((char *)ccline.cmdbuff) && !no_hlsearch) { redraw_all_later(UPD_SOME_VALID); set_no_hlsearch(true); } @@ -2027,7 +2027,7 @@ static int command_line_not_changed(CommandLineState *s) /// Guess that the pattern matches everything. Only finds specific cases, such /// as a trailing \|, which can happen while typing a pattern. -static int empty_pattern(char_u *p) +static int empty_pattern(char *p) { size_t n = STRLEN(p); @@ -3952,8 +3952,9 @@ static int get_cmdline_type(void) /// Get the current command line in allocated memory. /// Only works when the command line is being edited. -/// Returns NULL when something is wrong. -static char_u *get_cmdline_str(void) +/// +/// @return NULL when something is wrong. +static char *get_cmdline_str(void) { if (cmdline_star > 0) { return NULL; @@ -3963,11 +3964,11 @@ static char_u *get_cmdline_str(void) if (p == NULL) { return NULL; } - return vim_strnsave(p->cmdbuff, (size_t)p->cmdlen); + return (char *)vim_strnsave(p->cmdbuff, (size_t)p->cmdlen); } /// Get the current command-line completion type. -static char_u *get_cmdline_completion(void) +static char *get_cmdline_completion(void) { if (cmdline_star > 0) { return NULL; @@ -3978,7 +3979,7 @@ static char_u *get_cmdline_completion(void) set_expand_context(p->xpc); char *cmd_compl = get_user_cmd_complete(p->xpc, p->xpc->xp_context); if (cmd_compl != NULL) { - return vim_strsave((char_u *)cmd_compl); + return xstrdup(cmd_compl); } } @@ -3989,14 +3990,14 @@ static char_u *get_cmdline_completion(void) void f_getcmdcompltype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { rettv->v_type = VAR_STRING; - rettv->vval.v_string = (char *)get_cmdline_completion(); + rettv->vval.v_string = get_cmdline_completion(); } /// "getcmdline()" function void f_getcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { rettv->v_type = VAR_STRING; - rettv->vval.v_string = (char *)get_cmdline_str(); + rettv->vval.v_string = get_cmdline_str(); } /// "getcmdpos()" function diff --git a/src/nvim/fold.c b/src/nvim/fold.c index d8c864df5b..0f085df3d0 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -111,7 +111,7 @@ static int prev_lnum_lvl = -1; #define DONE_FOLD 2 // did find a fold static size_t foldstartmarkerlen; -static char_u *foldendmarker; +static char *foldendmarker; static size_t foldendmarkerlen; // Exported folding functions. {{{1 @@ -982,7 +982,7 @@ void foldAdjustVisual(void) } pos_T *start, *end; - char_u *ptr; + char *ptr; if (ltoreq(VIsual, curwin->w_cursor)) { start = &VIsual; @@ -995,7 +995,7 @@ void foldAdjustVisual(void) start->col = 0; } if (hasFolding(end->lnum, NULL, &end->lnum)) { - ptr = (char_u *)ml_get(end->lnum); + ptr = ml_get(end->lnum); end->col = (colnr_T)STRLEN(ptr); if (end->col > 0 && *p_sel == 'o') { end->col--; @@ -1556,7 +1556,7 @@ static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end) } parseMarker(wp); - foldAddMarker(buf, start, (char_u *)wp->w_p_fmr, foldstartmarkerlen); + foldAddMarker(buf, start, wp->w_p_fmr, foldstartmarkerlen); foldAddMarker(buf, end, foldendmarker, foldendmarkerlen); // Update both changes here, to avoid all folds after the start are @@ -1573,22 +1573,22 @@ static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end) // foldAddMarker() {{{2 /// Add "marker[markerlen]" in 'commentstring' to position `pos`. -static void foldAddMarker(buf_T *buf, pos_T pos, const char_u *marker, size_t markerlen) +static void foldAddMarker(buf_T *buf, pos_T pos, const char *marker, size_t markerlen) { - char_u *cms = (char_u *)buf->b_p_cms; - char_u *newline; - char_u *p = (char_u *)strstr(buf->b_p_cms, "%s"); + char *cms = buf->b_p_cms; + char *newline; + char *p = strstr(buf->b_p_cms, "%s"); bool line_is_comment = false; linenr_T lnum = pos.lnum; // Allocate a new line: old-line + 'cms'-start + marker + 'cms'-end - char_u *line = ml_get_buf(buf, lnum, false); + char *line = (char *)ml_get_buf(buf, lnum, false); size_t line_len = STRLEN(line); size_t added = 0; if (u_save(lnum - 1, lnum + 1) == OK) { // Check if the line ends with an unclosed comment - skip_comment((char *)line, false, false, &line_is_comment); + skip_comment(line, false, false, &line_is_comment); newline = xmalloc(line_len + markerlen + STRLEN(cms) + 1); STRCPY(newline, line); // Append the marker to the end of the line @@ -1601,7 +1601,7 @@ static void foldAddMarker(buf_T *buf, pos_T pos, const char_u *marker, size_t ma STRCPY(newline + line_len + (p - cms) + markerlen, p + 2); added = markerlen + STRLEN(cms) - 2; } - ml_replace_buf(buf, lnum, (char *)newline, false); + ml_replace_buf(buf, lnum, newline, false); if (added) { extmark_splice_cols(buf, (int)lnum - 1, (int)line_len, 0, (int)added, kExtmarkUndo); @@ -1621,7 +1621,7 @@ static void deleteFoldMarkers(win_T *wp, fold_T *fp, int recursive, linenr_T lnu lnum_off + fp->fd_top); } } - foldDelMarker(wp->w_buffer, fp->fd_top + lnum_off, (char_u *)wp->w_p_fmr, + foldDelMarker(wp->w_buffer, fp->fd_top + lnum_off, wp->w_p_fmr, foldstartmarkerlen); foldDelMarker(wp->w_buffer, fp->fd_top + lnum_off + fp->fd_len - 1, foldendmarker, foldendmarkerlen); @@ -1632,16 +1632,16 @@ static void deleteFoldMarkers(win_T *wp, fold_T *fp, int recursive, linenr_T lnu /// Delete 'commentstring' if it matches. /// If the marker is not found, there is no error message. Could be a missing /// close-marker. -static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t markerlen) +static void foldDelMarker(buf_T *buf, linenr_T lnum, char *marker, size_t markerlen) { // end marker may be missing and fold extends below the last line if (lnum > buf->b_ml.ml_line_count) { return; } - char_u *cms = (char_u *)buf->b_p_cms; - char_u *line = ml_get_buf(buf, lnum, false); - for (char_u *p = line; *p != NUL; p++) { + char *cms = buf->b_p_cms; + char *line = (char *)ml_get_buf(buf, lnum, false); + for (char *p = line; *p != NUL; p++) { if (STRNCMP(p, marker, markerlen) != 0) { continue; } @@ -1652,7 +1652,7 @@ static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t mark } if (*cms != NUL) { // Also delete 'commentstring' if it matches. - char_u *cms2 = (char_u *)strstr((char *)cms, "%s"); + char *cms2 = strstr(cms, "%s"); if (p - line >= cms2 - cms && STRNCMP(p - (cms2 - cms), cms, cms2 - cms) == 0 && STRNCMP(p + len, cms2 + 2, STRLEN(cms2 + 2)) == 0) { @@ -1662,11 +1662,11 @@ static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t mark } if (u_save(lnum - 1, lnum + 1) == OK) { // Make new line: text-before-marker + text-after-marker - char_u *newline = xmalloc(STRLEN(line) - len + 1); + char *newline = xmalloc(STRLEN(line) - len + 1); assert(p >= line); memcpy(newline, line, (size_t)(p - line)); STRCPY(newline + (p - line), p + len); - ml_replace_buf(buf, lnum, (char *)newline, false); + ml_replace_buf(buf, lnum, newline, false); extmark_splice_cols(buf, (int)lnum - 1, (int)(p - line), (int)len, 0, kExtmarkUndo); } @@ -1683,10 +1683,10 @@ static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t mark /// @return the text for a closed fold /// /// Otherwise the result is in allocated memory. -char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldinfo, char_u *buf) +char *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldinfo, char *buf) FUNC_ATTR_NONNULL_ARG(1) { - char_u *text = NULL; + char *text = NULL; // an error occurred when evaluating 'fdt' setting static bool got_fdt_error = false; int save_did_emsg = did_emsg; @@ -1728,9 +1728,7 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldin curbuf = wp->w_buffer; emsg_silent++; // handle exceptions, but don't display errors - text = - (char_u *)eval_to_string_safe(wp->w_p_fdt, NULL, - was_set_insecurely(wp, "foldtext", OPT_LOCAL)); + text = eval_to_string_safe(wp->w_p_fdt, NULL, was_set_insecurely(wp, "foldtext", OPT_LOCAL)); emsg_silent--; if (text == NULL || did_emsg) { @@ -1751,23 +1749,23 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldin if (text != NULL) { // Replace unprintable characters, if there are any. But // replace a TAB with a space. - char_u *p; + char *p; for (p = text; *p != NUL; p++) { - int len = utfc_ptr2len((char *)p); + int len = utfc_ptr2len(p); if (len > 1) { - if (!vim_isprintc(utf_ptr2char((char *)p))) { + if (!vim_isprintc(utf_ptr2char(p))) { break; } p += len - 1; } else if (*p == TAB) { *p = ' '; - } else if (ptr2cells((char *)p) > 1) { + } else if (ptr2cells(p) > 1) { break; } } if (*p != NUL) { - p = (char_u *)transstr((const char *)text, true); + p = transstr((const char *)text, true); xfree(text); text = p; } @@ -1776,7 +1774,7 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldin if (text == NULL) { unsigned long count = (unsigned long)(lnume - lnum + 1); - vim_snprintf((char *)buf, FOLD_TEXT_LEN, + vim_snprintf(buf, FOLD_TEXT_LEN, NGETTEXT("+--%3ld line folded", "+--%3ld lines folded ", count), count); @@ -1787,17 +1785,17 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldin // foldtext_cleanup() {{{2 /// Remove 'foldmarker' and 'commentstring' from "str" (in-place). -static void foldtext_cleanup(char_u *str) +static void foldtext_cleanup(char *str) { // Ignore leading and trailing white space in 'commentstring'. - char_u *cms_start = (char_u *)skipwhite(curbuf->b_p_cms); + char *cms_start = skipwhite(curbuf->b_p_cms); size_t cms_slen = STRLEN(cms_start); while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) { cms_slen--; } // locate "%s" in 'commentstring', use the part before and after it. - char_u *cms_end = (char_u *)strstr((char *)cms_start, "%s"); + char *cms_end = strstr(cms_start, "%s"); size_t cms_elen = 0; if (cms_end != NULL) { cms_elen = cms_slen - (size_t)(cms_end - cms_start); @@ -1809,7 +1807,7 @@ static void foldtext_cleanup(char_u *str) } // skip "%s" and white space after it - char_u *s = (char_u *)skipwhite((char *)cms_end + 2); + char *s = skipwhite(cms_end + 2); cms_elen -= (size_t)(s - cms_end); cms_end = s; } @@ -1818,7 +1816,7 @@ static void foldtext_cleanup(char_u *str) bool did1 = false; bool did2 = false; - for (char_u *s = str; *s != NUL;) { + for (char *s = str; *s != NUL;) { size_t len = 0; if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0) { len = foldstartmarkerlen; @@ -1832,7 +1830,7 @@ static void foldtext_cleanup(char_u *str) // May remove 'commentstring' start. Useful when it's a double // quote and we already removed a double quote. - char_u *p; + char *p; for (p = s; p > str && ascii_iswhite(p[-1]); p--) {} if (p >= str + cms_slen && STRNCMP(p - cms_slen, cms_start, cms_slen) == 0) { @@ -2850,7 +2848,7 @@ static void foldlevelIndent(fline_T *flp) linenr_T lnum = flp->lnum + flp->off; buf_T *buf = flp->wp->w_buffer; - char_u *s = (char_u *)skipwhite((char *)ml_get_buf(buf, lnum, false)); + char *s = skipwhite((char *)ml_get_buf(buf, lnum, false)); // empty line or lines starting with a character in 'foldignore': level // depends on surrounding lines @@ -2985,8 +2983,8 @@ static void foldlevelExpr(fline_T *flp) /// Relies on the option value to have been checked for correctness already. static void parseMarker(win_T *wp) { - foldendmarker = (char_u *)vim_strchr(wp->w_p_fmr, ','); - foldstartmarkerlen = (size_t)(foldendmarker++ - (char_u *)wp->w_p_fmr); + foldendmarker = vim_strchr(wp->w_p_fmr, ','); + foldstartmarkerlen = (size_t)(foldendmarker++ - wp->w_p_fmr); foldendmarkerlen = STRLEN(foldendmarker); } @@ -3003,23 +3001,23 @@ static void foldlevelMarker(fline_T *flp) int start_lvl = flp->lvl; // cache a few values for speed - char_u *startmarker = (char_u *)flp->wp->w_p_fmr; - int cstart = *startmarker; + char *startmarker = flp->wp->w_p_fmr; + int cstart = (unsigned char)(*startmarker); startmarker++; - int cend = *foldendmarker; + int cend = (unsigned char)(*foldendmarker); // Default: no start found, next level is same as current level flp->start = 0; flp->lvl_next = flp->lvl; - char_u *s = ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off, false); + char *s = (char *)ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off, false); while (*s) { if (*s == cstart && STRNCMP(s + 1, startmarker, foldstartmarkerlen - 1) == 0) { // found startmarker: set flp->lvl s += foldstartmarkerlen; if (ascii_isdigit(*s)) { - int n = atoi((char *)s); + int n = atoi(s); if (n > 0) { flp->lvl = n; flp->lvl_next = n; @@ -3039,7 +3037,7 @@ static void foldlevelMarker(fline_T *flp) // found endmarker: set flp->lvl_next s += foldendmarkerlen; if (ascii_isdigit(*s)) { - int n = atoi((char *)s); + int n = atoi(s); if (n > 0) { flp->lvl = n; flp->lvl_next = n - 1; @@ -3240,7 +3238,7 @@ void f_foldtext(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) linenr_T foldstart = (linenr_T)get_vim_var_nr(VV_FOLDSTART); linenr_T foldend = (linenr_T)get_vim_var_nr(VV_FOLDEND); - char_u *dashes = (char_u *)get_vim_var_str(VV_FOLDDASHES); + char *dashes = get_vim_var_str(VV_FOLDDASHES); if (foldstart > 0 && foldend <= curbuf->b_ml.ml_line_count) { // Find first non-empty line in the fold. linenr_T lnum; @@ -3268,20 +3266,20 @@ void f_foldtext(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) + STRLEN(dashes) // for %s + 20 // for %3ld + STRLEN(s); // concatenated - char_u *r = xmalloc(len); - snprintf((char *)r, len, txt, dashes, count); + char *r = xmalloc(len); + snprintf(r, len, txt, dashes, count); len = STRLEN(r); STRCAT(r, s); // remove 'foldmarker' and 'commentstring' foldtext_cleanup(r + len); - rettv->vval.v_string = (char *)r; + rettv->vval.v_string = r; } } /// "foldtextresult(lnum)" function void f_foldtextresult(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { - char_u buf[FOLD_TEXT_LEN]; + char buf[FOLD_TEXT_LEN]; static bool entered = false; rettv->v_type = VAR_STRING; @@ -3298,11 +3296,11 @@ void f_foldtextresult(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) foldinfo_T info = fold_info(curwin, lnum); if (info.fi_lines > 0) { - char_u *text = get_foldtext(curwin, lnum, lnum + info.fi_lines - 1, info, buf); + char *text = get_foldtext(curwin, lnum, lnum + info.fi_lines - 1, info, buf); if (text == buf) { - text = vim_strsave(text); + text = xstrdup(text); } - rettv->vval.v_string = (char *)text; + rettv->vval.v_string = text; } entered = false; diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index f592b54f67..947594be4f 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -1541,17 +1541,16 @@ ssize_t mb_utf_index_to_bytes(const char_u *s, size_t len, size_t index, bool us return -1; } -/* - * Version of strnicmp() that handles multi-byte characters. - * Needed for Big5, Shift-JIS and UTF-8 encoding. Other DBCS encodings can - * probably use strnicmp(), because there are no ASCII characters in the - * second byte. - * Returns zero if s1 and s2 are equal (ignoring case), the difference between - * two characters otherwise. - */ -int mb_strnicmp(const char_u *s1, const char_u *s2, const size_t nn) +/// Version of strnicmp() that handles multi-byte characters. +/// Needed for Big5, Shift-JIS and UTF-8 encoding. Other DBCS encodings can +/// probably use strnicmp(), because there are no ASCII characters in the +/// second byte. +/// +/// @return zero if s1 and s2 are equal (ignoring case), the difference between +/// two characters otherwise. +int mb_strnicmp(const char *s1, const char *s2, const size_t nn) { - return utf_strnicmp(s1, s2, nn, nn); + return utf_strnicmp((char_u *)s1, (char_u *)s2, nn, nn); } /// Compare strings case-insensitively @@ -1568,7 +1567,7 @@ int mb_strnicmp(const char_u *s1, const char_u *s2, const size_t nn) /// @return 0 if strings are equal, <0 if s1 < s2, >0 if s1 > s2. int mb_stricmp(const char *s1, const char *s2) { - return mb_strnicmp((const char_u *)s1, (const char_u *)s2, MAXCOL); + return mb_strnicmp(s1, s2, MAXCOL); } /* diff --git a/src/nvim/path.c b/src/nvim/path.c index 5bbcbc7144..8973d4dfdb 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -384,7 +384,7 @@ int path_fnamencmp(const char *const fname1, const char *const fname2, size_t le return p_fic ? CH_FOLD(c1) - CH_FOLD(c2) : c1 - c2; #else if (p_fic) { - return mb_strnicmp((const char_u *)fname1, (const char_u *)fname2, len); + return mb_strnicmp(fname1, fname2, len); } return strncmp(fname1, fname2, len); #endif diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index f471f1c8e0..563d85964c 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -1282,7 +1282,7 @@ static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T e len = (int)STRLEN(p + ccol); } - if (cstrncmp(p + ccol, rex.input, &len) != 0) { + if (cstrncmp((char *)p + ccol, (char *)rex.input, &len) != 0) { return RA_NOMATCH; // doesn't match } if (bytelen != NULL) { @@ -1395,10 +1395,10 @@ static void mb_decompose(int c, int *c1, int *c2, int *c3) } } -// Compare two strings, ignore case if rex.reg_ic set. -// Return 0 if strings match, non-zero otherwise. -// Correct the length "*n" when composing characters are ignored. -static int cstrncmp(char_u *s1, char_u *s2, int *n) +/// Compare two strings, ignore case if rex.reg_ic set. +/// Return 0 if strings match, non-zero otherwise. +/// Correct the length "*n" when composing characters are ignored. +static int cstrncmp(char *s1, char *s2, int *n) { int result; @@ -1406,12 +1406,12 @@ static int cstrncmp(char_u *s1, char_u *s2, int *n) result = STRNCMP(s1, s2, *n); } else { assert(*n >= 0); - result = mb_strnicmp(s1, s2, (size_t)*n); + result = mb_strnicmp(s1, s2, (size_t)(*n)); } // if it failed and it's utf8 and we want to combineignore: if (result != 0 && rex.reg_icombine) { - char_u *str1, *str2; + char *str1, *str2; int c1, c2, c11, c12; int junk; @@ -2112,36 +2112,33 @@ exit: return (int)((dst - dest) + 1); } -/* - * Call reg_getline() with the line numbers from the submatch. If a - * substitute() was used the reg_maxline and other values have been - * overwritten. - */ -static char_u *reg_getline_submatch(linenr_T lnum) +/// Call reg_getline() with the line numbers from the submatch. If a +/// substitute() was used the reg_maxline and other values have been +/// overwritten. +static char *reg_getline_submatch(linenr_T lnum) { - char_u *s; + char *s; linenr_T save_first = rex.reg_firstlnum; linenr_T save_max = rex.reg_maxline; rex.reg_firstlnum = rsm.sm_firstlnum; rex.reg_maxline = rsm.sm_maxline; - s = reg_getline(lnum); + s = (char *)reg_getline(lnum); rex.reg_firstlnum = save_first; rex.reg_maxline = save_max; return s; } -/* - * Used for the submatch() function: get the string from the n'th submatch in - * allocated memory. - * Returns NULL when not in a ":s" command and for a non-existing submatch. - */ -char_u *reg_submatch(int no) +/// Used for the submatch() function: get the string from the n'th submatch in +/// allocated memory. +/// +/// @return NULL when not in a ":s" command and for a non-existing submatch. +char *reg_submatch(int no) { - char_u *retval = NULL; - char_u *s; + char *retval = NULL; + char *s; int round; linenr_T lnum; @@ -2211,11 +2208,11 @@ char_u *reg_submatch(int no) } } } else { - s = rsm.sm_match->startp[no]; + s = (char *)rsm.sm_match->startp[no]; if (s == NULL || rsm.sm_match->endp[no] == NULL) { retval = NULL; } else { - retval = vim_strnsave(s, (size_t)(rsm.sm_match->endp[no] - s)); + retval = xstrnsave(s, (size_t)(rsm.sm_match->endp[no] - (char_u *)s)); } } @@ -2250,16 +2247,16 @@ list_T *reg_submatch_list(int no) list = tv_list_alloc(elnum - slnum + 1); - s = (const char *)reg_getline_submatch(slnum) + scol; + s = reg_getline_submatch(slnum) + scol; if (slnum == elnum) { tv_list_append_string(list, s, ecol - scol); } else { tv_list_append_string(list, s, -1); for (int i = 1; i < elnum - slnum; i++) { - s = (const char *)reg_getline_submatch(slnum + i); + s = reg_getline_submatch(slnum + i); tv_list_append_string(list, s, -1); } - s = (const char *)reg_getline_submatch(elnum); + s = reg_getline_submatch(elnum); tv_list_append_string(list, s, ecol); } } else { diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c index b951df69d6..9b9b33b09f 100644 --- a/src/nvim/regexp_bt.c +++ b/src/nvim/regexp_bt.c @@ -4039,7 +4039,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) } else { // Need to match first byte again for multi-byte. len = (int)STRLEN(opnd); - if (cstrncmp(opnd, rex.input, &len) != 0) { + if (cstrncmp((char *)opnd, (char *)rex.input, &len) != 0) { status = RA_NOMATCH; } } @@ -4270,7 +4270,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) } else { // Compare current input with back-ref in the same line. len = (int)(rex.reg_endp[no] - rex.reg_startp[no]); - if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0) { + if (cstrncmp((char *)rex.reg_startp[no], (char *)rex.input, &len) != 0) { status = RA_NOMATCH; } } @@ -4283,8 +4283,8 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) && rex.reg_endpos[no].lnum == rex.lnum) { // Compare back-ref within the current line. len = rex.reg_endpos[no].col - rex.reg_startpos[no].col; - if (cstrncmp(rex.line + rex.reg_startpos[no].col, - rex.input, &len) != 0) { + if (cstrncmp((char *)rex.line + rex.reg_startpos[no].col, + (char *)rex.input, &len) != 0) { status = RA_NOMATCH; } } else { @@ -4320,7 +4320,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) if (re_extmatch_in != NULL && re_extmatch_in->matches[no] != NULL) { int len = (int)STRLEN(re_extmatch_in->matches[no]); - if (cstrncmp(re_extmatch_in->matches[no], rex.input, &len) != 0) { + if (cstrncmp((char *)re_extmatch_in->matches[no], (char *)rex.input, &len) != 0) { status = RA_NOMATCH; } else { rex.input += len; @@ -5069,14 +5069,14 @@ static long bt_regexec_both(char_u *line, colnr_T col, proftime_T *tm, int *time // the loop to avoid overhead of conditions. if (!rex.reg_ic) { while ((s = (char_u *)vim_strchr((char *)s, c)) != NULL) { - if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0) { + if (cstrncmp((char *)s, (char *)prog->regmust, &prog->regmlen) == 0) { break; // Found it. } MB_PTR_ADV(s); } } else { while ((s = cstrchr(s, c)) != NULL) { - if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0) { + if (cstrncmp((char *)s, (char *)prog->regmust, &prog->regmlen) == 0) { break; // Found it. } MB_PTR_ADV(s); diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c index e1327ce155..d01404b5c2 100644 --- a/src/nvim/regexp_nfa.c +++ b/src/nvim/regexp_nfa.c @@ -5421,8 +5421,8 @@ retempty: && sub->list.multi[subidx].end_lnum == rex.lnum) { len = sub->list.multi[subidx].end_col - sub->list.multi[subidx].start_col; - if (cstrncmp(rex.line + sub->list.multi[subidx].start_col, - rex.input, &len) == 0) { + if (cstrncmp((char *)rex.line + sub->list.multi[subidx].start_col, + (char *)rex.input, &len) == 0) { *bytelen = len; return true; } @@ -5441,7 +5441,7 @@ retempty: goto retempty; } len = (int)(sub->list.line[subidx].end - sub->list.line[subidx].start); - if (cstrncmp(sub->list.line[subidx].start, rex.input, &len) == 0) { + if (cstrncmp((char *)sub->list.line[subidx].start, (char *)rex.input, &len) == 0) { *bytelen = len; return true; } @@ -5466,7 +5466,7 @@ static int match_zref(int subidx, int *bytelen) } len = (int)STRLEN(re_extmatch_in->matches[subidx]); - if (cstrncmp(re_extmatch_in->matches[subidx], rex.input, &len) == 0) { + if (cstrncmp((char *)re_extmatch_in->matches[subidx], (char *)rex.input, &len) == 0) { *bytelen = len; return true; } diff --git a/src/nvim/search.c b/src/nvim/search.c index d7f8d4e1cd..226d949825 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -1504,7 +1504,7 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) } else if (*p != NUL) { // Ignore empty lines. // Expanding lines or words. assert(ins_compl_len() >= 0); - if ((p_ic ? mb_strnicmp(p, pat, (size_t)ins_compl_len()) + if ((p_ic ? mb_strnicmp((char *)p, (char *)pat, (size_t)ins_compl_len()) : STRNCMP(p, pat, ins_compl_len())) == 0) { return OK; } @@ -3792,7 +3792,7 @@ search_line: // compare the first "len" chars from "ptr" startp = (char_u *)skipwhite((char *)p); if (p_ic) { - matched = !mb_strnicmp(startp, ptr, len); + matched = !mb_strnicmp((char *)startp, (char *)ptr, len); } else { matched = !STRNCMP(startp, ptr, len); } diff --git a/src/nvim/shada.c b/src/nvim/shada.c index d2f1b39ca4..e20bce5b34 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -4001,7 +4001,7 @@ static bool shada_removable(const char *name) if (part[0] == 'r') { home_replace(NULL, part + 1, (char *)NameBuff, MAXPATHL, true); size_t n = STRLEN(NameBuff); - if (mb_strnicmp((char_u *)NameBuff, (char_u *)new_name, n) == 0) { + if (mb_strnicmp(NameBuff, new_name, n) == 0) { retval = true; break; } diff --git a/src/nvim/sign.c b/src/nvim/sign.c index ed7f53d3ba..7d931a853b 100644 --- a/src/nvim/sign.c +++ b/src/nvim/sign.c @@ -26,11 +26,11 @@ typedef struct sign sign_T; struct sign { - sign_T *sn_next; // next sign in list + sign_T *sn_next; // next sign in list int sn_typenr; // type number of sign - char_u *sn_name; // name of sign - char_u *sn_icon; // name of pixmap - char_u *sn_text; // text used instead of pixmap + char *sn_name; // name of sign + char *sn_icon; // name of pixmap + char *sn_text; // text used instead of pixmap int sn_line_hl; // highlight ID for line int sn_text_hl; // highlight ID for text int sn_cul_hl; // highlight ID for text on current line when 'cursorline' is set @@ -71,14 +71,13 @@ void init_signs(void) /// A new sign in group 'groupname' is added. If the group is not present, /// create it. Otherwise reference the group. -/// -static signgroup_T *sign_group_ref(const char_u *groupname) +static signgroup_T *sign_group_ref(const char *groupname) { hash_T hash; hashitem_T *hi; signgroup_T *group; - hash = hash_hash(groupname); + hash = hash_hash((char_u *)groupname); hi = hash_lookup(&sg_table, (char *)groupname, STRLEN(groupname), hash); if (HASHITEM_EMPTY(hi)) { // new group @@ -99,11 +98,11 @@ static signgroup_T *sign_group_ref(const char_u *groupname) /// A sign in group 'groupname' is removed. If all the signs in this group are /// removed, then remove the group. -static void sign_group_unref(char_u *groupname) +static void sign_group_unref(char *groupname) { signgroup_T *group; - hashitem_T *hi = hash_find(&sg_table, (char *)groupname); + hashitem_T *hi = hash_find(&sg_table, groupname); if (!HASHITEM_EMPTY(hi)) { group = HI2SG(hi); group->sg_refcount--; @@ -118,7 +117,7 @@ static void sign_group_unref(char_u *groupname) /// @return true if 'sign' is in 'group'. /// A sign can either be in the global group (sign->group == NULL) /// or in a named group. If 'group' is '*', then the sign is part of the group. -static bool sign_in_group(sign_entry_T *sign, const char_u *group) +static bool sign_in_group(sign_entry_T *sign, const char *group) { return ((group != NULL && STRCMP(group, "*") == 0) || (group == NULL && sign->se_group == NULL) @@ -127,7 +126,7 @@ static bool sign_in_group(sign_entry_T *sign, const char_u *group) } /// Get the next free sign identifier in the specified group -static int sign_group_get_next_signid(buf_T *buf, const char_u *groupname) +static int sign_group_get_next_signid(buf_T *buf, const char *groupname) { int id = 1; signgroup_T *group = NULL; @@ -154,7 +153,7 @@ static int sign_group_get_next_signid(buf_T *buf, const char_u *groupname) // Check whether this sign is already placed in the buffer found = true; FOR_ALL_SIGNS_IN_BUF(buf, sign) { - if (id == sign->se_id && sign_in_group(sign, groupname)) { + if (id == sign->se_id && sign_in_group(sign, (char *)groupname)) { found = false; // sign identifier is in use break; } @@ -177,7 +176,7 @@ static int sign_group_get_next_signid(buf_T *buf, const char_u *groupname) /// @param typenr typenr of sign we are adding /// @param has_text_or_icon sign has text or icon static void insert_sign(buf_T *buf, sign_entry_T *prev, sign_entry_T *next, int id, - const char_u *group, int prio, linenr_T lnum, int typenr, + const char *group, int prio, linenr_T lnum, int typenr, bool has_text_or_icon) { sign_entry_T *newsign = xmalloc(sizeof(sign_entry_T)); @@ -224,7 +223,7 @@ static void insert_sign(buf_T *buf, sign_entry_T *prev, sign_entry_T *next, int /// @param lnum line number which gets the mark /// @param typenr typenr of sign we are adding /// @param has_text_or_icon sign has text or icon -static void insert_sign_by_lnum_prio(buf_T *buf, sign_entry_T *prev, int id, const char_u *group, +static void insert_sign_by_lnum_prio(buf_T *buf, sign_entry_T *prev, int id, const char *group, int prio, linenr_T lnum, int typenr, bool has_text_or_icon) { sign_entry_T *sign; @@ -259,7 +258,7 @@ static sign_T *find_sign_by_typenr(int typenr) } /// Get the name of a sign by its typenr. -static char_u *sign_typenr2name(int typenr) +static char *sign_typenr2name(int typenr) { sign_T *sp; @@ -268,7 +267,7 @@ static char_u *sign_typenr2name(int typenr) return sp->sn_name; } } - return (char_u *)_("[Deleted]"); + return _("[Deleted]"); } /// Return information about a sign in a Dict @@ -280,7 +279,7 @@ static dict_T *sign_get_info(sign_entry_T *sign) ? (char *)"" : (char *)sign->se_group->sg_name)); tv_dict_add_nr(d, S_LEN("lnum"), sign->se_lnum); - tv_dict_add_str(d, S_LEN("name"), (char *)sign_typenr2name(sign->se_typenr)); + tv_dict_add_str(d, S_LEN("name"), sign_typenr2name(sign->se_typenr)); tv_dict_add_nr(d, S_LEN("priority"), sign->se_priority); return d; @@ -369,7 +368,7 @@ static void sign_sort_by_prio_on_line(buf_T *buf, sign_entry_T *sign) /// @param lnum line number which gets the mark /// @param typenr typenr of sign we are adding /// @param has_text_or_icon sign has text or icon -static void buf_addsign(buf_T *buf, int id, const char_u *groupname, int prio, linenr_T lnum, +static void buf_addsign(buf_T *buf, int id, const char *groupname, int prio, linenr_T lnum, int typenr, bool has_text_or_icon) { sign_entry_T *sign; // a sign in the signlist @@ -416,13 +415,13 @@ static void buf_addsign(buf_T *buf, int id, const char_u *groupname, int prio, l /// @param group sign group /// @param typenr typenr of sign we are adding /// @param prio sign priority -static linenr_T buf_change_sign_type(buf_T *buf, int markId, const char_u *group, int typenr, +static linenr_T buf_change_sign_type(buf_T *buf, int markId, const char *group, int typenr, int prio) { sign_entry_T *sign; // a sign in the signlist FOR_ALL_SIGNS_IN_BUF(buf, sign) { - if (sign->se_id == markId && sign_in_group(sign, group)) { + if (sign->se_id == markId && sign_in_group(sign, (char *)group)) { sign->se_typenr = typenr; sign->se_priority = prio; sign_sort_by_prio_on_line(buf, sign); @@ -534,7 +533,7 @@ int buf_get_signattrs(buf_T *buf, linenr_T lnum, SignTextAttrs sattrs[], HlPriAt /// /// @return the line number of the deleted sign. If multiple signs are deleted, /// then returns the line number of the last sign deleted. -static linenr_T buf_delsign(buf_T *buf, linenr_T atlnum, int id, char_u *group) +static linenr_T buf_delsign(buf_T *buf, linenr_T atlnum, int id, char *group) { sign_entry_T **lastp; // pointer to pointer to current sign sign_entry_T *sign; // a sign in a b_signlist @@ -555,7 +554,7 @@ static linenr_T buf_delsign(buf_T *buf, linenr_T atlnum, int id, char_u *group) lnum = sign->se_lnum; buf_signcols_del_check(buf, lnum, lnum); if (sign->se_group != NULL) { - sign_group_unref(sign->se_group->sg_name); + sign_group_unref((char *)sign->se_group->sg_name); } xfree(sign); redraw_buf_line_later(buf, lnum); @@ -590,7 +589,7 @@ static linenr_T buf_delsign(buf_T *buf, linenr_T atlnum, int id, char_u *group) /// @param buf buffer to store sign in /// @param id sign ID /// @param group sign group -static int buf_findsign(buf_T *buf, int id, char_u *group) +static int buf_findsign(buf_T *buf, int id, char *group) { sign_entry_T *sign; // a sign in the signlist @@ -609,7 +608,7 @@ static int buf_findsign(buf_T *buf, int id, char_u *group) /// @param buf buffer whose sign we are searching for /// @param lnum line number of sign /// @param groupname sign group name -static sign_entry_T *buf_getsign_at_line(buf_T *buf, linenr_T lnum, char_u *groupname) +static sign_entry_T *buf_getsign_at_line(buf_T *buf, linenr_T lnum, char *groupname) { sign_entry_T *sign; // a sign in the signlist @@ -633,7 +632,7 @@ static sign_entry_T *buf_getsign_at_line(buf_T *buf, linenr_T lnum, char_u *grou /// @param buf buffer whose sign we are searching for /// @param lnum line number of sign /// @param groupname sign group name -static int buf_findsign_id(buf_T *buf, linenr_T lnum, char_u *groupname) +static int buf_findsign_id(buf_T *buf, linenr_T lnum, char *groupname) { sign_entry_T *sign; // a sign in the signlist @@ -661,13 +660,13 @@ void buf_delete_signs(buf_T *buf, char *group) lastp = &buf->b_signlist; for (sign = buf->b_signlist; sign != NULL; sign = next) { next = sign->se_next; - if (sign_in_group(sign, (char_u *)group)) { + if (sign_in_group(sign, group)) { *lastp = next; if (next != NULL) { next->se_prev = sign->se_prev; } if (sign->se_group != NULL) { - sign_group_unref(sign->se_group->sg_name); + sign_group_unref((char *)sign->se_group->sg_name); } xfree(sign); } else { @@ -678,7 +677,7 @@ void buf_delete_signs(buf_T *buf, char *group) } /// List placed signs for "rbuf". If "rbuf" is NULL do it for all buffers. -static void sign_list_placed(buf_T *rbuf, char_u *sign_group) +static void sign_list_placed(buf_T *rbuf, char *sign_group) { buf_T *buf; sign_entry_T *sign; @@ -778,12 +777,12 @@ void sign_mark_adjust(linenr_T line1, linenr_T line2, linenr_T amount, linenr_T /// /// @param begin_cmd begin of sign subcmd /// @param end_cmd just after sign subcmd -static int sign_cmd_idx(char_u *begin_cmd, char_u *end_cmd) +static int sign_cmd_idx(char *begin_cmd, char *end_cmd) { int idx; - char_u save = *end_cmd; + char save = *end_cmd; - *end_cmd = (char_u)NUL; + *end_cmd = NUL; for (idx = 0;; idx++) { if (cmds[idx] == NULL || STRCMP(begin_cmd, cmds[idx]) == 0) { break; @@ -794,7 +793,7 @@ static int sign_cmd_idx(char_u *begin_cmd, char_u *end_cmd) } /// Find a sign by name. Also returns pointer to the previous sign. -static sign_T *sign_find(const char_u *name, sign_T **sp_prev) +static sign_T *sign_find(const char *name, sign_T **sp_prev) { sign_T *sp; @@ -814,7 +813,7 @@ static sign_T *sign_find(const char_u *name, sign_T **sp_prev) } /// Allocate a new sign -static sign_T *alloc_new_sign(char_u *name) +static sign_T *alloc_new_sign(char *name) { sign_T *sp; sign_T *lp; @@ -848,24 +847,24 @@ static sign_T *alloc_new_sign(char_u *name) next_sign_typenr = 1; // wrap around } - sp->sn_name = vim_strsave(name); + sp->sn_name = xstrdup(name); return sp; } /// Initialize the icon information for a new sign -static void sign_define_init_icon(sign_T *sp, char_u *icon) +static void sign_define_init_icon(sign_T *sp, char *icon) { xfree(sp->sn_icon); - sp->sn_icon = vim_strsave(icon); - backslash_halve((char *)sp->sn_icon); + sp->sn_icon = xstrdup(icon); + backslash_halve(sp->sn_icon); } /// Initialize the text for a new sign -static int sign_define_init_text(sign_T *sp, char_u *text) +static int sign_define_init_text(sign_T *sp, char *text) { - char_u *s; - char_u *endp; + char *s; + char *endp; int cells; size_t len; @@ -880,11 +879,11 @@ static int sign_define_init_text(sign_T *sp, char_u *text) } // Count cells and check for non-printable chars cells = 0; - for (s = text; s < endp; s += utfc_ptr2len((char *)s)) { - if (!vim_isprintc(utf_ptr2char((char *)s))) { + for (s = text; s < endp; s += utfc_ptr2len(s)) { + if (!vim_isprintc(utf_ptr2char(s))) { break; } - cells += utf_ptr2cells((char *)s); + cells += utf_ptr2cells(s); } // Currently must be empty, one or two display cells if (s != endp || cells > 2) { @@ -900,7 +899,7 @@ static int sign_define_init_text(sign_T *sp, char_u *text) // Allocate one byte more if we need to pad up // with a space. len = (size_t)(endp - text + ((cells == 1) ? 1 : 0)); - sp->sn_text = vim_strnsave(text, len); + sp->sn_text = xstrnsave(text, len); if (cells == 1) { STRCPY(sp->sn_text + len - 1, " "); @@ -910,8 +909,8 @@ static int sign_define_init_text(sign_T *sp, char_u *text) } /// Define a new sign or update an existing sign -static int sign_define_by_name(char_u *name, char_u *icon, char_u *linehl, char_u *text, - char_u *texthl, char_u *culhl, char *numhl) +static int sign_define_by_name(char *name, char *icon, char *linehl, char *text, char *texthl, + char *culhl, char *numhl) { sign_T *sp_prev; sign_T *sp; @@ -952,7 +951,7 @@ static int sign_define_by_name(char_u *name, char_u *icon, char_u *linehl, char_ if (*linehl == NUL) { sp->sn_line_hl = 0; } else { - sp->sn_line_hl = syn_check_group((char *)linehl, STRLEN(linehl)); + sp->sn_line_hl = syn_check_group(linehl, STRLEN(linehl)); } } @@ -960,7 +959,7 @@ static int sign_define_by_name(char_u *name, char_u *icon, char_u *linehl, char_ if (*texthl == NUL) { sp->sn_text_hl = 0; } else { - sp->sn_text_hl = syn_check_group((char *)texthl, STRLEN(texthl)); + sp->sn_text_hl = syn_check_group(texthl, STRLEN(texthl)); } } @@ -968,7 +967,7 @@ static int sign_define_by_name(char_u *name, char_u *icon, char_u *linehl, char_ if (*culhl == NUL) { sp->sn_cul_hl = 0; } else { - sp->sn_cul_hl = syn_check_group((char *)culhl, STRLEN(culhl)); + sp->sn_cul_hl = syn_check_group(culhl, STRLEN(culhl)); } } @@ -984,7 +983,7 @@ static int sign_define_by_name(char_u *name, char_u *icon, char_u *linehl, char_ } /// Free the sign specified by 'name'. -static int sign_undefine_by_name(const char_u *name) +static int sign_undefine_by_name(const char *name) { sign_T *sp_prev; sign_T *sp; @@ -1000,7 +999,7 @@ static int sign_undefine_by_name(const char_u *name) } /// List the signs matching 'name' -static void sign_list_by_name(char_u *name) +static void sign_list_by_name(char *name) { sign_T *sp; @@ -1024,7 +1023,7 @@ static void may_force_numberwidth_recompute(buf_T *buf, int unplace) } /// Place a sign at the specified file location or update a sign. -static int sign_place(int *sign_id, const char_u *sign_group, const char_u *sign_name, buf_T *buf, +static int sign_place(int *sign_id, const char *sign_group, const char *sign_name, buf_T *buf, linenr_T lnum, int prio) { sign_T *sp; @@ -1044,7 +1043,7 @@ static int sign_place(int *sign_id, const char_u *sign_group, const char_u *sign return FAIL; } if (*sign_id == 0) { - *sign_id = sign_group_get_next_signid(buf, sign_group); + *sign_id = sign_group_get_next_signid(buf, (char *)sign_group); } if (lnum > 0) { @@ -1053,14 +1052,14 @@ static int sign_place(int *sign_id, const char_u *sign_group, const char_u *sign bool has_text_or_icon = sp->sn_text != NULL || sp->sn_icon != NULL; buf_addsign(buf, *sign_id, - sign_group, + (char *)sign_group, prio, lnum, sp->sn_typenr, has_text_or_icon); } else { // ":sign place {id} file={fname}": change sign type and/or priority - lnum = buf_change_sign_type(buf, *sign_id, sign_group, sp->sn_typenr, prio); + lnum = buf_change_sign_type(buf, *sign_id, (char *)sign_group, sp->sn_typenr, prio); } if (lnum > 0) { redraw_buf_line_later(buf, lnum); @@ -1077,7 +1076,7 @@ static int sign_place(int *sign_id, const char_u *sign_group, const char_u *sign } /// Unplace the specified sign -static int sign_unplace(int sign_id, char_u *sign_group, buf_T *buf, linenr_T atlnum) +static int sign_unplace(int sign_id, char *sign_group, buf_T *buf, linenr_T atlnum) { if (buf->b_signlist == NULL) { // No signs in the buffer return OK; @@ -1085,7 +1084,7 @@ static int sign_unplace(int sign_id, char_u *sign_group, buf_T *buf, linenr_T at if (sign_id == 0) { // Delete all the signs in the specified buffer redraw_buf_later(buf, UPD_NOT_VALID); - buf_delete_signs(buf, (char *)sign_group); + buf_delete_signs(buf, sign_group); } else { linenr_T lnum; @@ -1108,7 +1107,7 @@ static int sign_unplace(int sign_id, char_u *sign_group, buf_T *buf, linenr_T at } /// Unplace the sign at the current cursor line. -static void sign_unplace_at_cursor(char_u *groupname) +static void sign_unplace_at_cursor(char *groupname) { int id = -1; @@ -1121,7 +1120,7 @@ static void sign_unplace_at_cursor(char_u *groupname) } /// Jump to a sign. -static linenr_T sign_jump(int sign_id, char_u *sign_group, buf_T *buf) +static linenr_T sign_jump(int sign_id, char *sign_group, buf_T *buf) { linenr_T lnum; @@ -1154,49 +1153,49 @@ static linenr_T sign_jump(int sign_id, char_u *sign_group, buf_T *buf) } /// ":sign define {name} ..." command -static void sign_define_cmd(char_u *sign_name, char_u *cmdline) -{ - char_u *arg; - char_u *p = cmdline; - char_u *icon = NULL; - char_u *text = NULL; - char_u *linehl = NULL; - char_u *texthl = NULL; - char_u *culhl = NULL; - char_u *numhl = NULL; +static void sign_define_cmd(char *sign_name, char *cmdline) +{ + char *arg; + char *p = cmdline; + char *icon = NULL; + char *text = NULL; + char *linehl = NULL; + char *texthl = NULL; + char *culhl = NULL; + char *numhl = NULL; int failed = false; // set values for a defined sign. for (;;) { - arg = (char_u *)skipwhite((char *)p); + arg = skipwhite(p); if (*arg == NUL) { break; } - p = (char_u *)skiptowhite_esc((char *)arg); + p = skiptowhite_esc(arg); if (STRNCMP(arg, "icon=", 5) == 0) { arg += 5; XFREE_CLEAR(icon); - icon = vim_strnsave(arg, (size_t)(p - arg)); + icon = xstrnsave(arg, (size_t)(p - arg)); } else if (STRNCMP(arg, "text=", 5) == 0) { arg += 5; XFREE_CLEAR(text); - text = vim_strnsave(arg, (size_t)(p - arg)); + text = xstrnsave(arg, (size_t)(p - arg)); } else if (STRNCMP(arg, "linehl=", 7) == 0) { arg += 7; XFREE_CLEAR(linehl); - linehl = vim_strnsave(arg, (size_t)(p - arg)); + linehl = xstrnsave(arg, (size_t)(p - arg)); } else if (STRNCMP(arg, "texthl=", 7) == 0) { arg += 7; XFREE_CLEAR(texthl); - texthl = vim_strnsave(arg, (size_t)(p - arg)); + texthl = xstrnsave(arg, (size_t)(p - arg)); } else if (STRNCMP(arg, "culhl=", 6) == 0) { arg += 6; XFREE_CLEAR(culhl); - culhl = vim_strnsave(arg, (size_t)(p - arg)); + culhl = xstrnsave(arg, (size_t)(p - arg)); } else if (STRNCMP(arg, "numhl=", 6) == 0) { arg += 6; XFREE_CLEAR(numhl); - numhl = vim_strnsave(arg, (size_t)(p - arg)); + numhl = xstrnsave(arg, (size_t)(p - arg)); } else { semsg(_(e_invarg2), arg); failed = true; @@ -1205,7 +1204,8 @@ static void sign_define_cmd(char_u *sign_name, char_u *cmdline) } if (!failed) { - sign_define_by_name(sign_name, icon, linehl, text, texthl, culhl, (char *)numhl); + sign_define_by_name(sign_name, icon, linehl, text, + texthl, culhl, numhl); } xfree(icon); @@ -1217,7 +1217,7 @@ static void sign_define_cmd(char_u *sign_name, char_u *cmdline) } /// ":sign place" command -static void sign_place_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, char_u *group, +static void sign_place_cmd(buf_T *buf, linenr_T lnum, char *sign_name, int id, char *group, int prio) { if (id <= 0) { @@ -1250,7 +1250,7 @@ static void sign_place_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, } /// ":sign unplace" command -static void sign_unplace_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, char_u *group) +static void sign_unplace_cmd(buf_T *buf, linenr_T lnum, char *sign_name, int id, char *group) { if (lnum >= 0 || sign_name != NULL || (group != NULL && *group == '\0')) { emsg(_(e_invarg)); @@ -1272,7 +1272,7 @@ static void sign_unplace_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int i // :sign unplace * group=* FOR_ALL_BUFFERS(cbuf) { if (cbuf->b_signlist != NULL) { - buf_delete_signs(cbuf, (char *)group); + buf_delete_signs(cbuf, group); } } } @@ -1307,7 +1307,7 @@ static void sign_unplace_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int i /// :sign jump {id} buffer={nr} /// :sign jump {id} group={group} file={fname} /// :sign jump {id} group={group} buffer={nr} -static void sign_jump_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, char_u *group) +static void sign_jump_cmd(buf_T *buf, linenr_T lnum, char *sign_name, int id, char *group) { if (sign_name == NULL && group == NULL && id == -1) { emsg(_(e_argreq)); @@ -1329,31 +1329,31 @@ static void sign_jump_cmd(buf_T *buf, linenr_T lnum, char_u *sign_name, int id, /// ":sign jump" commands. /// The supported arguments are: line={lnum} name={name} group={group} /// priority={prio} and file={fname} or buffer={nr}. -static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *signid, - char_u **group, int *prio, buf_T **buf, linenr_T *lnum) +static int parse_sign_cmd_args(int cmd, char *arg, char **sign_name, int *signid, char **group, + int *prio, buf_T **buf, linenr_T *lnum) { - char_u *arg1; - char_u *name; - char_u *filename = NULL; + char *arg1; + char *name; + char *filename = NULL; int lnum_arg = false; // first arg could be placed sign id arg1 = arg; if (ascii_isdigit(*arg)) { - *signid = getdigits_int((char **)&arg, true, 0); + *signid = getdigits_int(&arg, true, 0); if (!ascii_iswhite(*arg) && *arg != NUL) { *signid = -1; arg = arg1; } else { - arg = (char_u *)skipwhite((char *)arg); + arg = skipwhite(arg); } } while (*arg != NUL) { if (STRNCMP(arg, "line=", 5) == 0) { arg += 5; - *lnum = atoi((char *)arg); - arg = (char_u *)skiptowhite((char *)arg); + *lnum = atoi(arg); + arg = skiptowhite(arg); lnum_arg = true; } else if (STRNCMP(arg, "*", 1) == 0 && cmd == SIGNCMD_UNPLACE) { if (*signid != -1) { @@ -1361,11 +1361,11 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si return FAIL; } *signid = -2; - arg = (char_u *)skiptowhite((char *)arg + 1); + arg = skiptowhite(arg + 1); } else if (STRNCMP(arg, "name=", 5) == 0) { arg += 5; name = arg; - arg = (char_u *)skiptowhite((char *)arg); + arg = skiptowhite(arg); if (*arg != NUL) { *arg++ = NUL; } @@ -1376,24 +1376,24 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si } else if (STRNCMP(arg, "group=", 6) == 0) { arg += 6; *group = arg; - arg = (char_u *)skiptowhite((char *)arg); + arg = skiptowhite(arg); if (*arg != NUL) { *arg++ = NUL; } } else if (STRNCMP(arg, "priority=", 9) == 0) { arg += 9; - *prio = atoi((char *)arg); - arg = (char_u *)skiptowhite((char *)arg); + *prio = atoi(arg); + arg = skiptowhite(arg); } else if (STRNCMP(arg, "file=", 5) == 0) { arg += 5; filename = arg; - *buf = buflist_findname_exp((char *)arg); + *buf = buflist_findname_exp(arg); break; } else if (STRNCMP(arg, "buffer=", 7) == 0) { arg += 7; filename = arg; - *buf = buflist_findnr(getdigits_int((char **)&arg, true, 0)); - if (*skipwhite((char *)arg) != NUL) { + *buf = buflist_findnr(getdigits_int(&arg, true, 0)); + if (*skipwhite(arg) != NUL) { semsg(_(e_trailing_arg), arg); } break; @@ -1401,7 +1401,7 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si emsg(_(e_invarg)); return FAIL; } - arg = (char_u *)skipwhite((char *)arg); + arg = skipwhite(arg); } if (filename != NULL && *buf == NULL) { @@ -1421,19 +1421,19 @@ static int parse_sign_cmd_args(int cmd, char_u *arg, char_u **sign_name, int *si /// ":sign" command void ex_sign(exarg_T *eap) { - char_u *arg = (char_u *)eap->arg; - char_u *p; + char *arg = eap->arg; + char *p; int idx; sign_T *sp; // Parse the subcommand. - p = (char_u *)skiptowhite((char *)arg); + p = skiptowhite(arg); idx = sign_cmd_idx(arg, p); if (idx == SIGNCMD_LAST) { semsg(_("E160: Unknown sign command: %s"), arg); return; } - arg = (char_u *)skipwhite((char *)p); + arg = skipwhite(p); if (idx <= SIGNCMD_LIST) { // Define, undefine or list signs. @@ -1445,18 +1445,18 @@ void ex_sign(exarg_T *eap) } else if (*arg == NUL) { emsg(_("E156: Missing sign name")); } else { - char_u *name; + char *name; // Isolate the sign name. If it's a number skip leading zeroes, // so that "099" and "99" are the same sign. But keep "0". - p = (char_u *)skiptowhite((char *)arg); + p = skiptowhite(arg); if (*p != NUL) { *p++ = NUL; } while (arg[0] == '0' && arg[1] != NUL) { arg++; } - name = vim_strsave(arg); + name = xstrdup(arg); if (idx == SIGNCMD_DEFINE) { sign_define_cmd(name, p); @@ -1474,8 +1474,8 @@ void ex_sign(exarg_T *eap) } else { int id = -1; linenr_T lnum = -1; - char_u *sign_name = NULL; - char_u *group = NULL; + char *sign_name = NULL; + char *group = NULL; int prio = SIGN_DEF_PRIO; buf_T *buf = NULL; @@ -1500,12 +1500,12 @@ static void sign_getinfo(sign_T *sp, dict_T *retdict) { const char *p; - tv_dict_add_str(retdict, S_LEN("name"), (char *)sp->sn_name); + tv_dict_add_str(retdict, S_LEN("name"), sp->sn_name); if (sp->sn_icon != NULL) { - tv_dict_add_str(retdict, S_LEN("icon"), (char *)sp->sn_icon); + tv_dict_add_str(retdict, S_LEN("icon"), sp->sn_icon); } if (sp->sn_text != NULL) { - tv_dict_add_str(retdict, S_LEN("text"), (char *)sp->sn_text); + tv_dict_add_str(retdict, S_LEN("text"), sp->sn_text); } if (sp->sn_line_hl > 0) { p = get_highlight_name_ext(NULL, sp->sn_line_hl - 1, false); @@ -1539,13 +1539,13 @@ static void sign_getinfo(sign_T *sp, dict_T *retdict) /// If 'name' is NULL, return a list of all the defined signs. /// Otherwise, return information about the specified sign. -static void sign_getlist(const char_u *name, list_T *retlist) +static void sign_getlist(const char *name, list_T *retlist) { sign_T *sp = first_sign; dict_T *dict; if (name != NULL) { - sp = sign_find(name, NULL); + sp = sign_find((char *)name, NULL); if (sp == NULL) { return; } @@ -1577,8 +1577,8 @@ list_T *get_buffer_signs(buf_T *buf) return l; } -/// Return information about all the signs placed in a buffer -static void sign_get_placed_in_buf(buf_T *buf, linenr_T lnum, int sign_id, const char_u *sign_group, +/// @return information about all the signs placed in a buffer +static void sign_get_placed_in_buf(buf_T *buf, linenr_T lnum, int sign_id, const char *sign_group, list_T *retlist) { dict_T *d; @@ -1594,7 +1594,7 @@ static void sign_get_placed_in_buf(buf_T *buf, linenr_T lnum, int sign_id, const tv_dict_add_list(d, S_LEN("signs"), l); FOR_ALL_SIGNS_IN_BUF(buf, sign) { - if (!sign_in_group(sign, sign_group)) { + if (!sign_in_group(sign, (char *)sign_group)) { continue; } if ((lnum == 0 && sign_id == 0) @@ -1609,7 +1609,7 @@ static void sign_get_placed_in_buf(buf_T *buf, linenr_T lnum, int sign_id, const /// Get a list of signs placed in buffer 'buf'. If 'num' is non-zero, return the /// sign placed at the line number. If 'lnum' is zero, return all the signs /// placed in 'buf'. If 'buf' is NULL, return signs placed in all the buffers. -static void sign_get_placed(buf_T *buf, linenr_T lnum, int sign_id, const char_u *sign_group, +static void sign_get_placed(buf_T *buf, linenr_T lnum, int sign_id, const char *sign_group, list_T *retlist) { if (buf != NULL) { @@ -1629,12 +1629,12 @@ static void sign_list_defined(sign_T *sp) smsg("sign %s", sp->sn_name); if (sp->sn_icon != NULL) { msg_puts(" icon="); - msg_outtrans((char *)sp->sn_icon); + msg_outtrans(sp->sn_icon); msg_puts(_(" (not supported)")); } if (sp->sn_text != NULL) { msg_puts(" text="); - msg_outtrans((char *)sp->sn_text); + msg_outtrans(sp->sn_text); } if (sp->sn_line_hl > 0) { msg_puts(" linehl="); @@ -1710,8 +1710,8 @@ static enum { EXP_SIGN_GROUPS, // expand with name of placed sign groups } expand_what; -// Return the n'th sign name (used for command line completion) -static char_u *get_nth_sign_name(int idx) +/// @return the n'th sign name (used for command line completion) +static char *get_nth_sign_name(int idx) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { // Complete with name of signs already defined @@ -1724,8 +1724,8 @@ static char_u *get_nth_sign_name(int idx) return NULL; } -// Return the n'th sign group name (used for command line completion) -static char_u *get_nth_sign_group_name(int idx) +/// @return the n'th sign group name (used for command line completion) +static char *get_nth_sign_group_name(int idx) { // Complete with name of sign groups already defined int current_idx = 0; @@ -1735,7 +1735,7 @@ static char_u *get_nth_sign_group_name(int idx) todo--; if (current_idx++ == idx) { signgroup_T *const group = HI2SG(hi); - return group->sg_name; + return (char *)group->sg_name; } } } @@ -1768,28 +1768,28 @@ char *get_sign_name(expand_T *xp, int idx) return unplace_arg[idx]; } case EXP_SIGN_NAMES: - return (char *)get_nth_sign_name(idx); + return get_nth_sign_name(idx); case EXP_SIGN_GROUPS: - return (char *)get_nth_sign_group_name(idx); + return get_nth_sign_group_name(idx); default: return NULL; } } /// Handle command line completion for :sign command. -void set_context_in_sign_cmd(expand_T *xp, char_u *arg) +void set_context_in_sign_cmd(expand_T *xp, char *arg) { - char_u *end_subcmd; - char_u *last; + char *end_subcmd; + char *last; int cmd_idx; - char_u *begin_subcmd_args; + char *begin_subcmd_args; // Default: expand subcommands. xp->xp_context = EXPAND_SIGN; expand_what = EXP_SUBCMD; - xp->xp_pattern = (char *)arg; + xp->xp_pattern = arg; - end_subcmd = (char_u *)skiptowhite((char *)arg); + end_subcmd = skiptowhite(arg); if (*end_subcmd == NUL) { // expand subcmd name // :sign {subcmd} @@ -1801,7 +1801,7 @@ void set_context_in_sign_cmd(expand_T *xp, char_u *arg) // :sign {subcmd} {subcmd_args} // | // begin_subcmd_args - begin_subcmd_args = (char_u *)skipwhite((char *)end_subcmd); + begin_subcmd_args = skipwhite(end_subcmd); // Expand last argument of subcmd. // @@ -1810,21 +1810,21 @@ void set_context_in_sign_cmd(expand_T *xp, char_u *arg) // p // Loop until reaching last argument. - char_u *p = begin_subcmd_args; + char *p = begin_subcmd_args; do { - p = (char_u *)skipwhite((char *)p); + p = skipwhite(p); last = p; - p = (char_u *)skiptowhite((char *)p); + p = skiptowhite(p); } while (*p != NUL); - p = (char_u *)vim_strchr((char *)last, '='); + p = vim_strchr(last, '='); // :sign define {name} {args}... {last}= // | | // last p if (p == NULL) { // Expand last argument name (before equal sign). - xp->xp_pattern = (char *)last; + xp->xp_pattern = last; switch (cmd_idx) { case SIGNCMD_DEFINE: expand_what = EXP_DEFINE; @@ -1854,7 +1854,7 @@ void set_context_in_sign_cmd(expand_T *xp, char_u *arg) } } else { // Expand last argument value (after equal sign). - xp->xp_pattern = (char *)p + 1; + xp->xp_pattern = p + 1; switch (cmd_idx) { case SIGNCMD_DEFINE: if (STRNCMP(last, "texthl", 6) == 0 @@ -1928,8 +1928,8 @@ static int sign_define_from_dict(const char *name_arg, dict_T *dict) numhl = tv_dict_get_string(dict, "numhl", true); } - if (sign_define_by_name((char_u *)name, (char_u *)icon, (char_u *)linehl, - (char_u *)text, (char_u *)texthl, (char_u *)culhl, numhl) + if (sign_define_by_name(name, icon, linehl, + text, texthl, culhl, numhl) == OK) { retval = 0; } @@ -2005,7 +2005,7 @@ void f_sign_getdefined(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) name = tv_get_string(&argvars[0]); } - sign_getlist((const char_u *)name, rettv->vval.v_list); + sign_getlist(name, rettv->vval.v_list); } /// "sign_getplaced()" function @@ -2062,8 +2062,7 @@ void f_sign_getplaced(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } } - sign_get_placed(buf, lnum, sign_id, (const char_u *)group, - rettv->vval.v_list); + sign_get_placed(buf, lnum, sign_id, group, rettv->vval.v_list); } /// "sign_jump()" function @@ -2103,7 +2102,7 @@ void f_sign_jump(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) goto cleanup; } - rettv->vval.v_number = sign_jump(sign_id, (char_u *)sign_group, buf); + rettv->vval.v_number = sign_jump(sign_id, sign_group, buf); cleanup: xfree(sign_group); @@ -2115,8 +2114,8 @@ static int sign_place_from_dict(typval_T *id_tv, typval_T *group_tv, typval_T *n typval_T *buf_tv, dict_T *dict) { int sign_id = 0; - char_u *group = NULL; - char_u *sign_name = NULL; + char *group = NULL; + char *sign_name = NULL; buf_T *buf = NULL; dictitem_T *di; linenr_T lnum = 0; @@ -2154,14 +2153,14 @@ static int sign_place_from_dict(typval_T *id_tv, typval_T *group_tv, typval_T *n if (group_tv == NULL) { group = NULL; // global group } else { - group = (char_u *)tv_get_string_chk(group_tv); + group = (char *)tv_get_string_chk(group_tv); if (group == NULL) { goto cleanup; } if (group[0] == '\0') { // global sign group group = NULL; } else { - group = vim_strsave(group); + group = xstrdup(group); } } @@ -2175,7 +2174,7 @@ static int sign_place_from_dict(typval_T *id_tv, typval_T *group_tv, typval_T *n if (name_tv == NULL) { goto cleanup; } - sign_name = (char_u *)tv_get_string_chk(name_tv); + sign_name = (char *)tv_get_string_chk(name_tv); if (sign_name == NULL) { goto cleanup; } @@ -2269,13 +2268,13 @@ void f_sign_placelist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// Undefine multiple signs static void sign_undefine_multiple(list_T *l, list_T *retlist) { - char_u *name; + char *name; int retval; TV_LIST_ITER_CONST(l, li, { retval = -1; - name = (char_u *)tv_get_string_chk(TV_LIST_ITEM_TV(li)); - if (name != NULL && (sign_undefine_by_name(name) == OK)) { + name = (char *)tv_get_string_chk(TV_LIST_ITEM_TV(li)); + if (name != NULL && (sign_undefine_by_name((char *)name) == OK)) { retval = 0; } tv_list_append_number(retlist, retval); @@ -2308,7 +2307,7 @@ void f_sign_undefine(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) return; } - if (sign_undefine_by_name((const char_u *)name) == OK) { + if (sign_undefine_by_name(name) == OK) { rettv->vval.v_number = 0; } } @@ -2321,20 +2320,20 @@ static int sign_unplace_from_dict(typval_T *group_tv, dict_T *dict) dictitem_T *di; int sign_id = 0; buf_T *buf = NULL; - char_u *group = NULL; + char *group = NULL; int retval = -1; // sign group if (group_tv != NULL) { - group = (char_u *)tv_get_string(group_tv); + group = (char *)tv_get_string(group_tv); } else { - group = (char_u *)tv_dict_get_string(dict, "group", false); + group = tv_dict_get_string(dict, "group", false); } if (group != NULL) { if (group[0] == '\0') { // global sign group group = NULL; } else { - group = vim_strsave(group); + group = xstrdup(group); } } diff --git a/src/nvim/sign_defs.h b/src/nvim/sign_defs.h index a4fb325ec8..1efde30008 100644 --- a/src/nvim/sign_defs.h +++ b/src/nvim/sign_defs.h @@ -34,7 +34,7 @@ struct sign_entry { /// Sign attributes. Used by the screen refresh routines. typedef struct { - char_u *text; + char *text; int hl_attr_id; int priority; } SignTextAttrs; diff --git a/src/nvim/spell.c b/src/nvim/spell.c index d8bc4b22c2..7c05c9fe53 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -3289,7 +3289,7 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg) // ignore case... assert(depth >= 0); if (depth <= patlen - && mb_strnicmp(word, pat, (size_t)depth) != 0) { + && mb_strnicmp((char *)word, (char *)pat, (size_t)depth) != 0) { depth--; } } @@ -3371,7 +3371,7 @@ static void dump_word(slang_T *slang, char_u *word, char_u *pat, Direction *dir, ml_append(lnum, (char *)p, (colnr_T)0, false); } else if (((dumpflags & DUMPFLAG_ICASE) - ? mb_strnicmp(p, pat, STRLEN(pat)) == 0 + ? mb_strnicmp((char *)p, (char *)pat, STRLEN(pat)) == 0 : STRNCMP(p, pat, STRLEN(pat)) == 0) && ins_compl_add_infercase(p, (int)STRLEN(p), p_ic, NULL, *dir, false) == OK) { diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index 1319894226..d8de23182c 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -797,7 +797,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) validate_current_state(); } -static void save_chartab(char_u *chartab) +static void save_chartab(char *chartab) { if (syn_block->b_syn_isk != empty_option) { memmove(chartab, syn_buf->b_chartab, (size_t)32); @@ -805,7 +805,7 @@ static void save_chartab(char_u *chartab) } } -static void restore_chartab(char_u *chartab) +static void restore_chartab(char *chartab) { if (syn_win->w_s->b_syn_isk != empty_option) { memmove(syn_buf->b_chartab, chartab, (size_t)32); @@ -819,7 +819,7 @@ static int syn_match_linecont(linenr_T lnum) regmmatch_T regmatch; // chartab array for syn iskeyword char_u buf_chartab[32]; - save_chartab(buf_chartab); + save_chartab((char *)buf_chartab); regmatch.rmm_ic = syn_block->b_syn_linecont_ic; regmatch.regprog = syn_block->b_syn_linecont_prog; @@ -827,7 +827,7 @@ static int syn_match_linecont(linenr_T lnum) IF_SYN_TIME(&syn_block->b_syn_linecont_time)); syn_block->b_syn_linecont_prog = regmatch.regprog; - restore_chartab(buf_chartab); + restore_chartab((char *)buf_chartab); return r; } return false; @@ -1677,7 +1677,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con ga_init(&zero_width_next_ga, (int)sizeof(int), 10); // use syntax iskeyword option - save_chartab(buf_chartab); + save_chartab((char *)buf_chartab); /* * Repeat matching keywords and patterns, to find contained items at the @@ -1713,7 +1713,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con && (current_col == 0 || !vim_iswordp_buf(cur_pos - 1 - utf_head_off((char *)line, (char *)cur_pos - 1), syn_buf))) { - syn_id = check_keyword_id(line, (int)current_col, &endcol, &flags, + syn_id = check_keyword_id((char *)line, (int)current_col, &endcol, &flags, &next_list, cur_si, &cchar); if (syn_id != 0) { push_current_state(KEYWORD_IDX); @@ -2004,7 +2004,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } while (found_match); - restore_chartab(buf_chartab); + restore_chartab((char *)buf_chartab); /* * Use attributes from the current state, if within its highlighting. @@ -2596,7 +2596,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ best_regmatch.startpos[0].col = 0; // avoid compiler warning // use syntax iskeyword option - save_chartab(buf_chartab); + save_chartab((char *)buf_chartab); for (;;) { /* @@ -2747,7 +2747,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ m_endpos->lnum = 0; } - restore_chartab(buf_chartab); + restore_chartab((char *)buf_chartab); // Remove external matches. unref_extmatch(re_extmatch_in); @@ -2932,17 +2932,17 @@ static int syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T /// @param next_listp return: next_list of matching keyword /// @param cur_si item at the top of the stack /// @param ccharp conceal substitution char -static int check_keyword_id(char_u *const line, const int startcol, int *const endcolp, +static int check_keyword_id(char *const line, const int startcol, int *const endcolp, long *const flagsp, int16_t **const next_listp, stateitem_T *const cur_si, int *const ccharp) { // Find first character after the keyword. First character was already // checked. - char_u *const kwp = line + startcol; + char *const kwp = line + startcol; int kwlen = 0; do { - kwlen += utfc_ptr2len((char *)kwp + kwlen); - } while (vim_iswordp_buf(kwp + kwlen, syn_buf)); + kwlen += utfc_ptr2len(kwp + kwlen); + } while (vim_iswordp_buf((char_u *)kwp + kwlen, syn_buf)); if (kwlen > MAXKEYWLEN) { return 0; @@ -2957,13 +2957,13 @@ static int check_keyword_id(char_u *const line, const int startcol, int *const e // matching case if (syn_block->b_keywtab.ht_used != 0) { - kp = match_keyword(keyword, &syn_block->b_keywtab, cur_si); + kp = match_keyword((char *)keyword, &syn_block->b_keywtab, cur_si); } // ignoring case if (kp == NULL && syn_block->b_keywtab_ic.ht_used != 0) { - str_foldcase(kwp, kwlen, keyword, MAXKEYWLEN + 1); - kp = match_keyword(keyword, &syn_block->b_keywtab_ic, cur_si); + str_foldcase((char_u *)kwp, kwlen, keyword, MAXKEYWLEN + 1); + kp = match_keyword((char *)keyword, &syn_block->b_keywtab_ic, cur_si); } if (kp != NULL) { @@ -2982,9 +2982,9 @@ static int check_keyword_id(char_u *const line, const int startcol, int *const e /// When current_next_list is non-zero accept only that group, otherwise: /// Accept a not-contained keyword at toplevel. /// Accept a keyword at other levels only if it is in the contains list. -static keyentry_T *match_keyword(char_u *keyword, hashtab_T *ht, stateitem_T *cur_si) +static keyentry_T *match_keyword(char *keyword, hashtab_T *ht, stateitem_T *cur_si) { - hashitem_T *hi = hash_find(ht, (char *)keyword); + hashitem_T *hi = hash_find(ht, keyword); if (!HASHITEM_EMPTY(hi)) { for (keyentry_T *kp = HI2KE(hi); kp != NULL; kp = kp->ke_next) { if (current_next_list != 0 @@ -3029,20 +3029,18 @@ static void syn_cmd_conceal(exarg_T *eap, int syncing) } } -/* - * Handle ":syntax case" command. - */ +/// Handle ":syntax case" command. static void syn_cmd_case(exarg_T *eap, int syncing) { - char_u *arg = (char_u *)eap->arg; - char_u *next; + char *arg = eap->arg; + char *next; - eap->nextcmd = find_nextcmd((char *)arg); + eap->nextcmd = find_nextcmd(arg); if (eap->skip) { return; } - next = (char_u *)skiptowhite((char *)arg); + next = skiptowhite(arg); if (*arg == NUL) { if (curwin->w_s->b_syn_ic) { msg("syntax case ignore"); @@ -3097,20 +3095,18 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) } } -/* - * Handle ":syntax spell" command. - */ +/// Handle ":syntax spell" command. static void syn_cmd_spell(exarg_T *eap, int syncing) { - char_u *arg = (char_u *)eap->arg; - char_u *next; + char *arg = eap->arg; + char *next; - eap->nextcmd = find_nextcmd((char *)arg); + eap->nextcmd = find_nextcmd(arg); if (eap->skip) { return; } - next = (char_u *)skiptowhite((char *)arg); + next = skiptowhite(arg); if (*arg == NUL) { if (curwin->w_s->b_syn_spell == SYNSPL_TOP) { msg("syntax spell toplevel"); @@ -3137,15 +3133,15 @@ static void syn_cmd_spell(exarg_T *eap, int syncing) /// Handle ":syntax iskeyword" command. static void syn_cmd_iskeyword(exarg_T *eap, int syncing) { - char_u *arg = (char_u *)eap->arg; - char_u save_chartab[32]; - char_u *save_isk; + char *arg = eap->arg; + char save_chartab[32]; + char *save_isk; if (eap->skip) { return; } - arg = (char_u *)skipwhite((char *)arg); + arg = skipwhite(arg); if (*arg == NUL) { msg_puts("\n"); if (curwin->w_s->b_syn_isk != empty_option) { @@ -3160,15 +3156,15 @@ static void syn_cmd_iskeyword(exarg_T *eap, int syncing) clear_string_option(&curwin->w_s->b_syn_isk); } else { memmove(save_chartab, curbuf->b_chartab, (size_t)32); - save_isk = (char_u *)curbuf->b_p_isk; - curbuf->b_p_isk = (char *)vim_strsave(arg); + save_isk = curbuf->b_p_isk; + curbuf->b_p_isk = xstrdup(arg); buf_init_chartab(curbuf, false); memmove(curwin->w_s->b_syn_chartab, curbuf->b_chartab, (size_t)32); memmove(curbuf->b_chartab, save_chartab, (size_t)32); clear_string_option(&curwin->w_s->b_syn_isk); curwin->w_s->b_syn_isk = curbuf->b_p_isk; - curbuf->b_p_isk = (char *)save_isk; + curbuf->b_p_isk = save_isk; } } redraw_later(curwin, UPD_NOT_VALID); @@ -3303,16 +3299,14 @@ static void syn_clear_cluster(synblock_T *block, int i) xfree(SYN_CLSTR(block)[i].scl_list); } -/* - * Handle ":syntax clear" command. - */ +/// Handle ":syntax clear" command. static void syn_cmd_clear(exarg_T *eap, int syncing) { - char_u *arg = (char_u *)eap->arg; - char_u *arg_end; + char *arg = eap->arg; + char *arg_end; int id; - eap->nextcmd = find_nextcmd((char *)arg); + eap->nextcmd = find_nextcmd(arg); if (eap->skip) { return; } @@ -3345,7 +3339,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) * Clear the group IDs that are in the argument. */ while (!ends_excmd(*arg)) { - arg_end = (char_u *)skiptowhite((char *)arg); + arg_end = skiptowhite(arg); if (*arg == '@') { id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { @@ -3360,7 +3354,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) XFREE_CLEAR(SYN_CLSTR(curwin->w_s)[scl_id].scl_list); } } else { - id = syn_name2id_len((char *)arg, (size_t)(arg_end - arg)); + id = syn_name2id_len(arg, (size_t)(arg_end - arg)); if (id == 0) { semsg(_(e_nogroup), arg); break; @@ -3368,7 +3362,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) syn_clear_one(id, syncing); } } - arg = (char_u *)skipwhite((char *)arg_end); + arg = skipwhite(arg_end); } } redraw_curbuf_later(UPD_SOME_VALID); @@ -3412,7 +3406,7 @@ static void syn_cmd_on(exarg_T *eap, int syncing) */ static void syn_cmd_reset(exarg_T *eap, int syncing) { - eap->nextcmd = (char *)check_nextcmd((char_u *)eap->arg); + eap->nextcmd = check_nextcmd(eap->arg); if (!eap->skip) { init_highlight(true, true); } @@ -3437,7 +3431,7 @@ static void syn_cmd_off(exarg_T *eap, int syncing) static void syn_cmd_onoff(exarg_T *eap, char *name) FUNC_ATTR_NONNULL_ALL { - eap->nextcmd = (char *)check_nextcmd((char_u *)eap->arg); + eap->nextcmd = check_nextcmd(eap->arg); if (!eap->skip) { did_syntax_onoff = true; char buf[100]; @@ -3524,7 +3518,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing) while (!ends_excmd(*arg) && !got_int) { arg_end = (char_u *)skiptowhite((char *)arg); if (*arg == '@') { - int id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); + int id = syn_scl_namen2id((char *)arg + 1, (int)(arg_end - arg - 1)); if (id == 0) { semsg(_("E392: No such syntax cluster: %s"), arg); } else { @@ -3541,7 +3535,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing) arg = (char_u *)skipwhite((char *)arg_end); } } - eap->nextcmd = (char *)check_nextcmd(arg); + eap->nextcmd = check_nextcmd((char *)arg); } static void syn_lines_msg(void) @@ -3977,13 +3971,14 @@ static void clear_keywtab(hashtab_T *ht) /// @param flags flags for this keyword /// @param cont_in_list containedin for this keyword /// @param next_list nextgroup for this keyword -static void add_keyword(char_u *const name, const int id, const int flags, +static void add_keyword(char *const name, const int id, const int flags, int16_t *const cont_in_list, int16_t *const next_list, const int conceal_char) { - char_u name_folded[MAXKEYWLEN + 1]; - const char_u *const name_ic = (curwin->w_s->b_syn_ic) - ? str_foldcase(name, (int)STRLEN(name), name_folded, sizeof(name_folded)) + char name_folded[MAXKEYWLEN + 1]; + const char *const name_ic = (curwin->w_s->b_syn_ic) + ? (char *)str_foldcase((char_u *)name, (int)STRLEN(name), (char_u *)name_folded, + sizeof(name_folded)) : name; keyentry_T *const kp = xmalloc(sizeof(keyentry_T) + STRLEN(name_ic)); @@ -4249,7 +4244,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) emsg(_("E397: Filename required")); return; } - sgl_id = syn_check_cluster((char_u *)arg, (int)(group_name_end - arg)); + sgl_id = syn_check_cluster(arg, (int)(group_name_end - arg)); if (sgl_id == 0) { return; } @@ -4364,7 +4359,7 @@ static void syn_cmd_keyword(exarg_T *eap, int syncing) if (p != NULL) { *p = NUL; } - add_keyword((char_u *)kw, syn_id, syn_opt_arg.flags, + add_keyword(kw, syn_id, syn_opt_arg.flags, syn_opt_arg.cont_in_list, syn_opt_arg.next_list, conceal_char); if (p == NULL) { @@ -4399,7 +4394,7 @@ error: } if (rest != NULL) { - eap->nextcmd = (char *)check_nextcmd((char_u *)rest); + eap->nextcmd = check_nextcmd(rest); } else { semsg(_(e_invarg2), arg); } @@ -4439,7 +4434,7 @@ static void syn_cmd_match(exarg_T *eap, int syncing) // get the pattern. init_syn_patterns(); CLEAR_FIELD(item); - rest = get_syn_pattern((char_u *)rest, &item); + rest = get_syn_pattern(rest, &item); if (vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) { syn_opt_arg.flags |= HL_HAS_EOL; } @@ -4451,7 +4446,7 @@ static void syn_cmd_match(exarg_T *eap, int syncing) /* * Check for trailing command and illegal trailing arguments. */ - eap->nextcmd = (char *)check_nextcmd((char_u *)rest); + eap->nextcmd = check_nextcmd(rest); if (!ends_excmd(*rest) || eap->skip) { rest = NULL; } else { @@ -4631,7 +4626,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) assert(item == ITEM_SKIP || item == ITEM_END); reg_do_extmatch = REX_USE; } - rest = get_syn_pattern((char_u *)rest, ppp->pp_synp); + rest = get_syn_pattern(rest, ppp->pp_synp); reg_do_extmatch = 0; if (item == ITEM_END && vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) { @@ -4658,7 +4653,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) * Check for trailing garbage or command. * If OK, add the item. */ - eap->nextcmd = (char *)check_nextcmd((char_u *)rest); + eap->nextcmd = check_nextcmd(rest); if (!ends_excmd(*rest) || eap->skip) { rest = NULL; } else { @@ -4863,12 +4858,12 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con *clstr1 = clstr; } -// Lookup a syntax cluster name and return its ID. -// If it is not found, 0 is returned. -static int syn_scl_name2id(char_u *name) +/// Lookup a syntax cluster name and return its ID. +/// If it is not found, 0 is returned. +static int syn_scl_name2id(char *name) { // Avoid using stricmp() too much, it's slow on some systems - char_u *name_u = vim_strsave_up(name); + char *name_u = (char *)vim_strsave_up((char_u *)name); int i; for (i = curwin->w_s->b_syn_clusters.ga_len; --i >= 0;) { if (SYN_CLSTR(curwin->w_s)[i].scl_name_u != NULL @@ -4880,25 +4875,24 @@ static int syn_scl_name2id(char_u *name) return i < 0 ? 0 : i + SYNID_CLUSTER; } -/* - * Like syn_scl_name2id(), but take a pointer + length argument. - */ -static int syn_scl_namen2id(char_u *linep, int len) +/// Like syn_scl_name2id(), but take a pointer + length argument. +static int syn_scl_namen2id(char *linep, int len) { - char_u *name = vim_strnsave(linep, (size_t)len); + char *name = xstrnsave(linep, (size_t)len); int id = syn_scl_name2id(name); xfree(name); return id; } -// Find syntax cluster name in the table and return its ID. -// The argument is a pointer to the name and the length of the name. -// If it doesn't exist yet, a new entry is created. -// Return 0 for failure. -static int syn_check_cluster(char_u *pp, int len) +/// Find syntax cluster name in the table and return its ID. +/// The argument is a pointer to the name and the length of the name. +/// If it doesn't exist yet, a new entry is created. +/// +/// @return 0 for failure. +static int syn_check_cluster(char *pp, int len) { - char_u *name = vim_strnsave(pp, (size_t)len); + char *name = xstrnsave(pp, (size_t)len); int id = syn_scl_name2id(name); if (id == 0) { // doesn't exist yet id = syn_add_cluster(name); @@ -4908,10 +4902,11 @@ static int syn_check_cluster(char_u *pp, int len) return id; } -// Add new syntax cluster and return its ID. -// "name" must be an allocated string, it will be consumed. -// Return 0 for failure. -static int syn_add_cluster(char_u *name) +/// Add new syntax cluster and return its ID. +/// "name" must be an allocated string, it will be consumed. +/// +/// @return 0 for failure. +static int syn_add_cluster(char *name) { /* * First call for this growarray: init growing array. @@ -4931,8 +4926,8 @@ static int syn_add_cluster(char_u *name) syn_cluster_T *scp = GA_APPEND_VIA_PTR(syn_cluster_T, &curwin->w_s->b_syn_clusters); CLEAR_POINTER(scp); - scp->scl_name = name; - scp->scl_name_u = vim_strsave_up(name); + scp->scl_name = (char_u *)name; + scp->scl_name_u = vim_strsave_up((char_u *)name); scp->scl_list = NULL; if (STRICMP(name, "Spell") == 0) { @@ -4966,7 +4961,7 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) rest = get_group_name(arg, &group_name_end); if (rest != NULL) { - int scl_id = syn_check_cluster((char_u *)arg, (int)(group_name_end - arg)); + int scl_id = syn_check_cluster(arg, (int)(group_name_end - arg)); if (scl_id == 0) { return; } @@ -5030,7 +5025,7 @@ static void init_syn_patterns(void) /// Stores the pattern and program in a synpat_T. /// /// @return a pointer to the next argument, or NULL in case of an error. -static char *get_syn_pattern(char_u *arg, synpat_T *ci) +static char *get_syn_pattern(char *arg, synpat_T *ci) { char *end; int *p; @@ -5042,13 +5037,13 @@ static char *get_syn_pattern(char_u *arg, synpat_T *ci) return NULL; } - end = skip_regexp((char *)arg + 1, *arg, true, NULL); - if (*end != (char)(*arg)) { // end delimiter not found + end = skip_regexp(arg + 1, *arg, true, NULL); + if (*end != *arg) { // end delimiter not found semsg(_("E401: Pattern delimiter not found: %s"), arg); return NULL; } // store the pattern and compiled regexp program - ci->sp_pattern = vim_strnsave(arg + 1, (size_t)(end - (char *)arg) - 1); + ci->sp_pattern = vim_strnsave((char_u *)arg + 1, (size_t)(end - arg) - 1); // Make 'cpoptions' empty, to avoid the 'l' flag cpo_save = p_cpo; @@ -5122,15 +5117,13 @@ static char *get_syn_pattern(char_u *arg, synpat_T *ci) return skipwhite(end); } -/* - * Handle ":syntax sync .." command. - */ +/// Handle ":syntax sync .." command. static void syn_cmd_sync(exarg_T *eap, int syncing) { - char_u *arg_start = (char_u *)eap->arg; + char *arg_start = eap->arg; char *arg_end; - char_u *key = NULL; - char_u *next_arg; + char *key = NULL; + char *next_arg; int illegal = false; int finished = false; char *cpo_save; @@ -5141,21 +5134,21 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) } while (!ends_excmd(*arg_start)) { - arg_end = skiptowhite((char *)arg_start); - next_arg = (char_u *)skipwhite(arg_end); + arg_end = skiptowhite(arg_start); + next_arg = skipwhite(arg_end); xfree(key); - key = vim_strnsave_up(arg_start, (size_t)(arg_end - (char *)arg_start)); + key = (char *)vim_strnsave_up((char_u *)arg_start, (size_t)(arg_end - arg_start)); if (STRCMP(key, "CCOMMENT") == 0) { if (!eap->skip) { curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT; } if (!ends_excmd(*next_arg)) { - arg_end = skiptowhite((char *)next_arg); + arg_end = skiptowhite(next_arg); if (!eap->skip) { curwin->w_s->b_syn_sync_id = - (int16_t)syn_check_group((char *)next_arg, (size_t)(arg_end - (char *)next_arg)); + (int16_t)syn_check_group(next_arg, (size_t)(arg_end - next_arg)); } - next_arg = (char_u *)skipwhite(arg_end); + next_arg = skipwhite(arg_end); } else if (!eap->skip) { curwin->w_s->b_syn_sync_id = (int16_t)syn_name2id("Comment"); } @@ -5164,11 +5157,11 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) || STRNCMP(key, "MAXLINES", 8) == 0 || STRNCMP(key, "LINEBREAKS", 10) == 0) { if (key[4] == 'S') { - arg_end = (char *)key + 6; + arg_end = key + 6; } else if (key[0] == 'L') { - arg_end = (char *)key + 11; + arg_end = key + 11; } else { - arg_end = (char *)key + 9; + arg_end = key + 9; } if (arg_end[-1] != '=' || !ascii_isdigit(*arg_end)) { illegal = true; @@ -5199,8 +5192,8 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) finished = true; break; } - arg_end = skip_regexp((char *)next_arg + 1, *next_arg, true, NULL); - if (*arg_end != (char)(*next_arg)) { // end delimiter not found + arg_end = skip_regexp(next_arg + 1, *next_arg, true, NULL); + if (*arg_end != *next_arg) { // end delimiter not found illegal = true; break; } @@ -5208,7 +5201,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) if (!eap->skip) { // store the pattern and compiled regexp program curwin->w_s->b_syn_linecont_pat = - (char *)vim_strnsave(next_arg + 1, (size_t)(arg_end - (char *)next_arg) - 1); + xstrnsave(next_arg + 1, (size_t)(arg_end - next_arg) - 1); curwin->w_s->b_syn_linecont_ic = curwin->w_s->b_syn_ic; // Make 'cpoptions' empty, to avoid the 'l' flag @@ -5225,9 +5218,9 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) break; } } - next_arg = (char_u *)skipwhite(arg_end + 1); + next_arg = skipwhite(arg_end + 1); } else { - eap->arg = (char *)next_arg; + eap->arg = next_arg; if (STRCMP(key, "MATCH") == 0) { syn_cmd_match(eap, true); } else if (STRCMP(key, "REGION") == 0) { @@ -5246,7 +5239,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) if (illegal) { semsg(_("E404: Illegal arguments: %s"), arg_start); } else if (!finished) { - eap->nextcmd = (char *)check_nextcmd(arg_start); + eap->nextcmd = check_nextcmd(arg_start); redraw_curbuf_later(UPD_SOME_VALID); syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } @@ -5327,7 +5320,7 @@ static int get_id_list(char **const arg, const int keylen, int16_t **const list, if (skip) { id = -1; } else { - id = syn_check_cluster((char_u *)name + 2, (int)(end - p - 1)); + id = syn_check_cluster(name + 2, (int)(end - p - 1)); } } else { /* @@ -5565,21 +5558,19 @@ static struct subcommand subcommands[] = { NULL, NULL } }; -/* - * ":syntax". - * This searches the subcommands[] table for the subcommand name, and calls a - * syntax_subcommand() function to do the rest. - */ +/// ":syntax". +/// This searches the subcommands[] table for the subcommand name, and calls a +/// syntax_subcommand() function to do the rest. void ex_syntax(exarg_T *eap) { - char_u *arg = (char_u *)eap->arg; - char_u *subcmd_end; + char *arg = eap->arg; + char *subcmd_end; syn_cmdlinep = eap->cmdlinep; // isolate subcommand name for (subcmd_end = arg; ASCII_ISALPHA(*subcmd_end); subcmd_end++) {} - char_u *const subcmd_name = vim_strnsave(arg, (size_t)(subcmd_end - arg)); + char *const subcmd_name = xstrnsave(arg, (size_t)(subcmd_end - arg)); if (eap->skip) { // skip error messages for all subcommands emsg_skip++; } @@ -5588,8 +5579,8 @@ void ex_syntax(exarg_T *eap) semsg(_("E410: Invalid :syntax subcommand: %s"), subcmd_name); break; } - if (STRCMP(subcmd_name, (char_u *)subcommands[i].name) == 0) { - eap->arg = skipwhite((char *)subcmd_end); + if (STRCMP(subcmd_name, subcommands[i].name) == 0) { + eap->arg = skipwhite(subcmd_end); (subcommands[i].func)(eap, false); break; } @@ -5602,8 +5593,8 @@ void ex_syntax(exarg_T *eap) void ex_ownsyntax(exarg_T *eap) { - char_u *old_value; - char_u *new_value; + char *old_value; + char *new_value; if (curwin->w_s == &curwin->w_buffer->b_s) { curwin->w_s = xcalloc(1, sizeof(synblock_T)); @@ -5620,25 +5611,25 @@ void ex_ownsyntax(exarg_T *eap) } // Save value of b:current_syntax. - old_value = get_var_value("b:current_syntax"); + old_value = (char *)get_var_value("b:current_syntax"); if (old_value != NULL) { - old_value = vim_strsave(old_value); + old_value = xstrdup(old_value); } // Apply the "syntax" autocommand event, this finds and loads the syntax file. apply_autocmds(EVENT_SYNTAX, eap->arg, curbuf->b_fname, true, curbuf); // Move value of b:current_syntax to w:current_syntax. - new_value = get_var_value("b:current_syntax"); + new_value = (char *)get_var_value("b:current_syntax"); if (new_value != NULL) { - set_internal_string_var("w:current_syntax", (char *)new_value); + set_internal_string_var("w:current_syntax", new_value); } // Restore value of b:current_syntax. if (old_value == NULL) { do_unlet(S_LEN("b:current_syntax"), true); } else { - set_internal_string_var("b:current_syntax", (char *)old_value); + set_internal_string_var("b:current_syntax", old_value); xfree(old_value); } } diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 4fd99b058b..54c1dc7741 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -502,9 +502,9 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) // Find the position of each old match in the new list. Need // to use parse_match() to find the tag line. for (j = 0; j < num_matches; j++) { - parse_match((char_u *)matches[j], &tagp); + parse_match(matches[j], &tagp); for (i = idx; i < new_num_matches; i++) { - parse_match((char_u *)new_matches[i], &tagp2); + parse_match(new_matches[i], &tagp2); if (STRCMP(tagp.tagname, tagp2.tagname) == 0) { char_u *p = (char_u *)new_matches[i]; for (k = i; k > idx; k--) { @@ -585,7 +585,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) tagstack[tagstackidx].cur_fnum = cur_fnum; // store user-provided data originating from tagfunc - if (use_tfu && parse_match((char_u *)matches[cur_match], &tagp2) == OK + if (use_tfu && parse_match(matches[cur_match], &tagp2) == OK && tagp2.user_data) { XFREE_CLEAR(tagstack[tagstackidx].user_data); tagstack[tagstackidx].user_data = (char *)vim_strnsave(tagp2.user_data, @@ -705,7 +705,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char // Assume that the first match indicates how long the tags can // be, and align the file names to that. - parse_match((char_u *)matches[0], &tagp); + parse_match(matches[0], &tagp); taglen = (int)(tagp.tagname_end - tagp.tagname + 2); if (taglen < 18) { taglen = 18; @@ -723,7 +723,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char msg_puts_attr(_("file\n"), HL_ATTR(HLF_T)); for (i = 0; i < num_matches && !got_int; i++) { - parse_match((char_u *)matches[i], &tagp); + parse_match(matches[i], &tagp); if (!new_tag && ( (g_do_tagpreview != 0 && i == ptag_entry.cur_match) @@ -897,7 +897,7 @@ static int add_llist_tags(char_u *tag, int num_matches, char **matches) long lnum; dict_T *dict; - parse_match((char_u *)matches[i], &tagp); + parse_match(matches[i], &tagp); // Save the tag name len = (int)(tagp.tagname_end - tagp.tagname); @@ -1957,7 +1957,7 @@ parse_line: break; } else if (state == TS_SKIP_BACK) { assert(cmplen >= 0); - if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) { + if (mb_strnicmp((char *)tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) { state = TS_STEP_FORWARD; } else { // Have to skip back more. Restore the curr_offset @@ -1967,7 +1967,7 @@ parse_line: continue; } else if (state == TS_STEP_FORWARD) { assert(cmplen >= 0); - if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) { + if (mb_strnicmp((char *)tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) { if ((off_T)vim_ftell(fp) > search_info.match_offset) { break; // past last match } else { @@ -1978,7 +1978,7 @@ parse_line: // skip this match if it can't match assert(cmplen >= 0); } - if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) { + if (mb_strnicmp((char *)tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) { continue; } @@ -2014,7 +2014,7 @@ parse_line: } else { if (orgpat.regmatch.rm_ic) { assert(cmplen >= 0); - match = mb_strnicmp(tagp.tagname, orgpat.pat, (size_t)cmplen) == 0; + match = mb_strnicmp((char *)tagp.tagname, (char *)orgpat.pat, (size_t)cmplen) == 0; if (match) { match_no_ic = (STRNCMP(tagp.tagname, orgpat.pat, cmplen) == 0); @@ -2552,18 +2552,17 @@ static size_t matching_line_len(const char_u *const lbuf) /// @param tagp output: pointers into the line /// /// @return OK or FAIL. -static int parse_match(char_u *lbuf, tagptrs_T *tagp) +static int parse_match(char *lbuf, tagptrs_T *tagp) { int retval; - char_u *p; - char_u *pc, *pt; + char *p; + char *pc, *pt; - tagp->tag_fname = lbuf + 1; + tagp->tag_fname = (char_u *)lbuf + 1; lbuf += STRLEN(tagp->tag_fname) + 2; // Find search pattern and the file name for non-etags. - retval = parse_tag_line(lbuf, - tagp); + retval = parse_tag_line((char_u *)lbuf, tagp); tagp->tagkind = NULL; tagp->user_data = NULL; @@ -2572,32 +2571,32 @@ static int parse_match(char_u *lbuf, tagptrs_T *tagp) if (retval == OK) { // Try to find a kind field: "kind:" or just "" - p = tagp->command; - if (find_extra(&p) == OK) { - tagp->command_end = p; - if (p > tagp->command && p[-1] == '|') { - tagp->command_end = p - 1; // drop trailing bar + p = (char *)tagp->command; + if (find_extra((char_u **)&p) == OK) { + tagp->command_end = (char_u *)p; + if (p > (char *)tagp->command && p[-1] == '|') { + tagp->command_end = (char_u *)p - 1; // drop trailing bar } p += 2; // skip ";\"" if (*p++ == TAB) { // Accept ASCII alphabetic kind characters and any multi-byte // character. - while (ASCII_ISALPHA(*p) || utfc_ptr2len((char *)p) > 1) { + while (ASCII_ISALPHA(*p) || utfc_ptr2len(p) > 1) { if (STRNCMP(p, "kind:", 5) == 0) { - tagp->tagkind = p + 5; + tagp->tagkind = (char_u *)p + 5; } else if (STRNCMP(p, "user_data:", 10) == 0) { - tagp->user_data = p + 10; + tagp->user_data = (char_u *)p + 10; } else if (STRNCMP(p, "line:", 5) == 0) { - tagp->tagline = atoi((char *)p + 5); + tagp->tagline = atoi(p + 5); } if (tagp->tagkind != NULL && tagp->user_data != NULL) { break; } - pc = (char_u *)vim_strchr((char *)p, ':'); - pt = (char_u *)vim_strchr((char *)p, '\t'); + pc = vim_strchr(p, ':'); + pt = vim_strchr(p, '\t'); if (pc == NULL || (pt != NULL && pc > pt)) { - tagp->tagkind = p; + tagp->tagkind = (char_u *)p; } if (pt == NULL) { break; @@ -2608,16 +2607,16 @@ static int parse_match(char_u *lbuf, tagptrs_T *tagp) } } if (tagp->tagkind != NULL) { - for (p = tagp->tagkind; + for (p = (char *)tagp->tagkind; *p && *p != '\t' && *p != '\r' && *p != '\n'; MB_PTR_ADV(p)) {} - tagp->tagkind_end = p; + tagp->tagkind_end = (char_u *)p; } if (tagp->user_data != NULL) { - for (p = tagp->user_data; + for (p = (char *)tagp->user_data; *p && *p != '\t' && *p != '\r' && *p != '\n'; MB_PTR_ADV(p)) {} - tagp->user_data_end = p; + tagp->user_data_end = (char_u *)p; } } return retval; @@ -2671,7 +2670,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) pbuf = xmalloc(LSIZE); // parse the match line into the tagp structure - if (parse_match(lbuf, &tagp) == FAIL) { + if (parse_match((char *)lbuf, &tagp) == FAIL) { tagp.fname_end = NULL; goto erret; } @@ -3121,7 +3120,7 @@ int expand_tags(int tagnames, char_u *pat, int *num_file, char ***file) for (i = 0; i < *num_file; i++) { size_t len; - parse_match((char_u *)(*file)[i], &t_p); + parse_match((*file)[i], &t_p); len = (size_t)(t_p.tagname_end - t_p.tagname); if (len > name_buf_size - 3) { char_u *buf; @@ -3201,7 +3200,7 @@ int get_tags(list_T *list, char_u *pat, char_u *buf_fname) TAG_REGEXP | TAG_NOIC, MAXCOL, (char *)buf_fname); if (ret == OK && num_matches > 0) { for (i = 0; i < num_matches; i++) { - int parse_result = parse_match((char_u *)matches[i], &tp); + int parse_result = parse_match(matches[i], &tp); // Avoid an unused variable warning in release builds. (void)parse_result; @@ -3350,9 +3349,9 @@ static void tagstack_shift(win_T *wp) wp->w_tagstacklen--; } -// Push a new item to the tag stack -static void tagstack_push_item(win_T *wp, char_u *tagname, int cur_fnum, int cur_match, pos_T mark, - int fnum, char_u *user_data) +/// Push a new item to the tag stack +static void tagstack_push_item(win_T *wp, char *tagname, int cur_fnum, int cur_match, pos_T mark, + int fnum, char *user_data) { taggy_T *tagstack = wp->w_tagstack; int idx = wp->w_tagstacklen; // top of the stack @@ -3364,7 +3363,7 @@ static void tagstack_push_item(win_T *wp, char_u *tagname, int cur_fnum, int cur } wp->w_tagstacklen++; - tagstack[idx].tagname = (char *)tagname; + tagstack[idx].tagname = tagname; tagstack[idx].cur_fnum = cur_fnum; tagstack[idx].cur_match = cur_match; if (tagstack[idx].cur_match < 0) { @@ -3372,16 +3371,16 @@ static void tagstack_push_item(win_T *wp, char_u *tagname, int cur_fnum, int cur } tagstack[idx].fmark.mark = mark; tagstack[idx].fmark.fnum = fnum; - tagstack[idx].user_data = (char *)user_data; + tagstack[idx].user_data = user_data; } -// Add a list of items to the tag stack in the specified window +/// Add a list of items to the tag stack in the specified window static void tagstack_push_items(win_T *wp, list_T *l) { listitem_T *li; dictitem_T *di; dict_T *itemdict; - char_u *tagname; + char *tagname; pos_T mark; int fnum; @@ -3400,8 +3399,7 @@ static void tagstack_push_items(win_T *wp, list_T *l) if (list2fpos(&di->di_tv, &mark, &fnum, NULL, false) != OK) { continue; } - if ((tagname = (char_u *)tv_dict_get_string(itemdict, "tagname", true)) - == NULL) { + if ((tagname = tv_dict_get_string(itemdict, "tagname", true)) == NULL) { continue; } @@ -3413,7 +3411,7 @@ static void tagstack_push_items(win_T *wp, list_T *l) (int)tv_dict_get_number(itemdict, "bufnr"), (int)tv_dict_get_number(itemdict, "matchnr") - 1, mark, fnum, - (char_u *)tv_dict_get_string(itemdict, "user_data", true)); + tv_dict_get_string(itemdict, "user_data", true)); } } diff --git a/src/nvim/ui.c b/src/nvim/ui.c index 46f4d137c4..08c1946e13 100644 --- a/src/nvim/ui.c +++ b/src/nvim/ui.c @@ -565,7 +565,7 @@ void ui_check_mouse(void) // - 'a' is in 'mouse' and "c" is in MOUSE_A, or // - the current buffer is a help file and 'h' is in 'mouse' and we are in a // normal editing mode (not at hit-return message). - for (char_u *p = (char_u *)p_mouse; *p; p++) { + for (char *p = p_mouse; *p; p++) { switch (*p) { case 'a': if (vim_strchr(MOUSE_A, checkfor) != NULL) { -- cgit From 0c6b39894f4cac99c3d81857986e4eae533fb59a Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 06:19:49 +0800 Subject: feat(mapset): support restoring Lua callback (#20024) vim-patch:9.0.0341: mapset() does not restore mapping properly Problem: mapset() does not restore mapping properly. Solution: Use an empty string for . (closes vim/vim#11022) https://github.com/vim/vim/commit/92a3d20682d46359bb50a452b4f831659e799155 --- .../pack/dist/opt/termdebug/plugin/termdebug.vim | 9 +---- src/nvim/mapping.c | 46 ++++++++++++++-------- src/nvim/testdir/test_maparg.vim | 33 +++++++++++++--- test/functional/vimscript/map_functions_spec.lua | 42 ++++++++++++++++++++ 4 files changed, 100 insertions(+), 30 deletions(-) diff --git a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim index 802ebd42b5..bfece6aa72 100644 --- a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim +++ b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim @@ -964,14 +964,7 @@ func s:DeleteCommands() nunmap K else " call mapset(s:k_map_saved) - let mode = s:k_map_saved.mode !=# ' ' ? s:k_map_saved.mode : '' - call nvim_set_keymap(mode, 'K', s:k_map_saved.rhs, { - \ 'expr': s:k_map_saved.expr ? v:true : v:false, - \ 'noremap': s:k_map_saved.noremap ? v:true : v:false, - \ 'nowait': s:k_map_saved.nowait ? v:true : v:false, - \ 'script': s:k_map_saved.script ? v:true : v:false, - \ 'silent': s:k_map_saved.silent ? v:true : v:false, - \ }) + call mapset('n', 0, s:k_map_saved) endif unlet s:k_map_saved endif diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index ae37141eac..5c9903aa6b 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -277,21 +277,29 @@ static bool set_maparg_lhs_rhs(const char *const orig_lhs, const size_t orig_lhs mapargs->alt_lhs_len = 0; } + set_maparg_rhs(orig_rhs, orig_rhs_len, rhs_lua, cpo_flags, mapargs); + + return true; +} + +/// @see set_maparg_lhs_rhs +static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len, + const LuaRef rhs_lua, const int cpo_flags, MapArguments *const mapargs) +{ mapargs->rhs_lua = rhs_lua; if (rhs_lua == LUA_NOREF) { mapargs->orig_rhs_len = orig_rhs_len; mapargs->orig_rhs = xcalloc(mapargs->orig_rhs_len + 1, sizeof(char_u)); STRLCPY(mapargs->orig_rhs, orig_rhs, mapargs->orig_rhs_len + 1); - if (STRICMP(orig_rhs, "") == 0) { // "" means nothing - mapargs->rhs = xcalloc(1, sizeof(char_u)); // single null-char + mapargs->rhs = xcalloc(1, sizeof(char_u)); // single NUL-char mapargs->rhs_len = 0; mapargs->rhs_is_noop = true; } else { char *rhs_buf = NULL; - replaced = replace_termcodes(orig_rhs, orig_rhs_len, &rhs_buf, REPTERM_DO_LT, NULL, - cpo_flags); + char *replaced = replace_termcodes(orig_rhs, orig_rhs_len, &rhs_buf, REPTERM_DO_LT, NULL, + cpo_flags); mapargs->rhs_len = STRLEN(replaced); // NB: replace_termcodes may produce an empty string even if orig_rhs is non-empty // (e.g. a single ^V, see :h map-empty-rhs) @@ -308,7 +316,6 @@ static bool set_maparg_lhs_rhs(const char *const orig_lhs, const size_t orig_lhs (char_u)KS_EXTRA, KE_LUA, rhs_lua); mapargs->rhs = vim_strsave((char_u *)tmp_buf); } - return true; } /// Parse a string of |:map-arguments| into a @ref MapArguments struct. @@ -2150,29 +2157,36 @@ void f_mapset(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) char *lhs = tv_dict_get_string(d, "lhs", false); char *lhsraw = tv_dict_get_string(d, "lhsraw", false); char *lhsrawalt = tv_dict_get_string(d, "lhsrawalt", false); - char *rhs = tv_dict_get_string(d, "rhs", false); - if (lhs == NULL || lhsraw == NULL || rhs == NULL) { + char *orig_rhs = tv_dict_get_string(d, "rhs", false); + LuaRef rhs_lua = LUA_NOREF; + dictitem_T *callback_di = tv_dict_find(d, S_LEN("callback")); + if (callback_di != NULL) { + Object callback_obj = vim_to_object(&callback_di->di_tv); + if (callback_obj.type == kObjectTypeLuaRef && callback_obj.data.luaref != LUA_NOREF) { + rhs_lua = callback_obj.data.luaref; + orig_rhs = ""; // need non-NULL for strlen() + callback_obj.data.luaref = LUA_NOREF; + } + api_free_object(callback_obj); + } + if (lhs == NULL || lhsraw == NULL || (orig_rhs == NULL && rhs_lua == LUA_NOREF)) { emsg(_("E460: entries missing in mapset() dict argument")); + api_free_luaref(rhs_lua); return; } - char *orig_rhs = rhs; - char *arg_buf = NULL; - rhs = replace_termcodes(rhs, STRLEN(rhs), &arg_buf, REPTERM_DO_LT, NULL, CPO_TO_CPO_FLAGS); - int noremap = tv_dict_get_number(d, "noremap") ? REMAP_NONE : 0; + int noremap = tv_dict_get_number(d, "noremap") != 0 ? REMAP_NONE : 0; if (tv_dict_get_number(d, "script") != 0) { noremap = REMAP_SCRIPT; } - MapArguments args = { // TODO(zeertzjq): support restoring "callback"? - .rhs = (char_u *)rhs, - .rhs_lua = LUA_NOREF, - .orig_rhs = vim_strsave((char_u *)orig_rhs), + MapArguments args = { .expr = tv_dict_get_number(d, "expr") != 0, .silent = tv_dict_get_number(d, "silent") != 0, .nowait = tv_dict_get_number(d, "nowait") != 0, .replace_keycodes = tv_dict_get_number(d, "replace_keycodes") != 0, .desc = tv_dict_get_string(d, "desc", false), }; + set_maparg_rhs(orig_rhs, strlen(orig_rhs), rhs_lua, CPO_TO_CPO_FLAGS, &args); scid_T sid = (scid_T)tv_dict_get_number(d, "sid"); linenr_T lnum = (linenr_T)tv_dict_get_number(d, "lnum"); bool buffer = tv_dict_get_number(d, "buffer") != 0; @@ -2183,7 +2197,7 @@ void f_mapset(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) // Delete any existing mapping for this lhs and mode. MapArguments unmap_args = MAP_ARGUMENTS_INIT; - set_maparg_lhs_rhs(lhs, strlen(lhs), rhs, strlen(rhs), LUA_NOREF, 0, &unmap_args); + set_maparg_lhs_rhs(lhs, strlen(lhs), "", 0, LUA_NOREF, 0, &unmap_args); unmap_args.buffer = buffer; buf_do_map(MAPTYPE_UNMAP, &unmap_args, mode, false, curbuf); xfree(unmap_args.rhs); diff --git a/src/nvim/testdir/test_maparg.vim b/src/nvim/testdir/test_maparg.vim index 17c5f433ac..f903f5b934 100644 --- a/src/nvim/testdir/test_maparg.vim +++ b/src/nvim/testdir/test_maparg.vim @@ -158,11 +158,11 @@ func Test_range_map() call assert_equal("abcd", getline(1)) endfunc -func One_mapset_test(keys) - exe 'nnoremap ' .. a:keys .. ' original' +func One_mapset_test(keys, rhs) + exe 'nnoremap ' .. a:keys .. ' ' .. a:rhs let orig = maparg(a:keys, 'n', 0, 1) call assert_equal(a:keys, orig.lhs) - call assert_equal('original', orig.rhs) + call assert_equal(a:rhs, orig.rhs) call assert_equal('n', orig.mode) exe 'nunmap ' .. a:keys @@ -172,15 +172,16 @@ func One_mapset_test(keys) call mapset('n', 0, orig) let d = maparg(a:keys, 'n', 0, 1) call assert_equal(a:keys, d.lhs) - call assert_equal('original', d.rhs) + call assert_equal(a:rhs, d.rhs) call assert_equal('n', d.mode) exe 'nunmap ' .. a:keys endfunc func Test_mapset() - call One_mapset_test('K') - call One_mapset_test('') + call One_mapset_test('K', 'original') + call One_mapset_test('', 'original') + call One_mapset_test('', 'Nop>') " Check <> key conversion new @@ -203,6 +204,26 @@ func Test_mapset() iunmap K + " Test that is restored properly + inoremap K + call feedkeys("SK\", 'xt') + call assert_equal('', getline(1)) + + let orig = maparg('K', 'i', 0, 1) + call assert_equal('K', orig.lhs) + call assert_equal('', orig.rhs) + call assert_equal('i', orig.mode) + + inoremap K foo + call feedkeys("SK\", 'xt') + call assert_equal('foo', getline(1)) + + call mapset('i', 0, orig) + call feedkeys("SK\", 'xt') + call assert_equal('', getline(1)) + + iunmap K + " Test literal using a backslash let cpo_save = &cpo set cpo-=B diff --git a/test/functional/vimscript/map_functions_spec.lua b/test/functional/vimscript/map_functions_spec.lua index aa64006de0..96b86d053e 100644 --- a/test/functional/vimscript/map_functions_spec.lua +++ b/test/functional/vimscript/map_functions_spec.lua @@ -3,6 +3,8 @@ local helpers = require('test.functional.helpers')(after_each) local clear = helpers.clear local eq = helpers.eq local eval = helpers.eval +local exec = helpers.exec +local exec_lua = helpers.exec_lua local expect = helpers.expect local feed = helpers.feed local funcs = helpers.funcs @@ -10,6 +12,7 @@ local meths = helpers.meths local nvim = helpers.nvim local source = helpers.source local command = helpers.command +local pcall_err = helpers.pcall_err describe('maparg()', function() before_each(clear) @@ -194,4 +197,43 @@ describe('mapset()', function() feed('foo') expect('<<') end) + + it('can restore Lua callback from the dict returned by maparg()', function() + eq(0, exec_lua([[ + GlobalCount = 0 + vim.api.nvim_set_keymap('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end }) + return GlobalCount + ]])) + feed('asdf') + eq(1, exec_lua([[return GlobalCount]])) + + exec_lua([[ + _G.saved_asdf_map = vim.fn.maparg('asdf', 'n', false, true) + vim.api.nvim_set_keymap('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 10 end }) + ]]) + feed('asdf') + eq(11, exec_lua([[return GlobalCount]])) + + exec_lua([[vim.fn.mapset('n', false, _G.saved_asdf_map)]]) + feed('asdf') + eq(12, exec_lua([[return GlobalCount]])) + + exec([[ + let g:saved_asdf_map = maparg('asdf', 'n', v:false, v:true) + lua vim.api.nvim_set_keymap('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 10 end }) + ]]) + feed('asdf') + eq(22, exec_lua([[return GlobalCount]])) + + command([[call mapset('n', v:false, g:saved_asdf_map)]]) + feed('asdf') + eq(23, exec_lua([[return GlobalCount]])) + end) + + it('does not leak memory if lhs is missing', function() + eq('Error executing lua: Vim:E460: entries missing in mapset() dict argument', + pcall_err(exec_lua, [[vim.fn.mapset('n', false, {rhs = 'foo'})]])) + eq('Error executing lua: Vim:E460: entries missing in mapset() dict argument', + pcall_err(exec_lua, [[vim.fn.mapset('n', false, {callback = function() end})]])) + end) end) -- cgit From 8740e0bd58c7311826e781591db5d29b4b3ffa73 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 09:12:20 +0800 Subject: vim-patch:9.0.0343: ColorScheme autocommand triggered when colorscheme not found (#20032) Problem: ColorScheme autocommand triggered when colorscheme is not found. (Romain Lafourcade) Solution: Only trigger ColorScheme when loading the colorscheme succeeds. (closes vim/vim#11024) https://github.com/vim/vim/commit/5d09a401ec393dc930e1104ceb38eab34681de64 Most of Test_colorscheme() is applicable to Nvim. --- src/nvim/highlight_group.c | 4 +++- src/nvim/testdir/test_gui.vim | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/nvim/testdir/test_gui.vim diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c index ed1f0185b7..da842e9f84 100644 --- a/src/nvim/highlight_group.c +++ b/src/nvim/highlight_group.c @@ -632,7 +632,9 @@ int load_colors(char_u *name) retval = source_runtime((char *)buf, DIP_START + DIP_OPT); } xfree(buf); - apply_autocmds(EVENT_COLORSCHEME, (char *)name, curbuf->b_fname, false, curbuf); + if (retval == OK) { + apply_autocmds(EVENT_COLORSCHEME, (char *)name, curbuf->b_fname, false, curbuf); + } recursive = false; diff --git a/src/nvim/testdir/test_gui.vim b/src/nvim/testdir/test_gui.vim new file mode 100644 index 0000000000..c3f1f3163a --- /dev/null +++ b/src/nvim/testdir/test_gui.vim @@ -0,0 +1,43 @@ + +func Test_colorscheme() + " call assert_equal('16777216', &t_Co) + + let colorscheme_saved = exists('g:colors_name') ? g:colors_name : 'default' + let g:color_count = 0 + augroup TestColors + au! + au ColorScheme * let g:color_count += 1 + \ | let g:after_colors = g:color_count + \ | let g:color_after = expand('') + au ColorSchemePre * let g:color_count += 1 + \ | let g:before_colors = g:color_count + \ | let g:color_pre = expand('') + augroup END + + colorscheme torte + redraw! + call assert_equal('dark', &background) + call assert_equal(1, g:before_colors) + call assert_equal(2, g:after_colors) + call assert_equal('torte', g:color_pre) + call assert_equal('torte', g:color_after) + call assert_equal("\ntorte", execute('colorscheme')) + + let a = substitute(execute('hi Search'), "\n\\s\\+", ' ', 'g') + " FIXME: temporarily check less while the colorscheme changes + " call assert_match("\nSearch xxx term=reverse cterm=reverse ctermfg=196 ctermbg=16 gui=reverse guifg=#ff0000 guibg=#000000", a) + " call assert_match("\nSearch xxx term=reverse ", a) + + call assert_fails('colorscheme does_not_exist', 'E185:') + call assert_equal('does_not_exist', g:color_pre) + call assert_equal('torte', g:color_after) + + exec 'colorscheme' colorscheme_saved + augroup TestColors + au! + augroup END + unlet g:color_count g:after_colors g:before_colors + redraw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab -- cgit From a62cb406b16c53dcfbcc74c164f5ebe888ddcd89 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 10:22:28 +0800 Subject: fix(maparg): remove double allocation (#20033) ASAN doesn't catch this, as it is referenced by the garbage collector. Also remove a condition that is always true. --- src/nvim/mapping.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 5c9903aa6b..50360ee084 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -2008,8 +2008,7 @@ static Dictionary mapblock_fill_dict(const mapblock_T *const mp, const char *lhs FUNC_ATTR_NONNULL_ARG(1) { Dictionary dict = ARRAY_DICT_INIT; - char *const lhs = str2special_save((const char *)mp->m_keys, - compatible, !compatible); + char *const lhs = str2special_save((const char *)mp->m_keys, compatible, !compatible); char *const mapmode = map_mode_to_chars(mp->m_mode); varnumber_T noremap_value; @@ -2122,13 +2121,15 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) } } else { // Return a dictionary. - tv_dict_alloc_ret(rettv); if (mp != NULL && (rhs != NULL || rhs_lua != LUA_NOREF)) { Dictionary dict = mapblock_fill_dict(mp, did_simplify ? (char *)keys_simplified : NULL, buffer_local, true); (void)object_to_vim(DICTIONARY_OBJ(dict), rettv, NULL); api_free_dictionary(dict); + } else { + // Return an empty dictionary. + tv_dict_alloc_ret(rettv); } } @@ -2164,12 +2165,12 @@ void f_mapset(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) Object callback_obj = vim_to_object(&callback_di->di_tv); if (callback_obj.type == kObjectTypeLuaRef && callback_obj.data.luaref != LUA_NOREF) { rhs_lua = callback_obj.data.luaref; - orig_rhs = ""; // need non-NULL for strlen() + orig_rhs = ""; callback_obj.data.luaref = LUA_NOREF; } api_free_object(callback_obj); } - if (lhs == NULL || lhsraw == NULL || (orig_rhs == NULL && rhs_lua == LUA_NOREF)) { + if (lhs == NULL || lhsraw == NULL || orig_rhs == NULL) { emsg(_("E460: entries missing in mapset() dict argument")); api_free_luaref(rhs_lua); return; -- cgit From 5f92d9b345e11adb73df33dc22a8e656aca73b6c Mon Sep 17 00:00:00 2001 From: bfredl Date: Thu, 1 Sep 2022 09:44:01 +0200 Subject: perf(messages): don't call ui_flush() per message line in various places When msgsep is used, message scrolling is emulated. To make message output fast, inhibit emulated scrolling until the full message text is known --- src/nvim/cmdexpand.c | 1 - src/nvim/cmdhist.c | 1 - src/nvim/ex_cmds.c | 1 - src/nvim/ex_docmd.c | 3 --- src/nvim/mapping.c | 1 - src/nvim/mark.c | 3 --- src/nvim/ops.c | 1 - src/nvim/option.c | 1 - src/nvim/quickfix.c | 2 -- src/nvim/search.c | 2 -- src/nvim/tag.c | 1 - 11 files changed, 17 deletions(-) diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 1c35f28301..7180a8de46 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -717,7 +717,6 @@ int showmatches(expand_T *xp, int wildmenu) msg_clr_eos(); msg_putchar('\n'); } - ui_flush(); // show one line at a time if (got_int) { got_int = false; break; diff --git a/src/nvim/cmdhist.c b/src/nvim/cmdhist.c index 1426054d0b..2057b0db9e 100644 --- a/src/nvim/cmdhist.c +++ b/src/nvim/cmdhist.c @@ -650,7 +650,6 @@ void ex_history(exarg_T *eap) STRCAT(IObuff, hist[i].hisstr); } msg_outtrans((char *)IObuff); - ui_flush(); } if (i == idx) { break; diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 17d45f207e..2c82436a25 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -5004,7 +5004,6 @@ void ex_oldfiles(exarg_T *eap) msg_outtrans((char *)tv_get_string(TV_LIST_ITEM_TV(li))); msg_clr_eos(); msg_putchar('\n'); - ui_flush(); // output one line at a time os_breakcheck(); } }); diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 8f72ba0e23..9e196e9516 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -4833,7 +4833,6 @@ static void ex_print(exarg_T *eap) if (++eap->line1 > eap->line2) { break; } - ui_flush(); // show one line at a time } setpcmark(); // put cursor at last line @@ -5035,7 +5034,6 @@ static void ex_tabs(exarg_T *eap) msg_putchar('\n'); vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++); msg_outtrans_attr((char *)IObuff, HL_ATTR(HLF_T)); - ui_flush(); // output one line at a time os_breakcheck(); FOR_ALL_WINDOWS_IN_TAB(wp, tp) { @@ -5054,7 +5052,6 @@ static void ex_tabs(exarg_T *eap) home_replace(wp->w_buffer, wp->w_buffer->b_fname, (char *)IObuff, IOSIZE, true); } msg_outtrans((char *)IObuff); - ui_flush(); // output one line at a time os_breakcheck(); } } diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index ae37141eac..a3705d5c6f 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -214,7 +214,6 @@ static void showmap(mapblock_T *mp, bool local) last_set_msg(mp->m_script_ctx); } msg_clr_eos(); - ui_flush(); // show one line at a time } /// Replace termcodes in the given LHS and RHS and store the results into the diff --git a/src/nvim/mark.c b/src/nvim/mark.c index 816599271d..7eab37e797 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -925,7 +925,6 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu msg_outtrans_attr((char *)name, current ? HL_ATTR(HLF_D) : 0); } } - ui_flush(); // show one line at a time } if (mustfree) { xfree(name); @@ -1058,7 +1057,6 @@ void ex_jumps(exarg_T *eap) xfree(name); os_breakcheck(); } - ui_flush(); } if (curwin->w_jumplistidx == curwin->w_jumplistlen) { msg_puts("\n>"); @@ -1101,7 +1099,6 @@ void ex_changes(exarg_T *eap) xfree(name); os_breakcheck(); } - ui_flush(); } if (curwin->w_changelistidx == curbuf->b_changelistlen) { msg_puts("\n>"); diff --git a/src/nvim/ops.c b/src/nvim/ops.c index adb071b754..d2321be4a4 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -3866,7 +3866,6 @@ void ex_display(exarg_T *eap) if (n > 1 && yb->y_type == kMTLineWise) { msg_puts_attr("^J", attr); } - ui_flush(); // show one line at a time } os_breakcheck(); } diff --git a/src/nvim/option.c b/src/nvim/option.c index 455070c742..269a21b512 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -3355,7 +3355,6 @@ static void showoptions(int all, int opt_flags) showoneopt(items[i], opt_flags); col += INC; } - ui_flush(); os_breakcheck(); } } diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index f1fc48ef40..86f60cb57e 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -3094,8 +3094,6 @@ static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel) if (tbuf != IObuff) { xfree(tbuf); } - - ui_flush(); // show one line at a time } // ":clist": list all errors diff --git a/src/nvim/search.c b/src/nvim/search.c index d7f8d4e1cd..e9ac9ecf2b 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -3714,7 +3714,6 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo } } } - ui_flush(); // output each line directly } if (new_fname != NULL) { @@ -4147,7 +4146,6 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, msg_puts(" "); } msg_prt_line((char *)line, false); - ui_flush(); // show one line at a time // Definition continues until line that doesn't end with '\' if (got_int || type != FIND_DEFINE || p < line || *p != '\\') { diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 4fd99b058b..b694297d63 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -1056,7 +1056,6 @@ void do_tags(exarg_T *eap) ? HL_ATTR(HLF_D) : 0); xfree(name); } - ui_flush(); // show one line at a time } if (tagstackidx == tagstacklen) { // idx at top of stack msg_puts("\n>"); -- cgit From db2e5f46f5aa5a6300395eaa9c4923835683c770 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 16:37:29 +0800 Subject: fix(lua): make ui_attach()/ui_detach() take effect immediately (#20037) --- src/nvim/ui_compositor.c | 4 ++-- test/functional/lua/ui_event_spec.lua | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c index 5167f291c3..b8c7834e2b 100644 --- a/src/nvim/ui_compositor.c +++ b/src/nvim/ui_compositor.c @@ -749,7 +749,7 @@ void ui_comp_add_cb(uint32_t ns_id, LuaRef cb, bool *ext_widgets) *item = event_cb; ui_comp_update_ext(); - ui_schedule_refresh(); + ui_refresh(); } void ui_comp_remove_cb(uint32_t ns_id) @@ -759,5 +759,5 @@ void ui_comp_remove_cb(uint32_t ns_id) pmap_del(uint32_t)(&ui_event_cbs, ns_id); } ui_comp_update_ext(); - ui_schedule_refresh(); + ui_refresh(); } diff --git a/test/functional/lua/ui_event_spec.lua b/test/functional/lua/ui_event_spec.lua index 05322a0fdb..294222ad13 100644 --- a/test/functional/lua/ui_event_spec.lua +++ b/test/functional/lua/ui_event_spec.lua @@ -88,10 +88,12 @@ describe('vim.ui_attach', function() { "popupmenu_hide" }; } - -- ui_detach stops events, and reenables builtin pum - exec_lua [[ vim.ui_detach(ns) ]] + -- vim.ui_detach() stops events, and reenables builtin pum immediately + exec_lua [[ + vim.ui_detach(ns) + vim.fn.complete(1, {'food', 'foobar', 'foo'}) + ]] - funcs.complete(1, {'food', 'foobar', 'foo'}) screen:expect{grid=[[ food^ | {3:food }{1: }| @@ -102,6 +104,5 @@ describe('vim.ui_attach', function() expect_events { } - end) end) -- cgit From 49e893f296bca9eef5ff45a3d746c261d055bf10 Mon Sep 17 00:00:00 2001 From: Dundar Göc Date: Fri, 26 Aug 2022 23:11:25 +0200 Subject: refactor: replace char_u with char Work on https://github.com/neovim/neovim/issues/459 --- src/nvim/change.c | 10 +- src/nvim/charset.c | 54 +++++----- src/nvim/cmdexpand.c | 71 +++++++------ src/nvim/cmdhist.c | 24 ++--- src/nvim/cmdhist.h | 2 +- src/nvim/cursor.c | 4 +- src/nvim/digraph.c | 24 ++--- src/nvim/edit.c | 36 +++---- src/nvim/eval.c | 4 +- src/nvim/eval/decode.c | 4 +- src/nvim/eval/funcs.c | 42 ++++---- src/nvim/eval/typval.c | 3 +- src/nvim/eval/userfunc.c | 197 ++++++++++++++++++------------------- src/nvim/ex_cmds.c | 8 +- src/nvim/ex_docmd.c | 4 +- src/nvim/ex_getln.c | 134 ++++++++++++------------- src/nvim/ex_getln.h | 2 +- src/nvim/file_search.c | 104 +++++++++----------- src/nvim/fileio.c | 22 ++--- src/nvim/getchar.c | 4 +- src/nvim/grid.c | 2 +- src/nvim/indent.c | 10 +- src/nvim/indent_c.c | 82 +++++++-------- src/nvim/insexpand.c | 120 +++++++++++----------- src/nvim/keycodes.c | 8 +- src/nvim/mark.c | 22 ++--- src/nvim/match.c | 26 ++--- src/nvim/mbyte.c | 42 ++++---- src/nvim/memline.c | 40 ++++---- src/nvim/message.c | 6 +- src/nvim/normal.c | 24 ++--- src/nvim/ops.c | 82 ++++++++------- src/nvim/option.c | 6 +- src/nvim/os/shell.c | 4 +- src/nvim/path.c | 33 ++++--- src/nvim/regexp.c | 6 +- src/nvim/regexp_bt.c | 16 +-- src/nvim/regexp_nfa.c | 10 +- src/nvim/search.c | 31 +++--- src/nvim/shada.c | 8 +- src/nvim/spell.c | 22 ++--- src/nvim/spellsuggest.c | 47 +++++---- src/nvim/strings.c | 21 +--- src/nvim/syntax.c | 33 ++++--- src/nvim/tag.c | 31 +++--- src/nvim/textformat.c | 14 +-- src/nvim/textobject.c | 4 +- src/nvim/viml/parser/expressions.c | 9 +- src/nvim/window.c | 6 +- 49 files changed, 742 insertions(+), 776 deletions(-) diff --git a/src/nvim/change.c b/src/nvim/change.c index 5bea388f28..5e9edac4f2 100644 --- a/src/nvim/change.c +++ b/src/nvim/change.c @@ -599,7 +599,7 @@ void ins_bytes_len(char *p, size_t len) size_t n; for (size_t i = 0; i < len; i += n) { // avoid reading past p[len] - n = (size_t)utfc_ptr2len_len((char_u *)p + i, (int)(len - i)); + n = (size_t)utfc_ptr2len_len(p + i, (int)(len - i)); ins_char_bytes(p + i, n); } } @@ -828,7 +828,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine) col = n; count = utf_ptr2len(oldp + n); n += count; - } while (utf_composinglike((char_u *)oldp + col, (char_u *)oldp + n)); + } while (utf_composinglike(oldp + col, oldp + n)); fixpos = false; } } @@ -1036,7 +1036,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) colnr_T mincol = curwin->w_cursor.col + 1; // make a copy of the current line so we can mess with it - char *saved_line = (char *)vim_strsave(get_cursor_line_ptr()); + char *saved_line = (char *)vim_strsave((char_u *)get_cursor_line_ptr()); if (State & VREPLACE_FLAG) { // With MODE_VREPLACE we make a copy of the next line, which we will be @@ -1181,7 +1181,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) if ((pos = findmatch(NULL, '(')) != NULL) { curwin->w_cursor.lnum = pos->lnum; newindent = get_indent(); - ptr = (char *)get_cursor_line_ptr(); + ptr = get_cursor_line_ptr(); } } // If last character is '{' do indent, without @@ -1838,7 +1838,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment) // stuff onto the replace stack (via ins_char()). if (State & VREPLACE_FLAG) { // Put new line in p_extra - p_extra = (char *)vim_strsave(get_cursor_line_ptr()); + p_extra = xstrdup(get_cursor_line_ptr()); // Put back original line ml_replace(curwin->w_cursor.lnum, next_line, false); diff --git a/src/nvim/charset.c b/src/nvim/charset.c index 4604bf7716..3396e2de41 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -789,7 +789,7 @@ bool vim_iswordc_buf(const int c, buf_T *const buf) bool vim_iswordp(const char_u *const p) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL { - return vim_iswordp_buf(p, curbuf); + return vim_iswordp_buf((char *)p, curbuf); } /// Just like vim_iswordc_buf() but uses a pointer to the (multi-byte) @@ -799,13 +799,13 @@ bool vim_iswordp(const char_u *const p) /// @param buf buffer whose keywords to use /// /// @return true if "p" points to a keyword character. -bool vim_iswordp_buf(const char_u *const p, buf_T *const buf) +bool vim_iswordp_buf(const char *const p, buf_T *const buf) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL { - int c = *p; + int c = (uint8_t)(*p); if (MB_BYTE2LEN(c) > 1) { - c = utf_ptr2char((char *)p); + c = utf_ptr2char(p); } return vim_iswordc_buf(c, buf); } @@ -829,8 +829,8 @@ bool vim_isfilec(int c) bool vim_isfilec_or_wc(int c) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { - char_u buf[2]; - buf[0] = (char_u)c; + char buf[2]; + buf[0] = (char)c; buf[1] = NUL; return vim_isfilec(c) || c == ']' || path_has_wildcard(buf); } @@ -905,15 +905,15 @@ bool in_win_border(win_T *wp, colnr_T vcol) /// @param end void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *end) { - char_u *ptr; // points to current char - char_u *posptr; // points to char at pos->col + char *ptr; // points to current char + char *posptr; // points to char at pos->col int incr; int head; long *vts = wp->w_buffer->b_p_vts_array; int ts = (int)wp->w_buffer->b_p_ts; colnr_T vcol = 0; - char_u *line = ptr = ml_get_buf(wp->w_buffer, pos->lnum, false); // start of the line + char *line = ptr = (char *)ml_get_buf(wp->w_buffer, pos->lnum, false); // start of the line if (pos->col == MAXCOL) { // continue until the NUL @@ -927,11 +927,11 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en } } posptr = ptr + pos->col; - posptr -= utf_head_off((char *)line, (char *)posptr); + posptr -= utf_head_off(line, posptr); } chartabsize_T cts; - init_chartabsize_arg(&cts, wp, pos->lnum, 0, (char *)line, (char *)line); + init_chartabsize_arg(&cts, wp, pos->lnum, 0, line, line); // This function is used very often, do some speed optimizations. // When 'list', 'linebreak', 'showbreak' and 'breakindent' are not set @@ -944,7 +944,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en && !cts.cts_has_virt_text) { for (;;) { head = 0; - int c = *ptr; + int c = (uint8_t)(*ptr); // make sure we don't go past the end of the line if (c == NUL) { @@ -960,7 +960,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en // For utf-8, if the byte is >= 0x80, need to look at // further bytes to find the cell width. if (c >= 0x80) { - incr = utf_ptr2cells((char *)ptr); + incr = utf_ptr2cells(ptr); } else { incr = g_chartab[c] & CT_CELL_MASK; } @@ -970,7 +970,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en // cells wide. if ((incr == 2) && wp->w_p_wrap - && (MB_BYTE2LEN(*ptr) > 1) + && (MB_BYTE2LEN((uint8_t)(*ptr)) > 1) && in_win_border(wp, vcol)) { incr++; head = 1; @@ -999,7 +999,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en break; } - if ((posptr != NULL) && ((char_u *)cts.cts_ptr >= posptr)) { + if ((posptr != NULL) && (cts.cts_ptr >= posptr)) { // character at pos->col break; } @@ -1008,7 +1008,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en MB_PTR_ADV(cts.cts_ptr); } vcol = cts.cts_vcol; - ptr = (char_u *)cts.cts_ptr; + ptr = cts.cts_ptr; } clear_chartabsize_arg(&cts); @@ -1076,10 +1076,10 @@ void getvvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *e colnr_T endadd = 0; // Cannot put the cursor on part of a wide character. - char_u *ptr = ml_get_buf(wp->w_buffer, pos->lnum, false); + char *ptr = (char *)ml_get_buf(wp->w_buffer, pos->lnum, false); if (pos->col < (colnr_T)STRLEN(ptr)) { - int c = utf_ptr2char((char *)ptr + pos->col); + int c = utf_ptr2char(ptr + pos->col); if ((c != TAB) && vim_isprintc(c)) { endadd = (colnr_T)(char2cells(c) - 1); if (coladd > endadd) { @@ -1182,7 +1182,7 @@ char *skipwhite_len(const char *p, size_t len) // columns (bytes) at the start of a given line intptr_t getwhitecols_curline(void) { - return getwhitecols((char *)get_cursor_line_ptr()); + return getwhitecols(get_cursor_line_ptr()); } intptr_t getwhitecols(const char *p) @@ -1338,7 +1338,7 @@ char *skip_to_newline(const char *const p) /// Gets a number from a string and skips over it, signalling overflow. /// -/// @param[out] pp A pointer to a pointer to char_u. +/// @param[out] pp A pointer to a pointer to char. /// It will be advanced past the read number. /// @param[out] nr Number read from the string. /// @@ -1355,7 +1355,7 @@ bool try_getdigits(char **pp, intmax_t *nr) /// Gets a number from a string and skips over it. /// -/// @param[out] pp Pointer to a pointer to char_u. +/// @param[out] pp Pointer to a pointer to char. /// It will be advanced past the read number. /// @param strict Abort on overflow. /// @param def Default value, if parsing fails or overflow occurs. @@ -1463,14 +1463,14 @@ bool vim_isblankline(char *lbuf) /// @param strict If true, fail if the number has unexpected trailing /// alphanumeric chars: *len is set to 0 and nothing else is /// returned. -void vim_str2nr(const char_u *const start, int *const prep, int *const len, const int what, +void vim_str2nr(const char *const start, int *const prep, int *const len, const int what, varnumber_T *const nptr, uvarnumber_T *const unptr, const int maxlen, const bool strict) FUNC_ATTR_NONNULL_ARG(1) { - const char *ptr = (const char *)start; + const char *ptr = start; #define STRING_ENDED(ptr) \ - (!(maxlen == 0 || (int)((ptr) - (const char *)start) < maxlen)) + (!(maxlen == 0 || (int)((ptr) - start) < maxlen)) int pre = 0; // default is decimal const bool negative = (ptr[0] == '-'); uvarnumber_T un = 0; @@ -1522,7 +1522,7 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, cons } else if ((what & (STR2NR_HEX | STR2NR_OCT | STR2NR_OOCT | STR2NR_BIN)) && !STRING_ENDED(ptr + 1) && ptr[0] == '0' && ptr[1] != '8' && ptr[1] != '9') { - pre = (char_u)ptr[1]; + pre = (uint8_t)ptr[1]; // Detect hexadecimal: 0x or 0X followed by hex digit. if ((what & STR2NR_HEX) && !STRING_ENDED(ptr + 2) @@ -1610,7 +1610,7 @@ vim_str2nr_hex: vim_str2nr_proceed: // Check for an alphanumeric character immediately following, that is // most likely a typo. - if (strict && ptr - (const char *)start != maxlen && ASCII_ISALNUM(*ptr)) { + if (strict && ptr - start != maxlen && ASCII_ISALNUM(*ptr)) { return; } @@ -1619,7 +1619,7 @@ vim_str2nr_proceed: } if (len != NULL) { - *len = (int)(ptr - (const char *)start); + *len = (int)(ptr - start); } if (nptr != NULL) { diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 6fc63f72a1..0d3aefc83e 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -177,7 +177,7 @@ int nextwild(expand_T *xp, int type, int options, bool escape) ui_flush(); } - i = (int)((char_u *)xp->xp_pattern - ccline->cmdbuff); + i = (int)(xp->xp_pattern - ccline->cmdbuff); assert(ccline->cmdpos >= i); xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i; @@ -186,20 +186,20 @@ int nextwild(expand_T *xp, int type, int options, bool escape) p2 = ExpandOne(xp, NULL, NULL, 0, type); } else { // Translate string into pattern and expand it. - p1 = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); + p1 = (char_u *)addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); const int use_options = (options | WILD_HOME_REPLACE | WILD_ADD_SLASH | WILD_SILENT | (escape ? WILD_ESCAPE : 0) | (p_wic ? WILD_ICASE : 0)); - p2 = ExpandOne(xp, p1, vim_strnsave(&ccline->cmdbuff[i], xp->xp_pattern_len), + p2 = ExpandOne(xp, p1, (char_u *)xstrnsave(&ccline->cmdbuff[i], xp->xp_pattern_len), use_options, type); xfree(p1); // xp->xp_pattern might have been modified by ExpandOne (for example, // in lua completion), so recompute the pattern index and length - i = (int)((char_u *)xp->xp_pattern - ccline->cmdbuff); + i = (int)(xp->xp_pattern - ccline->cmdbuff); xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i; // Longest match: make sure it is not shorter, happens with :help. @@ -220,7 +220,7 @@ int nextwild(expand_T *xp, int type, int options, bool escape) difflen = (int)STRLEN(p2) - (int)(xp->xp_pattern_len); if (ccline->cmdlen + difflen + 4 > ccline->cmdbufflen) { realloc_cmdbuff(ccline->cmdlen + difflen + 4); - xp->xp_pattern = (char *)ccline->cmdbuff + i; + xp->xp_pattern = ccline->cmdbuff + i; } assert(ccline->cmdpos <= ccline->cmdlen); memmove(&ccline->cmdbuff[ccline->cmdpos + difflen], @@ -573,7 +573,7 @@ int showmatches(expand_T *xp, int wildmenu) if (xp->xp_numfiles == -1) { set_expand_context(xp); - i = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos, + i = expand_cmdline(xp, (char_u *)ccline->cmdbuff, ccline->cmdpos, &num_files, &files_found); showtail = expand_showtail(xp); if (i != EXPAND_OK) { @@ -602,7 +602,7 @@ int showmatches(expand_T *xp, int wildmenu) .pum_kind = NULL, }; } - char_u *endpos = (char_u *)(showtail ? sm_gettail(xp->xp_pattern, true) : xp->xp_pattern); + char *endpos = (showtail ? sm_gettail(xp->xp_pattern, true) : xp->xp_pattern); if (ui_has(kUICmdline)) { compl_startcol = (int)(endpos - ccline->cmdbuff); } else { @@ -803,13 +803,13 @@ static bool expand_showtail(expand_T *xp) /// the name into allocated memory and prepend "^". /// /// @param context EXPAND_FILES etc. -char_u *addstar(char_u *fname, size_t len, int context) +char *addstar(char *fname, size_t len, int context) FUNC_ATTR_NONNULL_RET { - char_u *retval; + char *retval; size_t i, j; size_t new_len; - char_u *tail; + char *tail; int ends_in_star; if (context != EXPAND_FILES @@ -831,7 +831,7 @@ char_u *addstar(char_u *fname, size_t len, int context) || context == EXPAND_PACKADD || ((context == EXPAND_TAGS_LISTFILES || context == EXPAND_TAGS) && fname[0] == '/')) { - retval = vim_strnsave(fname, len); + retval = xstrnsave(fname, len); } else { new_len = len + 2; // +2 for '^' at start, NUL at end for (i = 0; i < len; i++) { @@ -901,7 +901,7 @@ char_u *addstar(char_u *fname, size_t len, int context) // $ could be anywhere in the tail. // ` could be anywhere in the file name. // When the name ends in '$' don't add a star, remove the '$'. - tail = (char_u *)path_tail((char *)retval); + tail = path_tail(retval); ends_in_star = (len > 0 && retval[len - 1] == '*'); #ifndef BACKSLASH_IN_FILENAME for (ssize_t k = (ssize_t)len - 2; k >= 0; k--) { @@ -913,8 +913,8 @@ char_u *addstar(char_u *fname, size_t len, int context) #endif if ((*retval != '~' || tail != retval) && !ends_in_star - && vim_strchr((char *)tail, '$') == NULL - && vim_strchr((char *)retval, '`') == NULL) { + && vim_strchr(tail, '$') == NULL + && vim_strchr(retval, '`') == NULL) { retval[len++] = '*'; } else if (len > 0 && retval[len - 1] == '$') { len--; @@ -976,7 +976,7 @@ void set_expand_context(expand_T *xp) xp->xp_context = EXPAND_NOTHING; return; } - set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true); + set_cmd_context(xp, (char_u *)ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true); } /// Sets the index of a built-in or user defined command "cmd" in eap->cmdidx. @@ -1850,7 +1850,7 @@ void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline set_context_for_expression(xp, (char *)str, CMD_SIZE); } else if (use_ccline && ccline->input_fn) { xp->xp_context = ccline->xp_context; - xp->xp_pattern = (char *)ccline->cmdbuff; + xp->xp_pattern = ccline->cmdbuff; xp->xp_arg = (char *)ccline->xp_arg; } else { while (nextcomm != NULL) { @@ -1897,7 +1897,7 @@ int expand_cmdline(expand_T *xp, char_u *str, int col, int *matchcount, char *** // add star to file name, or convert to regexp if not exp. files. assert((str + col) - (char_u *)xp->xp_pattern >= 0); xp->xp_pattern_len = (size_t)((str + col) - (char_u *)xp->xp_pattern); - file_str = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); + file_str = (char_u *)addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); if (p_wic) { options += WILD_ICASE; @@ -2437,9 +2437,9 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T FUNC_ATTR_NONNULL_ALL { CmdlineInfo *const ccline = get_cmdline_info(); - char_u keep = 0; + char keep = 0; typval_T args[4]; - char_u *pat = NULL; + char *pat = NULL; const sctx_T save_current_sctx = current_sctx; if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL) { @@ -2453,12 +2453,12 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T ccline->cmdbuff[ccline->cmdlen] = 0; } - pat = vim_strnsave((char_u *)xp->xp_pattern, xp->xp_pattern_len); + pat = xstrnsave(xp->xp_pattern, xp->xp_pattern_len); args[0].v_type = VAR_STRING; args[1].v_type = VAR_STRING; args[2].v_type = VAR_NUMBER; args[3].v_type = VAR_UNKNOWN; - args[0].vval.v_string = (char *)pat; + args[0].vval.v_string = pat; args[1].vval.v_string = xp->xp_line; args[2].vval.v_number = xp->xp_col; @@ -2478,30 +2478,29 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T /// Expand names with a function defined by the user. static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file) { - char_u *e; + char *e; garray_T ga; - char_u *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file, - file); + char *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file, + file); if (retstr == NULL) { return FAIL; } ga_init(&ga, (int)sizeof(char *), 3); - for (char_u *s = retstr; *s != NUL; s = e) { - e = (char_u *)vim_strchr((char *)s, '\n'); + for (char *s = retstr; *s != NUL; s = e) { + e = vim_strchr(s, '\n'); if (e == NULL) { e = s + STRLEN(s); } - const char_u keep = *e; + const char keep = *e; *e = NUL; - const bool skip = xp->xp_pattern[0] - && vim_regexec(regmatch, (char *)s, (colnr_T)0) == 0; + const bool skip = xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0; *e = keep; if (!skip) { - GA_APPEND(char_u *, &ga, vim_strnsave(s, (size_t)(e - s))); + GA_APPEND(char *, &ga, xstrnsave(s, (size_t)(e - s))); } if (*e != NUL) { @@ -2662,7 +2661,7 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) // cursor int found = false; - int j = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); + int j = (int)(xp->xp_pattern - cclp->cmdbuff); int i = 0; while (--j > 0) { // check for start of menu name @@ -2717,9 +2716,9 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) int found = false; int j = cclp->cmdpos; - int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); + int i = (int)(xp->xp_pattern - cclp->cmdbuff); while (--j > i) { - j -= utf_head_off((char *)cclp->cmdbuff, (char *)cclp->cmdbuff + j); + j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); if (vim_ispathsep(cclp->cmdbuff[j])) { found = true; break; @@ -2738,9 +2737,9 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) int found = false; int j = cclp->cmdpos - 1; - int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); + int i = (int)(xp->xp_pattern - cclp->cmdbuff); while (--j > i) { - j -= utf_head_off((char *)cclp->cmdbuff, (char *)cclp->cmdbuff + j); + j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); if (vim_ispathsep(cclp->cmdbuff[j]) #ifdef BACKSLASH_IN_FILENAME && vim_strchr((const char_u *)" *?[{`$%#", cclp->cmdbuff[j + 1]) @@ -2894,7 +2893,7 @@ void f_getcompletion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } theend: - pat = addstar((char_u *)xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context); + pat = (char_u *)addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context); ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP); tv_list_alloc_ret(rettv, xpc.xp_numfiles); diff --git a/src/nvim/cmdhist.c b/src/nvim/cmdhist.c index 2057b0db9e..629c47f24a 100644 --- a/src/nvim/cmdhist.c +++ b/src/nvim/cmdhist.c @@ -201,7 +201,7 @@ static int in_history(int type, char_u *str, int move_to_front, int sep) // For search history, check that the separator character matches as // well. - char_u *p = history[type][i].hisstr; + char_u *p = (char_u *)history[type][i].hisstr; if (STRCMP(str, p) == 0 && (type != HIST_SEARCH || sep == p[STRLEN(p) + 1])) { if (!move_to_front) { @@ -217,7 +217,7 @@ static int in_history(int type, char_u *str, int move_to_front, int sep) if (last_i >= 0) { list_T *const list = history[type][i].additional_elements; - str = history[type][i].hisstr; + str = (char_u *)history[type][i].hisstr; while (i != hisidx[type]) { if (++i >= hislen) { i = 0; @@ -227,7 +227,7 @@ static int in_history(int type, char_u *str, int move_to_front, int sep) } tv_list_unref(list); history[type][i].hisnum = ++hisnum[type]; - history[type][i].hisstr = str; + history[type][i].hisstr = (char *)str; history[type][i].timestamp = os_time(); history[type][i].additional_elements = NULL; return true; @@ -276,7 +276,7 @@ static int last_maptick = -1; // last seen maptick /// @param histype may be one of the HIST_ values. /// @param in_map consider maptick when inside a mapping /// @param sep separator character used (search hist) -void add_to_history(int histype, char_u *new_entry, int in_map, int sep) +void add_to_history(int histype, char *new_entry, int in_map, int sep) { histentry_T *hisptr; @@ -304,7 +304,7 @@ void add_to_history(int histype, char_u *new_entry, int in_map, int sep) } last_maptick = -1; } - if (!in_history(histype, new_entry, true, sep)) { + if (!in_history(histype, (char_u *)new_entry, true, sep)) { if (++hisidx[histype] == hislen) { hisidx[histype] = 0; } @@ -313,10 +313,10 @@ void add_to_history(int histype, char_u *new_entry, int in_map, int sep) // Store the separator after the NUL of the string. size_t len = STRLEN(new_entry); - hisptr->hisstr = vim_strnsave(new_entry, len + 2); + hisptr->hisstr = xstrnsave(new_entry, len + 2); hisptr->timestamp = os_time(); hisptr->additional_elements = NULL; - hisptr->hisstr[len + 1] = (char_u)sep; + hisptr->hisstr[len + 1] = (char)sep; hisptr->hisnum = ++hisnum[histype]; if (histype == HIST_SEARCH && in_map) { @@ -386,7 +386,7 @@ static char_u *get_history_entry(int histype, int idx) { idx = calc_hist_idx(histype, idx); if (idx >= 0) { - return history[histype][idx].hisstr; + return (char_u *)history[histype][idx].hisstr; } else { return (char_u *)""; } @@ -438,7 +438,7 @@ static int del_history_entry(int histype, char_u *str) if (hisptr->hisstr == NULL) { break; } - if (vim_regexec(®match, (char *)hisptr->hisstr, (colnr_T)0)) { + if (vim_regexec(®match, hisptr->hisstr, (colnr_T)0)) { found = true; hist_free_entry(hisptr); } else { @@ -509,7 +509,7 @@ void f_histadd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) str = tv_get_string_buf(&argvars[1], buf); if (*str != NUL) { init_history(); - add_to_history(histype, (char_u *)str, false, NUL); + add_to_history(histype, (char *)str, false, NUL); rettv->vval.v_number = true; return; } @@ -643,8 +643,8 @@ void ex_history(exarg_T *eap) msg_putchar('\n'); snprintf((char *)IObuff, IOSIZE, "%c%6d ", i == idx ? '>' : ' ', hist[i].hisnum); - if (vim_strsize((char *)hist[i].hisstr) > Columns - 10) { - trunc_string((char *)hist[i].hisstr, (char *)IObuff + STRLEN(IObuff), + if (vim_strsize(hist[i].hisstr) > Columns - 10) { + trunc_string(hist[i].hisstr, (char *)IObuff + STRLEN(IObuff), Columns - 10, IOSIZE - (int)STRLEN(IObuff)); } else { STRCAT(IObuff, hist[i].hisstr); diff --git a/src/nvim/cmdhist.h b/src/nvim/cmdhist.h index 797b79a5f0..8b7bb7ac24 100644 --- a/src/nvim/cmdhist.h +++ b/src/nvim/cmdhist.h @@ -22,7 +22,7 @@ typedef enum { /// History entry definition typedef struct hist_entry { int hisnum; ///< Entry identifier number. - char_u *hisstr; ///< Actual entry, separator char after the NUL. + char *hisstr; ///< Actual entry, separator char after the NUL. Timestamp timestamp; ///< Time when entry was added. list_T *additional_elements; ///< Additional entries from ShaDa file. } histentry_T; diff --git a/src/nvim/cursor.c b/src/nvim/cursor.c index 54e5ffff37..2a3fe9701c 100644 --- a/src/nvim/cursor.c +++ b/src/nvim/cursor.c @@ -493,9 +493,9 @@ void pchar_cursor(char_u c) } /// @return pointer to cursor line. -char_u *get_cursor_line_ptr(void) +char *get_cursor_line_ptr(void) { - return ml_get_buf(curbuf, curwin->w_cursor.lnum, false); + return (char *)ml_get_buf(curbuf, curwin->w_cursor.lnum, false); } /// @return pointer to cursor position. diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c index e4528f9038..53b6c66c46 100644 --- a/src/nvim/digraph.c +++ b/src/nvim/digraph.c @@ -2010,8 +2010,8 @@ void f_digraph_setlist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// structure used for b_kmap_ga.ga_data typedef struct { - char_u *from; - char_u *to; + char *from; + char *to; } kmap_T; #define KMAP_MAXLEN 20 // maximum length of "from" or "to" @@ -2064,10 +2064,10 @@ char *keymap_init(void) /// @param eap void ex_loadkeymap(exarg_T *eap) { - char_u *s; + char *s; #define KMAP_LLEN 200 // max length of "to" and "from" together - char_u buf[KMAP_LLEN + 11]; + char buf[KMAP_LLEN + 11]; char *save_cpo = p_cpo; if (!getline_equal(eap->getline, eap->cookie, getsourceline)) { @@ -2092,15 +2092,15 @@ void ex_loadkeymap(exarg_T *eap) break; } - char_u *p = (char_u *)skipwhite(line); + char *p = skipwhite(line); if ((*p != '"') && (*p != NUL)) { kmap_T *kp = GA_APPEND_VIA_PTR(kmap_T, &curbuf->b_kmap_ga); - s = (char_u *)skiptowhite((char *)p); - kp->from = vim_strnsave(p, (size_t)(s - p)); - p = (char_u *)skipwhite((char *)s); - s = (char_u *)skiptowhite((char *)p); - kp->to = vim_strnsave(p, (size_t)(s - p)); + s = skiptowhite(p); + kp->from = xstrnsave(p, (size_t)(s - p)); + p = skipwhite(s); + s = skiptowhite(p); + kp->to = xstrnsave(p, (size_t)(s - p)); if ((STRLEN(kp->from) + STRLEN(kp->to) >= KMAP_LLEN) || (*kp->from == NUL) @@ -2118,10 +2118,10 @@ void ex_loadkeymap(exarg_T *eap) // setup ":lmap" to map the keys for (int i = 0; i < curbuf->b_kmap_ga.ga_len; i++) { - vim_snprintf((char *)buf, sizeof(buf), " %s %s", + vim_snprintf(buf, sizeof(buf), " %s %s", ((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].from, ((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].to); - (void)do_map(MAPTYPE_MAP, buf, MODE_LANGMAP, false); + (void)do_map(MAPTYPE_MAP, (char_u *)buf, MODE_LANGMAP, false); } p_cpo = save_cpo; diff --git a/src/nvim/edit.c b/src/nvim/edit.c index 9144d055f7..eac184c096 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -190,7 +190,7 @@ static void insert_enter(InsertState *s) } } - Insstart_textlen = (colnr_T)linetabsize(get_cursor_line_ptr()); + Insstart_textlen = (colnr_T)linetabsize((char_u *)get_cursor_line_ptr()); Insstart_blank_vcol = MAXCOL; if (!did_ai) { @@ -274,7 +274,7 @@ static void insert_enter(InsertState *s) update_curswant(); if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum) || curwin->w_curswant > curwin->w_virtcol) - && *(s->ptr = get_cursor_line_ptr() + curwin->w_cursor.col) != NUL) { + && *(s->ptr = (char_u *)get_cursor_line_ptr() + curwin->w_cursor.col) != NUL) { if (s->ptr[1] == NUL) { curwin->w_cursor.col++; } else { @@ -1470,7 +1470,7 @@ static void init_prompt(int cmdchar_todo) char_u *text; curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; - text = get_cursor_line_ptr(); + text = (char_u *)get_cursor_line_ptr(); if (STRNCMP(text, prompt, STRLEN(prompt)) != 0) { // prompt is missing, insert it or append a line with it if (*text == NUL) { @@ -1544,7 +1544,7 @@ void display_dollar(colnr_T col) curwin->w_cursor.col = col; // If on the last byte of a multi-byte move to the first byte. - char_u *p = get_cursor_line_ptr(); + char_u *p = (char_u *)get_cursor_line_ptr(); curwin->w_cursor.col -= utf_head_off((char *)p, (char *)p + col); curs_columns(curwin, false); // Recompute w_wrow and w_wcol if (curwin->w_wcol < curwin->w_grid.cols) { @@ -1590,7 +1590,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang // MODE_VREPLACE state needs to know what the line was like before changing if (State & VREPLACE_FLAG) { - orig_line = vim_strsave(get_cursor_line_ptr()); // Deal with NULL below + orig_line = vim_strsave((char_u *)get_cursor_line_ptr()); // Deal with NULL below orig_col = curwin->w_cursor.col; } @@ -1670,7 +1670,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang // Advance the cursor until we reach the right screen column. last_vcol = 0; - ptr = get_cursor_line_ptr(); + ptr = (char_u *)get_cursor_line_ptr(); chartabsize_T cts; init_chartabsize_arg(&cts, curwin, 0, 0, (char *)ptr, (char *)ptr); while (cts.cts_vcol <= (int)curwin->w_virtcol) { @@ -1761,7 +1761,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang // then put it back again the way we wanted it. if (State & VREPLACE_FLAG) { // Save new line - new_line = vim_strsave(get_cursor_line_ptr()); + new_line = vim_strsave((char_u *)get_cursor_line_ptr()); // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; @@ -2082,7 +2082,7 @@ void insertchar(int c, int flags, int second_indent) // Need to remove existing (middle) comment leader and insert end // comment leader. First, check what comment leader we can find. - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); int i = get_leader_len((char *)line, &p, false, true); if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) { // Just checking // Skip middle-comment string @@ -2287,7 +2287,7 @@ int stop_arrow(void) // right, except when nothing was inserted yet. update_Insstart_orig = false; } - Insstart_textlen = (colnr_T)linetabsize(get_cursor_line_ptr()); + Insstart_textlen = (colnr_T)linetabsize((char_u *)get_cursor_line_ptr()); if (u_save_cursor() == OK) { arrow_used = false; @@ -2484,7 +2484,7 @@ void beginline(int flags) if (flags & (BL_WHITE | BL_SOL)) { char_u *ptr; - for (ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr) + for (ptr = (char_u *)get_cursor_line_ptr(); ascii_iswhite(*ptr) && !((flags & BL_FIX) && ptr[1] == NUL); ptr++) { curwin->w_cursor.col++; } @@ -2799,7 +2799,7 @@ static bool echeck_abbr(int c) return false; } - return check_abbr(c, get_cursor_line_ptr(), curwin->w_cursor.col, + return check_abbr(c, (char_u *)get_cursor_line_ptr(), curwin->w_cursor.col, curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); } @@ -3148,7 +3148,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) // cursor. } else if (*look == 'e') { if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4) { - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); if ((char_u *)skipwhite((char *)p) == p + curwin->w_cursor.col - 4 && STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0) { return true; @@ -3161,12 +3161,12 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) // class::method for C++). } else if (*look == ':') { if (try_match && keytyped == ':') { - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); if (cin_iscase(p, false) || cin_isscopedecl(p) || cin_islabel()) { return true; } // Need to get the line again after cin_islabel(). - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); if (curwin->w_cursor.col > 2 && p[curwin->w_cursor.col - 1] == ':' && p[curwin->w_cursor.col - 2] == ':') { @@ -3174,7 +3174,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) const bool i = cin_iscase(p, false) || cin_isscopedecl(p) || cin_islabel(); - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); p[curwin->w_cursor.col - 1] = ':'; if (i) { return true; @@ -3226,7 +3226,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) /* Just completed a word, check if it starts with "look". * search back for the start of a word. */ - line = get_cursor_line_ptr(); + line = (char_u *)get_cursor_line_ptr(); for (s = line + curwin->w_cursor.col; s > line; s = n) { n = mb_prevptr(line, s); if (!vim_iswordp(n)) { @@ -3805,7 +3805,7 @@ static void ins_shift(int c, int lastc) change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, true, 0, true); } - if (did_ai && *skipwhite((char *)get_cursor_line_ptr()) != NUL) { + if (did_ai && *skipwhite(get_cursor_line_ptr()) != NUL) { did_ai = false; } did_si = false; @@ -4609,7 +4609,7 @@ static bool ins_tab(void) if (State & VREPLACE_FLAG) { pos = curwin->w_cursor; cursor = &pos; - saved_line = vim_strsave(get_cursor_line_ptr()); + saved_line = vim_strsave((char_u *)get_cursor_line_ptr()); ptr = saved_line + pos.col; } else { ptr = get_cursor_pos_ptr(); diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 8927e52349..06ee4c8d81 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -2995,7 +2995,7 @@ static int eval7(char **arg, typval_T *rettv, int evaluate, int want_string) *arg = bp; } else { // decimal, hex or octal number - vim_str2nr((char_u *)(*arg), NULL, &len, STR2NR_ALL, &n, NULL, 0, true); + vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0, true); if (len == 0) { semsg(_(e_invexpr2), *arg); ret = FAIL; @@ -6450,7 +6450,7 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret } else { pos.lnum = curwin->w_cursor.lnum; if (charcol) { - pos.col = (colnr_T)mb_charlen(get_cursor_line_ptr()); + pos.col = (colnr_T)mb_charlen((char_u *)get_cursor_line_ptr()); } else { pos.col = (colnr_T)STRLEN(get_cursor_line_ptr()); } diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c index 7b975ce775..d585509df4 100644 --- a/src/nvim/eval/decode.c +++ b/src/nvim/eval/decode.c @@ -430,7 +430,7 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len, const char ubuf[] = { t[1], t[2], t[3], t[4] }; t += 4; uvarnumber_T ch; - vim_str2nr((char_u *)ubuf, NULL, NULL, + vim_str2nr(ubuf, NULL, NULL, STR2NR_HEX | STR2NR_FORCE, NULL, &ch, 4, true); if (ch == 0) { hasnul = true; @@ -600,7 +600,7 @@ parse_json_number_check: // Convert integer varnumber_T nr; int num_len; - vim_str2nr((char_u *)s, NULL, &num_len, 0, &nr, NULL, (int)(p - s), true); + vim_str2nr(s, NULL, &num_len, 0, &nr, NULL, (int)(p - s), true); if ((int)exp_num_len != num_len) { semsg(_("E685: internal error: while converting number \"%.*s\" " "to integer vim_str2nr consumed %i bytes in place of %zu"), diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 5a5293780d..60a6ec6201 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -5869,9 +5869,9 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) bool binary = false; bool blob = false; FILE *fd; - char_u buf[(IOSIZE/256) * 256]; // rounded to avoid odd + 1 + char buf[(IOSIZE/256) * 256]; // rounded to avoid odd + 1 int io_size = sizeof(buf); - char_u *prev = NULL; // previously read bytes, if any + char *prev = NULL; // previously read bytes, if any long prevlen = 0; // length of data in prev long prevsize = 0; // size of prev buffer long maxline = MAXLNUM; @@ -5922,13 +5922,13 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) // - an incomplete line gets written // - a "binary" file gets an empty line at the end if it ends in a // newline. - char_u *p; // Position in buf. - char_u *start; // Start of current line. + char *p; // Position in buf. + char *start; // Start of current line. for (p = buf, start = buf; p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary)); p++) { if (*p == '\n' || readlen <= 0) { - char_u *s = NULL; + char *s = NULL; size_t len = (size_t)(p - start); // Finished a line. Remove CRs before NL. @@ -5945,7 +5945,7 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } if (prevlen == 0) { assert(len < INT_MAX); - s = vim_strnsave(start, len); + s = xstrnsave(start, len); } else { // Change "prev" buffer to be the right size. This way // the bytes are only copied once, and very long lines are @@ -5960,7 +5960,7 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) tv_list_append_owned_tv(l, (typval_T) { .v_type = VAR_STRING, .v_lock = VAR_UNLOCKED, - .vval.v_string = (char *)s, + .vval.v_string = s, }); start = p + 1; // Step over newline. @@ -5980,18 +5980,18 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) *p = '\n'; // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this // when finding the BF and check the previous two bytes. - } else if (*p == 0xbf && !binary) { + } else if ((uint8_t)(*p) == 0xbf && !binary) { // Find the two bytes before the 0xbf. If p is at buf, or buf + 1, // these may be in the "prev" string. - char_u back1 = p >= buf + 1 ? p[-1] + char back1 = p >= buf + 1 ? p[-1] : prevlen >= 1 ? prev[prevlen - 1] : NUL; - char_u back2 = p >= buf + 2 ? p[-2] + char back2 = p >= buf + 2 ? p[-2] : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1] : prevlen >= - 2 ? prev[prevlen - 2] : NUL; + 2 ? prev[prevlen - 2] : NUL; - if (back2 == 0xef && back1 == 0xbb) { - char_u *dest = p - 2; + if ((uint8_t)back2 == 0xef && (uint8_t)back1 == 0xbb) { + char *dest = p - 2; // Usually a BOM is at the beginning of a file, and so at // the beginning of a line; then we can just step over it. @@ -8304,7 +8304,7 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) break; } varnumber_T n; - vim_str2nr(p, NULL, NULL, what, &n, NULL, 0, false); + vim_str2nr((char *)p, NULL, NULL, what, &n, NULL, 0, false); // Text after the number is silently ignored. if (isneg) { rettv->vval.v_number = -n; @@ -9416,10 +9416,10 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) { char buf1[NUMBUFLEN]; char buf2[NUMBUFLEN]; - const char_u *head = (const char_u *)tv_get_string_buf_chk(&argvars[0], buf1); - const char_u *mask = NULL; - const char_u *prev; - const char_u *p; + const char *head = tv_get_string_buf_chk(&argvars[0], buf1); + const char *mask = NULL; + const char *prev; + const char *p; int dir = 0; rettv->v_type = VAR_STRING; @@ -9434,7 +9434,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } if (argvars[1].v_type == VAR_STRING) { - mask = (const char_u *)tv_get_string_buf_chk(&argvars[1], buf2); + mask = tv_get_string_buf_chk(&argvars[1], buf2); if (argvars[2].v_type != VAR_UNKNOWN) { bool error = false; // leading or trailing characters to trim @@ -9472,7 +9472,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } } - const char_u *tail = head + STRLEN(head); + const char *tail = head + STRLEN(head); if (dir == 0 || dir == 2) { // Trim trailing characters for (; tail > head; tail = prev) { @@ -9495,7 +9495,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) } } } - rettv->vval.v_string = (char *)vim_strnsave(head, (size_t)(tail - head)); + rettv->vval.v_string = xstrnsave(head, (size_t)(tail - head)); } /// "type(expr)" function diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index d5b2b1f2ae..a409271596 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -3717,8 +3717,7 @@ varnumber_T tv_get_number_chk(const typval_T *const tv, bool *const ret_error) case VAR_STRING: { varnumber_T n = 0; if (tv->vval.v_string != NULL) { - vim_str2nr((char_u *)tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0, - false); + vim_str2nr(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0, false); } return n; } diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index bcaca0ca13..6611133ea4 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -525,22 +525,22 @@ static inline bool eval_fname_sid(const char *const name) /// /// @return transformed name: either `fname_buf` or a pointer to an allocated /// memory. -static char_u *fname_trans_sid(const char_u *const name, char_u *const fname_buf, - char_u **const tofree, int *const error) +static char *fname_trans_sid(const char *const name, char *const fname_buf, char **const tofree, + int *const error) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { - char_u *fname; - const int llen = eval_fname_script((const char *)name); + char *fname; + const int llen = eval_fname_script(name); if (llen > 0) { - fname_buf[0] = K_SPECIAL; - fname_buf[1] = KS_EXTRA; + fname_buf[0] = (char)K_SPECIAL; + fname_buf[1] = (char)KS_EXTRA; fname_buf[2] = KE_SNR; int i = 3; - if (eval_fname_sid((const char *)name)) { // "" or "s:" + if (eval_fname_sid(name)) { // "" or "s:" if (current_sctx.sc_sid <= 0) { *error = ERROR_SCRIPT; } else { - snprintf((char *)fname_buf + i, (size_t)(FLEN_FIXED + 1 - i), "%" PRId64 "_", + snprintf(fname_buf + i, (size_t)(FLEN_FIXED + 1 - i), "%" PRId64 "_", (int64_t)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } @@ -555,7 +555,7 @@ static char_u *fname_trans_sid(const char_u *const name, char_u *const fname_buf STRCPY(fname + i, name + llen); } } else { - fname = (char_u *)name; + fname = (char *)name; } return fname; @@ -1437,10 +1437,10 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t int ret = FAIL; int error = ERROR_NONE; ufunc_T *fp = NULL; - char_u fname_buf[FLEN_FIXED + 1]; - char_u *tofree = NULL; - char_u *fname = NULL; - char_u *name = NULL; + char fname_buf[FLEN_FIXED + 1]; + char *tofree = NULL; + char *fname = NULL; + char *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->selfdict; @@ -1463,8 +1463,8 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it could // be changed or deleted in the called function. - name = vim_strnsave((char_u *)funcname, (size_t)len); - fname = fname_trans_sid(name, fname_buf, &tofree, &error); + name = xstrnsave(funcname, (size_t)len); + fname = fname_trans_sid(name, (char *)fname_buf, &tofree, &error); } if (funcexe->doesrange != NULL) { @@ -1495,7 +1495,7 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t } if (error == ERROR_NONE && funcexe->evaluate) { - char_u *rfname = fname; + char *rfname = fname; // Ignore "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { @@ -1519,21 +1519,21 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t } else if (fp != NULL || !builtin_function((const char *)rfname, -1)) { // User defined function. if (fp == NULL) { - fp = find_func(rfname); + fp = find_func((char_u *)rfname); } // Trigger FuncUndefined event, may load the function. if (fp == NULL - && apply_autocmds(EVENT_FUNCUNDEFINED, (char *)rfname, (char *)rfname, true, NULL) + && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, true, NULL) && !aborting()) { // executed an autocommand, search for the function again - fp = find_func(rfname); + fp = find_func((char_u *)rfname); } // Try loading a package. if (fp == NULL && script_autoload((const char *)rfname, STRLEN(rfname), true) && !aborting()) { // Loaded a package, search for the function again. - fp = find_func(rfname); + fp = find_func((char_u *)rfname); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) { @@ -1570,11 +1570,11 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t } else if (funcexe->basetv != NULL) { // expr->method(): Find the method name in the table, call its // implementation with the base as one of the arguments. - error = call_internal_method(fname, argcount, argvars, rettv, + error = call_internal_method((char_u *)fname, argcount, argvars, rettv, funcexe->basetv); } else { // Find the function name in the table, call its implementation. - error = call_internal_func(fname, argcount, argvars, rettv); + error = call_internal_func((char_u *)fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might @@ -1596,7 +1596,7 @@ theend: // Report an error unless the argument evaluation or function call has been // cancelled due to an aborting error, an interrupt, or an exception. if (!aborting()) { - user_func_error(error, (name != NULL) ? name : (char_u *)funcname); + user_func_error(error, (name != NULL) ? (char_u *)name : (char_u *)funcname); } // clear the copies made from the partial @@ -1890,15 +1890,15 @@ theend: /// ":function" void ex_function(exarg_T *eap) { - char_u *theline; - char_u *line_to_free = NULL; - char_u c; + char *theline; + char *line_to_free = NULL; + char c; int saved_did_emsg; bool saved_wait_return = need_wait_return; - char_u *name = NULL; - char_u *p; - char_u *arg; - char_u *line_arg = NULL; + char *name = NULL; + char *p; + char *arg; + char *line_arg = NULL; garray_T newargs; garray_T default_args; garray_T newlines; @@ -1918,8 +1918,8 @@ void ex_function(exarg_T *eap) linenr_T sourcing_lnum_off; linenr_T sourcing_lnum_top; bool is_heredoc = false; - char_u *skip_until = NULL; - char_u *heredoc_trimmed = NULL; + char *skip_until = NULL; + char *heredoc_trimmed = NULL; bool show_block = false; bool do_concat = true; @@ -1950,7 +1950,7 @@ void ex_function(exarg_T *eap) * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { - p = (char_u *)skip_regexp(eap->arg + 1, '/', true, NULL); + p = skip_regexp(eap->arg + 1, '/', true, NULL); if (!eap->skip) { regmatch_T regmatch; @@ -1978,7 +1978,7 @@ void ex_function(exarg_T *eap) if (*p == '/') { p++; } - eap->nextcmd = check_nextcmd((char *)p); + eap->nextcmd = check_nextcmd(p); return; } @@ -1996,9 +1996,9 @@ void ex_function(exarg_T *eap) // "fudi.fd_di" set, "fudi.fd_newkey" == NULL // s:func script-local function name // g:func global function name, same as "func" - p = (char_u *)eap->arg; - name = trans_function_name((char **)&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL); - paren = (vim_strchr((char *)p, '(') != NULL); + p = eap->arg; + name = (char *)trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL); + paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression @@ -2028,16 +2028,16 @@ void ex_function(exarg_T *eap) // - exclude line numbers from function body // if (!paren) { - if (!ends_excmd(*skipwhite((char *)p))) { + if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_arg), p); goto ret_free; } - eap->nextcmd = check_nextcmd((char *)p); + eap->nextcmd = check_nextcmd(p); if (eap->nextcmd != NULL) { *p = NUL; } if (!eap->skip && !got_int) { - fp = find_func(name); + fp = find_func((char_u *)name); if (fp != NULL) { list_func_head(fp, !eap->forceit, eap->forceit); for (int j = 0; j < fp->uf_lines.ga_len && !got_int; j++) { @@ -2063,7 +2063,7 @@ void ex_function(exarg_T *eap) msg_puts(eap->forceit ? "endfunction" : " endfunction"); } } else { - emsg_funcname(N_("E123: Undefined function: %s"), name); + emsg_funcname(N_("E123: Undefined function: %s"), (char_u *)name); } } goto ret_free; @@ -2072,18 +2072,18 @@ void ex_function(exarg_T *eap) /* * ":function name(arg1, arg2)" Define function. */ - p = (char_u *)skipwhite((char *)p); + p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_("E124: Missing '(': %s"), eap->arg); goto ret_free; } // attempt to continue by skipping some text - if (vim_strchr((char *)p, '(') != NULL) { - p = (char_u *)vim_strchr((char *)p, '('); + if (vim_strchr(p, '(') != NULL) { + p = vim_strchr(p, '('); } } - p = (char_u *)skipwhite((char *)p + 1); + p = skipwhite(p + 1); ga_init(&newargs, (int)sizeof(char_u *), 3); ga_init(&newlines, (int)sizeof(char_u *), 3); @@ -2094,15 +2094,15 @@ void ex_function(exarg_T *eap) if (name != NULL) { arg = name; } else { - arg = fudi.fd_newkey; + arg = (char *)fudi.fd_newkey; } if (arg != NULL && (fudi.fd_di == NULL || !tv_is_func(fudi.fd_di->di_tv))) { - int j = (*arg == K_SPECIAL) ? 3 : 0; + int j = ((uint8_t)(*arg) == K_SPECIAL) ? 3 : 0; while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j]) : eval_isnamec(arg[j]))) { j++; } if (arg[j] != NUL) { - emsg_funcname((char *)e_invarg2, arg); + emsg_funcname((char *)e_invarg2, (char_u *)arg); } } // Disallow using the g: dict. @@ -2111,7 +2111,7 @@ void ex_function(exarg_T *eap) } } - if (get_function_args((char **)&p, ')', &newargs, &varargs, + if (get_function_args(&p, ')', &newargs, &varargs, &default_args, eap->skip) == FAIL) { goto errret_2; } @@ -2123,7 +2123,7 @@ void ex_function(exarg_T *eap) // find extra arguments "range", "dict", "abort" and "closure" for (;;) { - p = (char_u *)skipwhite((char *)p); + p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; @@ -2137,9 +2137,8 @@ void ex_function(exarg_T *eap) flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { - emsg_funcname(N_ - ("E932: Closure function should not be at top level: %s"), - name == NULL ? (char_u *)"" : name); + emsg_funcname(N_("E932: Closure function should not be at top level: %s"), + name == NULL ? (char_u *)"" : (char_u *)name); goto erret; } } else { @@ -2165,8 +2164,8 @@ void ex_function(exarg_T *eap) if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) { emsg(_(e_funcdict)); - } else if (name != NULL && find_func(name) != NULL) { - emsg_funcname(e_funcexts, name); + } else if (name != NULL && find_func((char_u *)name) != NULL) { + emsg_funcname(e_funcexts, (char_u *)name); } } @@ -2195,7 +2194,7 @@ void ex_function(exarg_T *eap) if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; - p = (char_u *)vim_strchr((char *)theline, '\n'); + p = vim_strchr(theline, '\n'); if (p == NULL) { line_arg += STRLEN(line_arg); } else { @@ -2205,9 +2204,9 @@ void ex_function(exarg_T *eap) } else { xfree(line_to_free); if (eap->getline == NULL) { - theline = getcmdline(':', 0L, indent, do_concat); + theline = (char *)getcmdline(':', 0L, indent, do_concat); } else { - theline = (char_u *)eap->getline(':', eap->cookie, indent, do_concat); + theline = eap->getline(':', eap->cookie, indent, do_concat); } line_to_free = theline; } @@ -2237,13 +2236,13 @@ void ex_function(exarg_T *eap) // * ":python < 0) { - give_warning2(_("W22: Text found after :endfunction: %s"), - (char *)p, true); + give_warning2(_("W22: Text found after :endfunction: %s"), p, true); } if (nextcmd != NULL) { // Another command follows. If the line came from "eap" we // can simply point into it, otherwise we need to change // "eap->cmdlinep". - eap->nextcmd = (char *)nextcmd; + eap->nextcmd = nextcmd; if (line_to_free != NULL) { xfree(*eap->cmdlinep); - *eap->cmdlinep = (char *)line_to_free; + *eap->cmdlinep = line_to_free; line_to_free = NULL; } } @@ -2299,13 +2297,13 @@ void ex_function(exarg_T *eap) } // Check for defining a function inside this function. - if (checkforcmd((char **)&p, "function", 2)) { + if (checkforcmd(&p, "function", 2)) { if (*p == '!') { - p = (char_u *)skipwhite((char *)p + 1); + p = skipwhite(p + 1); } p += eval_fname_script((const char *)p); - xfree(trans_function_name((char **)&p, true, 0, NULL, NULL)); - if (*skipwhite((char *)p) == '(') { + xfree(trans_function_name(&p, true, 0, NULL, NULL)); + if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) { emsg(_("E1058: function nesting too deep")); } else { @@ -2316,7 +2314,7 @@ void ex_function(exarg_T *eap) } // Check for ":append", ":change", ":insert". - p = (char_u *)skip_range((char *)p, NULL); + p = skip_range(p, NULL); if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) @@ -2328,11 +2326,11 @@ void ex_function(exarg_T *eap) && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's')))))) { - skip_until = vim_strsave((char_u *)"."); + skip_until = xstrdup("."); } // heredoc: Check for ":python <di_tv.v_type == VAR_FUNC) { emsg_funcname(N_("E707: Function name conflicts with variable: %s"), - name); + (char_u *)name); goto erret; } - fp = find_func(name); + fp = find_func((char_u *)name); if (fp != NULL) { // Function can be replaced with "function!" and when sourcing the // same script again, but only once. if (!eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq)) { - emsg_funcname(e_funcexts, name); + emsg_funcname(e_funcexts, (char_u *)name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), - name); + (char_u *)name); goto erret; } if (fp->uf_refcount > 1) { @@ -2480,12 +2477,12 @@ void ex_function(exarg_T *eap) // Give the function a sequential number. Can only be used with a // Funcref! xfree(name); - sprintf(numbuf, "%d", ++func_nr); - name = vim_strsave((char_u *)numbuf); + sprintf(numbuf, "%d", ++func_nr); // NOLINT(runtime/printf) + name = xstrdup(numbuf); } if (fp == NULL) { - if (fudi.fd_dict == NULL && vim_strchr((char *)name, AUTOLOAD_CHAR) != NULL) { + if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; @@ -2493,7 +2490,7 @@ void ex_function(exarg_T *eap) int j = FAIL; if (SOURCING_NAME != NULL) { scriptname = (char_u *)autoload_name((const char *)name, STRLEN(name)); - p = (char_u *)vim_strchr((char *)scriptname, '/'); + p = vim_strchr((char *)scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && FNAMECMP(p, SOURCING_NAME + slen - plen) == 0) { @@ -2524,16 +2521,16 @@ void ex_function(exarg_T *eap) tv_clear(&fudi.fd_di->di_tv); } fudi.fd_di->di_tv.v_type = VAR_FUNC; - fudi.fd_di->di_tv.vval.v_string = (char *)vim_strsave(name); + fudi.fd_di->di_tv.vval.v_string = xstrdup(name); // behave like "dict" was used flags |= FC_DICT; } // insert the new function in the function list - set_ufunc_name(fp, name); + set_ufunc_name(fp, (char_u *)name); if (overwrite) { - hi = hash_find(&func_hashtab, (char *)name); + hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { xfree(fp); @@ -3213,7 +3210,7 @@ void make_partial(dict_T *const selfdict, typval_T *const rettv) ? (char_u *)rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. - fname = fname_trans_sid(fname, fname_buf, &tofree, &error); + fname = (char_u *)fname_trans_sid((char *)fname, (char *)fname_buf, (char **)&tofree, &error); fp = find_func(fname); xfree(tofree); } @@ -3559,7 +3556,7 @@ bool set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) } if (fp_in == NULL) { - fname = fname_trans_sid(name, fname_buf, &tofree, &error); + fname = (char_u *)fname_trans_sid((char *)name, (char *)fname_buf, (char **)&tofree, &error); fp = find_func(fname); } if (fp != NULL) { diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index db79187b7d..126129b24d 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -330,7 +330,7 @@ static int linelen(int *has_tab) // Get the line. If it's empty bail out early (could be the empty string // for an unloaded buffer). - line = (char *)get_cursor_line_ptr(); + line = get_cursor_line_ptr(); if (*line == NUL) { return 0; } @@ -601,7 +601,7 @@ void ex_sort(exarg_T *eap) nrs[lnum - eap->line1].st_u.num.value = 0; } else { nrs[lnum - eap->line1].st_u.num.is_number = true; - vim_str2nr((char_u *)s, NULL, NULL, sort_what, + vim_str2nr(s, NULL, NULL, sort_what, &nrs[lnum - eap->line1].st_u.num.value, NULL, 0, false); } } else { @@ -2808,7 +2808,7 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum // keep it. Also when it moves within a line. But not when it moves // to the first non-blank. if (!equalpos(curwin->w_cursor, orig_pos)) { - const char *text = (char *)get_cursor_line_ptr(); + const char *text = get_cursor_line_ptr(); if (curwin->w_cursor.lnum != orig_pos.lnum || curwin->w_cursor.col != (int)(skipwhite(text) - text)) { @@ -3354,7 +3354,7 @@ static bool sub_joining_lines(exarg_T *eap, char *pat, char *sub, char *cmd, boo save_re_pat(RE_SUBST, (char_u *)pat, p_magic); } // put pattern in history - add_to_history(HIST_SEARCH, (char_u *)pat, true, NUL); + add_to_history(HIST_SEARCH, pat, true, NUL); } return true; diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 0af737ff50..8ef7903db5 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -3689,7 +3689,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp) // Decide to expand wildcards *before* replacing '%', '#', etc. If // the file name contains a wildcard it should not cause expanding. // (it will be expanded anyway if there is a wildcard before replacing). - int has_wildcards = path_has_wildcard((char_u *)p); + int has_wildcards = path_has_wildcard(p); while (*p != NUL) { // Skip over `=expr`, wildcards in it are not expanded. if (p[0] == '`' && p[1] == '=') { @@ -3794,7 +3794,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp) if (vim_strchr(eap->arg, '$') != NULL || vim_strchr(eap->arg, '~') != NULL) { expand_env_esc((char_u *)eap->arg, (char_u *)NameBuff, MAXPATHL, true, true, NULL); - has_wildcards = path_has_wildcard((char_u *)NameBuff); + has_wildcards = path_has_wildcard(NameBuff); p = (char *)NameBuff; } else { p = NULL; diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 9d1cebd43e..2112385533 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -255,7 +255,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s exarg_T ea = { .line1 = 1, .line2 = 1, - .cmd = (char *)ccline.cmdbuff, + .cmd = ccline.cmdbuff, .addr_type = ADDR_LINES, }; @@ -336,7 +336,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s } // found a non-empty pattern or // - *skiplen = (int)((char_u *)p - ccline.cmdbuff); + *skiplen = (int)(p - ccline.cmdbuff); *patlen = (int)(end - p); // parse the address range @@ -409,7 +409,7 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat int found; // do_search() result // Use the previous pattern for ":s//". - next_char = ccline.cmdbuff[skiplen + patlen]; + next_char = (char_u)ccline.cmdbuff[skiplen + patlen]; use_last_pat = patlen == 0 && skiplen > 0 && ccline.cmdbuff[skiplen - 1] == next_char; @@ -436,9 +436,9 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat .sa_tm = &tm, }; found = do_search(NULL, firstc == ':' ? '/' : firstc, search_delim, - ccline.cmdbuff + skiplen, count, + (char_u *)ccline.cmdbuff + skiplen, count, search_flags, &sia); - ccline.cmdbuff[skiplen + patlen] = next_char; + ccline.cmdbuff[skiplen + patlen] = (char)next_char; emsg_off--; if (curwin->w_cursor.lnum < search_first_line || curwin->w_cursor.lnum > search_last_line) { @@ -487,13 +487,13 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat // Disable 'hlsearch' highlighting if the pattern matches // everything. Avoids a flash when typing "foo\|". if (!use_last_pat) { - next_char = ccline.cmdbuff[skiplen + patlen]; + next_char = (char_u)ccline.cmdbuff[skiplen + patlen]; ccline.cmdbuff[skiplen + patlen] = NUL; - if (empty_pattern((char *)ccline.cmdbuff) && !no_hlsearch) { + if (empty_pattern(ccline.cmdbuff) && !no_hlsearch) { redraw_all_later(UPD_SOME_VALID); set_no_hlsearch(true); } - ccline.cmdbuff[skiplen + patlen] = next_char; + ccline.cmdbuff[skiplen + patlen] = (char)next_char; } validate_cursor(); @@ -548,7 +548,7 @@ static int may_add_char_to_search(int firstc, int *c, incsearch_state_T *s) // command line has no uppercase characters, convert // the character to lowercase if (p_ic && p_scs - && !pat_has_uppercase(ccline.cmdbuff + skiplen)) { + && !pat_has_uppercase((char_u *)ccline.cmdbuff + skiplen)) { *c = mb_tolower(*c); } if (*c == search_delim @@ -724,7 +724,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init if (ccline.input_fn) { s->xpc.xp_context = ccline.xp_context; - s->xpc.xp_pattern = (char *)ccline.cmdbuff; + s->xpc.xp_pattern = ccline.cmdbuff; s->xpc.xp_arg = (char *)ccline.xp_arg; } @@ -854,7 +854,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init s->histype == HIST_SEARCH ? s->firstc : NUL); if (s->firstc == ':') { xfree(new_last_cmdline); - new_last_cmdline = (char *)vim_strsave(ccline.cmdbuff); + new_last_cmdline = xstrdup(ccline.cmdbuff); } } @@ -897,7 +897,7 @@ theend: xfree(ccline.last_colors.cmdbuff); kv_destroy(ccline.last_colors.colors); - char_u *p = ccline.cmdbuff; + char_u *p = (char_u *)ccline.cmdbuff; if (ui_has(kUICmdline)) { ui_call_cmdline_hide(ccline.level); @@ -1339,7 +1339,7 @@ static int may_do_command_line_next_incsearch(int firstc, long count, incsearch_ skiplen = 0; patlen = (int)STRLEN(pat); } else { - pat = ccline.cmdbuff + skiplen; + pat = (char_u *)ccline.cmdbuff + skiplen; } if (next_match) { @@ -1483,24 +1483,24 @@ static int command_line_handle_key(CommandLineState *s) } if (s->c == K_DEL) { - ccline.cmdpos += mb_off_next(ccline.cmdbuff, - ccline.cmdbuff + ccline.cmdpos); + ccline.cmdpos += mb_off_next((char_u *)ccline.cmdbuff, + (char_u *)ccline.cmdbuff + ccline.cmdpos); } if (ccline.cmdpos > 0) { char_u *p; int j = ccline.cmdpos; - p = mb_prevptr(ccline.cmdbuff, ccline.cmdbuff + j); + p = mb_prevptr((char_u *)ccline.cmdbuff, (char_u *)ccline.cmdbuff + j); if (s->c == Ctrl_W) { - while (p > ccline.cmdbuff && ascii_isspace(*p)) { - p = mb_prevptr(ccline.cmdbuff, p); + while (p > (char_u *)ccline.cmdbuff && ascii_isspace(*p)) { + p = mb_prevptr((char_u *)ccline.cmdbuff, p); } int i = mb_get_class(p); - while (p > ccline.cmdbuff && mb_get_class(p) == i) { - p = mb_prevptr(ccline.cmdbuff, p); + while (p > (char_u *)ccline.cmdbuff && mb_get_class(p) == i) { + p = mb_prevptr((char_u *)ccline.cmdbuff, p); } if (mb_get_class(p) != i) { @@ -1508,7 +1508,7 @@ static int command_line_handle_key(CommandLineState *s) } } - ccline.cmdpos = (int)(p - ccline.cmdbuff); + ccline.cmdpos = (int)(p - (char_u *)ccline.cmdbuff); ccline.cmdlen -= j - ccline.cmdpos; int i = ccline.cmdpos; @@ -1688,7 +1688,7 @@ static int command_line_handle_key(CommandLineState *s) } ccline.cmdspos += cells; - ccline.cmdpos += utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos); + ccline.cmdpos += utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos); } while ((s->c == K_S_RIGHT || s->c == K_C_RIGHT || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))) && ccline.cmdbuff[ccline.cmdpos] != ' '); @@ -1704,8 +1704,8 @@ static int command_line_handle_key(CommandLineState *s) do { ccline.cmdpos--; // Move to first byte of possibly multibyte char. - ccline.cmdpos -= utf_head_off((char *)ccline.cmdbuff, - (char *)ccline.cmdbuff + ccline.cmdpos); + ccline.cmdpos -= utf_head_off(ccline.cmdbuff, + ccline.cmdbuff + ccline.cmdpos); ccline.cmdspos -= cmdline_charsize(ccline.cmdpos); } while (ccline.cmdpos > 0 && (s->c == K_S_LEFT || s->c == K_C_LEFT @@ -1761,7 +1761,7 @@ static int command_line_handle_key(CommandLineState *s) // Count ">" for double-wide char that doesn't fit. correct_screencol(ccline.cmdpos, cells, &ccline.cmdspos); - ccline.cmdpos += utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos) - 1; + ccline.cmdpos += utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos) - 1; ccline.cmdspos += cells; } return command_line_not_changed(s); @@ -1855,7 +1855,7 @@ static int command_line_handle_key(CommandLineState *s) // save current command string so it can be restored later if (s->lookfor == NULL) { - s->lookfor = vim_strsave(ccline.cmdbuff); + s->lookfor = vim_strsave((char_u *)ccline.cmdbuff); s->lookfor[ccline.cmdpos] = NUL; } @@ -1874,7 +1874,7 @@ static int command_line_handle_key(CommandLineState *s) if (s->hiscnt == get_hislen()) { p = s->lookfor; // back to the old one } else { - p = get_histentry(s->histype)[s->hiscnt].hisstr; + p = (char_u *)get_histentry(s->histype)[s->hiscnt].hisstr; } if (s->histype == HIST_SEARCH @@ -1892,7 +1892,7 @@ static int command_line_handle_key(CommandLineState *s) if (p[j] == old_firstc && (j == 0 || p[j - 1] != '\\')) { if (i > 0) { - ccline.cmdbuff[len] = (char_u)s->firstc; + ccline.cmdbuff[len] = (char)s->firstc; } } else { // Escape new sep, unless it is already @@ -1906,7 +1906,7 @@ static int command_line_handle_key(CommandLineState *s) } if (i > 0) { - ccline.cmdbuff[len] = p[j]; + ccline.cmdbuff[len] = (char)p[j]; } } len++; @@ -2281,7 +2281,7 @@ static bool cmdpreview_may_show(CommandLineState *s) CmdParseInfo cmdinfo; // Copy the command line so we can modify it. int cmdpreview_type = 0; - char *cmdline = xstrdup((char *)ccline.cmdbuff); + char *cmdline = xstrdup(ccline.cmdbuff); char *errormsg = NULL; emsg_off++; // Block errors when parsing the command line, and don't update v:errmsg if (!parse_cmdline(cmdline, &ea, &cmdinfo, &errormsg)) { @@ -2659,7 +2659,7 @@ static int cmdline_charsize(int idx) if (cmdline_star > 0) { // showing '*', always 1 position return 1; } - return ptr2cells((char *)ccline.cmdbuff + idx); + return ptr2cells(ccline.cmdbuff + idx); } /// Compute the offset of the cursor on the command line for the prompt and @@ -2685,7 +2685,7 @@ int cmd_screencol(int bytepos) } for (int i = 0; i < ccline.cmdlen && i < bytepos; - i += utfc_ptr2len((char *)ccline.cmdbuff + i)) { + i += utfc_ptr2len(ccline.cmdbuff + i)) { int c = cmdline_charsize(i); // Count ">" for double-wide multi-byte char that doesn't fit. correct_screencol(i, c, &col); @@ -2704,8 +2704,8 @@ int cmd_screencol(int bytepos) /// character that doesn't fit, so that a ">" must be displayed. static void correct_screencol(int idx, int cells, int *col) { - if (utfc_ptr2len((char *)ccline.cmdbuff + idx) > 1 - && utf_ptr2cells((char *)ccline.cmdbuff + idx) > 1 + if (utfc_ptr2len(ccline.cmdbuff + idx) > 1 + && utf_ptr2cells(ccline.cmdbuff + idx) > 1 && (*col) % Columns + cells > Columns) { (*col)++; } @@ -2764,7 +2764,7 @@ void realloc_cmdbuff(int len) return; // no need to resize } - char_u *p = ccline.cmdbuff; + char_u *p = (char_u *)ccline.cmdbuff; alloc_cmdbuff(len); // will get some more // There isn't always a NUL after the command, but it may need to be // there, thus copy up to the NUL and add a NUL. @@ -2781,7 +2781,7 @@ void realloc_cmdbuff(int len) // If xp_pattern points inside the old cmdbuff it needs to be adjusted // to point into the newly allocated memory. if (i >= 0 && i <= ccline.cmdlen) { - ccline.xpc->xp_pattern = (char *)ccline.cmdbuff + i; + ccline.xpc->xp_pattern = ccline.cmdbuff + i; } } } @@ -2904,7 +2904,7 @@ static bool color_cmdline(CmdlineInfo *colored_ccline) bool arg_allocated = false; typval_T arg = { .v_type = VAR_STRING, - .vval.v_string = (char *)colored_ccline->cmdbuff, + .vval.v_string = colored_ccline->cmdbuff, }; typval_T tv = { .v_type = VAR_UNKNOWN }; @@ -3107,16 +3107,16 @@ static void draw_cmdline(int start, int len) if (cmdline_star > 0) { for (int i = 0; i < len; i++) { msg_putchar('*'); - i += utfc_ptr2len((char *)ccline.cmdbuff + start + i) - 1; + i += utfc_ptr2len(ccline.cmdbuff + start + i) - 1; } } else if (p_arshape && !p_tbidi && len > 0) { bool do_arabicshape = false; int mb_l; for (int i = start; i < start + len; i += mb_l) { - char_u *p = ccline.cmdbuff + i; + char_u *p = (char_u *)ccline.cmdbuff + i; int u8cc[MAX_MCO]; int u8c = utfc_ptr2char_len(p, u8cc, start + len - i); - mb_l = utfc_ptr2len_len(p, start + len - i); + mb_l = utfc_ptr2len_len((char *)p, start + len - i); if (ARABIC_CHAR(u8c)) { do_arabicshape = true; break; @@ -3140,7 +3140,7 @@ static void draw_cmdline(int start, int len) } int newlen = 0; - if (utf_iscomposing(utf_ptr2char((char *)ccline.cmdbuff + start))) { + if (utf_iscomposing(utf_ptr2char(ccline.cmdbuff + start))) { // Prepend a space to draw the leading composing char on. arshape_buf[0] = ' '; newlen = 1; @@ -3149,10 +3149,10 @@ static void draw_cmdline(int start, int len) int prev_c = 0; int prev_c1 = 0; for (int i = start; i < start + len; i += mb_l) { - char_u *p = ccline.cmdbuff + i; + char_u *p = (char_u *)ccline.cmdbuff + i; int u8cc[MAX_MCO]; int u8c = utfc_ptr2char_len(p, u8cc, start + len - i); - mb_l = utfc_ptr2len_len(p, start + len - i); + mb_l = utfc_ptr2len_len((char *)p, start + len - i); if (ARABIC_CHAR(u8c)) { int pc; int pc1 = 0; @@ -3208,12 +3208,12 @@ draw_cmdline_no_arabicshape: continue; } const int chunk_start = MAX(chunk.start, start); - msg_outtrans_len_attr((char *)ccline.cmdbuff + chunk_start, + msg_outtrans_len_attr(ccline.cmdbuff + chunk_start, chunk.end - chunk_start, chunk.attr); } } else { - msg_outtrans_len((char *)ccline.cmdbuff + start, len); + msg_outtrans_len(ccline.cmdbuff + start, len); } } } @@ -3225,7 +3225,7 @@ static void ui_ext_cmdline_show(CmdlineInfo *line) if (cmdline_star) { content = arena_array(&arena, 1); size_t len = 0; - for (char_u *p = ccline.cmdbuff; *p; MB_PTR_ADV(p)) { + for (char_u *p = (char_u *)ccline.cmdbuff; *p; MB_PTR_ADV(p)) { len++; } char *buf = arena_alloc(&arena, len, false); @@ -3380,7 +3380,7 @@ void unputcmdline(void) if (ccline.cmdlen == ccline.cmdpos && !ui_has(kUICmdline)) { msg_putchar(' '); } else { - draw_cmdline(ccline.cmdpos, utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos)); + draw_cmdline(ccline.cmdpos, utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos)); } msg_no_more = false; cursorcmd(); @@ -3422,7 +3422,7 @@ void put_on_cmdline(char_u *str, int len, int redraw) // Count nr of bytes in cmdline that are overwritten by these // characters. for (i = ccline.cmdpos; i < ccline.cmdlen && m > 0; - i += utfc_ptr2len((char *)ccline.cmdbuff + i)) { + i += utfc_ptr2len(ccline.cmdbuff + i)) { m--; } if (i < ccline.cmdlen) { @@ -3440,17 +3440,17 @@ void put_on_cmdline(char_u *str, int len, int redraw) // When the inserted text starts with a composing character, // backup to the character before it. There could be two of them. i = 0; - c = utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos); + c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos); while (ccline.cmdpos > 0 && utf_iscomposing(c)) { - i = utf_head_off((char *)ccline.cmdbuff, (char *)ccline.cmdbuff + ccline.cmdpos - 1) + 1; + i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos - 1) + 1; ccline.cmdpos -= i; len += i; - c = utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos); + c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos); } if (i == 0 && ccline.cmdpos > 0 && arabic_maycombine(c)) { // Check the previous character for Arabic combining pair. - i = utf_head_off((char *)ccline.cmdbuff, (char *)ccline.cmdbuff + ccline.cmdpos - 1) + 1; - if (arabic_combine(utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos - i), c)) { + i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos - 1) + 1; + if (arabic_combine(utf_ptr2char(ccline.cmdbuff + ccline.cmdpos - i), c)) { ccline.cmdpos -= i; len += i; } else { @@ -3459,7 +3459,7 @@ void put_on_cmdline(char_u *str, int len, int redraw) } if (i != 0) { // Also backup the cursor position. - i = ptr2cells((char *)ccline.cmdbuff + ccline.cmdpos); + i = ptr2cells(ccline.cmdbuff + ccline.cmdpos); ccline.cmdspos -= i; msg_col -= i; if (msg_col < 0) { @@ -3498,7 +3498,7 @@ void put_on_cmdline(char_u *str, int len, int redraw) if (ccline.cmdspos + c < m) { ccline.cmdspos += c; } - c = utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos) - 1; + c = utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos) - 1; if (c > len - i - 1) { c = len - i - 1; } @@ -3580,14 +3580,14 @@ static bool cmdline_paste(int regname, bool literally, bool remcr) int len; // Locate start of last word in the cmd buffer. - for (w = ccline.cmdbuff + ccline.cmdpos; w > ccline.cmdbuff;) { - len = utf_head_off((char *)ccline.cmdbuff, (char *)w - 1) + 1; + for (w = (char_u *)ccline.cmdbuff + ccline.cmdpos; w > (char_u *)ccline.cmdbuff;) { + len = utf_head_off(ccline.cmdbuff, (char *)w - 1) + 1; if (!vim_iswordc(utf_ptr2char((char *)w - len))) { break; } w -= len; } - len = (int)((ccline.cmdbuff + ccline.cmdpos) - w); + len = (int)(((char_u *)ccline.cmdbuff + ccline.cmdpos) - w); if (p_ic ? STRNICMP(w, arg, len) == 0 : STRNCMP(w, arg, len) == 0) { p += len; } @@ -3823,7 +3823,7 @@ static int ccheck_abbr(int c) spos = 0; } - return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, spos); + return check_abbr(c, (char_u *)ccline.cmdbuff, ccline.cmdpos, spos); } /// Escape special characters in "fname", depending on "what": @@ -3964,7 +3964,7 @@ static char *get_cmdline_str(void) if (p == NULL) { return NULL; } - return (char *)vim_strnsave(p->cmdbuff, (size_t)p->cmdlen); + return xstrnsave(p->cmdbuff, (size_t)p->cmdlen); } /// Get the current command-line completion type. @@ -4126,7 +4126,7 @@ int get_list_range(char **str, int *num1, int *num2) *str = skipwhite((*str)); if (**str == '-' || ascii_isdigit(**str)) { // parse "from" part of range - vim_str2nr((char_u *)(*str), NULL, &len, 0, &num, NULL, 0, false); + vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false); *str += len; *num1 = (int)num; first = true; @@ -4134,7 +4134,7 @@ int get_list_range(char **str, int *num1, int *num2) *str = skipwhite((*str)); if (**str == ',') { // parse "to" part of range *str = skipwhite((*str) + 1); - vim_str2nr((char_u *)(*str), NULL, &len, 0, &num, NULL, 0, false); + vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false); if (len > 0) { *num2 = (int)num; *str = skipwhite((*str) + len); @@ -4270,7 +4270,7 @@ static int open_cmdwin(void) i = 0; } if (get_histentry(histtype)[i].hisstr != NULL) { - ml_append(lnum++, (char *)get_histentry(histtype)[i].hisstr, (colnr_T)0, false); + ml_append(lnum++, get_histentry(histtype)[i].hisstr, (colnr_T)0, false); } } while (i != *get_hisidx(histtype)); } @@ -4278,7 +4278,7 @@ static int open_cmdwin(void) // Replace the empty last line with the current command-line and put the // cursor there. - ml_replace(curbuf->b_ml.ml_line_count, (char *)ccline.cmdbuff, true); + ml_replace(curbuf->b_ml.ml_line_count, ccline.cmdbuff, true); curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; curwin->w_cursor.col = ccline.cmdpos; changed_line_abv_curs(); @@ -4348,7 +4348,7 @@ static int open_cmdwin(void) if (histtype == HIST_CMD) { // Execute the command directly. - ccline.cmdbuff = (char_u *)xstrdup(p); + ccline.cmdbuff = xstrdup(p); cmdwin_result = CAR; } else { // First need to cancel what we were doing. @@ -4362,10 +4362,10 @@ static int open_cmdwin(void) // and don't modify the cmd window. ccline.cmdbuff = NULL; } else { - ccline.cmdbuff = vim_strsave(get_cursor_line_ptr()); + ccline.cmdbuff = xstrdup(get_cursor_line_ptr()); } if (ccline.cmdbuff == NULL) { - ccline.cmdbuff = vim_strsave((char_u *)""); + ccline.cmdbuff = xstrdup(""); ccline.cmdlen = 0; ccline.cmdbufflen = 1; ccline.cmdpos = 0; diff --git a/src/nvim/ex_getln.h b/src/nvim/ex_getln.h index 5e3ad20a31..919a6c8f11 100644 --- a/src/nvim/ex_getln.h +++ b/src/nvim/ex_getln.h @@ -41,7 +41,7 @@ typedef enum { /// structure. typedef struct cmdline_info CmdlineInfo; struct cmdline_info { - char_u *cmdbuff; ///< pointer to command line buffer + char *cmdbuff; ///< pointer to command line buffer int cmdbufflen; ///< length of cmdbuff int cmdlen; ///< number of chars in command line int cmdpos; ///< current cursor position diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index e87e0853f3..f75dc51ca5 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -174,12 +174,12 @@ typedef struct ff_search_ctx_T { ff_visited_list_hdr_T *ffsc_dir_visited_list; ff_visited_list_hdr_T *ffsc_visited_lists_list; ff_visited_list_hdr_T *ffsc_dir_visited_lists_list; - char_u *ffsc_file_to_search; - char_u *ffsc_start_dir; - char_u *ffsc_fix_path; - char_u *ffsc_wc_path; + char *ffsc_file_to_search; + char *ffsc_start_dir; + char *ffsc_fix_path; + char *ffsc_wc_path; int ffsc_level; - char_u **ffsc_stopdirs_v; + char **ffsc_stopdirs_v; int ffsc_find_what; int ffsc_tagfile; } ff_search_ctx_T; @@ -245,11 +245,10 @@ static char_u e_pathtoolong[] = N_("E854: path too long for completion"); /// /// @param tagfile expanding names of tags files /// @param rel_fname file name to use for "." -void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int level, - int free_visited, int find_what, void *search_ctx_arg, int tagfile, - char_u *rel_fname) +void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, int free_visited, + int find_what, void *search_ctx_arg, int tagfile, char *rel_fname) { - char_u *wc_part; + char *wc_part; ff_stack_T *sptr; ff_search_ctx_T *search_ctx; @@ -274,12 +273,12 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le /* Reuse old visited lists. Get the visited list for the given * filename. If no list for the current filename exists, creates a new * one. */ - search_ctx->ffsc_visited_list = ff_get_visited_list(filename, + search_ctx->ffsc_visited_list = ff_get_visited_list((char_u *)filename, &search_ctx->ffsc_visited_lists_list); if (search_ctx->ffsc_visited_list == NULL) { goto error_return; } - search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename, + search_ctx->ffsc_dir_visited_list = ff_get_visited_list((char_u *)filename, &search_ctx->ffsc_dir_visited_lists_list); if (search_ctx->ffsc_dir_visited_list == NULL) { goto error_return; @@ -296,19 +295,19 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le && (vim_ispathsep(path[1]) || path[1] == NUL) && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL) && rel_fname != NULL) { - size_t len = (size_t)((char_u *)path_tail((char *)rel_fname) - rel_fname); + size_t len = (size_t)(path_tail(rel_fname) - rel_fname); - if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL) { + if (!vim_isAbsName((char_u *)rel_fname) && len + 1 < MAXPATHL) { // Make the start dir an absolute path name. STRLCPY(ff_expand_buffer, rel_fname, len + 1); - search_ctx->ffsc_start_dir = (char_u *)FullName_save((char *)ff_expand_buffer, false); + search_ctx->ffsc_start_dir = FullName_save((char *)ff_expand_buffer, false); } else { - search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len); + search_ctx->ffsc_start_dir = xstrnsave(rel_fname, len); } if (*++path != NUL) { path++; } - } else if (*path == NUL || !vim_isAbsName(path)) { + } else if (*path == NUL || !vim_isAbsName((char_u *)path)) { #ifdef BACKSLASH_IN_FILENAME // "c:dir" needs "c:" to be expanded, otherwise use current dir if (*path != NUL && path[1] == ':') { @@ -329,7 +328,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le goto error_return; } - search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer); + search_ctx->ffsc_start_dir = (char *)vim_strsave(ff_expand_buffer); #ifdef BACKSLASH_IN_FILENAME /* A path that starts with "/dir" is relative to the drive, not to the @@ -352,7 +351,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le * ff_path_in_stoplist() for details. */ if (stopdirs != NULL) { - char_u *walker = stopdirs; + char *walker = stopdirs; while (*walker == ';') { walker++; @@ -362,25 +361,23 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le search_ctx->ffsc_stopdirs_v = xmalloc(sizeof(char_u *)); do { - char_u *helper; + char *helper; void *ptr; helper = walker; ptr = xrealloc(search_ctx->ffsc_stopdirs_v, (dircount + 1) * sizeof(char_u *)); search_ctx->ffsc_stopdirs_v = ptr; - walker = (char_u *)vim_strchr((char *)walker, ';'); + walker = vim_strchr(walker, ';'); if (walker) { assert(walker - helper >= 0); - search_ctx->ffsc_stopdirs_v[dircount - 1] = - vim_strnsave(helper, (size_t)(walker - helper)); + search_ctx->ffsc_stopdirs_v[dircount - 1] = xstrnsave(helper, (size_t)(walker - helper)); walker++; } else { /* this might be "", which means ascent till top * of directory tree. */ - search_ctx->ffsc_stopdirs_v[dircount - 1] = - vim_strsave(helper); + search_ctx->ffsc_stopdirs_v[dircount - 1] = xstrdup(helper); } dircount++; @@ -394,7 +391,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le * -fix path * -wildcard_stuff (might be NULL) */ - wc_part = (char_u *)vim_strchr((char *)path, '*'); + wc_part = vim_strchr(path, '*'); if (wc_part != NULL) { int64_t llevel; int len; @@ -402,7 +399,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le // save the fix part of the path assert(wc_part - path >= 0); - search_ctx->ffsc_fix_path = vim_strnsave(path, (size_t)(wc_part - path)); + search_ctx->ffsc_fix_path = xstrnsave(path, (size_t)(wc_part - path)); /* * copy wc_path and add restricts to the '**' wildcard. @@ -420,19 +417,19 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le break; } if (STRNCMP(wc_part, "**", 2) == 0) { - ff_expand_buffer[len++] = *wc_part++; - ff_expand_buffer[len++] = *wc_part++; + ff_expand_buffer[len++] = (char_u)(*wc_part++); + ff_expand_buffer[len++] = (char_u)(*wc_part++); - llevel = strtol((char *)wc_part, &errpt, 10); - if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255) { + llevel = strtol(wc_part, &errpt, 10); + if (errpt != wc_part && llevel > 0 && llevel < 255) { ff_expand_buffer[len++] = (char_u)llevel; - } else if ((char_u *)errpt != wc_part && llevel == 0) { + } else if (errpt != wc_part && llevel == 0) { // restrict is 0 -> remove already added '**' len -= 2; } else { ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND; } - wc_part = (char_u *)errpt; + wc_part = errpt; if (*wc_part != NUL && !vim_ispathsep(*wc_part)) { semsg(_( "E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), @@ -440,20 +437,20 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le goto error_return; } } else { - ff_expand_buffer[len++] = *wc_part++; + ff_expand_buffer[len++] = (char_u)(*wc_part++); } } ff_expand_buffer[len] = NUL; - search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer); + search_ctx->ffsc_wc_path = (char *)vim_strsave(ff_expand_buffer); } else { - search_ctx->ffsc_fix_path = vim_strsave(path); + search_ctx->ffsc_fix_path = xstrdup(path); } if (search_ctx->ffsc_start_dir == NULL) { /* store the fix part as startdir. * This is needed if the parameter path is fully qualified. */ - search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path); + search_ctx->ffsc_start_dir = xstrdup(search_ctx->ffsc_fix_path); search_ctx->ffsc_fix_path[0] = NUL; } @@ -475,9 +472,9 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path); add_pathsep((char *)ff_expand_buffer); } else { - char_u *p = (char_u *)path_tail((char *)search_ctx->ffsc_fix_path); - char_u *wc_path = NULL; - char_u *temp = NULL; + char *p = path_tail(search_ctx->ffsc_fix_path); + char *wc_path = NULL; + char *temp = NULL; int len = 0; if (p > search_ctx->ffsc_fix_path) { @@ -495,7 +492,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le } if (search_ctx->ffsc_wc_path != NULL) { - wc_path = vim_strsave(search_ctx->ffsc_wc_path); + wc_path = xstrdup(search_ctx->ffsc_wc_path); temp = xmalloc(STRLEN(search_ctx->ffsc_wc_path) + STRLEN(search_ctx->ffsc_fix_path + len) + 1); @@ -509,10 +506,10 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le xfree(buf); } - sptr = ff_create_stack_element(ff_expand_buffer, search_ctx->ffsc_wc_path, level, 0); + sptr = ff_create_stack_element(ff_expand_buffer, (char_u *)search_ctx->ffsc_wc_path, level, 0); ff_push(search_ctx, sptr); - search_ctx->ffsc_file_to_search = vim_strsave(filename); + search_ctx->ffsc_file_to_search = xstrdup(filename); return search_ctx; error_return: @@ -598,8 +595,7 @@ char_u *vim_findfile(void *search_ctx_arg) // store the end of the start dir -- needed for upward search if (search_ctx->ffsc_start_dir != NULL) { - path_end = &search_ctx->ffsc_start_dir[ - STRLEN(search_ctx->ffsc_start_dir)]; + path_end = (char_u *)&search_ctx->ffsc_start_dir[STRLEN(search_ctx->ffsc_start_dir)]; } // upward search loop @@ -930,19 +926,17 @@ char_u *vim_findfile(void *search_ctx_arg) ff_stack_T *sptr; // is the last starting directory in the stop list? - if (ff_path_in_stoplist(search_ctx->ffsc_start_dir, - (int)(path_end - search_ctx->ffsc_start_dir), - search_ctx->ffsc_stopdirs_v) == true) { + if (ff_path_in_stoplist((char_u *)search_ctx->ffsc_start_dir, + (int)(path_end - (char_u *)search_ctx->ffsc_start_dir), + (char_u **)search_ctx->ffsc_stopdirs_v) == true) { break; } // cut of last dir - while (path_end > search_ctx->ffsc_start_dir - && vim_ispathsep(*path_end)) { + while (path_end > (char_u *)search_ctx->ffsc_start_dir && vim_ispathsep(*path_end)) { path_end--; } - while (path_end > search_ctx->ffsc_start_dir - && !vim_ispathsep(path_end[-1])) { + while (path_end > (char_u *)search_ctx->ffsc_start_dir && !vim_ispathsep(path_end[-1])) { path_end--; } *path_end = 0; @@ -964,7 +958,7 @@ char_u *vim_findfile(void *search_ctx_arg) // create a new stack entry sptr = ff_create_stack_element(file_path, - search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0); + (char_u *)search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0); ff_push(search_ctx, sptr); } else { break; @@ -1528,9 +1522,9 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first // get the stopdir string r_ptr = vim_findfile_stopdir((char_u *)buf); - fdip_search_ctx = vim_findfile_init((char_u *)buf, ff_file_to_find, - r_ptr, 100, false, find_what, - fdip_search_ctx, false, rel_fname); + fdip_search_ctx = vim_findfile_init(buf, (char *)ff_file_to_find, + (char *)r_ptr, 100, false, find_what, + fdip_search_ctx, false, (char *)rel_fname); if (fdip_search_ctx != NULL) { did_findfile_init = true; } diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 517424f4c1..889e569672 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -719,7 +719,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, fenc_alloced = false; } else { fenc_next = p_fencs; // try items in 'fileencodings' - fenc = (char *)next_fenc(&fenc_next, &fenc_alloced); + fenc = next_fenc(&fenc_next, &fenc_alloced); } /* @@ -813,7 +813,7 @@ retry: xfree(fenc); } if (fenc_next != NULL) { - fenc = (char *)next_fenc(&fenc_next, &fenc_alloced); + fenc = next_fenc(&fenc_next, &fenc_alloced); } else { fenc = ""; fenc_alloced = false; @@ -2068,25 +2068,25 @@ void set_forced_fenc(exarg_T *eap) /// NULL. /// When *pp is not set to NULL, the result is in allocated memory and "alloced" /// is set to true. -static char_u *next_fenc(char **pp, bool *alloced) +static char *next_fenc(char **pp, bool *alloced) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { - char_u *p; - char_u *r; + char *p; + char *r; *alloced = false; if (**pp == NUL) { *pp = NULL; - return (char_u *)""; + return ""; } - p = (char_u *)vim_strchr((*pp), ','); + p = vim_strchr((*pp), ','); if (p == NULL) { - r = (char_u *)enc_canonize(*pp); + r = enc_canonize(*pp); *pp += STRLEN(*pp); } else { - r = vim_strnsave((char_u *)(*pp), (size_t)(p - (char_u *)(*pp))); - *pp = (char *)p + 1; - p = (char_u *)enc_canonize((char *)r); + r = xstrnsave(*pp, (size_t)(p - *pp)); + *pp = p + 1; + p = enc_canonize(r); xfree(r); r = p; } diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index 4d7339f3b5..97c3b1c61f 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -2566,7 +2566,7 @@ static int vgetorpeek(bool advance) // white-space, so find the last non-white // character -- webb curwin->w_wcol = 0; - ptr = get_cursor_line_ptr(); + ptr = (char_u *)get_cursor_line_ptr(); chartabsize_T cts; init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0, (char *)ptr, (char *)ptr); @@ -2596,7 +2596,7 @@ static int vgetorpeek(bool advance) if (col > 0 && curwin->w_wcol > 0) { // Correct when the cursor is on the right halve // of a double-wide character. - ptr = get_cursor_line_ptr(); + ptr = (char_u *)get_cursor_line_ptr(); col -= utf_head_off((char *)ptr, (char *)ptr + col); if (utf_ptr2cells((char *)ptr + col) > 1) { curwin->w_wcol--; diff --git a/src/nvim/grid.c b/src/nvim/grid.c index 329adfda12..22445b9ec7 100644 --- a/src/nvim/grid.c +++ b/src/nvim/grid.c @@ -240,7 +240,7 @@ void grid_puts_len(ScreenGrid *grid, char *text, int textlen, int row, int col, c = (unsigned char)(*ptr); // check if this is the first byte of a multibyte mbyte_blen = len > 0 - ? utfc_ptr2len_len((char_u *)ptr, (int)((text + len) - ptr)) + ? utfc_ptr2len_len(ptr, (int)((text + len) - ptr)) : utfc_ptr2len(ptr); u8c = len >= 0 ? utfc_ptr2char_len((char_u *)ptr, u8cc, (int)((text + len) - ptr)) diff --git a/src/nvim/indent.c b/src/nvim/indent.c index da4bcf6934..a41a396abc 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -343,7 +343,7 @@ int get_sts_value(void) // Count the size (in window cells) of the indent in the current line. int get_indent(void) { - return get_indent_str_vtab((char *)get_cursor_line_ptr(), + return get_indent_str_vtab(get_cursor_line_ptr(), curbuf->b_p_ts, curbuf->b_p_vts_array, false); @@ -454,7 +454,7 @@ int set_indent(int size, int flags) // characters needed for the indent. todo = size; ind_len = 0; - p = oldline = get_cursor_line_ptr(); + p = oldline = (char_u *)get_cursor_line_ptr(); // Calculate the buffer size for the new indent, and check to see if it // isn't already set. @@ -857,7 +857,7 @@ int inindent(int extra) char_u *ptr; colnr_T col; - for (col = 0, ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr); col++) { + for (col = 0, ptr = (char_u *)get_cursor_line_ptr(); ascii_iswhite(*ptr); col++) { ptr++; } @@ -979,7 +979,7 @@ int get_lisp_indent(void) continue; } - for (that = get_cursor_line_ptr(); *that != NUL; that++) { + for (that = (char_u *)get_cursor_line_ptr(); *that != NUL; that++) { if (*that == ';') { while (*(that + 1) != NUL) { that++; @@ -1029,7 +1029,7 @@ int get_lisp_indent(void) curwin->w_cursor.col = pos->col; col = pos->col; - that = get_cursor_line_ptr(); + that = (char_u *)get_cursor_line_ptr(); if (vi_lisp && (get_indent() == 0)) { amount = 2; diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c index ccee4dd48a..7dcc9e3c27 100644 --- a/src/nvim/indent_c.c +++ b/src/nvim/indent_c.c @@ -355,7 +355,7 @@ static bool cin_islabel_skip(const char_u **s) // Note: curwin->w_cursor must be where we are looking for the label. bool cin_islabel(void) // XXX { - const char_u *s = cin_skipcomment(get_cursor_line_ptr()); + const char_u *s = cin_skipcomment((char_u *)get_cursor_line_ptr()); // Exclude "default" from labels, since it should be indented // like a switch label. Same for C++ scope declarations. @@ -390,7 +390,7 @@ bool cin_islabel(void) // XXX curwin->w_cursor = *trypos; } - line = get_cursor_line_ptr(); + line = (char_u *)get_cursor_line_ptr(); if (cin_ispreproc(line)) { // ignore #defines, #if, etc. continue; } @@ -421,7 +421,7 @@ static int cin_isinit(void) const char_u *s; static char *skip[] = { "static", "public", "protected", "private" }; - s = cin_skipcomment(get_cursor_line_ptr()); + s = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_starts_with(s, "typedef")) { s = cin_skipcomment(s + 7); @@ -642,17 +642,17 @@ static int skip_label(linenr_T lnum, const char_u **pp) cursor_save = curwin->w_cursor; curwin->w_cursor.lnum = lnum; - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); // XXX if (cin_iscase(l, false) || cin_isscopedecl(l) || cin_islabel()) { amount = get_indent_nolabel(lnum); - l = after_label(get_cursor_line_ptr()); + l = after_label((char_u *)get_cursor_line_ptr()); if (l == NULL) { // just in case - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); } } else { amount = get_indent(); - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); } *pp = l; @@ -674,7 +674,7 @@ static int cin_first_id_amount(void) pos_T fp; colnr_T col; - line = get_cursor_line_ptr(); + line = (char_u *)get_cursor_line_ptr(); p = (char_u *)skipwhite((char *)line); len = (int)((char_u *)skiptowhite((char *)p) - p); if (len == 6 && STRNCMP(p, "static", 6) == 0) { @@ -1033,7 +1033,7 @@ static int cin_iswhileofdo(const char_u *p, linenr_T lnum) // XXX cursor_save = curwin->w_cursor; curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); while (*p && *p != 'w') { // skip any '}', until the 'w' of the "while" p++; curwin->w_cursor.col++; @@ -1110,7 +1110,7 @@ static int cin_iswhileofdo_end(int terminated) return false; } - p = line = get_cursor_line_ptr(); + p = line = (char_u *)get_cursor_line_ptr(); while (*p != NUL) { p = cin_skipcomment(p); if (*p == ')') { @@ -1133,7 +1133,7 @@ static int cin_iswhileofdo_end(int terminated) } // Searching may have made "line" invalid, get it again. - line = get_cursor_line_ptr(); + line = (char_u *)get_cursor_line_ptr(); p = line + i; } } @@ -1168,7 +1168,7 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) const char_u *s; int class_or_struct, lookfor_ctor_init, cpp_base_class; linenr_T lnum = curwin->w_cursor.lnum; - const char_u *line = get_cursor_line_ptr(); + const char_u *line = (char_u *)get_cursor_line_ptr(); if (pos->lnum <= lnum) { return cached->found; // Use the cached result @@ -1322,11 +1322,11 @@ static int get_baseclass_amount(int col) if (col == 0) { amount = get_indent(); - if (find_last_paren(get_cursor_line_ptr(), '(', ')') + if (find_last_paren((char_u *)get_cursor_line_ptr(), '(', ')') && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) { amount = get_indent_lnum(trypos->lnum); // XXX } - if (!cin_ends_in(get_cursor_line_ptr(), (char_u *)",", NULL)) { + if (!cin_ends_in((char_u *)get_cursor_line_ptr(), (char_u *)",", NULL)) { amount += curbuf->b_ind_cpp_baseclass; } } else { @@ -2287,7 +2287,7 @@ int get_c_indent(void) /* Ignore a '(' in front of the line that has a match before * our matching '('. */ curwin->w_cursor.lnum = our_paren_pos.lnum; - line = get_cursor_line_ptr(); + line = (char_u *)get_cursor_line_ptr(); look_col = (int)(look - line); curwin->w_cursor.col = look_col + 1; if ((trypos = findmatchlimit(NULL, ')', 0, @@ -2472,7 +2472,7 @@ int get_c_indent(void) // ldfd) { // } if ((curbuf->b_ind_js || curbuf->b_ind_keep_case_label) - && cin_iscase((char_u *)skipwhite((char *)get_cursor_line_ptr()), false)) { + && cin_iscase((char_u *)skipwhite(get_cursor_line_ptr()), false)) { amount = get_indent(); } else if (curbuf->b_ind_js) { amount = get_indent_lnum(lnum); @@ -2539,7 +2539,7 @@ int get_c_indent(void) if (start_brace == BRACE_AT_END) { // '{' is at end of line amount += curbuf->b_ind_open_imag; - l = (char_u *)skipwhite((char *)get_cursor_line_ptr()); + l = (char_u *)skipwhite(get_cursor_line_ptr()); if (cin_is_cpp_namespace(l)) { amount += curbuf->b_ind_cpp_namespace; } else if (cin_is_cpp_extern_c(l)) { @@ -2614,7 +2614,7 @@ int get_c_indent(void) break; } - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); /* * If we're in a comment or raw string now, skip to @@ -2734,7 +2734,7 @@ int get_c_indent(void) break; } - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); /* If we're in a comment or raw string now, skip * to the start of it. */ @@ -2777,7 +2777,7 @@ int get_c_indent(void) continue; } - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); /* * If this is a switch() label, may line up relative to that. @@ -2853,7 +2853,7 @@ int get_c_indent(void) // -> y = y + 1; if (n) { amount = n; - l = after_label(get_cursor_line_ptr()); + l = after_label((char_u *)get_cursor_line_ptr()); if (l != NULL && cin_is_cinword((char *)l)) { if (theline[0] == '{') { amount += curbuf->b_ind_open_extra; @@ -2898,7 +2898,7 @@ int get_c_indent(void) * Ignore jump labels with nothing after them. */ if (!curbuf->b_ind_js && cin_islabel()) { - l = after_label(get_cursor_line_ptr()); + l = after_label((char_u *)get_cursor_line_ptr()); if (l == NULL || cin_nocode(l)) { continue; } @@ -2910,7 +2910,7 @@ int get_c_indent(void) * (need to get the line again, cin_islabel() may have * unlocked it) */ - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount) || cin_nocode(l)) { continue; @@ -2922,7 +2922,7 @@ int get_c_indent(void) n = 0; if (lookfor != LOOKFOR_TERM && curbuf->b_ind_cpp_baseclass > 0) { n = cin_is_cpp_baseclass(&cache_cpp_baseclass); - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); } if (n) { if (lookfor == LOOKFOR_UNTERM) { @@ -3039,7 +3039,7 @@ int get_c_indent(void) * asdf) */ curwin->w_cursor = *trypos; - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); if (cin_iscase(l, false) || cin_isscopedecl(l)) { curwin->w_cursor.lnum++; curwin->w_cursor.col = 0; @@ -3154,7 +3154,7 @@ int get_c_indent(void) * x = 1; * -> here */ - l = (char_u *)skipwhite((char *)get_cursor_line_ptr()); + l = (char_u *)skipwhite(get_cursor_line_ptr()); if (cin_isdo(l)) { if (whilelevel == 0) { break; @@ -3174,7 +3174,7 @@ int get_c_indent(void) * not the one from "if () {". */ if (*l == '}') { curwin->w_cursor.col = - (colnr_T)(l - get_cursor_line_ptr()) + 1; + (colnr_T)(l - (char_u *)get_cursor_line_ptr()) + 1; } if ((trypos = find_start_brace()) == NULL @@ -3231,7 +3231,7 @@ int get_c_indent(void) // line up with this line, remember its indent // 100 + // NOLINT(whitespace/tab) // -> here; // NOLINT(whitespace/tab) - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); amount = cur_amount; n = (int)STRLEN(l); @@ -3341,7 +3341,7 @@ int get_c_indent(void) * may be lined up with the case label. */ if (lookfor == LOOKFOR_NOBREAK - && cin_isbreak((char_u *)skipwhite((char *)get_cursor_line_ptr()))) { + && cin_isbreak((char_u *)skipwhite(get_cursor_line_ptr()))) { lookfor = LOOKFOR_ANY; continue; } @@ -3350,7 +3350,7 @@ int get_c_indent(void) * Handle "do {" line. */ if (whilelevel > 0) { - l = cin_skipcomment(get_cursor_line_ptr()); + l = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_isdo(l)) { amount = get_indent(); // XXX whilelevel--; @@ -3408,7 +3408,7 @@ int get_c_indent(void) * here; */ term_again: - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); if (find_last_paren(l, '(', ')') && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) { // Check if we are on a case label now. This is @@ -3416,7 +3416,7 @@ term_again: // case xx: if ( asdf && // asdf) curwin->w_cursor = *trypos; - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); if (cin_iscase(l, false) || cin_isscopedecl(l)) { curwin->w_cursor.lnum++; curwin->w_cursor.col = 0; @@ -3475,13 +3475,13 @@ term_again: * If we're at the end of a block, skip to the start of * that block. */ - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); if (find_last_paren(l, '{', '}') // XXX && (trypos = find_start_brace()) != NULL) { curwin->w_cursor = *trypos; // if not "else {" check for terminated again // but skip block for "} else {" - l = cin_skipcomment(get_cursor_line_ptr()); + l = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (*l == '}' || !cin_iselse(l)) { goto term_again; } @@ -3547,7 +3547,7 @@ term_again: curwin->w_cursor.lnum--; curwin->w_cursor.col = 0; - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); // If we're in a comment or raw string now, skip to the start // of it. @@ -3563,7 +3563,7 @@ term_again: n = 0; if (curbuf->b_ind_cpp_baseclass != 0) { n = cin_is_cpp_baseclass(&cache_cpp_baseclass); - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); } if (n) { // XXX @@ -3635,7 +3635,7 @@ term_again: if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0)) { // XXX break; } - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); /* * Finding the closing '}' of a previous function. Put @@ -3709,7 +3709,7 @@ term_again: || (*l != NUL && l[STRLEN(l) - 1] == '\\')) { break; } - l = get_cursor_line_ptr(); + l = (char_u *)get_cursor_line_ptr(); } /* @@ -3786,7 +3786,7 @@ static int find_match(int lookfor, linenr_T ourscope) curwin->w_cursor.lnum--; curwin->w_cursor.col = 0; - look = cin_skipcomment(get_cursor_line_ptr()); + look = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (!cin_iselse(look) && !cin_isif(look) && !cin_isdo(look) // XXX @@ -3826,7 +3826,7 @@ static int find_match(int lookfor, linenr_T ourscope) * then we need to go back to another if, so * increment elselevel */ - look = cin_skipcomment(get_cursor_line_ptr()); + look = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_iselse(look)) { mightbeif = cin_skipcomment(look + 4); if (!cin_isif(mightbeif)) { @@ -3845,7 +3845,7 @@ static int find_match(int lookfor, linenr_T ourscope) } // If it's an "if" decrement elselevel - look = cin_skipcomment(get_cursor_line_ptr()); + look = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_isif(look)) { elselevel--; /* diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index a530061280..dce72a2611 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -231,7 +231,7 @@ static pos_T compl_startpos; static int compl_length = 0; static colnr_T compl_col = 0; ///< column where the text starts ///< that is being completed -static char_u *compl_orig_text = NULL; ///< text as it was before +static char *compl_orig_text = NULL; ///< text as it was before ///< completion started static int compl_cont_mode = 0; static expand_T compl_xp; @@ -587,7 +587,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_ // Rule 1: Were any chars converted to lower? { - const char_u *p = compl_orig_text; + const char_u *p = (char_u *)compl_orig_text; for (int i = 0; i < min_len; i++) { const int c = mb_ptr2char_adv(&p); if (mb_islower(c)) { @@ -606,7 +606,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_ // Rule 2: No lower case, 2nd consecutive letter converted to // upper case. if (!has_lower) { - const char_u *p = compl_orig_text; + const char_u *p = (char_u *)compl_orig_text; for (int i = 0; i < min_len; i++) { const int c = mb_ptr2char_adv(&p); if (was_letter && mb_isupper(c) && mb_islower(wca[i])) { @@ -622,7 +622,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_ // Copy the original case of the part we typed. { - const char_u *p = compl_orig_text; + const char_u *p = (char_u *)compl_orig_text; for (int i = 0; i < min_len; i++) { const int c = mb_ptr2char_adv(&p); if (mb_islower(c)) { @@ -699,7 +699,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, // Find actual length of original text. { - const char_u *p = compl_orig_text; + const char_u *p = (char_u *)compl_orig_text; compl_char_len = 0; while (*p != NUL) { MB_PTR_ADV(p); @@ -720,7 +720,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, flags |= CP_ICASE; } - int res = ins_compl_add(str, len, fname, NULL, false, NULL, dir, flags, false); + int res = ins_compl_add((char *)str, len, (char *)fname, NULL, false, NULL, dir, flags, false); xfree(tofree); return res; } @@ -748,9 +748,9 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, /// @return NOTDONE if the given string is already in the list of completions, /// otherwise it is added to the list and OK is returned. FAIL will be /// returned in case of error. -static int ins_compl_add(char_u *const str, int len, char_u *const fname, - char_u *const *const cptext, const bool cptext_allocated, - typval_T *user_data, const Direction cdir, int flags_arg, const bool adup) +static int ins_compl_add(char *const str, int len, char *const fname, char *const *const cptext, + const bool cptext_allocated, typval_T *user_data, const Direction cdir, + int flags_arg, const bool adup) FUNC_ATTR_NONNULL_ARG(1) { compl_T *match; @@ -802,7 +802,7 @@ static int ins_compl_add(char_u *const str, int len, char_u *const fname, if (flags & CP_ORIGINAL_TEXT) { match->cp_number = 0; } - match->cp_str = vim_strnsave(str, (size_t)len); + match->cp_str = (char_u *)xstrnsave(str, (size_t)len); // match-fname is: // - compl_curr_match->cp_fname if it is a string equal to fname. @@ -814,7 +814,7 @@ static int ins_compl_add(char_u *const str, int len, char_u *const fname, && STRCMP(fname, compl_curr_match->cp_fname) == 0) { match->cp_fname = compl_curr_match->cp_fname; } else if (fname != NULL) { - match->cp_fname = vim_strsave(fname); + match->cp_fname = vim_strsave((char_u *)fname); flags |= CP_FREE_FNAME; } else { match->cp_fname = NULL; @@ -830,8 +830,8 @@ static int ins_compl_add(char_u *const str, int len, char_u *const fname, } if (*cptext[i] != NUL) { match->cp_text[i] = (cptext_allocated - ? cptext[i] - : (char_u *)xstrdup((char *)cptext[i])); + ? (char_u *)cptext[i] + : (char_u *)xstrdup(cptext[i])); } else if (cptext_allocated) { xfree(cptext[i]); } @@ -957,7 +957,7 @@ static void ins_compl_add_matches(int num_matches, char **matches, int icase) Direction dir = compl_direction; for (int i = 0; i < num_matches && add_r != FAIL; i++) { - if ((add_r = ins_compl_add((char_u *)matches[i], -1, NULL, NULL, false, NULL, dir, + if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, false, NULL, dir, CP_FAST | (icase ? CP_ICASE : 0), false)) == OK) { // If dir was BACKWARD then honor it just once. @@ -1621,8 +1621,8 @@ int ins_compl_len(void) /// to be got from the user. int ins_compl_bs(void) { - char_u *line = get_cursor_line_ptr(); - char_u *p = line + curwin->w_cursor.col; + char *line = get_cursor_line_ptr(); + char *p = line + curwin->w_cursor.col; MB_PTR_BACK(line, p); ptrdiff_t p_off = p - line; @@ -1649,7 +1649,7 @@ int ins_compl_bs(void) line = get_cursor_line_ptr(); xfree(compl_leader); - compl_leader = vim_strnsave(line + compl_col, (size_t)(p_off - (ptrdiff_t)compl_col)); + compl_leader = (char_u *)xstrnsave(line + compl_col, (size_t)(p_off - (ptrdiff_t)compl_col)); ins_compl_new_leader(); if (compl_shown_match != NULL) { @@ -1743,8 +1743,8 @@ void ins_compl_addleader(int c) } xfree(compl_leader); - compl_leader = vim_strnsave(get_cursor_line_ptr() + compl_col, - (size_t)(curwin->w_cursor.col - compl_col)); + compl_leader = (char_u *)xstrnsave(get_cursor_line_ptr() + compl_col, + (size_t)(curwin->w_cursor.col - compl_col)); ins_compl_new_leader(); } @@ -2008,7 +2008,7 @@ static bool ins_compl_stop(const int c, const int prev_mode, bool retval) if (compl_leader != NULL) { p = compl_leader; } else if (compl_first_match != NULL) { - p = compl_orig_text; + p = (char_u *)compl_orig_text; } if (p != NULL) { const int compl_len = get_compl_len(); @@ -2174,7 +2174,7 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) } } if (compl_orig_text != NULL) { - p = compl_orig_text; + p = (char_u *)compl_orig_text; for (len = 0; p[len] != NUL && p[len] == ptr[len]; len++) {} if (len > 0) { len -= utf_head_off((char *)p, (char *)p + len); @@ -2360,7 +2360,7 @@ static int ins_compl_add_tv(typval_T *const tv, const Direction dir, bool fast) tv_clear(&user_data); return FAIL; } - int status = ins_compl_add((char_u *)word, -1, NULL, (char_u **)cptext, true, + int status = ins_compl_add((char *)word, -1, NULL, cptext, true, &user_data, dir, flags, dup); if (status != OK) { tv_clear(&user_data); @@ -2430,8 +2430,8 @@ static void set_completion(colnr_T startcol, list_T *list) compl_col = startcol; compl_length = (int)curwin->w_cursor.col - (int)startcol; // compl_pattern doesn't need to be set - compl_orig_text = vim_strnsave(get_cursor_line_ptr() + compl_col, - (size_t)compl_length); + compl_orig_text = xstrnsave(get_cursor_line_ptr() + compl_col, + (size_t)compl_length); if (p_ic) { flags |= CP_ICASE; } @@ -3513,7 +3513,7 @@ static int ins_compl_next(bool allow_get_expansion, int count, bool insert_match // Insert the text of the new completion, or the compl_leader. if (compl_no_insert && !started) { - ins_bytes((char *)compl_orig_text + get_compl_len()); + ins_bytes(compl_orig_text + get_compl_len()); compl_used_match = false; } else if (insert_match) { if (!compl_get_longest || compl_used_match) { @@ -3697,7 +3697,7 @@ static bool ins_compl_use_match(int c) /// completion) /// Sets the global variables: compl_col, compl_length and compl_pattern. /// Uses the global variables: compl_cont_status and ctrl_x_mode -static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) +static int get_normal_compl_info(char *line, int startcol, colnr_T curs_col) { if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines()) { if (!compl_status_adding()) { @@ -3706,25 +3706,25 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) compl_length = curs_col - startcol; } if (p_ic) { - compl_pattern = (char *)str_foldcase(line + compl_col, compl_length, NULL, 0); + compl_pattern = (char *)str_foldcase((char_u *)line + compl_col, compl_length, NULL, 0); } else { - compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length); + compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length); } } else if (compl_status_adding()) { char_u *prefix = (char_u *)"\\<"; // we need up to 2 extra chars for the prefix - compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, - compl_length) + 2); - if (!vim_iswordp(line + compl_col) - || (compl_col > 0 && (vim_iswordp(mb_prevptr(line, line + compl_col))))) { + compl_pattern = xmalloc(quote_meta(NULL, (char_u *)line + compl_col, compl_length) + 2); + if (!vim_iswordp((char_u *)line + compl_col) + || (compl_col > 0 + && (vim_iswordp(mb_prevptr((char_u *)line, (char_u *)line + compl_col))))) { prefix = (char_u *)""; } STRCPY(compl_pattern, prefix); (void)quote_meta((char_u *)compl_pattern + STRLEN(prefix), - line + compl_col, compl_length); + (char_u *)line + compl_col, compl_length); } else if (--startcol < 0 - || !vim_iswordp(mb_prevptr(line, line + startcol + 1))) { + || !vim_iswordp(mb_prevptr((char_u *)line, (char_u *)line + startcol + 1))) { // Match any word of at least two chars compl_pattern = xstrdup("\\<\\k\\k"); compl_col += curs_col; @@ -3732,11 +3732,11 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) } else { // Search the point of change class of multibyte character // or not a word single byte character backward. - startcol -= utf_head_off((char *)line, (char *)line + startcol); - int base_class = mb_get_class(line + startcol); + startcol -= utf_head_off(line, line + startcol); + int base_class = mb_get_class((char_u *)line + startcol); while (--startcol >= 0) { - int head_off = utf_head_off((char *)line, (char *)line + startcol); - if (base_class != mb_get_class(line + startcol - head_off)) { + int head_off = utf_head_off(line, line + startcol); + if (base_class != mb_get_class((char_u *)line + startcol - head_off)) { break; } startcol -= head_off; @@ -3749,13 +3749,13 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) // xmalloc(7) is enough -- Acevedo compl_pattern = xmalloc(7); STRCPY(compl_pattern, "\\<"); - (void)quote_meta((char_u *)compl_pattern + 2, line + compl_col, 1); + (void)quote_meta((char_u *)compl_pattern + 2, (char_u *)line + compl_col, 1); STRCAT(compl_pattern, "\\k"); } else { - compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, + compl_pattern = xmalloc(quote_meta(NULL, (char_u *)line + compl_col, compl_length) + 2); STRCPY(compl_pattern, "\\<"); - (void)quote_meta((char_u *)compl_pattern + 2, line + compl_col, compl_length); + (void)quote_meta((char_u *)compl_pattern + 2, (char_u *)line + compl_col, compl_length); } } @@ -3765,17 +3765,17 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col) /// Get the pattern, column and length for whole line completion or for the /// complete() function. /// Sets the global variables: compl_col, compl_length and compl_pattern. -static int get_wholeline_compl_info(char_u *line, colnr_T curs_col) +static int get_wholeline_compl_info(char *line, colnr_T curs_col) { - compl_col = (colnr_T)getwhitecols((char *)line); + compl_col = (colnr_T)getwhitecols(line); compl_length = (int)curs_col - (int)compl_col; if (compl_length < 0) { // cursor in indent: empty pattern compl_length = 0; } if (p_ic) { - compl_pattern = (char *)str_foldcase(line + compl_col, compl_length, NULL, 0); + compl_pattern = (char *)str_foldcase((char_u *)line + compl_col, compl_length, NULL, 0); } else { - compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length); + compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length); } return OK; @@ -3802,16 +3802,16 @@ static int get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col) compl_col += startcol; compl_length = (int)curs_col - startcol; - compl_pattern = (char *)addstar(line + compl_col, (size_t)compl_length, EXPAND_FILES); + compl_pattern = addstar((char *)line + compl_col, (size_t)compl_length, EXPAND_FILES); return OK; } /// Get the pattern, column and length for command-line completion. /// Sets the global variables: compl_col, compl_length and compl_pattern. -static int get_cmdline_compl_info(char_u *line, colnr_T curs_col) +static int get_cmdline_compl_info(char *line, colnr_T curs_col) { - compl_pattern = (char *)vim_strnsave(line, (size_t)curs_col); + compl_pattern = xstrnsave(line, (size_t)curs_col); set_cmd_context(&compl_xp, (char_u *)compl_pattern, (int)STRLEN(compl_pattern), curs_col, false); if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL || compl_xp.xp_context == EXPAND_NOTHING) { @@ -3893,9 +3893,9 @@ static int get_userdefined_compl_info(colnr_T curs_col) // Setup variables for completion. Need to obtain "line" again, // it may have become invalid. - char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum); + char *line = ml_get(curwin->w_cursor.lnum); compl_length = curs_col - compl_col; - compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length); + compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length); return OK; } @@ -3919,8 +3919,8 @@ static int get_spell_compl_info(int startcol, colnr_T curs_col) compl_length = (int)curs_col - compl_col; } // Need to obtain "line" again, it may have become invalid. - char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum); - compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length); + char *line = ml_get(curwin->w_cursor.lnum); + compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length); return OK; } @@ -3939,13 +3939,13 @@ static int compl_get_info(char_u *line, int startcol, colnr_T curs_col, bool *li if (ctrl_x_mode_normal() || ((ctrl_x_mode & CTRL_X_WANT_IDENT) && !thesaurus_func_complete(ctrl_x_mode))) { - return get_normal_compl_info(line, startcol, curs_col); + return get_normal_compl_info((char *)line, startcol, curs_col); } else if (ctrl_x_mode_line_or_eval()) { - return get_wholeline_compl_info(line, curs_col); + return get_wholeline_compl_info((char *)line, curs_col); } else if (ctrl_x_mode_files()) { return get_filename_compl_info(line, startcol, curs_col); } else if (ctrl_x_mode == CTRL_X_CMDLINE) { - return get_cmdline_compl_info(line, curs_col); + return get_cmdline_compl_info((char *)line, curs_col); } else if (ctrl_x_mode_function() || ctrl_x_mode_omni() || thesaurus_func_complete(ctrl_x_mode)) { if (get_userdefined_compl_info(curs_col) == FAIL) { @@ -4036,7 +4036,7 @@ static int ins_compl_start(void) return FAIL; } - char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum); + char *line = ml_get(curwin->w_cursor.lnum); colnr_T curs_col = curwin->w_cursor.col; compl_pending = 0; @@ -4044,7 +4044,7 @@ static int ins_compl_start(void) && compl_cont_mode == ctrl_x_mode) { // this same ctrl-x_mode was interrupted previously. Continue the // completion. - ins_compl_continue_search(line); + ins_compl_continue_search((char_u *)line); } else { compl_cont_status &= CONT_LOCAL; } @@ -4064,7 +4064,7 @@ static int ins_compl_start(void) // Work out completion pattern and original text -- webb bool line_invalid = false; - if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL) { + if (compl_get_info((char_u *)line, startcol, curs_col, &line_invalid) == FAIL) { if (ctrl_x_mode_function() || ctrl_x_mode_omni() || thesaurus_func_complete(ctrl_x_mode)) { // restore did_ai, so that adding comment leader works @@ -4074,7 +4074,7 @@ static int ins_compl_start(void) } // If "line" was changed while getting completion info get it again. if (line_invalid) { - line = (char_u *)ml_get(curwin->w_cursor.lnum); + line = ml_get(curwin->w_cursor.lnum); } if (compl_status_adding()) { @@ -4108,7 +4108,7 @@ static int ins_compl_start(void) // Always add completion for the original text. xfree(compl_orig_text); - compl_orig_text = vim_strnsave(line + compl_col, (size_t)compl_length); + compl_orig_text = xstrnsave(line + compl_col, (size_t)compl_length); int flags = CP_ORIGINAL_TEXT; if (p_ic) { flags |= CP_ICASE; diff --git a/src/nvim/keycodes.c b/src/nvim/keycodes.c index 2b00d371f0..a3763ea9bb 100644 --- a/src/nvim/keycodes.c +++ b/src/nvim/keycodes.c @@ -650,7 +650,7 @@ int find_special_key(const char_u **const srcp, const size_t src_len, int *const if (*bp == '-') { last_dash = bp; if (bp + 1 <= end) { - l = utfc_ptr2len_len(bp + 1, (int)(end - bp) + 1); + l = utfc_ptr2len_len((char *)bp + 1, (int)(end - bp) + 1); // Anything accepted, like . // or are not special in strings as " is // the string delimiter. With a backslash it works: @@ -665,7 +665,7 @@ int find_special_key(const char_u **const srcp, const size_t src_len, int *const if (end - bp > 3 && bp[0] == 't' && bp[1] == '_') { bp += 3; // skip t_xx, xx may be '-' or '>' } else if (end - bp > 4 && STRNICMP(bp, "char-", 5) == 0) { - vim_str2nr(bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true); + vim_str2nr((char *)bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true); if (l == 0) { emsg(_(e_invarg)); return 0; @@ -695,7 +695,7 @@ int find_special_key(const char_u **const srcp, const size_t src_len, int *const if (STRNICMP(last_dash + 1, "char-", 5) == 0 && ascii_isdigit(last_dash[6])) { // or or - vim_str2nr(last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true); + vim_str2nr((char *)last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true); if (l == 0) { emsg(_(e_invarg)); return 0; @@ -993,7 +993,7 @@ char *replace_termcodes(const char *const from, const size_t from_len, char **co } // skip multibyte char correctly - for (i = utfc_ptr2len_len(src, (int)(end - src) + 1); i > 0; i--) { + for (i = utfc_ptr2len_len((char *)src, (int)(end - src) + 1); i > 0; i--) { // If the character is K_SPECIAL, replace it with K_SPECIAL // KS_SPECIAL KE_FILLER. if (*src == K_SPECIAL) { diff --git a/src/nvim/mark.c b/src/nvim/mark.c index 7eab37e797..c6d08eb689 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -800,31 +800,29 @@ void clrallmarks(buf_T *const buf) char_u *fm_getname(fmark_T *fmark, int lead_len) { if (fmark->fnum == curbuf->b_fnum) { // current buffer - return mark_line(&(fmark->mark), lead_len); + return (char_u *)mark_line(&(fmark->mark), lead_len); } return (char_u *)buflist_nr2name(fmark->fnum, false, true); } -/* - * Return the line at mark "mp". Truncate to fit in window. - * The returned string has been allocated. - */ -static char_u *mark_line(pos_T *mp, int lead_len) +/// Return the line at mark "mp". Truncate to fit in window. +/// The returned string has been allocated. +static char *mark_line(pos_T *mp, int lead_len) { - char_u *s, *p; + char *s, *p; int len; if (mp->lnum == 0 || mp->lnum > curbuf->b_ml.ml_line_count) { - return vim_strsave((char_u *)"-invalid-"); + return xstrdup("-invalid-"); } assert(Columns >= 0); // Allow for up to 5 bytes per character. - s = vim_strnsave((char_u *)skipwhite(ml_get(mp->lnum)), (size_t)Columns * 5); + s = xstrnsave(skipwhite(ml_get(mp->lnum)), (size_t)Columns * 5); // Truncate the line to fit it in the window len = 0; for (p = s; *p != NUL; MB_PTR_ADV(p)) { - len += ptr2cells((char *)p); + len += ptr2cells(p); if (len >= Columns - lead_len) { break; } @@ -908,7 +906,7 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu && p->lnum != 0) { // don't output anything if 'q' typed at --more-- prompt if (name == NULL && current) { - name = mark_line(p, 15); + name = (char_u *)mark_line(p, 15); mustfree = true; } if (!message_filtered((char *)name)) { @@ -1094,7 +1092,7 @@ void ex_changes(exarg_T *eap) (long)curbuf->b_changelist[i].mark.lnum, curbuf->b_changelist[i].mark.col); msg_outtrans((char *)IObuff); - name = mark_line(&curbuf->b_changelist[i].mark, 17); + name = (char_u *)mark_line(&curbuf->b_changelist[i].mark, 17); msg_outtrans_attr((char *)name, HL_ATTR(HLF_D)); xfree(name); os_breakcheck(); diff --git a/src/nvim/match.c b/src/nvim/match.c index 48f0d0fc05..b6d700b148 100644 --- a/src/nvim/match.c +++ b/src/nvim/match.c @@ -1159,9 +1159,9 @@ void f_matchdelete(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) /// skipping commands to find the next command. void ex_match(exarg_T *eap) { - char_u *p; - char_u *g = NULL; - char_u *end; + char *p; + char *g = NULL; + char *end; int c; int id; @@ -1178,25 +1178,25 @@ void ex_match(exarg_T *eap) } if (ends_excmd(*eap->arg)) { - end = (char_u *)eap->arg; + end = eap->arg; } else if ((STRNICMP(eap->arg, "none", 4) == 0 && (ascii_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4])))) { - end = (char_u *)eap->arg + 4; + end = eap->arg + 4; } else { - p = (char_u *)skiptowhite(eap->arg); + p = skiptowhite(eap->arg); if (!eap->skip) { - g = vim_strnsave((char_u *)eap->arg, (size_t)(p - (char_u *)eap->arg)); + g = xstrnsave(eap->arg, (size_t)(p - eap->arg)); } - p = (char_u *)skipwhite((char *)p); + p = skipwhite(p); if (*p == NUL) { // There must be two arguments. xfree(g); semsg(_(e_invarg2), eap->arg); return; } - end = (char_u *)skip_regexp((char *)p + 1, *p, true, NULL); + end = skip_regexp(p + 1, *p, true, NULL); if (!eap->skip) { - if (*end != NUL && !ends_excmd(*skipwhite((char *)end + 1))) { + if (*end != NUL && !ends_excmd(*skipwhite(end + 1))) { xfree(g); eap->errmsg = ex_errmsg(e_trailing_arg, (const char *)end); return; @@ -1207,13 +1207,13 @@ void ex_match(exarg_T *eap) return; } - c = *end; + c = (uint8_t)(*end); *end = NUL; match_add(curwin, (const char *)g, (const char *)p + 1, 10, id, NULL, NULL); xfree(g); - *end = (char_u)c; + *end = (char)c; } } - eap->nextcmd = find_nextcmd((char *)end); + eap->nextcmd = find_nextcmd(end); } diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index 947594be4f..0a4182a892 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -587,7 +587,7 @@ size_t mb_string2cells_len(const char *str, size_t size) size_t clen = 0; for (const char_u *p = (char_u *)str; *p != NUL && p < (char_u *)str + size; - p += utfc_ptr2len_len(p, (int)size + (int)(p - (char_u *)str))) { + p += utfc_ptr2len_len((char *)p, (int)size + (int)(p - (char_u *)str))) { clen += (size_t)utf_ptr2cells((char *)p); } @@ -727,12 +727,10 @@ int mb_cptr2char_adv(const char_u **pp) return c; } -/* - * Check if the character pointed to by "p2" is a composing character when it - * comes after "p1". For Arabic sometimes "ab" is replaced with "c", which - * behaves like a composing character. - */ -bool utf_composinglike(const char_u *p1, const char_u *p2) +/// Check if the character pointed to by "p2" is a composing character when it +/// comes after "p1". For Arabic sometimes "ab" is replaced with "c", which +/// behaves like a composing character. +bool utf_composinglike(const char *p1, const char *p2) { int c2; @@ -765,7 +763,7 @@ int utfc_ptr2char(const char *p_in, int *pcc) // Only accept a composing char when the first char isn't illegal. if ((len > 1 || *p < 0x80) && p[len] >= 0x80 - && utf_composinglike(p, p + len)) { + && utf_composinglike((char *)p, (char *)p + len)) { int cc = utf_ptr2char((char *)p + len); for (;;) { pcc[i++] = cc; @@ -809,7 +807,7 @@ int utfc_ptr2char_len(const char_u *p, int *pcc, int maxlen) int len_cc = utf_ptr2len_len(p + len, maxlen - len); safe = len_cc > 1 && len_cc <= maxlen - len; if (!safe || (pcc[i] = utf_ptr2char((char *)p + len)) < 0x80 - || !(i == 0 ? utf_composinglike(p, p + len) : utf_iscomposing(pcc[i]))) { + || !(i == 0 ? utf_composinglike((char *)p, (char *)p + len) : utf_iscomposing(pcc[i]))) { break; } len += len_cc; @@ -916,7 +914,7 @@ int utfc_ptr2len(const char *const p_in) // skip all of them (otherwise the cursor would get stuck). int prevlen = 0; for (;;) { - if (p[len] < 0x80 || !utf_composinglike(p + prevlen, p + len)) { + if (p[len] < 0x80 || !utf_composinglike((char *)p + prevlen, (char *)p + len)) { return len; } @@ -926,13 +924,11 @@ int utfc_ptr2len(const char *const p_in) } } -/* - * Return the number of bytes the UTF-8 encoding of the character at "p[size]" - * takes. This includes following composing characters. - * Returns 0 for an empty string. - * Returns 1 for an illegal char or an incomplete byte sequence. - */ -int utfc_ptr2len_len(const char_u *p, int size) +/// Return the number of bytes the UTF-8 encoding of the character at "p[size]" +/// takes. This includes following composing characters. +/// Returns 0 for an empty string. +/// Returns 1 for an illegal char or an incomplete byte sequence. +int utfc_ptr2len_len(const char *p, int size) { int len; int prevlen; @@ -940,15 +936,15 @@ int utfc_ptr2len_len(const char_u *p, int size) if (size < 1 || *p == NUL) { return 0; } - if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) { // be quick for ASCII + if ((uint8_t)p[0] < 0x80 && (size == 1 || (uint8_t)p[1] < 0x80)) { // be quick for ASCII return 1; } // Skip over first UTF-8 char, stopping at a NUL byte. - len = utf_ptr2len_len(p, size); + len = utf_ptr2len_len((char_u *)p, size); // Check for illegal byte and incomplete byte sequence. - if ((len == 1 && p[0] >= 0x80) || len > size) { + if ((len == 1 && (uint8_t)p[0] >= 0x80) || len > size) { return 1; } @@ -960,7 +956,7 @@ int utfc_ptr2len_len(const char_u *p, int size) while (len < size) { int len_next_char; - if (p[len] < 0x80) { + if ((uint8_t)p[len] < 0x80) { break; } @@ -968,7 +964,7 @@ int utfc_ptr2len_len(const char_u *p, int size) * Next character length should not go beyond size to ensure that * utf_composinglike(...) does not read beyond size. */ - len_next_char = utf_ptr2len_len(p + len, size - len); + len_next_char = utf_ptr2len_len((char_u *)p + len, size - len); if (len_next_char > size - len) { break; } @@ -2420,7 +2416,7 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen if (utf_ptr2cells(from) > 1) { *to++ = '?'; } - l = utfc_ptr2len_len((const char_u *)from, (int)fromlen); + l = utfc_ptr2len_len(from, (int)fromlen); from += l; fromlen -= (size_t)l; } else if (ICONV_ERRNO != ICONV_E2BIG) { diff --git a/src/nvim/memline.c b/src/nvim/memline.c index a30a98d6e9..cd143bd52c 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -735,12 +735,12 @@ void ml_recover(bool checkext) { buf_T *buf = NULL; memfile_T *mfp = NULL; - char_u *fname; - char_u *fname_used = NULL; + char *fname; + char *fname_used = NULL; bhdr_T *hp = NULL; ZERO_BL *b0p; int b0_ff; - char_u *b0_fenc = NULL; + char *b0_fenc = NULL; PTR_BL *pp; DATA_BL *dp; infoptr_T *ip; @@ -748,7 +748,7 @@ void ml_recover(bool checkext) int len; bool directly; linenr_T lnum; - char_u *p; + char *p; int i; long error; bool cannot_open; @@ -770,9 +770,9 @@ void ml_recover(bool checkext) // If the file name ends in ".s[a-w][a-z]" we assume this is the swap file. // Otherwise a search is done to find the swap file(s). - fname = (char_u *)curbuf->b_fname; + fname = curbuf->b_fname; if (fname == NULL) { // When there is no file name - fname = (char_u *)""; + fname = ""; } len = (int)STRLEN(fname); if (checkext && len >= 4 @@ -780,12 +780,12 @@ void ml_recover(bool checkext) && vim_strchr("abcdefghijklmnopqrstuvw", TOLOWER_ASC(fname[len - 2])) != NULL && ASCII_ISALPHA(fname[len - 1])) { directly = true; - fname_used = vim_strsave(fname); // make a copy for mf_open() + fname_used = xstrdup(fname); // make a copy for mf_open() } else { directly = false; // count the number of matching swap files - len = recover_names(fname, false, 0, NULL); + len = recover_names((char_u *)fname, false, 0, NULL); if (len == 0) { // no swap files found semsg(_("E305: No swap file found for %s"), fname); goto theend; @@ -794,7 +794,7 @@ void ml_recover(bool checkext) i = 1; } else { // several swap files found, choose // list the names of the swap files - (void)recover_names(fname, true, 0, NULL); + (void)recover_names((char_u *)fname, true, 0, NULL); msg_putchar('\n'); msg_puts(_("Enter number of swap file to use (0 to quit): ")); i = get_number(false, NULL); @@ -803,7 +803,7 @@ void ml_recover(bool checkext) } } // get the swap file name that will be used - (void)recover_names(fname, false, i, &fname_used); + (void)recover_names((char_u *)fname, false, i, (char_u **)&fname_used); } if (fname_used == NULL) { goto theend; // user chose invalid number. @@ -833,9 +833,9 @@ void ml_recover(bool checkext) /* * open the memfile from the old swap file */ - p = vim_strsave(fname_used); // save "fname_used" for the message: - // mf_open() will consume "fname_used"! - mfp = mf_open((char *)fname_used, O_RDONLY); + p = xstrdup(fname_used); // save "fname_used" for the message: + // mf_open() will consume "fname_used"! + mfp = mf_open(fname_used, O_RDONLY); fname_used = p; if (mfp == NULL || mfp->mf_fd < 0) { semsg(_("E306: Cannot open %s"), fname_used); @@ -962,8 +962,8 @@ void ml_recover(bool checkext) if (b0p->b0_flags & B0_HAS_FENC) { int fnsize = B0_FNAME_SIZE_NOCRYPT; - for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; p--) {} - b0_fenc = vim_strnsave(p, (size_t)(b0p->b0_fname + fnsize - p)); + for (p = (char *)b0p->b0_fname + fnsize; (char_u *)p > b0p->b0_fname && p[-1] != NUL; p--) {} + b0_fenc = xstrnsave(p, (size_t)(b0p->b0_fname + fnsize - (char_u *)p)); } mf_put(mfp, hp, false, false); // release block 0 @@ -991,7 +991,7 @@ void ml_recover(bool checkext) set_fileformat(b0_ff - 1, OPT_LOCAL); } if (b0_fenc != NULL) { - set_option_value_give_err("fenc", 0L, (char *)b0_fenc, OPT_LOCAL); + set_option_value_give_err("fenc", 0L, b0_fenc, OPT_LOCAL); xfree(b0_fenc); } unchanged(curbuf, true, true); @@ -1133,12 +1133,12 @@ void ml_recover(bool checkext) txt_start = (dp->db_index[i] & DB_INDEX_MASK); if (txt_start <= (int)HEADER_SIZE || txt_start >= (int)dp->db_txt_end) { - p = (char_u *)"???"; + p = "???"; error++; } else { - p = (char_u *)dp + txt_start; + p = (char *)dp + txt_start; } - ml_append(lnum++, (char *)p, (colnr_T)0, true); + ml_append(lnum++, p, (colnr_T)0, true); } if (has_error) { ml_append(lnum++, _("???END"), (colnr_T)0, true); @@ -1177,7 +1177,7 @@ void ml_recover(bool checkext) } else { for (idx = 1; idx <= lnum; idx++) { // Need to copy one line, fetching the other one may flush it. - p = vim_strsave((char_u *)ml_get(idx)); + p = xstrdup(ml_get(idx)); i = STRCMP(p, ml_get(idx + lnum)); xfree(p); if (i != 0) { diff --git a/src/nvim/message.c b/src/nvim/message.c index e7959c73c6..87cfe06edc 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -1581,7 +1581,7 @@ int msg_outtrans_len_attr(const char *msgstr, int len, int attr) */ while (--len >= 0 && !got_int) { // Don't include composing chars after the end. - mb_l = utfc_ptr2len_len((char_u *)str, len + 1); + mb_l = utfc_ptr2len_len(str, len + 1); if (mb_l > 1) { c = utf_ptr2char(str); if (vim_isprintc(c)) { @@ -2219,7 +2219,7 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse) if (has_last_char) { if (maxlen >= 0) { // Avoid including composing chars after the end. - l = utfc_ptr2len_len((char_u *)s, (int)((str + maxlen) - s)); + l = utfc_ptr2len_len(s, (int)((str + maxlen) - s)); } else { l = utfc_ptr2len(s); } @@ -2316,7 +2316,7 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse) cw = utf_ptr2cells(s); if (maxlen >= 0) { // avoid including composing chars after the end - l = utfc_ptr2len_len((char_u *)s, (int)((str + maxlen) - s)); + l = utfc_ptr2len_len(s, (int)((str + maxlen) - s)); } else { l = utfc_ptr2len(s); } diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 17b79e27c1..66038d0c3c 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -3134,7 +3134,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_ } else { par_pos = curwin->w_cursor; while (curwin->w_cursor.lnum > 1 - && *skipwhite((char *)get_cursor_line_ptr()) != NUL) { + && *skipwhite(get_cursor_line_ptr()) != NUL) { curwin->w_cursor.lnum--; } } @@ -3171,13 +3171,13 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_ } break; } - if (get_leader_len((char *)get_cursor_line_ptr(), NULL, false, true) > 0) { + if (get_leader_len(get_cursor_line_ptr(), NULL, false, true) > 0) { // Ignore this line, continue at start of next line. curwin->w_cursor.lnum++; curwin->w_cursor.col = 0; continue; } - bool valid = is_ident(get_cursor_line_ptr(), curwin->w_cursor.col); + bool valid = is_ident((char_u *)get_cursor_line_ptr(), curwin->w_cursor.col); // If the current position is not a valid identifier and a previous match is // present, favor that one instead. @@ -3232,7 +3232,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_ /// @return true if able to move cursor, false otherwise. static bool nv_screengo(oparg_T *oap, int dir, long dist) { - int linelen = linetabsize(get_cursor_line_ptr()); + int linelen = linetabsize((char_u *)get_cursor_line_ptr()); bool retval = true; bool atend = false; int n; @@ -3303,7 +3303,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) } curwin->w_cursor.lnum--; - linelen = linetabsize(get_cursor_line_ptr()); + linelen = linetabsize((char_u *)get_cursor_line_ptr()); if (linelen > width1) { int w = (((linelen - width1 - 1) / width2) + 1) * width2; assert(curwin->w_curswant <= INT_MAX - w); @@ -3339,7 +3339,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) if (curwin->w_curswant >= width1) { curwin->w_curswant -= width2; } - linelen = linetabsize(get_cursor_line_ptr()); + linelen = linetabsize((char_u *)get_cursor_line_ptr()); } } } @@ -4294,7 +4294,7 @@ static void nv_ident(cmdarg_T *cap) // Call setpcmark() first, so "*``" puts the cursor back where // it was. setpcmark(); - curwin->w_cursor.col = (colnr_T)(ptr - (char *)get_cursor_line_ptr()); + curwin->w_cursor.col = (colnr_T)(ptr - get_cursor_line_ptr()); if (!g_cmd && vim_iswordp((char_u *)ptr)) { STRCPY(buf, "\\<"); @@ -4382,13 +4382,13 @@ static void nv_ident(cmdarg_T *cap) // Execute the command. if (cmdchar == '*' || cmdchar == '#') { if (!g_cmd - && vim_iswordp(mb_prevptr(get_cursor_line_ptr(), (char_u *)ptr))) { + && vim_iswordp(mb_prevptr((char_u *)get_cursor_line_ptr(), (char_u *)ptr))) { STRCAT(buf, "\\>"); } // put pattern in search history init_history(); - add_to_history(HIST_SEARCH, (char_u *)buf, true, NUL); + add_to_history(HIST_SEARCH, buf, true, NUL); (void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0, NULL); } else { @@ -4425,7 +4425,7 @@ bool get_visual_text(cmdarg_T *cap, char **pp, size_t *lenp) return false; } if (VIsual_mode == 'V') { - *pp = (char *)get_cursor_line_ptr(); + *pp = get_cursor_line_ptr(); *lenp = STRLEN(*pp); } else { if (lt(curwin->w_cursor, VIsual)) { @@ -6068,7 +6068,7 @@ static void nv_g_underscore_cmd(cmdarg_T *cap) return; } - char_u *ptr = get_cursor_line_ptr(); + char_u *ptr = (char_u *)get_cursor_line_ptr(); // In Visual mode we may end up after the line. if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) { @@ -6279,7 +6279,7 @@ static void nv_g_cmd(cmdarg_T *cap) case 'M': oap->motion_type = kMTCharWise; oap->inclusive = false; - i = linetabsize(get_cursor_line_ptr()); + i = linetabsize((char_u *)get_cursor_line_ptr()); if (cap->count0 > 0 && cap->count0 <= 100) { coladvance((colnr_T)(i * cap->count0 / 100)); } else { diff --git a/src/nvim/ops.c b/src/nvim/ops.c index d2321be4a4..01fd4bb9a7 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -225,7 +225,7 @@ void op_shift(oparg_T *oap, int curs_top, int amount) } for (i = oap->line_count - 1; i >= 0; i--) { - first_char = *get_cursor_line_ptr(); + first_char = (uint8_t)(*get_cursor_line_ptr()); if (first_char == NUL) { // empty line curwin->w_cursor.col = 0; } else if (oap->motion_type == kMTBlockWise) { @@ -356,7 +356,7 @@ static void shift_block(oparg_T *oap, int amount) return; // multiplication overflow } - char_u *const oldp = get_cursor_line_ptr(); + char_u *const oldp = (char_u *)get_cursor_line_ptr(); int startcol, oldlen, newlen; @@ -668,7 +668,7 @@ void op_reindent(oparg_T *oap, Indenter how) // indented, unless there is only one line. if (i != oap->line_count - 1 || oap->line_count == 1 || how != get_lisp_indent) { - l = (char_u *)skipwhite((char *)get_cursor_line_ptr()); + l = (char_u *)skipwhite(get_cursor_line_ptr()); if (*l == NUL) { // empty or blank line amount = 0; } else { @@ -1735,7 +1735,7 @@ int op_delete(oparg_T *oap) if (virtual_op) { // fix up things for virtualedit-delete: // break the tabs which are going to get in our way - char_u *curline = get_cursor_line_ptr(); + char_u *curline = (char_u *)get_cursor_line_ptr(); int len = (int)STRLEN(curline); if (oap->end.coladd != 0 @@ -1926,7 +1926,7 @@ static int op_replace(oparg_T *oap, int c) num_chars = numc; numc *= utf_char2len(c); - oldp = get_cursor_line_ptr(); + oldp = (char_u *)get_cursor_line_ptr(); oldlen = (int)STRLEN(oldp); size_t newp_size = (size_t)bd.textcol + (size_t)bd.startspaces; @@ -2240,7 +2240,7 @@ bool swapchar(int op_type, pos_T *pos) void op_insert(oparg_T *oap, long count1) { long ins_len, pre_textlen = 0; - char_u *firstline, *ins_text; + char *firstline, *ins_text; colnr_T ind_pre_col = 0, ind_post_col; int ind_pre_vcol = 0, ind_post_vcol = 0; struct block_def bd; @@ -2281,7 +2281,7 @@ void op_insert(oparg_T *oap, long count1) // Get indent information ind_pre_col = (colnr_T)getwhitecols_curline(); ind_pre_vcol = get_indent(); - firstline = (char_u *)ml_get(oap->start.lnum) + bd.textcol; + firstline = ml_get(oap->start.lnum) + bd.textcol; if (oap->op_type == OP_APPEND) { firstline += bd.textlen; @@ -2413,7 +2413,7 @@ void op_insert(oparg_T *oap, long count1) * Subsequent calls to ml_get() flush the firstline data - take a * copy of the required string. */ - firstline = (char_u *)ml_get(oap->start.lnum); + firstline = ml_get(oap->start.lnum); const size_t len = STRLEN(firstline); colnr_T add = bd.textcol; colnr_T offset = 0; // offset when cursor was moved in insert mode @@ -2438,10 +2438,10 @@ void op_insert(oparg_T *oap, long count1) } ins_len = (long)STRLEN(firstline) - pre_textlen - offset; if (pre_textlen >= 0 && ins_len > 0) { - ins_text = vim_strnsave(firstline, (size_t)ins_len); + ins_text = xstrnsave(firstline, (size_t)ins_len); // block handled here if (u_save(oap->start.lnum, (linenr_T)(oap->end.lnum + 1)) == OK) { - block_insert(oap, ins_text, (oap->op_type == OP_INSERT), &bd); + block_insert(oap, (char_u *)ins_text, (oap->op_type == OP_INSERT), &bd); } curwin->w_cursor.col = oap->start.col; @@ -2934,9 +2934,9 @@ static void do_autocmd_textyankpost(oparg_T *oap, yankreg_T *reg) /// @param dir BACKWARD for 'P', FORWARD for 'p' void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) { - char_u *ptr; - char_u *newp; - char_u *oldp; + char *ptr; + char *newp; + char *oldp; int yanklen; size_t totlen = 0; // init for gcc linenr_T lnum = 0; @@ -3082,13 +3082,13 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) * Loop twice: count the number of lines and save them. */ for (;;) { y_size = 0; - ptr = (char_u *)insert_string; + ptr = insert_string; while (ptr != NULL) { if (y_array != NULL) { - y_array[y_size] = (char *)ptr; + y_array[y_size] = ptr; } y_size++; - ptr = (char_u *)vim_strchr((char *)ptr, '\n'); + ptr = vim_strchr(ptr, '\n'); if (ptr != NULL) { if (y_array != NULL) { *ptr = NUL; @@ -3136,12 +3136,12 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) if (u_save_cursor() == FAIL) { goto end; } - char_u *p = get_cursor_pos_ptr(); + char *p = (char *)get_cursor_pos_ptr(); if (dir == FORWARD && *p != NUL) { MB_PTR_ADV(p); } - ptr = vim_strsave(p); - ml_append(curwin->w_cursor.lnum, (char *)ptr, (colnr_T)0, false); + ptr = xstrdup(p); + ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, false); xfree(ptr); oldp = get_cursor_line_ptr(); @@ -3149,8 +3149,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) if (dir == FORWARD && *p != NUL) { MB_PTR_ADV(p); } - ptr = vim_strnsave(oldp, (size_t)(p - oldp)); - ml_replace(curwin->w_cursor.lnum, (char *)ptr, false); + ptr = xstrnsave(oldp, (size_t)(p - oldp)); + ml_replace(curwin->w_cursor.lnum, ptr, false); nr_lines++; dir = FORWARD; } @@ -3298,8 +3298,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) oldp = get_cursor_line_ptr(); oldlen = STRLEN(oldp); chartabsize_T cts; - init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0, - (char *)oldp, (char *)oldp); + init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0, oldp, oldp); while (cts.cts_vcol < col && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) @@ -3307,7 +3306,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) cts.cts_vcol += incr; } vcol = cts.cts_vcol; - ptr = (char_u *)cts.cts_ptr; + ptr = cts.cts_ptr; bd.textcol = (colnr_T)(ptr - oldp); clear_chartabsize_arg(&cts); @@ -3320,7 +3319,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) bd.startspaces = incr - bd.endspaces; bd.textcol--; delcount = 1; - bd.textcol -= utf_head_off((char *)oldp, (char *)oldp + bd.textcol); + bd.textcol -= utf_head_off(oldp, oldp + bd.textcol); if (oldp[bd.textcol] != TAB) { /* Only a Tab can be split into spaces. Other * characters will have to be moved to after the @@ -3356,9 +3355,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) break; } - totlen = (size_t)(count * (yanklen + spaces) - + bd.startspaces + bd.endspaces); - newp = (char_u *)xmalloc(totlen + oldlen + 1); + totlen = (size_t)(count * (yanklen + spaces) + bd.startspaces + bd.endspaces); + newp = xmalloc(totlen + oldlen + 1); // copy part up to cursor to new line ptr = newp; @@ -3391,7 +3389,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) int columns = (int)oldlen - bd.textcol - delcount + 1; assert(columns >= 0); memmove(ptr, oldp + bd.textcol + delcount, (size_t)columns); - ml_replace(curwin->w_cursor.lnum, (char *)newp, false); + ml_replace(curwin->w_cursor.lnum, newp, false); extmark_splice_cols(curbuf, (int)curwin->w_cursor.lnum - 1, bd.textcol, delcount, (int)totlen + lines_appended, kExtmarkUndo); @@ -3482,7 +3480,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) } else { totlen = (size_t)(count * yanklen); do { - oldp = (char_u *)ml_get(lnum); + oldp = ml_get(lnum); oldlen = STRLEN(oldp); if (lnum > start_lnum) { pos_T pos = { @@ -3498,7 +3496,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) lnum++; continue; } - newp = (char_u *)xmalloc(totlen + oldlen + 1); + newp = xmalloc(totlen + oldlen + 1); memmove(newp, oldp, (size_t)col); ptr = newp + col; for (i = 0; i < (size_t)count; i++) { @@ -3506,10 +3504,10 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) ptr += yanklen; } STRMOVE(ptr, oldp + col); - ml_replace(lnum, (char *)newp, false); + ml_replace(lnum, newp, false); // compute the byte offset for the last character - first_byte_off = utf_head_off((char *)newp, (char *)ptr - 1); + first_byte_off = utf_head_off(newp, ptr - 1); // Place cursor on last putted char. if (lnum == curwin->w_cursor.lnum) { @@ -3553,23 +3551,23 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) // First insert y_array[size - 1] in front of second line. // Then append y_array[0] to first line. lnum = new_cursor.lnum; - ptr = (char_u *)ml_get(lnum) + col; + ptr = ml_get(lnum) + col; totlen = STRLEN(y_array[y_size - 1]); - newp = (char_u *)xmalloc((size_t)(STRLEN(ptr) + totlen + 1)); + newp = xmalloc((size_t)(STRLEN(ptr) + totlen + 1)); STRCPY(newp, y_array[y_size - 1]); STRCAT(newp, ptr); // insert second line - ml_append(lnum, (char *)newp, (colnr_T)0, false); + ml_append(lnum, newp, (colnr_T)0, false); new_lnum++; xfree(newp); - oldp = (char_u *)ml_get(lnum); - newp = (char_u *)xmalloc((size_t)col + (size_t)yanklen + 1); + oldp = ml_get(lnum); + newp = xmalloc((size_t)col + (size_t)yanklen + 1); // copy first part of line memmove(newp, oldp, (size_t)col); // append to first line memmove(newp + col, y_array[0], (size_t)yanklen + 1); - ml_replace(lnum, (char *)newp, false); + ml_replace(lnum, newp, false); curwin->w_cursor.lnum = lnum; i = 1; @@ -3587,7 +3585,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) if (flags & PUT_FIXINDENT) { old_pos = curwin->w_cursor; curwin->w_cursor.lnum = lnum; - ptr = (char_u *)ml_get(lnum); + ptr = ml_get(lnum); if (cnt == count && i == y_size - 1) { lendiff = (int)STRLEN(ptr); } @@ -4656,7 +4654,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) : length); } - vim_str2nr(ptr + col, &pre, &length, + vim_str2nr((char *)ptr + col, &pre, &length, 0 + (do_bin ? STR2NR_BIN : 0) + (do_oct ? STR2NR_OCT : 0) + (do_hex ? STR2NR_HEX : 0), @@ -5504,7 +5502,7 @@ void cursor_pos_info(dict_T *dict) (int64_t)byte_count_cursor, (int64_t)byte_count); } } else { - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); validate_virtcol(); col_print((char *)buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1); diff --git a/src/nvim/option.c b/src/nvim/option.c index 269a21b512..f8b7d96305 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -664,8 +664,8 @@ void set_init_3(void) : !(options[idx_sp].flags & P_WAS_SET); size_t len = 0; - char_u *p = (char_u *)invocation_path_tail(p_sh, &len); - p = vim_strnsave(p, len); + char *p = (char *)invocation_path_tail(p_sh, &len); + p = xstrnsave(p, len); { // @@ -1131,7 +1131,7 @@ int do_set(char *arg, int opt_flags) } } else if (*arg == '-' || ascii_isdigit(*arg)) { // Allow negative, octal and hex numbers. - vim_str2nr((char_u *)arg, NULL, &i, STR2NR_ALL, &value, NULL, 0, true); + vim_str2nr(arg, NULL, &i, STR2NR_ALL, &value, NULL, 0, true); if (i == 0 || (arg[i] != NUL && !ascii_iswhite(arg[i]))) { errmsg = e_number_required_after_equal; goto skip; diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index 35390e3dc1..f3b3c1dfbf 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -64,7 +64,7 @@ static void save_patterns(int num_pat, char **pat, int *num_file, char ***file) static bool have_wildcard(int num, char **file) { for (int i = 0; i < num; i++) { - if (path_has_wildcard((char_u *)file[i])) { + if (path_has_wildcard(file[i])) { return true; } } @@ -1106,7 +1106,7 @@ static void out_data_append_to_screen(char *output, size_t *count, bool eof) // incomplete UTF-8 sequence that could be composing with the last // complete sequence. // This will be corrected when we switch to vterm based implementation - int i = *p ? utfc_ptr2len_len((char_u *)p, (int)(end - p)) : 1; + int i = *p ? utfc_ptr2len_len(p, (int)(end - p)) : 1; if (!eof && i == 1 && utf8len_tab_zero[*(uint8_t *)p] > (end - p)) { *count = (size_t)(p - output); goto end; diff --git a/src/nvim/path.c b/src/nvim/path.c index 8973d4dfdb..e6de5388e0 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -509,7 +509,7 @@ char *save_abs_path(const char *name) /// @param p The path to expand. /// @returns Unix: True if it contains one of "?[{`'$". /// @returns Windows: True if it contains one of "*?$[". -bool path_has_wildcard(const char_u *p) +bool path_has_wildcard(const char *p) FUNC_ATTR_NONNULL_ALL { for (; *p; MB_PTR_ADV(p)) { @@ -1252,7 +1252,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i p = (char_u *)pat[i]; if (vim_backtick(p)) { - add_pat = expand_backtick(&ga, p, flags); + add_pat = expand_backtick(&ga, (char *)p, flags); if (add_pat == -1) { recursive = false; FreeWild(ga.ga_len, ga.ga_data); @@ -1367,14 +1367,14 @@ static int vim_backtick(char_u *p) /// Returns number of file names found, -1 if an error is encountered. /// /// @param flags EW_* flags -static int expand_backtick(garray_T *gap, char_u *pat, int flags) +static int expand_backtick(garray_T *gap, char *pat, int flags) { char *p; char *buffer; int cnt = 0; // Create the command: lop off the backticks. - char *cmd = (char *)vim_strnsave(pat + 1, STRLEN(pat) - 2); + char *cmd = xstrnsave(pat + 1, STRLEN(pat) - 2); if (*cmd == '=') { // `={expr}`: Expand expression buffer = eval_to_string(cmd + 1, &p, true); @@ -1683,17 +1683,17 @@ static char *eval_includeexpr(const char *const ptr, const size_t len) /// Otherwise like file_name_at_cursor(). /// /// @param rel_fname file we are searching relative to -char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count, char_u *rel_fname) +char *find_file_name_in_path(char *ptr, size_t len, int options, long count, char *rel_fname) { - char_u *file_name; - char_u *tofree = NULL; + char *file_name; + char *tofree = NULL; if (len == 0) { return NULL; } if ((options & FNAME_INCL) && *curbuf->b_p_inex != NUL) { - tofree = (char_u *)eval_includeexpr((char *)ptr, len); + tofree = eval_includeexpr(ptr, len); if (tofree != NULL) { ptr = tofree; len = STRLEN(ptr); @@ -1701,8 +1701,8 @@ char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count, } if (options & FNAME_EXP) { - file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS, true, - rel_fname); + file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS, true, + (char_u *)rel_fname); /* * If the file could not be found in a normal way, try applying @@ -1710,16 +1710,16 @@ char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count, */ if (file_name == NULL && !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL) { - tofree = (char_u *)eval_includeexpr((char *)ptr, len); + tofree = eval_includeexpr(ptr, len); if (tofree != NULL) { ptr = tofree; len = STRLEN(ptr); - file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS, - true, rel_fname); + file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS, + true, (char_u *)rel_fname); } } if (file_name == NULL && (options & FNAME_MESS)) { - char_u c = ptr[len]; + char c = ptr[len]; ptr[len] = NUL; semsg(_("E447: Can't find file \"%s\" in path"), ptr); ptr[len] = c; @@ -1729,10 +1729,11 @@ char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count, * appears several times in the path. */ while (file_name != NULL && --count > 0) { xfree(file_name); - file_name = find_file_in_path(ptr, len, options, false, rel_fname); + file_name = + (char *)find_file_in_path((char_u *)ptr, len, options, false, (char_u *)rel_fname); } } else { - file_name = vim_strnsave(ptr, len); + file_name = xstrnsave(ptr, len); } xfree(tofree); diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c index 563d85964c..ffa68c56b2 100644 --- a/src/nvim/regexp.c +++ b/src/nvim/regexp.c @@ -1623,14 +1623,14 @@ static int fill_submatch_list(int argc FUNC_ATTR_UNUSED, typval_T *argv, int arg // There are always 10 list items in staticList10_T. listitem_T *li = tv_list_first(listarg->vval.v_list); for (int i = 0; i < 10; i++) { - char_u *s = rsm.sm_match->startp[i]; + char *s = (char *)rsm.sm_match->startp[i]; if (s == NULL || rsm.sm_match->endp[i] == NULL) { s = NULL; } else { - s = vim_strnsave(s, (size_t)(rsm.sm_match->endp[i] - s)); + s = xstrnsave(s, (size_t)(rsm.sm_match->endp[i] - (char_u *)s)); } TV_LIST_ITEM_TV(li)->v_type = VAR_STRING; - TV_LIST_ITEM_TV(li)->vval.v_string = (char *)s; + TV_LIST_ITEM_TV(li)->vval.v_string = s; li = TV_LIST_ITEM_NEXT(argv->vval.v_list, li); } return argskip + 1; diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c index 9b9b33b09f..ccf2b60da2 100644 --- a/src/nvim/regexp_bt.c +++ b/src/nvim/regexp_bt.c @@ -2469,7 +2469,7 @@ do_multibyte: // Need to get composing character too. for (;;) { l = utf_ptr2len((char *)regparse); - if (!utf_composinglike((char_u *)regparse, (char_u *)regparse + l)) { + if (!utf_composinglike(regparse, regparse + l)) { break; } regmbc(utf_ptr2char((char *)regparse)); @@ -3192,7 +3192,7 @@ static int regrepeat(char_u *p, long maxcount) case SKWORD: case SKWORD + ADD_NL: while (count < maxcount) { - if (vim_iswordp_buf(scan, rex.reg_buf) + if (vim_iswordp_buf((char *)scan, rex.reg_buf) && (testval || !ascii_isdigit(*scan))) { MB_PTR_ADV(scan); } else if (*scan == NUL) { @@ -3829,7 +3829,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) break; case KWORD: - if (!vim_iswordp_buf(rex.input, rex.reg_buf)) { + if (!vim_iswordp_buf((char *)rex.input, rex.reg_buf)) { status = RA_NOMATCH; } else { ADVANCE_REGINPUT(); @@ -3838,7 +3838,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) case SKWORD: if (ascii_isdigit(*rex.input) - || !vim_iswordp_buf(rex.input, rex.reg_buf)) { + || !vim_iswordp_buf((char *)rex.input, rex.reg_buf)) { status = RA_NOMATCH; } else { ADVANCE_REGINPUT(); @@ -4046,7 +4046,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out) // Check for following composing character, unless %C // follows (skips over all composing chars). if (status != RA_NOMATCH - && utf_composinglike(rex.input, rex.input + len) + && utf_composinglike((char *)rex.input, (char *)rex.input + len) && !rex.reg_icombine && OP(next) != RE_COMPOSING) { // raaron: This code makes a composing character get @@ -4975,13 +4975,13 @@ static long regtry(bt_regprog_T *prog, colnr_T col, proftime_T *tm, int *timed_o && reg_endzpos[i].lnum == reg_startzpos[i].lnum && reg_endzpos[i].col >= reg_startzpos[i].col) { re_extmatch_out->matches[i] = - vim_strnsave(reg_getline(reg_startzpos[i].lnum) + reg_startzpos[i].col, - (size_t)(reg_endzpos[i].col - reg_startzpos[i].col)); + (char_u *)xstrnsave((char *)reg_getline(reg_startzpos[i].lnum) + reg_startzpos[i].col, + (size_t)(reg_endzpos[i].col - reg_startzpos[i].col)); } } else { if (reg_startzp[i] != NULL && reg_endzp[i] != NULL) { re_extmatch_out->matches[i] = - vim_strnsave(reg_startzp[i], (size_t)(reg_endzp[i] - reg_startzp[i])); + (char_u *)xstrnsave((char *)reg_startzp[i], (size_t)(reg_endzp[i] - reg_startzp[i])); } } } diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c index d01404b5c2..4c1058ba36 100644 --- a/src/nvim/regexp_nfa.c +++ b/src/nvim/regexp_nfa.c @@ -6643,13 +6643,13 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, regsubs_T *subm break; case NFA_KWORD: // \k - result = vim_iswordp_buf(rex.input, rex.reg_buf); + result = vim_iswordp_buf((char *)rex.input, rex.reg_buf); ADD_STATE_IF_MATCH(t->state); break; case NFA_SKWORD: // \K result = !ascii_isdigit(curc) - && vim_iswordp_buf(rex.input, rex.reg_buf); + && vim_iswordp_buf((char *)rex.input, rex.reg_buf); ADD_STATE_IF_MATCH(t->state); break; @@ -7362,15 +7362,15 @@ static long nfa_regtry(nfa_regprog_T *prog, colnr_T col, proftime_T *tm, int *ti && mpos->start_lnum == mpos->end_lnum && mpos->end_col >= mpos->start_col) { re_extmatch_out->matches[i] = - vim_strnsave(reg_getline(mpos->start_lnum) + mpos->start_col, - (size_t)(mpos->end_col - mpos->start_col)); + (char_u *)xstrnsave((char *)reg_getline(mpos->start_lnum) + mpos->start_col, + (size_t)(mpos->end_col - mpos->start_col)); } } else { struct linepos *lpos = &subs.synt.list.line[i]; if (lpos->start != NULL && lpos->end != NULL) { re_extmatch_out->matches[i] = - vim_strnsave(lpos->start, (size_t)(lpos->end - lpos->start)); + (char_u *)xstrnsave((char *)lpos->start, (size_t)(lpos->end - lpos->start)); } } } diff --git a/src/nvim/search.c b/src/nvim/search.c index db1c766eb2..5c1fe3a657 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -161,7 +161,7 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc magic = spats[i].magic; no_smartcase = spats[i].no_scs; } else if (options & SEARCH_HIS) { // put new pattern in history - add_to_history(HIST_SEARCH, pat, true, NUL); + add_to_history(HIST_SEARCH, (char *)pat, true, NUL); } if (mr_pattern_alloced) { @@ -1574,7 +1574,7 @@ int searchc(cmdarg_T *cap, int t_cmd) cap->oap->inclusive = true; } - p = get_cursor_line_ptr(); + p = (char_u *)get_cursor_line_ptr(); col = curwin->w_cursor.col; len = (int)STRLEN(p); @@ -1649,22 +1649,21 @@ static bool check_prevcol(char_u *linep, int col, int ch, int *prevcol) return col >= 0 && linep[col] == ch; } -/* - * Raw string start is found at linep[startpos.col - 1]. - * Return true if the matching end can be found between startpos and endpos. - */ -static bool find_rawstring_end(char_u *linep, pos_T *startpos, pos_T *endpos) +/// Raw string start is found at linep[startpos.col - 1]. +/// +/// @return true if the matching end can be found between startpos and endpos. +static bool find_rawstring_end(char *linep, pos_T *startpos, pos_T *endpos) { - char_u *p; + char *p; linenr_T lnum; for (p = linep + startpos->col + 1; *p && *p != '('; p++) {} size_t delim_len = (size_t)((p - linep) - startpos->col - 1); - char_u *delim_copy = vim_strnsave(linep + startpos->col + 1, delim_len); + char *delim_copy = xstrnsave(linep + startpos->col + 1, delim_len); bool found = false; for (lnum = startpos->lnum; lnum <= endpos->lnum; lnum++) { - char_u *line = (char_u *)ml_get(lnum); + char *line = ml_get(lnum); for (p = line + (lnum == startpos->lnum ? startpos->col + 1 : 0); *p; p++) { if (lnum == endpos->lnum && (colnr_T)(p - line) >= endpos->col) { @@ -2082,7 +2081,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) // delimiter we can check if it ends before where we // started searching, or before the previously found // raw string start. - if (!find_rawstring_end(linep, &pos, + if (!find_rawstring_end((char *)linep, &pos, count > 0 ? &match_pos : &curwin->w_cursor)) { count++; match_pos = pos; @@ -3598,11 +3597,11 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo if (inc_opt != NULL && strstr(inc_opt, "\\zs") != NULL) { // Use text from '\zs' to '\ze' (or end) of 'include'. - new_fname = find_file_name_in_path(incl_regmatch.startp[0], - (size_t)(incl_regmatch.endp[0] - - incl_regmatch.startp[0]), - FNAME_EXP|FNAME_INCL|FNAME_REL, - 1L, p_fname); + new_fname = (char_u *)find_file_name_in_path((char *)incl_regmatch.startp[0], + (size_t)(incl_regmatch.endp[0] + - incl_regmatch.startp[0]), + FNAME_EXP|FNAME_INCL|FNAME_REL, + 1L, (char *)p_fname); } else { // Use text after match with 'include'. new_fname = file_name_in_line(incl_regmatch.endp[0], 0, diff --git a/src/nvim/shada.c b/src/nvim/shada.c index e20bce5b34..1a70b77053 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -882,10 +882,10 @@ static const void *shada_hist_iter(const void *const iter, const uint8_t history .data = { .history_item = { .histtype = history_type, - .string = (char *)hist_he.hisstr, + .string = hist_he.hisstr, .sep = (char)(history_type == HIST_SEARCH - ? (char)hist_he.hisstr[STRLEN(hist_he.hisstr) + 1] - : 0), + ? hist_he.hisstr[STRLEN(hist_he.hisstr) + 1] + : 0), .additional_elements = hist_he.additional_elements, } } @@ -1008,7 +1008,7 @@ static inline void hms_to_he_array(const HistoryMergerState *const hms_p, HMLL_FORALL(&hms_p->hmll, cur_entry, { hist->timestamp = cur_entry->data.timestamp; hist->hisnum = (int)(hist - hist_array) + 1; - hist->hisstr = (char_u *)cur_entry->data.data.history_item.string; + hist->hisstr = cur_entry->data.data.history_item.string; hist->additional_elements = cur_entry->data.data.history_item.additional_elements; hist++; diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 7c05c9fe53..c0d05eb799 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -2104,8 +2104,8 @@ static void clear_midword(win_T *wp) XFREE_CLEAR(wp->w_s->b_spell_ismw_mb); } -// Use the "sl_midword" field of language "lp" for buffer "buf". -// They add up to any currently used midword characters. +/// Use the "sl_midword" field of language "lp" for buffer "buf". +/// They add up to any currently used midword characters. static void use_midword(slang_T *lp, win_T *wp) FUNC_ATTR_NONNULL_ALL { @@ -2113,20 +2113,20 @@ static void use_midword(slang_T *lp, win_T *wp) return; } - for (char_u *p = lp->sl_midword; *p != NUL;) { - const int c = utf_ptr2char((char *)p); - const int l = utfc_ptr2len((char *)p); + for (char *p = (char *)lp->sl_midword; *p != NUL;) { + const int c = utf_ptr2char(p); + const int l = utfc_ptr2len(p); if (c < 256 && l <= 2) { wp->w_s->b_spell_ismw[c] = true; } else if (wp->w_s->b_spell_ismw_mb == NULL) { // First multi-byte char in "b_spell_ismw_mb". - wp->w_s->b_spell_ismw_mb = (char *)vim_strnsave(p, (size_t)l); + wp->w_s->b_spell_ismw_mb = xstrnsave(p, (size_t)l); } else { // Append multi-byte chars to "b_spell_ismw_mb". const int n = (int)STRLEN(wp->w_s->b_spell_ismw_mb); - char_u *bp = vim_strnsave((char_u *)wp->w_s->b_spell_ismw_mb, (size_t)n + (size_t)l); + char *bp = xstrnsave(wp->w_s->b_spell_ismw_mb, (size_t)n + (size_t)l); xfree(wp->w_s->b_spell_ismw_mb); - wp->w_s->b_spell_ismw_mb = (char *)bp; + wp->w_s->b_spell_ismw_mb = bp; STRLCPY(bp + n, p, l + 1); } p += l; @@ -2470,7 +2470,7 @@ bool check_need_cap(linenr_T lnum, colnr_T col) return false; } - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); char_u *line_copy = NULL; colnr_T endcol = 0; if (getwhitecols((char *)line) >= (int)col) { @@ -2548,7 +2548,7 @@ void ex_spellrepall(exarg_T *eap) // Only replace when the right word isn't there yet. This happens // when changing "etc" to "etc.". - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col, repl_to, STRLEN(repl_to)) != 0) { char_u *p = xmalloc(STRLEN(line) + (size_t)addlen + 1); @@ -3497,7 +3497,7 @@ int spell_word_start(int startcol) return startcol; } - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); char_u *p; // Find a word character before "startcol". diff --git a/src/nvim/spellsuggest.c b/src/nvim/spellsuggest.c index 23c8c621b5..c07e460ea8 100644 --- a/src/nvim/spellsuggest.c +++ b/src/nvim/spellsuggest.c @@ -65,7 +65,7 @@ typedef struct suginfo_S { /// One word suggestion. Used in "si_ga". typedef struct { - char_u *st_word; ///< suggested word, allocated string + char *st_word; ///< suggested word, allocated string int st_wordlen; ///< STRLEN(st_word) int st_orglen; ///< length of replaced text int st_score; ///< lower is better @@ -453,7 +453,7 @@ void spell_suggest(int count) // No bad word or it starts after the cursor: use the word under the // cursor. curwin->w_cursor = prev_cursor; - line = get_cursor_line_ptr(); + line = (char_u *)get_cursor_line_ptr(); p = line + curwin->w_cursor.col; // Backup to before start of word. while (p > line && spell_iswordp_nmw(p, curwin)) { @@ -477,7 +477,7 @@ void spell_suggest(int count) need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col); // Make a copy of current line since autocommands may free the line. - line = vim_strsave(get_cursor_line_ptr()); + line = vim_strsave((char_u *)get_cursor_line_ptr()); spell_suggest_timeout = 5000; // Get the list of suggestions. Limit to 'lines' - 2 or the number in @@ -593,15 +593,15 @@ void spell_suggest(int count) if (sug.su_badlen > stp->st_orglen) { // Replacing less than "su_badlen", append the remainder to // repl_to. - repl_from = vim_strnsave(sug.su_badptr, (size_t)sug.su_badlen); + repl_from = (char_u *)xstrnsave((char *)sug.su_badptr, (size_t)sug.su_badlen); vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word, sug.su_badlen - stp->st_orglen, sug.su_badptr + stp->st_orglen); repl_to = vim_strsave(IObuff); } else { // Replacing su_badlen or more, use the whole word. - repl_from = vim_strnsave(sug.su_badptr, (size_t)stp->st_orglen); - repl_to = vim_strsave(stp->st_word); + repl_from = (char_u *)xstrnsave((char *)sug.su_badptr, (size_t)stp->st_orglen); + repl_to = vim_strsave((char_u *)stp->st_word); } // Replace the word. @@ -748,7 +748,7 @@ static void spell_find_suggest(char_u *badptr, int badlen, suginfo_T *su, int ma c = utf_ptr2char((char *)su->su_badptr); if (!SPELL_ISUPPER(c) && attr == HLF_COUNT) { make_case_word(su->su_badword, buf, WF_ONECAP); - add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE, + add_suggestion(su, &su->su_ga, (char *)buf, su->su_badlen, SCORE_ICASE, 0, true, su->su_sallang, false); } @@ -814,7 +814,7 @@ static void spell_suggest_expr(suginfo_T *su, char_u *expr) // Get the word and the score from the items. score = get_spellword(TV_LIST_ITEM_TV(li)->vval.v_list, &p); if (score >= 0 && score <= su->su_maxscore) { - add_suggestion(su, &su->su_ga, (const char_u *)p, su->su_badlen, + add_suggestion(su, &su->su_ga, p, su->su_badlen, score, 0, true, su->su_sallang, false); } } @@ -864,7 +864,7 @@ static void spell_suggest_file(suginfo_T *su, char_u *fname) p = cword; } - add_suggestion(su, &su->su_ga, p, su->su_badlen, + add_suggestion(su, &su->su_ga, (char *)p, su->su_badlen, SCORE_FILE, 0, true, su->su_sallang, false); } } @@ -985,7 +985,7 @@ static void suggest_try_special(suginfo_T *su) // Give a soundalike score of 0, compute the score as if deleting one // character. - add_suggestion(su, &su->su_ga, word, su->su_badlen, + add_suggestion(su, &su->su_ga, (char *)word, su->su_badlen, RESCORE(SCORE_REP, 0), 0, true, su->su_sallang, false); } } @@ -1330,7 +1330,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (newscore <= su->su_maxscore) { - add_suggestion(su, &su->su_ga, preword, + add_suggestion(su, &su->su_ga, (char *)preword, sp->ts_splitfidx - repextra, newscore, 0, false, lp->lp_sallang, false); @@ -1492,7 +1492,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so // Add the suggestion if the score isn't too bad. if (score <= su->su_maxscore) { - add_suggestion(su, &su->su_ga, preword, + add_suggestion(su, &su->su_ga, (char *)preword, sp->ts_fidx - repextra, score, 0, false, lp->lp_sallang, false); @@ -1505,7 +1505,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so preword + sp->ts_prewordlen, c == 0 ? WF_ALLCAP : 0); - add_suggestion(su, &su->su_ga, preword, + add_suggestion(su, &su->su_ga, (char *)preword, sp->ts_fidx - repextra, score + SCORE_ICASE, 0, false, lp->lp_sallang, false); @@ -2494,7 +2494,7 @@ static void score_comp_sal(suginfo_T *su) if (score < SCORE_MAXMAX) { // Add the suggestion. sstp = &SUG(su->su_sga, su->su_sga.ga_len); - sstp->st_word = vim_strsave(stp->st_word); + sstp->st_word = xstrdup(stp->st_word); sstp->st_wordlen = stp->st_wordlen; sstp->st_score = score; sstp->st_altscore = 0; @@ -2551,8 +2551,7 @@ static void score_combine(suginfo_T *su) // Add the alternate score to su_sga. for (int i = 0; i < su->su_sga.ga_len; i++) { stp = &SUG(su->su_sga, i); - stp->st_altscore = spell_edit_score(slang, - su->su_badword, stp->st_word); + stp->st_altscore = spell_edit_score(slang, su->su_badword, (char_u *)stp->st_word); if (stp->st_score == SCORE_MAXMAX) { stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8; } else { @@ -2579,7 +2578,7 @@ static void score_combine(suginfo_T *su) gap = round == 1 ? &su->su_ga : &su->su_sga; if (i < gap->ga_len) { // Don't add a word if it's already there. - p = SUG(*gap, i).st_word; + p = (char_u *)SUG(*gap, i).st_word; int j; for (j = 0; j < ga.ga_len; j++) { if (STRCMP(stp[j].st_word, p) == 0) { @@ -2636,7 +2635,7 @@ static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u * // removing the space. Don't do it when the good word also contains a // space. if (ascii_iswhite(su->su_badptr[su->su_badlen]) - && *skiptowhite((char *)stp->st_word) == NUL) { + && *skiptowhite(stp->st_word) == NUL) { for (p = fword; *(p = (char_u *)skiptowhite((char *)p)) != NUL;) { STRMOVE(p, p + 1); } @@ -2654,7 +2653,7 @@ static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u * su->su_badptr + su->su_badlen - lendiff, lendiff + 1); pgood = goodword; } else { - pgood = stp->st_word; + pgood = (char_u *)stp->st_word; } // Sound-fold the word and compute the score for the difference. @@ -2883,7 +2882,7 @@ badword: if (sps_flags & SPS_DOUBLE) { // Add the suggestion if the score isn't too bad. if (score <= su->su_maxscore) { - add_suggestion(su, &su->su_sga, p, su->su_badlen, + add_suggestion(su, &su->su_sga, (char *)p, su->su_badlen, score, 0, false, slang, false); } } else { @@ -2931,7 +2930,7 @@ badword: // Add the suggestion if the score isn't too bad. goodscore = RESCORE(goodscore, score); if (goodscore <= su->su_sfmaxscore) { - add_suggestion(su, &su->su_ga, p, su->su_badlen, + add_suggestion(su, &su->su_ga, (char *)p, su->su_badlen, goodscore, score, true, slang, true); } } @@ -3061,7 +3060,7 @@ static bool similar_chars(slang_T *slang, int c1, int c2) /// @param had_bonus value for st_had_bonus /// @param slang language for sound folding /// @param maxsf su_maxscore applies to soundfold score, su_sfmaxscore to the total score. -static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword, int badlenarg, +static void add_suggestion(suginfo_T *su, garray_T *gap, const char *goodword, int badlenarg, int score, int altscore, bool had_bonus, slang_T *slang, bool maxsf) { int goodlen; // len of goodword changed @@ -3071,7 +3070,7 @@ static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword, // Minimize "badlen" for consistency. Avoids that changing "the the" to // "thee the" is added next to changing the first "the" the "thee". - const char_u *pgood = goodword + STRLEN(goodword); + const char *pgood = goodword + STRLEN(goodword); char_u *pbad = su->su_badptr + badlenarg; for (;;) { goodlen = (int)(pgood - goodword); @@ -3144,7 +3143,7 @@ static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword, if (i < 0) { // Add a suggestion. stp = GA_APPEND_VIA_PTR(suggest_T, gap); - stp->st_word = vim_strnsave(goodword, (size_t)goodlen); + stp->st_word = xstrnsave(goodword, (size_t)goodlen); stp->st_wordlen = goodlen; stp->st_score = score; stp->st_altscore = altscore; diff --git a/src/nvim/strings.c b/src/nvim/strings.c index 16691d0ded..423436eccc 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -59,15 +59,6 @@ char_u *vim_strsave(const char_u *string) /// Copy up to `len` bytes of `string` into newly allocated memory and /// terminate with a NUL. The allocated memory always has size `len + 1`, even /// when `string` is shorter. -char_u *vim_strnsave(const char_u *string, size_t len) - FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL -{ - // strncpy is intentional: some parts of Vim use `string` shorter than `len` - // and expect the remainder to be zeroed out. - return (char_u *)strncpy(xmallocz(len), (char *)string, len); -} - -/// A clone of vim_strnsave() that uses char* instead of char_u* char *xstrnsave(const char *string, size_t len) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { @@ -318,15 +309,13 @@ char_u *vim_strsave_up(const char_u *string) return p1; } -/* - * Like vim_strnsave(), but make all characters uppercase. - * This uses ASCII lower-to-upper case translation, language independent. - */ -char_u *vim_strnsave_up(const char_u *string, size_t len) +/// Like xstrnsave(), but make all characters uppercase. +/// This uses ASCII lower-to-upper case translation, language independent. +char *vim_strnsave_up(const char *string, size_t len) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { - char_u *p1 = vim_strnsave(string, len); - vim_strup(p1); + char *p1 = xstrnsave(string, len); + vim_strup((char_u *)p1); return p1; } diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index d8de23182c..9eb412b803 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -93,7 +93,7 @@ typedef struct syn_pattern { int16_t *sp_cont_list; // cont. group IDs, if non-zero int16_t *sp_next_list; // next group IDs, if non-zero struct sp_syn sp_syn; // struct passed to in_id_list() - char_u *sp_pattern; // regexp to match, pattern + char *sp_pattern; // regexp to match, pattern regprog_T *sp_prog; // regexp to match, program syn_time_T sp_time; } synpat_T; @@ -1709,9 +1709,10 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con if (do_keywords) { line = (char_u *)syn_getcurline(); const char_u *cur_pos = line + current_col; - if (vim_iswordp_buf(cur_pos, syn_buf) + if (vim_iswordp_buf((char *)cur_pos, syn_buf) && (current_col == 0 - || !vim_iswordp_buf(cur_pos - 1 - utf_head_off((char *)line, (char *)cur_pos - 1), + || !vim_iswordp_buf((char *)cur_pos - 1 - + utf_head_off((char *)line, (char *)cur_pos - 1), syn_buf))) { syn_id = check_keyword_id((char *)line, (int)current_col, &endcol, &flags, &next_list, cur_si, &cchar); @@ -2942,7 +2943,7 @@ static int check_keyword_id(char *const line, const int startcol, int *const end int kwlen = 0; do { kwlen += utfc_ptr2len(kwp + kwlen); - } while (vim_iswordp_buf((char_u *)kwp + kwlen, syn_buf)); + } while (vim_iswordp_buf(kwp + kwlen, syn_buf)); if (kwlen > MAXKEYWLEN) { return 0; @@ -3772,14 +3773,14 @@ static void put_pattern(const char *const s, const int c, const synpat_T *const msg_putchar(c); // output the pattern, in between a char that is not in the pattern - for (i = 0; vim_strchr((char *)spp->sp_pattern, sepchars[i]) != NULL;) { + for (i = 0; vim_strchr(spp->sp_pattern, sepchars[i]) != NULL;) { if (sepchars[++i] == NUL) { i = 0; // no good char found, just use the first one break; } } msg_putchar(sepchars[i]); - msg_outtrans((char *)spp->sp_pattern); + msg_outtrans(spp->sp_pattern); msg_putchar(sepchars[i]); // output any pattern options @@ -4048,7 +4049,7 @@ static char *get_group_name(char *arg, char **name_end) /// Return NULL for any error; static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, int skip) { - char_u *gname_start, *gname; + char *gname_start, *gname; int syn_id; int len = 0; char *p; @@ -4157,16 +4158,16 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i emsg(_("E393: group[t]here not accepted here")); return NULL; } - gname_start = (char_u *)arg; + gname_start = arg; arg = skiptowhite(arg); - if (gname_start == (char_u *)arg) { + if (gname_start == arg) { return NULL; } - gname = vim_strnsave(gname_start, (size_t)((char_u *)arg - gname_start)); + gname = xstrnsave(gname_start, (size_t)(arg - gname_start)); if (STRCMP(gname, "NONE") == 0) { *opt->sync_idx = NONE_IDX; } else { - syn_id = syn_name2id((char *)gname); + syn_id = syn_name2id(gname); int i; for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0;) { if (SYN_ITEMS(curwin->w_s)[i].sp_syn.id == syn_id @@ -4566,7 +4567,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) key_end++; } xfree(key); - key = (char *)vim_strnsave_up((char_u *)rest, (size_t)(key_end - rest)); + key = vim_strnsave_up(rest, (size_t)(key_end - rest)); if (STRCMP(key, "MATCHGROUP") == 0) { item = ITEM_MATCHGROUP; } else if (STRCMP(key, "START") == 0) { @@ -5043,12 +5044,12 @@ static char *get_syn_pattern(char *arg, synpat_T *ci) return NULL; } // store the pattern and compiled regexp program - ci->sp_pattern = vim_strnsave((char_u *)arg + 1, (size_t)(end - arg) - 1); + ci->sp_pattern = xstrnsave(arg + 1, (size_t)(end - arg) - 1); // Make 'cpoptions' empty, to avoid the 'l' flag cpo_save = p_cpo; p_cpo = empty_option; - ci->sp_prog = vim_regcomp((char *)ci->sp_pattern, RE_MAGIC); + ci->sp_prog = vim_regcomp(ci->sp_pattern, RE_MAGIC); p_cpo = cpo_save; if (ci->sp_prog == NULL) { @@ -5137,7 +5138,7 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) arg_end = skiptowhite(arg_start); next_arg = skipwhite(arg_end); xfree(key); - key = (char *)vim_strnsave_up((char_u *)arg_start, (size_t)(arg_end - arg_start)); + key = vim_strnsave_up(arg_start, (size_t)(arg_end - arg_start)); if (STRCMP(key, "CCOMMENT") == 0) { if (!eap->skip) { curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT; @@ -5975,7 +5976,7 @@ static void syntime_report(void) proftime_T tm = profile_divide(spp->sp_time.total, (int)spp->sp_time.count); p->average = tm; p->id = spp->sp_syn.id; - p->pattern = spp->sp_pattern; + p->pattern = (char_u *)spp->sp_pattern; } } diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 648eb751fe..d1d5514648 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -66,11 +66,11 @@ typedef struct tag_pointers { char_u *command_end; // first char after command char_u *tag_fname; // file name of the tags file. This is used // when 'tr' is set. - char_u *tagkind; // "kind:" value - char_u *tagkind_end; // end of tagkind - char_u *user_data; // user_data string + char_u *tagkind; // "kind:" value + char_u *tagkind_end; // end of tagkind + char *user_data; // user_data string char_u *user_data_end; // end of user_data - linenr_T tagline; // "line:" value + linenr_T tagline; // "line:" value } tagptrs_T; /* @@ -588,9 +588,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) if (use_tfu && parse_match(matches[cur_match], &tagp2) == OK && tagp2.user_data) { XFREE_CLEAR(tagstack[tagstackidx].user_data); - tagstack[tagstackidx].user_data = (char *)vim_strnsave(tagp2.user_data, - (size_t)(tagp2.user_data_end - - tagp2.user_data)); + tagstack[tagstackidx].user_data = + xstrnsave(tagp2.user_data, (size_t)(tagp2.user_data_end - (char_u *)tagp2.user_data)); } tagstackidx++; @@ -1425,7 +1424,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc int help_pri = 0; char_u *help_lang_find = NULL; // lang to be found char_u help_lang[3]; // lang of current tags file - char_u *saved_pat = NULL; // copy of pat[] + char *saved_pat = NULL; // copy of pat[] bool is_txt = false; pat_T orgpat; // holds unconverted pattern info @@ -1503,9 +1502,9 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc if (orgpat.len > 3 && pat[orgpat.len - 3] == '@' && ASCII_ISALPHA(pat[orgpat.len - 2]) && ASCII_ISALPHA(pat[orgpat.len - 1])) { - saved_pat = vim_strnsave((char_u *)pat, (size_t)orgpat.len - 3); + saved_pat = xstrnsave(pat, (size_t)orgpat.len - 3); help_lang_find = (char_u *)&pat[orgpat.len - 2]; - orgpat.pat = saved_pat; + orgpat.pat = (char_u *)saved_pat; orgpat.len -= 3; } } @@ -2430,11 +2429,11 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) STRMOVE(filename + 1, filename); *filename++ = NUL; - tnp->tn_search_ctx = vim_findfile_init((char_u *)buf, filename, - (char_u *)r_ptr, 100, + tnp->tn_search_ctx = vim_findfile_init(buf, (char *)filename, + r_ptr, 100, false, // don't free visited list FINDFILE_FILE, // we search for a file - tnp->tn_search_ctx, true, (char_u *)curbuf->b_ffname); + tnp->tn_search_ctx, true, curbuf->b_ffname); if (tnp->tn_search_ctx != NULL) { tnp->tn_did_filefind_init = true; } @@ -2584,7 +2583,7 @@ static int parse_match(char *lbuf, tagptrs_T *tagp) if (STRNCMP(p, "kind:", 5) == 0) { tagp->tagkind = (char_u *)p + 5; } else if (STRNCMP(p, "user_data:", 10) == 0) { - tagp->user_data = (char_u *)p + 10; + tagp->user_data = p + 10; } else if (STRNCMP(p, "line:", 5) == 0) { tagp->tagline = atoi(p + 5); } @@ -2612,7 +2611,7 @@ static int parse_match(char *lbuf, tagptrs_T *tagp) tagp->tagkind_end = (char_u *)p; } if (tagp->user_data != NULL) { - for (p = (char *)tagp->user_data; + for (p = tagp->user_data; *p && *p != '\t' && *p != '\r' && *p != '\n'; MB_PTR_ADV(p)) {} tagp->user_data_end = (char_u *)p; @@ -2980,7 +2979,7 @@ static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bo /* * Expand file name (for environment variables) when needed. */ - if (expand && path_has_wildcard(fname)) { + if (expand && path_has_wildcard((char *)fname)) { ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; expanded_fname = ExpandOne(&xpc, fname, NULL, diff --git a/src/nvim/textformat.c b/src/nvim/textformat.c index 5ded0c9ab2..6e69fb95c8 100644 --- a/src/nvim/textformat.c +++ b/src/nvim/textformat.c @@ -117,7 +117,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on // Don't break until after the comment leader if (do_comments) { - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); leader_len = get_leader_len((char *)line, NULL, false, true); if (leader_len == 0 && curbuf->b_p_cin) { // Check for a line comment after code. @@ -624,8 +624,8 @@ void auto_format(bool trailblank, bool prev_line) { pos_T pos; colnr_T len; - char_u *old; - char_u *new, *pnew; + char *old; + char *new, *pnew; int wasatend; int cc; @@ -663,7 +663,7 @@ void auto_format(bool trailblank, bool prev_line) // With the 'c' flag in 'formatoptions' and 't' missing: only format // comments. if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP) - && get_leader_len((char *)old, NULL, false, true) == 0) { + && get_leader_len(old, NULL, false, true) == 0) { return; } @@ -700,10 +700,10 @@ void auto_format(bool trailblank, bool prev_line) new = get_cursor_line_ptr(); len = (colnr_T)STRLEN(new); if (curwin->w_cursor.col == len) { - pnew = vim_strnsave(new, (size_t)len + 2); + pnew = xstrnsave(new, (size_t)len + 2); pnew[len] = ' '; pnew[len + 1] = NUL; - ml_replace(curwin->w_cursor.lnum, (char *)pnew, false); + ml_replace(curwin->w_cursor.lnum, pnew, false); // remove the space later did_add_space = true; } else { @@ -1026,7 +1026,7 @@ void format_lines(linenr_T line_count, bool avoid_fex) // paragraph doesn't really end. if (next_leader_flags == NULL || STRNCMP(next_leader_flags, "://", 3) != 0 - || check_linecomment((char *)get_cursor_line_ptr()) == MAXCOL) { + || check_linecomment(get_cursor_line_ptr()) == MAXCOL) { is_end_par = true; } } diff --git a/src/nvim/textobject.c b/src/nvim/textobject.c index a8f4cc7aeb..6863b40599 100644 --- a/src/nvim/textobject.c +++ b/src/nvim/textobject.c @@ -1032,7 +1032,7 @@ int current_block(oparg_T *oap, long count, bool include, int what, int other) /// @return true if the cursor is on a "" tag. Ignore "". static bool in_html_tag(bool end_tag) { - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); char_u *p; int c; int lc = NUL; @@ -1493,7 +1493,7 @@ static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *e bool current_quote(oparg_T *oap, long count, bool include, int quotechar) FUNC_ATTR_NONNULL_ALL { - char_u *line = get_cursor_line_ptr(); + char_u *line = (char_u *)get_cursor_line_ptr(); int col_end; int col_start = curwin->w_cursor.col; bool inclusive = false; diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c index 387b9d61f2..d12a690b83 100644 --- a/src/nvim/viml/parser/expressions.c +++ b/src/nvim/viml/parser/expressions.c @@ -66,8 +66,6 @@ #include "nvim/viml/parser/expressions.h" #include "nvim/viml/parser/parser.h" -#define VIM_STR2NR(s, ...) vim_str2nr((const char_u *)(s), __VA_ARGS__) - typedef kvec_withinit_t(ExprASTNode **, 16) ExprASTStack; /// Which nodes may be wanted @@ -371,7 +369,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags) significand_part = significand_part * 10 + (pline.data[i] - '0'); } if (exp_start) { - VIM_STR2NR(pline.data + exp_start, NULL, NULL, 0, NULL, &exp_part, + vim_str2nr(pline.data + exp_start, NULL, NULL, 0, NULL, &exp_part, (int)(ret.len - exp_start), false); } if (exp_negative) { @@ -389,7 +387,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags) } else { int len; int prep; - VIM_STR2NR(pline.data, &prep, &len, STR2NR_ALL, NULL, + vim_str2nr(pline.data, &prep, &len, STR2NR_ALL, NULL, &ret.data.num.val.integer, (int)pline.size, false); ret.len = (size_t)len; const uint8_t bases[] = { @@ -696,8 +694,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags) // Everything else is not valid. default: - ret.len = (size_t)utfc_ptr2len_len((const char_u *)pline.data, - (int)pline.size); + ret.len = (size_t)utfc_ptr2len_len(pline.data, (int)pline.size); ret.type = kExprLexInvalid; ret.data.err.type = kExprLexPlainIdentifier; ret.data.err.msg = _("E15: Unidentified character: %.*s"); diff --git a/src/nvim/window.c b/src/nvim/window.c index c11484d1b8..8ca40cdd35 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -6522,7 +6522,7 @@ char_u *grab_file_name(long count, linenr_T *file_lnum) *file_lnum = (linenr_T)getdigits_long(&p, false, 0); } - return find_file_name_in_path((char_u *)ptr, len, options, count, (char_u *)curbuf->b_ffname); + return (char_u *)find_file_name_in_path(ptr, len, options, count, curbuf->b_ffname); } return file_name_at_cursor(options | FNAME_HYP, count, file_lnum); } @@ -6542,7 +6542,7 @@ char_u *grab_file_name(long count, linenr_T *file_lnum) */ char_u *file_name_at_cursor(int options, long count, linenr_T *file_lnum) { - return file_name_in_line(get_cursor_line_ptr(), + return file_name_in_line((char_u *)get_cursor_line_ptr(), curwin->w_cursor.col, options, count, (char_u *)curbuf->b_ffname, file_lnum); } @@ -6649,7 +6649,7 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u } } - return find_file_name_in_path((char_u *)ptr, len, options, count, rel_fname); + return (char_u *)find_file_name_in_path(ptr, len, options, count, (char *)rel_fname); } /// Add or remove a status line from window(s), according to the -- cgit From c65b1f3e15662cd14c443e34862237d3dee30977 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 20:18:17 +0800 Subject: vim-patch:9.0.0342: ":wincmd =" equalizes in two directions Problem: ":wincmd =" equalizes in two directions. Solution: Make ":vertical wincmd =" equalize vertically only and ":horizontal wincmd =" equalize horizontally only. https://github.com/vim/vim/commit/21c3a80a7fd6b7fc250ce5dc287963511f54b86f --- runtime/doc/windows.txt | 13 +++++++++++- src/nvim/ex_cmds.lua | 6 ++++++ src/nvim/ex_docmd.c | 6 +++++- src/nvim/testdir/test_window_cmd.vim | 40 ++++++++++++++++++++++++++++++++++++ src/nvim/window.c | 8 +++++--- src/nvim/window.h | 17 +++++++-------- 6 files changed, 77 insertions(+), 13 deletions(-) diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 2627068a14..ddf4d09e92 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -235,9 +235,16 @@ and 'winminwidth' are relevant. *:vert* *:vertical* :vert[ical] {cmd} Execute {cmd}. If it contains a command that splits a window, - it will be split vertically. + it will be split vertically. For `vertical wincmd =` windows + will be equialized only vertically. Doesn't work for |:execute| and |:normal|. + *:hor* *:horizontal* +:hor[izontal] {cmd} + Execute {cmd}. Currently only makes a difference for + `horizontal wincmd =`, which will equal windows only + horizontally. + :lefta[bove] {cmd} *:lefta* *:leftabove* :abo[veleft] {cmd} *:abo* *:aboveleft* Execute {cmd}. If it contains a command that splits a window, @@ -530,6 +537,10 @@ CTRL-W = Make all windows (almost) equally high and wide, but use 'winheight' and 'winwidth' for the current window. Windows with 'winfixheight' set keep their height and windows with 'winfixwidth' set keep their width. + To equalize only vertically (make window equally high) use + `vertical wincmd =` + To equalize only horizontally (make window equally wide) use + `horizontal wincmd =` :res[ize] -N *:res* *:resize* *CTRL-W_-* CTRL-W - Decrease current window height by N (default 1). diff --git a/src/nvim/ex_cmds.lua b/src/nvim/ex_cmds.lua index 4bed1e94b9..04b8832428 100644 --- a/src/nvim/ex_cmds.lua +++ b/src/nvim/ex_cmds.lua @@ -1140,6 +1140,12 @@ module.cmds = { addr_type='ADDR_NONE', func='ex_history', }, + { + command='horizontal', + flags=bit.bor(NEEDARG, EXTRA, NOTRLCOM), + addr_type='ADDR_NONE', + func='ex_wrongmodifier', + }, { command='insert', flags=bit.bor(BANG, RANGE, TRLBAR, CMDWIN, LOCK_OK, MODIFY), diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 0af737ff50..f99253ea75 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -2438,8 +2438,12 @@ int parse_command_modifiers(exarg_T *eap, char **errormsg, cmdmod_T *cmod, bool continue; } - // ":hide" and ":hide | cmd" are not modifiers case 'h': + if (checkforcmd(&eap->cmd, "horizontal", 3)) { + cmod->cmod_split |= WSP_HOR; + continue; + } + // ":hide" and ":hide | cmd" are not modifiers if (p != eap->cmd || !checkforcmd(&p, "hide", 3) || *p == NUL || ends_excmd(*p)) { break; diff --git a/src/nvim/testdir/test_window_cmd.vim b/src/nvim/testdir/test_window_cmd.vim index 83a3216534..1f4b9b77c6 100644 --- a/src/nvim/testdir/test_window_cmd.vim +++ b/src/nvim/testdir/test_window_cmd.vim @@ -343,6 +343,46 @@ func Test_window_height() bw Xa Xb Xc endfunc +func Test_wincmd_equal() + edit Xone + below split Xtwo + rightbelow vsplit Xthree + call assert_equal('Xone', bufname(winbufnr(1))) + call assert_equal('Xtwo', bufname(winbufnr(2))) + call assert_equal('Xthree', bufname(winbufnr(3))) + + " Xone and Xtwo should be about the same height + let [wh1, wh2] = [winheight(1), winheight(2)] + call assert_inrange(wh1 - 1, wh1 + 1, wh2) + " Xtwo and Xthree should be about the same width + let [ww2, ww3] = [winwidth(2), winwidth(3)] + call assert_inrange(ww2 - 1, ww2 + 1, ww3) + + 1wincmd w + 10wincmd _ + 2wincmd w + 20wincmd | + call assert_equal(10, winheight(1)) + call assert_equal(20, winwidth(2)) + + " equalizing horizontally doesn't change the heights + hor wincmd = + call assert_equal(10, winheight(1)) + let [ww2, ww3] = [winwidth(2), winwidth(3)] + call assert_inrange(ww2 - 1, ww2 + 1, ww3) + + 2wincmd w + 20wincmd | + call assert_equal(20, winwidth(2)) + " equalizing vertically doesn't change the widths + vert wincmd = + call assert_equal(20, winwidth(2)) + let [wh1, wh2] = [winheight(1), winheight(2)] + call assert_inrange(wh1 - 1, wh1 + 1, wh2) + + bwipe Xone Xtwo Xthree +endfunc + func Test_window_width() e Xa vsplit Xb diff --git a/src/nvim/window.c b/src/nvim/window.c index c11484d1b8..c0b73ff837 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -417,10 +417,12 @@ newwindow: | ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT)); break; - // make all windows the same height - case '=': - win_equal(NULL, false, 'b'); + // make all windows the same width and/or height + case '=': { + int mod = cmdmod.cmod_split & (WSP_VERT | WSP_HOR); + win_equal(NULL, false, mod == WSP_VERT ? 'v' : mod == WSP_HOR ? 'h' : 'b'); break; + } // increase current window height case '+': diff --git a/src/nvim/window.h b/src/nvim/window.h index b75b8abd9b..3137035b25 100644 --- a/src/nvim/window.h +++ b/src/nvim/window.h @@ -17,14 +17,15 @@ #define FNAME_UNESC 32 // remove backslashes used for escaping // arguments for win_split() -#define WSP_ROOM 1 // require enough room -#define WSP_VERT 2 // split vertically -#define WSP_TOP 4 // window at top-left of shell -#define WSP_BOT 8 // window at bottom-right of shell -#define WSP_HELP 16 // creating the help window -#define WSP_BELOW 32 // put new window below/right -#define WSP_ABOVE 64 // put new window above/left -#define WSP_NEWLOC 128 // don't copy location list +#define WSP_ROOM 0x01 // require enough room +#define WSP_VERT 0x02 // split/equalize vertically +#define WSP_HOR 0x04 // equalize horizontally +#define WSP_TOP 0x08 // window at top-left of shell +#define WSP_BOT 0x10 // window at bottom-right of shell +#define WSP_HELP 0x20 // creating the help window +#define WSP_BELOW 0x40 // put new window below/right +#define WSP_ABOVE 0x80 // put new window above/left +#define WSP_NEWLOC 0x100 // don't copy location list // Minimum screen size #define MIN_COLUMNS 12 // minimal columns for screen -- cgit From 56bf026deac8eddb1abc8e1d46fde992cfc67ac2 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 20:25:34 +0800 Subject: vim-patch:9.0.0346: :horizontal modifier not fully supported Problem: :horizontal modifier not fully supported. Solution: Also use :horizontal for completion and user commands. (closes vim/vim#11025) https://github.com/vim/vim/commit/d3de178e5352fedf0f30b979f46a2fcbca24ea40 --- runtime/doc/map.txt | 10 +++++----- src/nvim/cmdexpand.c | 1 + src/nvim/ex_docmd.c | 1 + src/nvim/testdir/test_cmdline.vim | 4 ++++ src/nvim/testdir/test_usercommands.vim | 4 ++++ src/nvim/usercmd.c | 4 ++++ 6 files changed, 19 insertions(+), 5 deletions(-) diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt index ca1ddaabd4..da6a305e89 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -1623,11 +1623,11 @@ The valid escape sequences are ** ** *:command-modifiers* The command modifiers, if specified. Otherwise, expands to nothing. Supported modifiers are |:aboveleft|, |:belowright|, - |:botright|, |:browse|, |:confirm|, |:hide|, |:keepalt|, - |:keepjumps|, |:keepmarks|, |:keeppatterns|, |:leftabove|, - |:lockmarks|, |:noautocmd|, |:noswapfile| |:rightbelow|, - |:sandbox|, |:silent|, |:tab|, |:topleft|, |:unsilent|, - |:verbose|, and |:vertical|. + |:botright|, |:browse|, |:confirm|, |:hide|, |:horizontal|, + |:keepalt|, |:keepjumps|, |:keepmarks|, |:keeppatterns|, + |:leftabove|, |:lockmarks|, |:noautocmd|, |:noswapfile| + |:rightbelow|, |:sandbox|, |:silent|, |:tab|, |:topleft|, + |:unsilent|, |:verbose|, and |:vertical|. Note that |:filter| is not supported. Examples: > command! -nargs=+ -complete=file MyEdit diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 6fc63f72a1..9d8dd197bd 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -1203,6 +1203,7 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, cons case CMD_folddoclosed: case CMD_folddoopen: case CMD_hide: + case CMD_horizontal: case CMD_keepalt: case CMD_keepjumps: case CMD_keepmarks: diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index f99253ea75..ea21dc8ae7 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -1757,6 +1757,7 @@ static bool skip_cmd(const exarg_T *eap) case CMD_filter: case CMD_help: case CMD_hide: + case CMD_horizontal: case CMD_ijump: case CMD_ilist: case CMD_isearch: diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index 4bfd22cb6c..bc06e70ff4 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -926,6 +926,10 @@ func Test_cmdline_complete_various() call feedkeys(":all abc\\\"\", 'xt') call assert_equal("\"all abc\", @:) + " completion for :wincmd with :horizontal modifier + call feedkeys(":horizontal wincm\\\"\", 'xt') + call assert_equal("\"horizontal wincmd", @:) + " completion for a command with a command modifier call feedkeys(":topleft new\\\"\", 'xt') call assert_equal("\"topleft new", @:) diff --git a/src/nvim/testdir/test_usercommands.vim b/src/nvim/testdir/test_usercommands.vim index e37fe43b22..1065dd16e2 100644 --- a/src/nvim/testdir/test_usercommands.vim +++ b/src/nvim/testdir/test_usercommands.vim @@ -101,6 +101,10 @@ function Test_cmdmods() call assert_equal('vertical', g:mods) vert MyCmd call assert_equal('vertical', g:mods) + horizontal MyCmd + call assert_equal('horizontal', g:mods) + hor MyCmd + call assert_equal('horizontal', g:mods) aboveleft belowright botright browse confirm hide keepalt keepjumps \ keepmarks keeppatterns lockmarks noautocmd noswapfile silent diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index 9cc9fb5588..3726273d28 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -1247,6 +1247,10 @@ size_t add_win_cmd_modifers(char *buf, const cmdmod_T *cmod, bool *multi_mods) if (cmod->cmod_split & WSP_VERT) { result += add_cmd_modifier(buf, "vertical", multi_mods); } + // :horizontal + if (cmod->cmod_split & WSP_HOR) { + result += add_cmd_modifier(buf, "horizontal", multi_mods); + } return result; } -- cgit From 689f5d604e59eba1ddab6f91b458a8163dc6629d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 20:32:59 +0800 Subject: feat(api): add support for :horizontal modifier --- runtime/doc/api.txt | 1 + src/nvim/api/command.c | 7 +++++++ src/nvim/api/keysets.lua | 1 + src/nvim/lua/executor.c | 2 ++ test/functional/api/command_spec.lua | 13 +++++++++++-- test/functional/api/vim_spec.lua | 26 ++++++++++++++++++++++++-- 6 files changed, 46 insertions(+), 4 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 89baf84c86..82978d0b3c 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1839,6 +1839,7 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* • browse: (boolean) |:browse|. • confirm: (boolean) |:confirm|. • hide: (boolean) |:hide|. + • horizontal: (boolean) |:horizontal|. • keepalt: (boolean) |:keepalt|. • keepjumps: (boolean) |:keepjumps|. • keepmarks: (boolean) |:keepmarks|. diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index 1323fc347b..b821e07d60 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -62,6 +62,7 @@ /// - browse: (boolean) |:browse|. /// - confirm: (boolean) |:confirm|. /// - hide: (boolean) |:hide|. +/// - horizontal: (boolean) |:horizontal|. /// - keepalt: (boolean) |:keepalt|. /// - keepjumps: (boolean) |:keepjumps|. /// - keepmarks: (boolean) |:keepmarks|. @@ -250,6 +251,7 @@ Dictionary nvim_parse_cmd(String str, Dictionary opts, Error *err) PUT(mods, "lockmarks", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_LOCKMARKS)); PUT(mods, "noswapfile", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_NOSWAPFILE)); PUT(mods, "vertical", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_split & WSP_VERT)); + PUT(mods, "horizontal", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_split & WSP_HOR)); const char *split; if (cmdinfo.cmdmod.cmod_split & WSP_BOT) { @@ -576,6 +578,10 @@ String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Error OBJ_TO_BOOL(vertical, mods.vertical, false, "'mods.vertical'"); cmdinfo.cmdmod.cmod_split |= (vertical ? WSP_VERT : 0); + bool horizontal; + OBJ_TO_BOOL(horizontal, mods.horizontal, false, "'mods.horizontal'"); + cmdinfo.cmdmod.cmod_split |= (horizontal ? WSP_HOR : 0); + if (HAS_KEY(mods.split)) { if (mods.split.type != kObjectTypeString) { VALIDATION_ERROR("'mods.split' must be a String"); @@ -753,6 +759,7 @@ static void build_cmdline_str(char **cmdlinep, exarg_T *eap, CmdParseInfo *cmdin } while (0) CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_split & WSP_VERT, "vertical "); + CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_split & WSP_HOR, "horizontal "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_SANDBOX, "sandbox "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_NOAUTOCMD, "noautocmd "); CMDLINE_APPEND_IF(cmdinfo->cmdmod.cmod_flags & CMOD_BROWSE, "browse "); diff --git a/src/nvim/api/keysets.lua b/src/nvim/api/keysets.lua index 6fad52ba75..af3dc24f51 100644 --- a/src/nvim/api/keysets.lua +++ b/src/nvim/api/keysets.lua @@ -188,6 +188,7 @@ return { "browse"; "confirm"; "hide"; + "horizontal"; "keepalt"; "keepjumps"; "keepmarks"; diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index f144e47c3a..2315ecd874 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -2103,6 +2103,8 @@ int nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap, bool preview) lua_pushboolean(lstate, cmdmod.cmod_split & WSP_VERT); lua_setfield(lstate, -2, "vertical"); + lua_pushboolean(lstate, cmdmod.cmod_split & WSP_HOR); + lua_setfield(lstate, -2, "horizontal"); lua_pushboolean(lstate, cmdmod.cmod_flags & CMOD_SILENT); lua_setfield(lstate, -2, "silent"); lua_pushboolean(lstate, cmdmod.cmod_flags & CMOD_ERRSILENT); diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua index 440e93da0e..2d8bf23f5b 100644 --- a/test/functional/api/command_spec.lua +++ b/test/functional/api/command_spec.lua @@ -125,6 +125,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -160,6 +161,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -195,6 +197,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -224,12 +227,13 @@ describe('nvim_create_user_command', function() bang = true, line1 = 10, line2 = 10, - mods = "confirm unsilent botright", + mods = "confirm unsilent botright horizontal", smods = { browse = false, confirm = true, emsg_silent = false, hide = false, + horizontal = true, keepalt = false, keepjumps = false, keepmarks = false, @@ -249,7 +253,7 @@ describe('nvim_create_user_command', function() count = 10, reg = "", }, exec_lua [=[ - vim.api.nvim_command('unsilent botright confirm 10CommandWithLuaCallback! h\tey ') + vim.api.nvim_command('unsilent horizontal botright confirm 10CommandWithLuaCallback! h\tey ') return result ]=]) @@ -265,6 +269,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -300,6 +305,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -347,6 +353,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -383,6 +390,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -429,6 +437,7 @@ describe('nvim_create_user_command', function() confirm = false, emsg_silent = false, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua index 24d0b6da45..2e37c4787d 100644 --- a/test/functional/api/vim_spec.lua +++ b/test/functional/api/vim_spec.lua @@ -3195,6 +3195,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3236,6 +3237,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3277,6 +3279,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3318,6 +3321,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3359,6 +3363,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3400,6 +3405,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3441,6 +3447,7 @@ describe('API', function() force = false }, hide = false, + horizontal = true, keepalt = false, keepjumps = false, keepmarks = false, @@ -3456,7 +3463,7 @@ describe('API', function() verbose = 15, vertical = false, }, - }, meths.parse_cmd('15verbose silent! aboveleft topleft tab filter /foo/ split foo.txt', {})) + }, meths.parse_cmd('15verbose silent! horizontal topleft tab filter /foo/ split foo.txt', {})) eq({ cmd = 'split', args = { 'foo.txt' }, @@ -3480,6 +3487,7 @@ describe('API', function() force = true }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3522,6 +3530,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3563,6 +3572,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3605,6 +3615,7 @@ describe('API', function() force = false }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3697,6 +3708,7 @@ describe('API', function() force = false, }, hide = false, + horizontal = false, keepalt = false, keepjumps = false, keepmarks = false, @@ -3798,10 +3810,20 @@ describe('API', function() eq('1', meths.cmd({ cmd = 'echomsg', args = { '1' }, mods = { silent = true } }, { output = true })) - -- with :silent message isn't added to message history + -- but message isn't added to message history eq('', meths.cmd({ cmd = 'messages' }, { output = true })) meths.create_user_command("Foo", 'set verbose', {}) eq(" verbose=1", meths.cmd({ cmd = "Foo", mods = { verbose = 1 } }, { output = true })) + meths.create_user_command("Mods", "echo ''", {}) + eq('keepmarks keeppatterns silent 3verbose aboveleft horizontal', + meths.cmd({ cmd = "Mods", mods = { + horizontal = true, + keepmarks = true, + keeppatterns = true, + silent = true, + split = 'aboveleft', + verbose = 3, + } }, { output = true })) eq(0, meths.get_option_value("verbose", {})) command('edit foo.txt | edit bar.txt') eq(' 1 #h "foo.txt" line 1', -- cgit From ce80b8f50d7d56ac12aa06a64a65799ec18b69af Mon Sep 17 00:00:00 2001 From: Jonas Strittmatter <40792180+smjonas@users.noreply.github.com> Date: Fri, 2 Sep 2022 08:16:17 +0200 Subject: vim-patch:9.0.0349: filetype of *.sil files not well detected (#20050) Problem: Filetype of *.sil files not well detected. Solution: Inspect the file contents to guess the filetype. https://github.com/vim/vim/commit/be807d582499acbe314ead3891481cba6ca136df --- runtime/autoload/dist/ft.vim | 19 ++++++++++++++++++- runtime/filetype.vim | 6 +++--- runtime/lua/vim/filetype.lua | 4 +++- runtime/lua/vim/filetype/detect.lua | 13 +++++++++++++ src/nvim/testdir/test_filetype.vim | 38 +++++++++++++++++++++++++++++++++++++ 5 files changed, 75 insertions(+), 5 deletions(-) diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim index 77140d62b1..7333e5a7e7 100644 --- a/runtime/autoload/dist/ft.vim +++ b/runtime/autoload/dist/ft.vim @@ -468,7 +468,7 @@ endfunc " Returns true if file content looks like LambdaProlog module func IsLProlog() - " skip apparent comments and blank lines, what looks like + " skip apparent comments and blank lines, what looks like " LambdaProlog comment may be RAPID header let l = nextnonblank(1) while l > 0 && l < line('$') && getline(l) =~ '^\s*%' " LambdaProlog comment @@ -877,6 +877,23 @@ func dist#ft#FTsig() endif endfunc +" This function checks the first 100 lines of files matching "*.sil" to +" resolve detection between Swift Intermediate Language and SILE. +func dist#ft#FTsil() + for lnum in range(1, [line('$'), 100]->min()) + let line = getline(lnum) + if line =~ '^\s*[\\%]' + setf sile + return + elseif line =~ '^\s*\S' + setf sil + return + endif + endfor + " no clue, default to "sil" + setf sil +endfunc + func dist#ft#FTsys() if exists("g:filetype_sys") exe "setf " .. g:filetype_sys diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 98d9df8b5c..d26cb808b5 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1823,7 +1823,7 @@ au BufNewFile,BufRead *.score setf slrnsc au BufNewFile,BufRead *.st setf st " Smalltalk (and Rexx, TeX, and Visual Basic) -au BufNewFile,BufRead *.cls call dist#ft#FTcls() +au BufNewFile,BufRead *.cls call dist#ft#FTcls() " Smarty templates au BufNewFile,BufRead *.tpl setf smarty @@ -1930,8 +1930,8 @@ au BufNewFile,BufRead *.cm setf voscm au BufNewFile,BufRead *.swift setf swift au BufNewFile,BufRead *.swift.gyb setf swiftgyb -" Swift Intermediate Language -au BufNewFile,BufRead *.sil setf sil +" Swift Intermediate Language or SILE +au BufNewFile,BufRead *.sil call dist#ft#FTsil() " Sysctl au BufNewFile,BufRead */etc/sysctl.conf,*/etc/sysctl.d/*.conf setf sysctl diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index fcd697a7c1..6306605641 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -902,7 +902,9 @@ local extension = { sig = function(path, bufnr) return require('vim.filetype.detect').sig(bufnr) end, - sil = 'sil', + sil = function(path, bufnr) + return require('vim.filetype.detect').sil(bufnr) + end, sim = 'simula', ['s85'] = 'sinda', sin = 'sinda', diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index 2be9dcff88..7fc7f1b7ca 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -1194,6 +1194,19 @@ function M.shell(path, contents, name) return name end +-- Swift Intermediate Language or SILE +function M.sil(bufnr) + for _, line in ipairs(getlines(bufnr, 1, 100)) do + if line:find('^%s*[\\%%]') then + return 'sile' + elseif line:find('^%s*%S') then + return 'sil' + end + end + -- No clue, default to "sil" + return 'sil' +end + -- SMIL or SNMP MIB file function M.smi(bufnr) local line = getlines(bufnr, 1) diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 68ce9148a4..4f5ae830b7 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -1824,6 +1824,44 @@ func Test_sig_file() filetype off endfunc +" Test dist#ft#FTsil() +func Test_sil_file() + filetype on + + split Xfile.sil + call assert_equal('sil', &filetype) + bwipe! + + let lines =<< trim END + // valid + let protoErasedPathA = \ABCProtocol.a + + // also valid + let protoErasedPathA = + \ABCProtocol.a + END + call writefile(lines, 'Xfile.sil') + + split Xfile.sil + call assert_equal('sil', &filetype) + bwipe! + + " SILE + + call writefile(['% some comment'], 'Xfile.sil') + split Xfile.sil + call assert_equal('sile', &filetype) + bwipe! + + call writefile(['\begin[papersize=a6]{document}foo\end{document}'], 'Xfile.sil') + split Xfile.sil + call assert_equal('sile', &filetype) + bwipe! + + call delete('Xfile.sil') + filetype off +endfunc + func Test_inc_file() filetype on -- cgit From 2dd55f81f736d5fe9697cd0e15c96f763eb90458 Mon Sep 17 00:00:00 2001 From: Famiu Haque Date: Fri, 2 Sep 2022 17:44:14 +0600 Subject: fix(ui): ui compositor does not correctly free event callbacks Prior to this PR, when freeing event callbacks, UI compositor did not free the luarefs which could cause potential memory leaks. This PR fixes that by freeing the luarefs properly. --- src/nvim/ui_compositor.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c index b8c7834e2b..2fb70eae8a 100644 --- a/src/nvim/ui_compositor.c +++ b/src/nvim/ui_compositor.c @@ -98,7 +98,7 @@ void ui_comp_free_all_mem(void) { UIEventCallback *event_cb; map_foreach_value(&ui_event_cbs, event_cb, { - xfree(event_cb); + free_ui_event_callback(event_cb); }) pmap_destroy(uint32_t)(&ui_event_cbs); } -- cgit From 2afcdbd63a5b0cbeaad9d83b096a3af5201c67a9 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Fri, 2 Sep 2022 15:20:29 +0100 Subject: feat(Man): port to Lua (#19912) Co-authored-by: zeertzjq --- .luacheckrc | 7 + runtime/autoload/man.vim | 529 ------------------------------- runtime/doc/filetype.txt | 4 +- runtime/doc/vim_diff.txt | 2 +- runtime/ftplugin/man.vim | 4 +- runtime/lua/man.lua | 601 +++++++++++++++++++++++++++++++++++- runtime/plugin/man.lua | 34 ++ runtime/plugin/man.vim | 15 - src/nvim/testdir/test_profile.vim | 6 +- test/functional/plugin/man_spec.lua | 15 +- 10 files changed, 651 insertions(+), 566 deletions(-) delete mode 100644 runtime/autoload/man.vim create mode 100644 runtime/plugin/man.lua delete mode 100644 runtime/plugin/man.vim diff --git a/.luacheckrc b/.luacheckrc index 9bbd323e84..8c1f4cf41c 100644 --- a/.luacheckrc +++ b/.luacheckrc @@ -28,6 +28,13 @@ read_globals = { globals = { "vim.g", + "vim.b", + "vim.w", + "vim.o", + "vim.bo", + "vim.wo", + "vim.go", + "vim.env" } exclude_files = { diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim deleted file mode 100644 index b8a73a64c9..0000000000 --- a/runtime/autoload/man.vim +++ /dev/null @@ -1,529 +0,0 @@ -" Maintainer: Anmol Sethi - -if exists('s:loaded_man') - finish -endif -let s:loaded_man = 1 - -let s:find_arg = '-w' -let s:localfile_arg = v:true " Always use -l if possible. #6683 - -function! man#init() abort - try - " Check for -l support. - call s:get_page(s:get_path('', 'man')) - catch /command error .*/ - let s:localfile_arg = v:false - endtry -endfunction - -function! man#open_page(count, mods, ...) abort - if a:0 > 2 - call s:error('too many arguments') - return - elseif a:0 == 0 - let ref = &filetype ==# 'man' ? expand('') : expand('') - if empty(ref) - call s:error('no identifier under cursor') - return - endif - elseif a:0 ==# 1 - let ref = a:1 - else - " Combine the name and sect into a manpage reference so that all - " verification/extraction can be kept in a single function. - " If a:2 is a reference as well, that is fine because it is the only - " reference that will match. - let ref = a:2.'('.a:1.')' - endif - try - let [sect, name] = s:extract_sect_and_name_ref(ref) - if a:count >= 0 - let sect = string(a:count) - endif - let path = s:verify_exists(sect, name) - let [sect, name] = s:extract_sect_and_name_path(path) - catch - call s:error(v:exception) - return - endtry - - let [l:buf, l:save_tfu] = [bufnr(), &tagfunc] - try - setlocal tagfunc=man#goto_tag - let l:target = l:name . '(' . l:sect . ')' - if a:mods !~# 'tab' && s:find_man() - execute 'silent keepalt tag' l:target - else - execute 'silent keepalt' a:mods 'stag' l:target - endif - call s:set_options(v:false) - finally - call setbufvar(l:buf, '&tagfunc', l:save_tfu) - endtry - - let b:man_sect = sect -endfunction - -" Called when a man:// buffer is opened. -function! man#read_page(ref) abort - try - let [sect, name] = s:extract_sect_and_name_ref(a:ref) - let path = s:verify_exists(sect, name) - let [sect, name] = s:extract_sect_and_name_path(path) - let page = s:get_page(path) - catch - call s:error(v:exception) - return - endtry - let b:man_sect = sect - call s:put_page(page) -endfunction - -" Handler for s:system() function. -function! s:system_handler(jobid, data, event) dict abort - if a:event is# 'stdout' || a:event is# 'stderr' - let self[a:event] .= join(a:data, "\n") - else - let self.exit_code = a:data - endif -endfunction - -" Run a system command and timeout after 30 seconds. -function! s:system(cmd, ...) abort - let opts = { - \ 'stdout': '', - \ 'stderr': '', - \ 'exit_code': 0, - \ 'on_stdout': function('s:system_handler'), - \ 'on_stderr': function('s:system_handler'), - \ 'on_exit': function('s:system_handler'), - \ } - let jobid = jobstart(a:cmd, opts) - - if jobid < 1 - throw printf('command error %d: %s', jobid, join(a:cmd)) - endif - - let res = jobwait([jobid], 30000) - if res[0] == -1 - try - call jobstop(jobid) - throw printf('command timed out: %s', join(a:cmd)) - catch /^Vim(call):E900:/ - endtry - elseif res[0] == -2 - throw printf('command interrupted: %s', join(a:cmd)) - endif - if opts.exit_code != 0 - throw printf("command error (%d) %s: %s", jobid, join(a:cmd), substitute(opts.stderr, '\_s\+$', '', &gdefault ? '' : 'g')) - endif - - return opts.stdout -endfunction - -function! s:set_options(pager) abort - setlocal noswapfile buftype=nofile bufhidden=hide - setlocal nomodified readonly nomodifiable - let b:pager = a:pager - setlocal filetype=man -endfunction - -function! s:get_page(path) abort - " Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065). - " Soft-wrap: ftplugin/man.vim sets wrap/breakindent/…. - " Hard-wrap: driven by `man`. - let manwidth = !get(g:, 'man_hardwrap', 1) ? 999 : (empty($MANWIDTH) ? winwidth(0) : $MANWIDTH) - " Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db). - " http://comments.gmane.org/gmane.editors.vim.devel/29085 - " Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces. - let cmd = ['env', 'MANPAGER=cat', 'MANWIDTH='.manwidth, 'MAN_KEEP_FORMATTING=1', 'man'] - return s:system(cmd + (s:localfile_arg ? ['-l', a:path] : [a:path])) -endfunction - -function! s:put_page(page) abort - setlocal modifiable noreadonly noswapfile - silent keepjumps %delete _ - silent put =a:page - while getline(1) =~# '^\s*$' - silent keepjumps 1delete _ - endwhile - " XXX: nroff justifies text by filling it with whitespace. That interacts - " badly with our use of $MANWIDTH=999. Hack around this by using a fixed - " size for those whitespace regions. - silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g - 1 - lua require("man").highlight_man_page() - call s:set_options(v:false) -endfunction - -function! man#show_toc() abort - let bufname = bufname('%') - let info = getloclist(0, {'winid': 1}) - if !empty(info) && getwinvar(info.winid, 'qf_toc') ==# bufname - lopen - return - endif - - let toc = [] - let lnum = 2 - let last_line = line('$') - 1 - while lnum && lnum < last_line - let text = getline(lnum) - if text =~# '^\%( \{3\}\)\=\S.*$' - " if text is a section title - call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text}) - elseif text =~# '^\s\+\%(+\|-\)\S\+' - " if text is a flag title. we strip whitespaces and prepend two - " spaces to have a consistent format in the loclist. - let text = ' ' .. substitute(text, '^\s*\(.\{-}\)\s*$', '\1', '') - call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text}) - endif - let lnum = nextnonblank(lnum + 1) - endwhile - - call setloclist(0, toc, ' ') - call setloclist(0, [], 'a', {'title': 'Man TOC'}) - lopen - let w:qf_toc = bufname -endfunction - -" attempt to extract the name and sect out of 'name(sect)' -" otherwise just return the largest string of valid characters in ref -function! s:extract_sect_and_name_ref(ref) abort - if a:ref[0] ==# '-' " try ':Man -pandoc' with this disabled. - throw 'manpage name cannot start with ''-''' - endif - let ref = matchstr(a:ref, '[^()]\+([^()]\+)') - if empty(ref) - let name = matchstr(a:ref, '[^()]\+') - if empty(name) - throw 'manpage reference cannot contain only parentheses' - endif - return ['', s:spaces_to_underscores(name)] - endif - let left = split(ref, '(') - " see ':Man 3X curses' on why tolower. - " TODO(nhooyr) Not sure if this is portable across OSs - " but I have not seen a single uppercase section. - return [tolower(split(left[1], ')')[0]), s:spaces_to_underscores(left[0])] -endfunction - -" replace spaces in a man page name with underscores -" intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)'; -" while editing SQL source code, it's nice to visually select 'CREATE TABLE' -" and hit 'K', which requires this transformation -function! s:spaces_to_underscores(str) - return substitute(a:str, ' ', '_', 'g') -endfunction - -function! s:get_path(sect, name) abort - " Some man implementations (OpenBSD) return all available paths from the - " search command. Previously, this function would simply select the first one. - " - " However, some searches will report matches that are incorrect: - " man -w strlen may return string.3 followed by strlen.3, and therefore - " selecting the first would get us the wrong page. Thus, we must find the - " first matching one. - " - " There's yet another special case here. Consider the following: - " If you run man -w strlen and string.3 comes up first, this is a problem. We - " should search for a matching named one in the results list. - " However, if you search for man -w clock_gettime, you will *only* get - " clock_getres.2, which is the right page. Searching the resuls for - " clock_gettime will no longer work. In this case, we should just use the - " first one that was found in the correct section. - " - " Finally, we can avoid relying on -S or -s here since they are very - " inconsistently supported. Instead, call -w with a section and a name. - if empty(a:sect) - let results = split(s:system(['man', s:find_arg, a:name])) - else - let results = split(s:system(['man', s:find_arg, a:sect, a:name])) - endif - - if empty(results) - return '' - endif - - " find any that match the specified name - let namematches = filter(copy(results), 'fnamemodify(v:val, ":t") =~ a:name') - let sectmatches = [] - - if !empty(namematches) && !empty(a:sect) - let sectmatches = filter(copy(namematches), 'fnamemodify(v:val, ":e") == a:sect') - endif - - return substitute(get(sectmatches, 0, get(namematches, 0, results[0])), '\n\+$', '', '') -endfunction - -" s:verify_exists attempts to find the path to a manpage -" based on the passed section and name. -" -" 1. If the passed section is empty, b:man_default_sects is used. -" 2. If manpage could not be found with the given sect and name, -" then another attempt is made with b:man_default_sects. -" 3. If it still could not be found, then we try again without a section. -" 4. If still not found but $MANSECT is set, then we try again with $MANSECT -" unset. -" -" This function is careful to avoid duplicating a search if a previous -" step has already done it. i.e if we use b:man_default_sects in step 1, -" then we don't do it again in step 2. -function! s:verify_exists(sect, name) abort - let sect = a:sect - - if empty(sect) - " no section specified, so search with b:man_default_sects - if exists('b:man_default_sects') - let sects = split(b:man_default_sects, ',') - for sec in sects - try - let res = s:get_path(sec, a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - endfor - endif - else - " try with specified section - try - let res = s:get_path(sect, a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - - " try again with b:man_default_sects - if exists('b:man_default_sects') - let sects = split(b:man_default_sects, ',') - for sec in sects - try - let res = s:get_path(sec, a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - endfor - endif - endif - - " if none of the above worked, we will try with no section - try - let res = s:get_path('', a:name) - if !empty(res) - return res - endif - catch /^command error (/ - endtry - - " if that still didn't work, we will check for $MANSECT and try again with it - " unset - if !empty($MANSECT) - try - let MANSECT = $MANSECT - call setenv('MANSECT', v:null) - let res = s:get_path('', a:name) - if !empty(res) - return res - endif - catch /^command error (/ - finally - call setenv('MANSECT', MANSECT) - endtry - endif - - " finally, if that didn't work, there is no hope - throw 'no manual entry for ' . a:name -endfunction - -" Extracts the name/section from the 'path/name.sect', because sometimes the actual section is -" more specific than what we provided to `man` (try `:Man 3 App::CLI`). -" Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we -" still want the name of the buffer to be 'printf'. -function! s:extract_sect_and_name_path(path) abort - let tail = fnamemodify(a:path, ':t') - if a:path =~# '\.\%([glx]z\|bz2\|lzma\|Z\)$' " valid extensions - let tail = fnamemodify(tail, ':r') - endif - let sect = matchstr(tail, '\.\zs[^.]\+$') - let name = matchstr(tail, '^.\+\ze\.') - return [sect, name] -endfunction - -function! s:find_man() abort - let l:win = 1 - while l:win <= winnr('$') - let l:buf = winbufnr(l:win) - if getbufvar(l:buf, '&filetype', '') ==# 'man' - execute l:win.'wincmd w' - return 1 - endif - let l:win += 1 - endwhile - return 0 -endfunction - -function! s:error(msg) abort - redraw - echohl ErrorMsg - echon 'man.vim: ' a:msg - echohl None -endfunction - -" see s:extract_sect_and_name_ref on why tolower(sect) -function! man#complete(arg_lead, cmd_line, cursor_pos) abort - let args = split(a:cmd_line) - let cmd_offset = index(args, 'Man') - if cmd_offset > 0 - " Prune all arguments up to :Man itself. Otherwise modifier commands like - " :tab, :vertical, etc. would lead to a wrong length. - let args = args[cmd_offset:] - endif - let l = len(args) - if l > 3 - return - elseif l ==# 1 - let name = '' - let sect = '' - elseif a:arg_lead =~# '^[^()]\+([^()]*$' - " cursor (|) is at ':Man printf(|' or ':Man 1 printf(|' - " The later is is allowed because of ':Man pri'. - " It will offer 'priclass.d(1m)' even though section is specified as 1. - let tmp = split(a:arg_lead, '(') - let name = tmp[0] - let sect = tolower(get(tmp, 1, '')) - return s:complete(sect, '', name) - elseif args[1] !~# '^[^()]\+$' - " cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|' - " or ':Man 3() pri |' - return - elseif l ==# 2 - if empty(a:arg_lead) - " cursor (|) is at ':Man 1 |' - let name = '' - let sect = tolower(args[1]) - else - " cursor (|) is at ':Man pri|' - if a:arg_lead =~# '\/' - " if the name is a path, complete files - " TODO(nhooyr) why does this complete the last one automatically - return glob(a:arg_lead.'*', 0, 1) - endif - let name = a:arg_lead - let sect = '' - endif - elseif a:arg_lead !~# '^[^()]\+$' - " cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|' - return - else - " cursor (|) is at ':Man 3 pri|' - let name = a:arg_lead - let sect = tolower(args[1]) - endif - return s:complete(sect, sect, name) -endfunction - -function! s:get_paths(sect, name, do_fallback) abort - " callers must try-catch this, as some `man` implementations don't support `s:find_arg` - try - let mandirs = join(split(s:system(['man', s:find_arg]), ':\|\n'), ',') - let paths = globpath(mandirs, 'man?/'.a:name.'*.'.a:sect.'*', 0, 1) - try - " Prioritize the result from verify_exists as it obeys b:man_default_sects. - let first = s:verify_exists(a:sect, a:name) - let paths = filter(paths, 'v:val !=# first') - let paths = [first] + paths - catch - endtry - return paths - catch - if !a:do_fallback - throw v:exception - endif - - " Fallback to a single path, with the page we're trying to find. - try - return [s:verify_exists(a:sect, a:name)] - catch - return [] - endtry - endtry -endfunction - -function! s:complete(sect, psect, name) abort - let pages = s:get_paths(a:sect, a:name, v:false) - " We remove duplicates in case the same manpage in different languages was found. - return uniq(sort(map(pages, 's:format_candidate(v:val, a:psect)'), 'i')) -endfunction - -function! s:format_candidate(path, psect) abort - if a:path =~# '\.\%(pdf\|in\)$' " invalid extensions - return - endif - let [sect, name] = s:extract_sect_and_name_path(a:path) - if sect ==# a:psect - return name - elseif sect =~# a:psect.'.\+$' - " We include the section if the user provided section is a prefix - " of the actual section. - return name.'('.sect.')' - endif -endfunction - -" Called when Nvim is invoked as $MANPAGER. -function! man#init_pager() abort - if getline(1) =~# '^\s*$' - silent keepjumps 1delete _ - else - keepjumps 1 - endif - lua require("man").highlight_man_page() - " Guess the ref from the heading (which is usually uppercase, so we cannot - " know the correct casing, cf. `man glDrawArraysInstanced`). - let ref = substitute(matchstr(getline(1), '^[^)]\+)'), ' ', '_', 'g') - try - let b:man_sect = s:extract_sect_and_name_ref(ref)[0] - catch - let b:man_sect = '' - endtry - if -1 == match(bufname('%'), 'man:\/\/') " Avoid duplicate buffers, E95. - execute 'silent file man://'.tolower(fnameescape(ref)) - endif - - call s:set_options(v:true) -endfunction - -function! man#goto_tag(pattern, flags, info) abort - let [l:sect, l:name] = s:extract_sect_and_name_ref(a:pattern) - - let l:paths = s:get_paths(l:sect, l:name, v:true) - let l:structured = [] - - for l:path in l:paths - let [l:sect, l:name] = s:extract_sect_and_name_path(l:path) - let l:structured += [{ - \ 'name': l:name, - \ 'title': l:name . '(' . l:sect . ')' - \ }] - endfor - - if &cscopetag - " return only a single entry so we work well with :cstag (#11675) - let l:structured = l:structured[:0] - endif - - return map(l:structured, { - \ _, entry -> { - \ 'name': entry.name, - \ 'filename': 'man://' . entry.title, - \ 'cmd': '1' - \ } - \ }) -endfunction - -call man#init() diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 7fff74a963..9f8ef248f8 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -586,12 +586,12 @@ Local mappings: to the end of the file in Normal mode. This means "> " is inserted in each line. -MAN *ft-man-plugin* *:Man* *man.vim* +MAN *ft-man-plugin* *:Man* *man.lua* View manpages in Nvim. Supports highlighting, completion, locales, and navigation. Also see |find-manpage|. -man.vim will always attempt to reuse the closest man window (above/left) but +man.lua will always attempt to reuse the closest man window (above/left) but otherwise create a split. The case sensitivity of completion is controlled by 'fileignorecase'. diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index 0011cd9821..b013e00fe8 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -73,7 +73,7 @@ centralized reference of the differences. - 'wildmenu' is enabled - 'wildoptions' defaults to "pum,tagfile" -- |man.vim| plugin is enabled, so |:Man| is available by default. +- |man.lua| plugin is enabled, so |:Man| is available by default. - |matchit| plugin is enabled. To disable it in your config: > :let loaded_matchit = 1 diff --git a/runtime/ftplugin/man.vim b/runtime/ftplugin/man.vim index d7a08a9941..277ce3c0b3 100644 --- a/runtime/ftplugin/man.vim +++ b/runtime/ftplugin/man.vim @@ -17,12 +17,12 @@ setlocal iskeyword=@-@,:,a-z,A-Z,48-57,_,.,-,(,) setlocal nonumber norelativenumber setlocal foldcolumn=0 colorcolumn=0 nolist nofoldenable -setlocal tagfunc=man#goto_tag +setlocal tagfunc=v:lua.require'man'.goto_tag if !exists('g:no_plugin_maps') && !exists('g:no_man_maps') nnoremap j gj nnoremap k gk - nnoremap gO :call man#show_toc() + nnoremap gO :lua require'man'.show_toc() nnoremap <2-LeftMouse> :Man if get(b:, 'pager') nnoremap q :lcloseq diff --git a/runtime/lua/man.lua b/runtime/lua/man.lua index 5da3d2a92f..4b8239ce74 100644 --- a/runtime/lua/man.lua +++ b/runtime/lua/man.lua @@ -1,7 +1,75 @@ require('vim.compat') +local api, fn = vim.api, vim.fn + +local find_arg = '-w' +local localfile_arg = true -- Always use -l if possible. #6683 local buf_hls = {} +local M = {} + +local function man_error(msg) + M.errormsg = 'man.lua: ' .. vim.inspect(msg) + error(M.errormsg) +end + +-- Run a system command and timeout after 30 seconds. +local function man_system(cmd, silent) + local stdout_data = {} + local stderr_data = {} + local stdout = vim.loop.new_pipe(false) + local stderr = vim.loop.new_pipe(false) + + local done = false + local exit_code + + local handle = vim.loop.spawn(cmd[1], { + args = vim.list_slice(cmd, 2), + stdio = { nil, stdout, stderr }, + }, function(code) + exit_code = code + stdout:close() + stderr:close() + done = true + end) + + if handle then + stdout:read_start(function(_, data) + stdout_data[#stdout_data + 1] = data + end) + stderr:read_start(function(_, data) + stderr_data[#stderr_data + 1] = data + end) + else + stdout:close() + stderr:close() + if not silent then + man_error(string.format('command error: %s', table.concat(cmd))) + end + end + + vim.wait(30000, function() + return done + end) + + if not done then + if handle then + vim.loop.shutdown(handle) + stdout:close() + stderr:close() + end + man_error(string.format('command timed out: %s', table.concat(cmd, ' '))) + end + + if exit_code ~= 0 and not silent then + man_error( + string.format("command error '%s': %s", table.concat(cmd, ' '), table.concat(stderr_data)) + ) + end + + return table.concat(stdout_data) +end + local function highlight_line(line, linenr) local chars = {} local prev_char = '' @@ -152,21 +220,540 @@ local function highlight_line(line, linenr) end local function highlight_man_page() - local mod = vim.api.nvim_buf_get_option(0, 'modifiable') - vim.api.nvim_buf_set_option(0, 'modifiable', true) + local mod = vim.bo.modifiable + vim.bo.modifiable = true - local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) + local lines = api.nvim_buf_get_lines(0, 0, -1, false) for i, line in ipairs(lines) do lines[i] = highlight_line(line, i) end - vim.api.nvim_buf_set_lines(0, 0, -1, false, lines) + api.nvim_buf_set_lines(0, 0, -1, false, lines) for _, args in ipairs(buf_hls) do - vim.api.nvim_buf_add_highlight(unpack(args)) + api.nvim_buf_add_highlight(unpack(args)) end buf_hls = {} - vim.api.nvim_buf_set_option(0, 'modifiable', mod) + vim.bo.modifiable = mod +end + +-- replace spaces in a man page name with underscores +-- intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)'; +-- while editing SQL source code, it's nice to visually select 'CREATE TABLE' +-- and hit 'K', which requires this transformation +local function spaces_to_underscores(str) + local res = str:gsub('%s', '_') + return res +end + +local function get_path(sect, name, silent) + name = name or '' + sect = sect or '' + -- Some man implementations (OpenBSD) return all available paths from the + -- search command. Previously, this function would simply select the first one. + -- + -- However, some searches will report matches that are incorrect: + -- man -w strlen may return string.3 followed by strlen.3, and therefore + -- selecting the first would get us the wrong page. Thus, we must find the + -- first matching one. + -- + -- There's yet another special case here. Consider the following: + -- If you run man -w strlen and string.3 comes up first, this is a problem. We + -- should search for a matching named one in the results list. + -- However, if you search for man -w clock_gettime, you will *only* get + -- clock_getres.2, which is the right page. Searching the resuls for + -- clock_gettime will no longer work. In this case, we should just use the + -- first one that was found in the correct section. + -- + -- Finally, we can avoid relying on -S or -s here since they are very + -- inconsistently supported. Instead, call -w with a section and a name. + local cmd + if sect == '' then + cmd = { 'man', find_arg, name } + else + cmd = { 'man', find_arg, sect, name } + end + + local lines = man_system(cmd, silent) + if lines == nil then + return nil + end + + local results = vim.split(lines, '\n', { trimempty = true }) + + if #results == 0 then + return + end + + -- find any that match the specified name + local namematches = vim.tbl_filter(function(v) + return fn.fnamemodify(v, ':t'):match(name) + end, results) or {} + local sectmatches = {} + + if #namematches > 0 and sect ~= '' then + sectmatches = vim.tbl_filter(function(v) + return fn.fnamemodify(v, ':e') == sect + end, namematches) + end + + return fn.substitute(sectmatches[1] or namematches[1] or results[1], [[\n\+$]], '', '') +end + +local function matchstr(text, pat_or_re) + local re = type(pat_or_re) == 'string' and vim.regex(pat_or_re) or pat_or_re + + local s, e = re:match_str(text) + + if s == nil then + return + end + + return text:sub(vim.str_utfindex(text, s) + 1, vim.str_utfindex(text, e)) +end + +-- attempt to extract the name and sect out of 'name(sect)' +-- otherwise just return the largest string of valid characters in ref +local function extract_sect_and_name_ref(ref) + ref = ref or '' + if ref:sub(1, 1) == '-' then -- try ':Man -pandoc' with this disabled. + man_error("manpage name cannot start with '-'") + end + local ref1 = ref:match('[^()]+%([^()]+%)') + if not ref1 then + local name = ref:match('[^()]+') + if not name then + man_error('manpage reference cannot contain only parentheses: ' .. ref) + end + return '', spaces_to_underscores(name) + end + local parts = vim.split(ref1, '(', { plain = true }) + -- see ':Man 3X curses' on why tolower. + -- TODO(nhooyr) Not sure if this is portable across OSs + -- but I have not seen a single uppercase section. + local sect = vim.split(parts[2] or '', ')', { plain = true })[1]:lower() + local name = spaces_to_underscores(parts[1]) + return sect, name +end + +-- verify_exists attempts to find the path to a manpage +-- based on the passed section and name. +-- +-- 1. If manpage could not be found with the given sect and name, +-- then try all the sections in b:man_default_sects. +-- 2. If it still could not be found, then we try again without a section. +-- 3. If still not found but $MANSECT is set, then we try again with $MANSECT +-- unset. +local function verify_exists(sect, name) + if sect and sect ~= '' then + local ret = get_path(sect, name, true) + if ret then + return ret + end + end + + if vim.b.man_default_sects ~= nil then + local sects = vim.split(vim.b.man_default_sects, ',', { plain = true, trimempty = true }) + for _, sec in ipairs(sects) do + local ret = get_path(sec, name, true) + if ret then + return ret + end + end + end + + -- if none of the above worked, we will try with no section + local res_empty_sect = get_path('', name, true) + if res_empty_sect then + return res_empty_sect + end + + -- if that still didn't work, we will check for $MANSECT and try again with it + -- unset + if vim.env.MANSECT then + local mansect = vim.env.MANSECT + vim.env.MANSECT = nil + local res = get_path('', name, true) + vim.env.MANSECT = mansect + if res then + return res + end + end + + -- finally, if that didn't work, there is no hope + man_error('no manual entry for ' .. name) +end + +local EXT_RE = vim.regex([[\.\%([glx]z\|bz2\|lzma\|Z\)$]]) + +-- Extracts the name/section from the 'path/name.sect', because sometimes the actual section is +-- more specific than what we provided to `man` (try `:Man 3 App::CLI`). +-- Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we +-- still want the name of the buffer to be 'printf'. +local function extract_sect_and_name_path(path) + local tail = fn.fnamemodify(path, ':t') + if EXT_RE:match_str(path) then -- valid extensions + tail = fn.fnamemodify(tail, ':r') + end + local name, sect = tail:match('^(.+)%.([^.]+)$') + return sect, name +end + +local function find_man() + local win = 1 + while win <= fn.winnr('$') do + local buf = fn.winbufnr(win) + if vim.bo[buf].filetype == 'man' then + vim.cmd(win .. 'wincmd w') + return true + end + win = win + 1 + end + return false +end + +local function set_options(pager) + vim.bo.swapfile = false + vim.bo.buftype = 'nofile' + vim.bo.bufhidden = 'hide' + vim.bo.modified = false + vim.bo.readonly = true + vim.bo.modifiable = false + vim.b.pager = pager + vim.bo.filetype = 'man' +end + +local function get_page(path, silent) + -- Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065). + -- Soft-wrap: ftplugin/man.lua sets wrap/breakindent/…. + -- Hard-wrap: driven by `man`. + local manwidth + if (vim.g.man_hardwrap or 1) ~= 1 then + manwidth = 999 + elseif vim.env.MANWIDTH then + manwidth = vim.env.MANWIDTH + else + manwidth = api.nvim_win_get_width(0) + end + -- Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db). + -- http://comments.gmane.org/gmane.editors.vim.devel/29085 + -- Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces. + local cmd = { 'env', 'MANPAGER=cat', 'MANWIDTH=' .. manwidth, 'MAN_KEEP_FORMATTING=1', 'man' } + if localfile_arg then + cmd[#cmd + 1] = '-l' + end + cmd[#cmd + 1] = path + return man_system(cmd, silent) +end + +local function put_page(page) + vim.bo.modified = true + vim.bo.readonly = false + vim.bo.swapfile = false + + api.nvim_buf_set_lines(0, 0, -1, false, vim.split(page, '\n')) + + while fn.getline(1):match('^%s*$') do + api.nvim_buf_set_lines(0, 0, 1, false, {}) + end + -- XXX: nroff justifies text by filling it with whitespace. That interacts + -- badly with our use of $MANWIDTH=999. Hack around this by using a fixed + -- size for those whitespace regions. + vim.cmd([[silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g]]) + vim.cmd('1') -- Move cursor to first line + highlight_man_page() + set_options(false) +end + +local function format_candidate(path, psect) + if matchstr(path, [[\.\%(pdf\|in\)$]]) then -- invalid extensions + return '' + end + local sect, name = extract_sect_and_name_path(path) + if sect == psect then + return name + elseif sect and name and matchstr(sect, psect .. '.\\+$') then -- invalid extensions + -- We include the section if the user provided section is a prefix + -- of the actual section. + return ('%s(%s)'):format(name, sect) + end + return '' end -return { highlight_man_page = highlight_man_page } +local function get_paths(sect, name, do_fallback) + -- callers must try-catch this, as some `man` implementations don't support `s:find_arg` + local ok, ret = pcall(function() + local mandirs = + table.concat(vim.split(man_system({ 'man', find_arg }), '[:\n]', { trimempty = true }), ',') + local paths = fn.globpath(mandirs, 'man?/' .. name .. '*.' .. sect .. '*', false, true) + pcall(function() + -- Prioritize the result from verify_exists as it obeys b:man_default_sects. + local first = verify_exists(sect, name) + paths = vim.tbl_filter(function(v) + return v ~= first + end, paths) + paths = { first, unpack(paths) } + end) + return paths + end) + + if not ok then + if not do_fallback then + error(ret) + end + + -- Fallback to a single path, with the page we're trying to find. + ok, ret = pcall(verify_exists, sect, name) + + return { ok and ret or nil } + end + return ret or {} +end + +local function complete(sect, psect, name) + local pages = get_paths(sect, name, false) + -- We remove duplicates in case the same manpage in different languages was found. + return fn.uniq(fn.sort(vim.tbl_map(function(v) + return format_candidate(v, psect) + end, pages) or {}, 'i')) +end + +-- see extract_sect_and_name_ref on why tolower(sect) +function M.man_complete(arg_lead, cmd_line, _) + local args = vim.split(cmd_line, '%s+', { trimempty = true }) + local cmd_offset = fn.index(args, 'Man') + if cmd_offset > 0 then + -- Prune all arguments up to :Man itself. Otherwise modifier commands like + -- :tab, :vertical, etc. would lead to a wrong length. + args = vim.list_slice(args, cmd_offset + 1) + end + + if #args > 3 then + return {} + end + + if #args == 1 then + -- returning full completion is laggy. Require some arg_lead to complete + -- return complete('', '', '') + return {} + end + + if arg_lead:match('^[^()]+%([^()]*$') then + -- cursor (|) is at ':Man printf(|' or ':Man 1 printf(|' + -- The later is is allowed because of ':Man pri'. + -- It will offer 'priclass.d(1m)' even though section is specified as 1. + local tmp = vim.split(arg_lead, '(', { plain = true }) + local name = tmp[1] + local sect = (tmp[2] or ''):lower() + return complete(sect, '', name) + end + + if not args[2]:match('^[^()]+$') then + -- cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|' + -- or ':Man 3() pri |' + return {} + end + + if #args == 2 then + local name, sect + if arg_lead == '' then + -- cursor (|) is at ':Man 1 |' + name = '' + sect = args[1]:lower() + else + -- cursor (|) is at ':Man pri|' + if arg_lead:match('/') then + -- if the name is a path, complete files + -- TODO(nhooyr) why does this complete the last one automatically + return fn.glob(arg_lead .. '*', false, true) + end + name = arg_lead + sect = '' + end + return complete(sect, sect, name) + end + + if not arg_lead:match('[^()]+$') then + -- cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|' + return {} + end + + -- cursor (|) is at ':Man 3 pri|' + local name = arg_lead + local sect = args[2]:lower() + return complete(sect, sect, name) +end + +function M.goto_tag(pattern, _, _) + local sect, name = extract_sect_and_name_ref(pattern) + + local paths = get_paths(sect, name, true) + local structured = {} + + for _, path in ipairs(paths) do + sect, name = extract_sect_and_name_path(path) + if sect and name then + structured[#structured + 1] = { + name = name, + title = name .. '(' .. sect .. ')', + } + end + end + + if vim.o.cscopetag then + -- return only a single entry so we work well with :cstag (#11675) + structured = { structured[1] } + end + + return vim.tbl_map(function(entry) + return { + name = entry.name, + filename = 'man://' .. entry.title, + cmd = '1', + } + end, structured) +end + +-- Called when Nvim is invoked as $MANPAGER. +function M.init_pager() + if fn.getline(1):match('^%s*$') then + api.nvim_buf_set_lines(0, 0, 1, false, {}) + else + vim.cmd('keepjumps 1') + end + highlight_man_page() + -- Guess the ref from the heading (which is usually uppercase, so we cannot + -- know the correct casing, cf. `man glDrawArraysInstanced`). + local ref = fn.substitute(matchstr(fn.getline(1), [[^[^)]\+)]]) or '', ' ', '_', 'g') + local ok, res = pcall(extract_sect_and_name_ref, ref) + vim.b.man_sect = ok and res or '' + + if not fn.bufname('%'):match('man://') then -- Avoid duplicate buffers, E95. + vim.cmd.file({ 'man://' .. fn.fnameescape(ref):lower(), mods = { silent = true } }) + end + + set_options(true) +end + +function M.open_page(count, smods, args) + if #args > 2 then + man_error('too many arguments') + end + + local ref + if #args == 0 then + ref = vim.bo.filetype == 'man' and fn.expand('') or fn.expand('') + if ref == '' then + man_error('no identifier under cursor') + end + elseif #args == 1 then + ref = args[1] + else + -- Combine the name and sect into a manpage reference so that all + -- verification/extraction can be kept in a single function. + -- If args[2] is a reference as well, that is fine because it is the only + -- reference that will match. + ref = ('%s(%s)'):format(args[2], args[1]) + end + + local sect, name = extract_sect_and_name_ref(ref) + if count >= 0 then + sect = tostring(count) + end + + local path = verify_exists(sect, name) + sect, name = extract_sect_and_name_path(path) + + local buf = fn.bufnr() + local save_tfu = vim.bo[buf].tagfunc + vim.bo[buf].tagfunc = "v:lua.require'man'.goto_tag" + + local target = ('%s(%s)'):format(name, sect) + + local ok, ret = pcall(function() + if not smods.tab and find_man() then + vim.cmd.tag({ target, mods = { silent = true, keepalt = true } }) + else + smods.silent = true + smods.keepalt = true + vim.cmd.stag({ target, mods = smods }) + end + end) + + vim.bo[buf].tagfunc = save_tfu + + if not ok then + error(ret) + else + set_options(false) + end + + vim.b.man_sect = sect +end + +-- Called when a man:// buffer is opened. +function M.read_page(ref) + local sect, name = extract_sect_and_name_ref(ref) + local path = verify_exists(sect, name) + sect = extract_sect_and_name_path(path) + local page = get_page(path) + vim.b.man_sect = sect + put_page(page) +end + +function M.show_toc() + local bufname = fn.bufname('%') + local info = fn.getloclist(0, { winid = 1 }) + if info ~= '' and vim.w[info.winid].qf_toc == bufname then + vim.cmd.lopen() + return + end + + local toc = {} + local lnum = 2 + local last_line = fn.line('$') - 1 + local section_title_re = vim.regex([[^\%( \{3\}\)\=\S.*$]]) + local flag_title_re = vim.regex([[^\s\+\%(+\|-\)\S\+]]) + while lnum and lnum < last_line do + local text = fn.getline(lnum) + if section_title_re:match_str(text) then + -- if text is a section title + toc[#toc + 1] = { + bufnr = fn.bufnr('%'), + lnum = lnum, + text = text, + } + elseif flag_title_re:match_str(text) then + -- if text is a flag title. we strip whitespaces and prepend two + -- spaces to have a consistent format in the loclist. + toc[#toc + 1] = { + bufnr = fn.bufnr('%'), + lnum = lnum, + text = ' ' .. fn.substitute(text, [[^\s*\(.\{-}\)\s*$]], [[\1]], ''), + } + end + lnum = fn.nextnonblank(lnum + 1) + end + + fn.setloclist(0, toc, ' ') + fn.setloclist(0, {}, 'a', { title = 'Man TOC' }) + vim.cmd.lopen() + vim.w.qf_toc = bufname +end + +local function init() + local path = get_path('', 'man', true) + local page + if path ~= nil then + -- Check for -l support. + page = get_page(path, true) + end + + if page == '' or page == nil then + localfile_arg = false + end +end + +init() + +return M diff --git a/runtime/plugin/man.lua b/runtime/plugin/man.lua new file mode 100644 index 0000000000..4b1528b0cb --- /dev/null +++ b/runtime/plugin/man.lua @@ -0,0 +1,34 @@ +if vim.g.loaded_man ~= nil then + return +end +vim.g.loaded_man = true + +vim.api.nvim_create_user_command('Man', function(params) + local man = require('man') + if params.bang then + man.init_pager() + else + local ok, err = pcall(man.open_page, params.count, params.smods, params.fargs) + if not ok then + vim.notify(man.errormsg or err, vim.log.levels.ERROR) + end + end +end, { + bang = true, + bar = true, + addr = 'other', + nargs = '*', + complete = function(...) + return require('man').man_complete(...) + end, +}) + +local augroup = vim.api.nvim_create_augroup('man', {}) + +vim.api.nvim_create_autocmd('BufReadCmd', { + group = augroup, + pattern = 'man://*', + callback = function(params) + require('man').read_page(vim.fn.matchstr(params.match, 'man://\\zs.*')) + end, +}) diff --git a/runtime/plugin/man.vim b/runtime/plugin/man.vim deleted file mode 100644 index b10677593f..0000000000 --- a/runtime/plugin/man.vim +++ /dev/null @@ -1,15 +0,0 @@ -" Maintainer: Anmol Sethi - -if exists('g:loaded_man') - finish -endif -let g:loaded_man = 1 - -command! -bang -bar -addr=other -complete=customlist,man#complete -nargs=* Man - \ if 0 | call man#init_pager() | - \ else | call man#open_page(, , ) | endif - -augroup man - autocmd! - autocmd BufReadCmd man://* call man#read_page(matchstr(expand(''), 'man://\zs.*')) -augroup END diff --git a/src/nvim/testdir/test_profile.vim b/src/nvim/testdir/test_profile.vim index fdb6f13e2b..4225b91bc4 100644 --- a/src/nvim/testdir/test_profile.vim +++ b/src/nvim/testdir/test_profile.vim @@ -40,8 +40,8 @@ func Test_profile_func() call writefile(lines, 'Xprofile_func.vim') call system(GetVimCommand() \ . ' -es --clean' - \ . ' -c "so Xprofile_func.vim"' - \ . ' -c "qall!"') + \ . ' --cmd "so Xprofile_func.vim"' + \ . ' --cmd "qall!"') call assert_equal(0, v:shell_error) let lines = readfile('Xprofile_func.log') @@ -475,7 +475,7 @@ func Test_profdel_func() call Foo3() [CODE] call writefile(lines, 'Xprofile_file.vim') - call system(GetVimCommandClean() . ' -es -c "so Xprofile_file.vim" -c q') + call system(GetVimCommandClean() . ' -es --cmd "so Xprofile_file.vim" --cmd q') call assert_equal(0, v:shell_error) let lines = readfile('Xprofile_file.log') diff --git a/test/functional/plugin/man_spec.lua b/test/functional/plugin/man_spec.lua index 9304aa6da9..3e63c5df9a 100644 --- a/test/functional/plugin/man_spec.lua +++ b/test/functional/plugin/man_spec.lua @@ -1,7 +1,8 @@ local helpers = require('test.functional.helpers')(after_each) local Screen = require('test.functional.ui.screen') -local command, eval, rawfeed = helpers.command, helpers.eval, helpers.rawfeed +local command, rawfeed = helpers.command, helpers.rawfeed local clear = helpers.clear +local exec_lua = helpers.exec_lua local funcs = helpers.funcs local nvim_prog = helpers.nvim_prog local matches = helpers.matches @@ -50,7 +51,7 @@ describe(':Man', function() | ]]} - eval('man#init_pager()') + exec_lua[[require'man'.init_pager()]] screen:expect([[ ^this {b:is} {b:a} test | @@ -74,7 +75,7 @@ describe(':Man', function() | ]=]} - eval('man#init_pager()') + exec_lua[[require'man'.init_pager()]] screen:expect([[ ^this {b:is }{bi:a }{biu:test} | @@ -89,7 +90,7 @@ describe(':Man', function() rawfeed([[ ithis iiss ああ test with _ö_v_e_r_s_t_r_u_̃_c_k te[3mxt¶[0m]]) - eval('man#init_pager()') + exec_lua[[require'man'.init_pager()]] screen:expect([[ ^this {b:is} {b:あ} test | @@ -105,7 +106,7 @@ describe(':Man', function() i__bbeeggiinnss mmiidd__ddllee _m_i_d___d_l_e]]) - eval('man#init_pager()') + exec_lua[[require'man'.init_pager()]] screen:expect([[ {b:^_begins} | @@ -121,7 +122,7 @@ describe(':Man', function() i· ·· +o ++oo double]]) - eval('man#init_pager()') + exec_lua[[require'man'.init_pager()]] screen:expect([[ ^· {b:·} | @@ -138,7 +139,7 @@ describe(':Man', function() [44m 4 [45m 5 [46m 6 [47m 7 [100m 8 [101m 9 [102m 10 [103m 11 [104m 12 [105m 13 [106m 14 [107m 15 [48:5:16m 16 ]]) - eval('man#init_pager()') + exec_lua[[require'man'.init_pager()]] screen:expect([[ ^ 0 1 2 3 | -- cgit From 1ef7720567b08caec0c077605fb2a01a9d6eafbc Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Thu, 1 Sep 2022 18:46:34 +0800 Subject: fix(api)!: correctly deal with number before :tab Now nvim_parse_cmd and nvim_create_user_command use a "tab" value which is the same as the number passed before :tab modifier instead of the number plus 1, and "tab" value is -1 if :tab modifier is not used. --- runtime/doc/api.txt | 2 +- runtime/lua/man.lua | 2 +- src/nvim/api/command.c | 14 ++++++------ src/nvim/lua/executor.c | 2 +- test/functional/api/command_spec.lua | 41 +++++++++++++++++++++++++++--------- test/functional/api/vim_spec.lua | 24 ++++++++++----------- 6 files changed, 54 insertions(+), 31 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 82978d0b3c..a4fe71bc86 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1846,7 +1846,7 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* • keeppatterns: (boolean) |:keeppatterns|. • lockmarks: (boolean) |:lockmarks|. • noswapfile: (boolean) |:noswapfile|. - • tab: (integer) |:tab|. + • tab: (integer) |:tab|. -1 when omitted. • verbose: (integer) |:verbose|. -1 when omitted. • vertical: (boolean) |:vertical|. • split: (string) Split modifier string, is an empty string when diff --git a/runtime/lua/man.lua b/runtime/lua/man.lua index 4b8239ce74..82ed0305f7 100644 --- a/runtime/lua/man.lua +++ b/runtime/lua/man.lua @@ -671,7 +671,7 @@ function M.open_page(count, smods, args) local target = ('%s(%s)'):format(name, sect) local ok, ret = pcall(function() - if not smods.tab and find_man() then + if smods.tab == -1 and find_man() then vim.cmd.tag({ target, mods = { silent = true, keepalt = true } }) else smods.silent = true diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index b821e07d60..11715a49dc 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -69,7 +69,7 @@ /// - keeppatterns: (boolean) |:keeppatterns|. /// - lockmarks: (boolean) |:lockmarks|. /// - noswapfile: (boolean) |:noswapfile|. -/// - tab: (integer) |:tab|. +/// - tab: (integer) |:tab|. -1 when omitted. /// - verbose: (integer) |:verbose|. -1 when omitted. /// - vertical: (boolean) |:vertical|. /// - split: (string) Split modifier string, is an empty string when there's no split @@ -239,7 +239,7 @@ Dictionary nvim_parse_cmd(String str, Dictionary opts, Error *err) PUT(mods, "unsilent", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_UNSILENT)); PUT(mods, "sandbox", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_SANDBOX)); PUT(mods, "noautocmd", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_NOAUTOCMD)); - PUT(mods, "tab", INTEGER_OBJ(cmdinfo.cmdmod.cmod_tab)); + PUT(mods, "tab", INTEGER_OBJ(cmdinfo.cmdmod.cmod_tab - 1)); PUT(mods, "verbose", INTEGER_OBJ(cmdinfo.cmdmod.cmod_verbose - 1)); PUT(mods, "browse", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_BROWSE)); PUT(mods, "confirm", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_CONFIRM)); @@ -559,15 +559,17 @@ String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Error } if (HAS_KEY(mods.tab)) { - if (mods.tab.type != kObjectTypeInteger || mods.tab.data.integer < 0) { - VALIDATION_ERROR("'mods.tab' must be a non-negative Integer"); + if (mods.tab.type != kObjectTypeInteger) { + VALIDATION_ERROR("'mods.tab' must be an Integer"); + } else if ((int)mods.tab.data.integer >= 0) { + // Silently ignore negative integers to allow mods.tab to be set to -1. + cmdinfo.cmdmod.cmod_tab = (int)mods.tab.data.integer + 1; } - cmdinfo.cmdmod.cmod_tab = (int)mods.tab.data.integer + 1; } if (HAS_KEY(mods.verbose)) { if (mods.verbose.type != kObjectTypeInteger) { - VALIDATION_ERROR("'mods.verbose' must be a Integer"); + VALIDATION_ERROR("'mods.verbose' must be an Integer"); } else if ((int)mods.verbose.data.integer >= 0) { // Silently ignore negative integers to allow mods.verbose to be set to -1. cmdinfo.cmdmod.cmod_verbose = (int)mods.verbose.data.integer + 1; diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 2315ecd874..1013cf76f9 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -2082,7 +2082,7 @@ int nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap, bool preview) lua_newtable(lstate); // smods table - lua_pushinteger(lstate, cmdmod.cmod_tab); + lua_pushinteger(lstate, cmdmod.cmod_tab - 1); lua_setfield(lstate, -2, "tab"); lua_pushinteger(lstate, cmdmod.cmod_verbose - 1); diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua index 2d8bf23f5b..44a19d8348 100644 --- a/test/functional/api/command_spec.lua +++ b/test/functional/api/command_spec.lua @@ -136,7 +136,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -172,7 +172,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -208,7 +208,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -244,7 +244,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "botright", - tab = 0, + tab = -1, unsilent = true, verbose = -1, vertical = false, @@ -280,7 +280,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -316,7 +316,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -364,7 +364,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -401,7 +401,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -448,7 +448,7 @@ describe('nvim_create_user_command', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -523,8 +523,29 @@ describe('nvim_create_user_command', function() vim.api.nvim_cmd({ cmd = 'echo', args = { '&verbose' }, mods = opts.smods }, {}) end, {}) ]] - eq("3", meths.cmd({ cmd = 'MyEcho', mods = { verbose = 3 } }, { output = true })) + + eq(1, #meths.list_tabpages()) + exec_lua[[ + vim.api.nvim_create_user_command('MySplit', function(opts) + vim.api.nvim_cmd({ cmd = 'split', mods = opts.smods }, {}) + end, {}) + ]] + meths.cmd({ cmd = 'MySplit' }, {}) + eq(1, #meths.list_tabpages()) + eq(2, #meths.list_wins()) + meths.cmd({ cmd = 'MySplit', mods = { tab = 1 } }, {}) + eq(2, #meths.list_tabpages()) + eq(2, funcs.tabpagenr()) + meths.cmd({ cmd = 'MySplit', mods = { tab = 1 } }, {}) + eq(3, #meths.list_tabpages()) + eq(2, funcs.tabpagenr()) + meths.cmd({ cmd = 'MySplit', mods = { tab = 3 } }, {}) + eq(4, #meths.list_tabpages()) + eq(4, funcs.tabpagenr()) + meths.cmd({ cmd = 'MySplit', mods = { tab = 0 } }, {}) + eq(5, #meths.list_tabpages()) + eq(1, funcs.tabpagenr()) end) end) diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua index 2e37c4787d..edbdd54c2f 100644 --- a/test/functional/api/vim_spec.lua +++ b/test/functional/api/vim_spec.lua @@ -3206,7 +3206,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3248,7 +3248,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3290,7 +3290,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3332,7 +3332,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3374,7 +3374,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3416,7 +3416,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3458,7 +3458,7 @@ describe('API', function() sandbox = false, silent = true, split = "topleft", - tab = 2, + tab = 1, unsilent = false, verbose = 15, vertical = false, @@ -3503,7 +3503,7 @@ describe('API', function() verbose = 0, vertical = false, }, - }, meths.parse_cmd('0verbose unsilent botright confirm filter! /foo/ split foo.txt', {})) + }, meths.parse_cmd('0verbose unsilent botright 0tab confirm filter! /foo/ split foo.txt', {})) end) it('works with user commands', function() command('command -bang -nargs=+ -range -addr=lines MyCommand echo foo') @@ -3541,7 +3541,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3583,7 +3583,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3626,7 +3626,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, @@ -3719,7 +3719,7 @@ describe('API', function() sandbox = false, silent = false, split = "", - tab = 0, + tab = -1, unsilent = false, verbose = -1, vertical = false, -- cgit From 1ffd527c837fb2465c9659273bbe5447a1352db2 Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Fri, 2 Sep 2022 17:39:49 +0100 Subject: refactor: migrate comment style (#20012) Done automatically using the following perl command: perl -pi -0777pe 's#\n\K */\*\n(.+?)\s*\*/\n#join("\n", map { $_ =~ s:^\s*\K \*://:; $_ } split("\n", $1)) . "\n"#sge' src/nvim/**/*.c Co-authored-by: zeertzjq Co-authored-by: zeertzjq --- src/nvim/buffer_defs.h | 337 ++++++-------- src/nvim/edit.c | 385 ++++++---------- src/nvim/eval.h | 52 ++- src/nvim/eval/userfunc.c | 54 +-- src/nvim/ex_cmds.c | 430 +++++++----------- src/nvim/ex_eval.c | 378 +++++++--------- src/nvim/ex_getln.c | 82 ++-- src/nvim/file_search.c | 224 ++++----- src/nvim/fileio.c | 535 ++++++++-------------- src/nvim/fold.h | 6 +- src/nvim/getchar.c | 257 ++++------- src/nvim/hardcopy.c | 442 +++++++----------- src/nvim/hardcopy.h | 12 +- src/nvim/if_cscope.c | 141 +++--- src/nvim/indent_c.c | 1121 +++++++++++++++++++--------------------------- src/nvim/main.c | 61 +-- src/nvim/mark.c | 133 ++---- src/nvim/mark_defs.h | 6 +- src/nvim/mbyte.c | 242 ++++------ src/nvim/mbyte.h | 10 +- src/nvim/memline.c | 686 +++++++++++----------------- src/nvim/memory.c | 18 +- src/nvim/menu.c | 148 ++---- src/nvim/message.c | 160 +++---- src/nvim/message.h | 8 +- src/nvim/move.c | 384 ++++++---------- src/nvim/normal.h | 8 +- src/nvim/ops.c | 166 +++---- src/nvim/ops.h | 16 +- src/nvim/option.c | 227 ++++------ src/nvim/option_defs.h | 12 +- src/nvim/path.c | 154 +++---- src/nvim/path.h | 4 +- src/nvim/search.c | 369 ++++++--------- src/nvim/strings.c | 78 ++-- src/nvim/syntax.c | 1046 +++++++++++++++--------------------------- src/nvim/tag.c | 341 +++++--------- src/nvim/window.c | 599 +++++++++---------------- 38 files changed, 3494 insertions(+), 5838 deletions(-) diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index c1ac20fd98..c26b18a7e7 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -48,25 +48,23 @@ typedef struct { #define GETFILE_SUCCESS(x) ((x) <= 0) #define MODIFIABLE(buf) (buf->b_p_ma) -/* - * Flags for w_valid. - * These are set when something in a window structure becomes invalid, except - * when the cursor is moved. Call check_cursor_moved() before testing one of - * the flags. - * These are reset when that thing has been updated and is valid again. - * - * Every function that invalidates one of these must call one of the - * invalidate_* functions. - * - * w_valid is supposed to be used only in screen.c. From other files, use the - * functions that set or reset the flags. - * - * VALID_BOTLINE VALID_BOTLINE_AP - * on on w_botline valid - * off on w_botline approximated - * off off w_botline not valid - * on off not possible - */ +// Flags for w_valid. +// These are set when something in a window structure becomes invalid, except +// when the cursor is moved. Call check_cursor_moved() before testing one of +// the flags. +// These are reset when that thing has been updated and is valid again. +// +// Every function that invalidates one of these must call one of the +// invalidate_* functions. +// +// w_valid is supposed to be used only in screen.c. From other files, use the +// functions that set or reset the flags. +// +// VALID_BOTLINE VALID_BOTLINE_AP +// on on w_botline valid +// off on w_botline approximated +// off off w_botline not valid +// on off not possible #define VALID_WROW 0x01 // w_wrow (window row) is valid #define VALID_WCOL 0x02 // w_wcol (window col) is valid #define VALID_VIRTCOL 0x04 // w_virtcol (file col) is valid @@ -112,9 +110,7 @@ typedef uint64_t disptick_T; // display tick type #include "nvim/sign_defs.h" #include "nvim/terminal.h" // for Terminal -/* - * The taggy struct is used to store the information about a :tag command. - */ +// The taggy struct is used to store the information about a :tag command. typedef struct taggy { char *tagname; // tag name fmark_T fmark; // cursor position BEFORE ":tag" @@ -126,17 +122,13 @@ typedef struct taggy { typedef struct buffblock buffblock_T; typedef struct buffheader buffheader_T; -/* - * structure used to store one block of the stuff/redo/recording buffers - */ +// structure used to store one block of the stuff/redo/recording buffers struct buffblock { buffblock_T *b_next; // pointer to next buffblock char b_str[1]; // contents (actually longer) }; -/* - * header used for the stuff buffer and the redo buffer - */ +// header used for the stuff buffer and the redo buffer struct buffheader { buffblock_T bh_first; // first (dummy) block of list buffblock_T *bh_curr; // buffblock for appending @@ -149,11 +141,9 @@ typedef struct { buffheader_T sr_old_redobuff; } save_redo_T; -/* - * Structure that contains all options that are local to a window. - * Used twice in a window: for the current buffer and for all buffers. - * Also used in wininfo_T. - */ +// Structure that contains all options that are local to a window. +// Used twice in a window: for the current buffer and for all buffers. +// Also used in wininfo_T. typedef struct { int wo_arab; #define w_p_arab w_onebuf_opt.wo_arab // 'arabic' @@ -268,16 +258,14 @@ typedef struct { #define w_p_script_ctx w_onebuf_opt.wo_script_ctx } winopt_T; -/* - * Window info stored with a buffer. - * - * Two types of info are kept for a buffer which are associated with a - * specific window: - * 1. Each window can have a different line number associated with a buffer. - * 2. The window-local options for a buffer work in a similar way. - * The window-info is kept in a list at b_wininfo. It is kept in - * most-recently-used order. - */ +// Window info stored with a buffer. +// +// Two types of info are kept for a buffer which are associated with a +// specific window: +// 1. Each window can have a different line number associated with a buffer. +// 2. The window-local options for a buffer work in a similar way. +// The window-info is kept in a list at b_wininfo. It is kept in +// most-recently-used order. struct wininfo_S { wininfo_T *wi_next; // next entry or NULL for last entry wininfo_T *wi_prev; // previous entry or NULL for first entry @@ -290,12 +278,10 @@ struct wininfo_S { int wi_changelistidx; // copy of w_changelistidx }; -/* - * Argument list: Array of file names. - * Used for the global argument list and the argument lists local to a window. - * - * TODO: move struct arglist to another header - */ +// Argument list: Array of file names. +// Used for the global argument list and the argument lists local to a window. +// +// TODO(neovim): move struct arglist to another header typedef struct arglist { garray_T al_ga; // growarray with the array of file names int al_refcount; // number of windows using this arglist @@ -321,9 +307,7 @@ typedef struct argentry { #define ARGCOUNT (ALIST(curwin)->al_ga.ga_len) #define WARGCOUNT(wp) (ALIST(wp)->al_ga.ga_len) -/* - * Used for the typeahead buffer: typebuf. - */ +// Used for the typeahead buffer: typebuf. typedef struct { uint8_t *tb_buf; // buffer for typed characters uint8_t *tb_noremap; // mapping flags for characters in tb_buf[] @@ -347,9 +331,7 @@ typedef struct { String save_inputbuf; } tasave_T; -/* - * Structure used for mappings and abbreviations. - */ +// Structure used for mappings and abbreviations. typedef struct mapblock mapblock_T; struct mapblock { mapblock_T *m_next; // next mapblock in list @@ -414,9 +396,7 @@ struct stl_item { typedef struct qf_info_S qf_info_T; -/* - * Used for :syntime: timing of executing a syntax pattern. - */ +// Used for :syntime: timing of executing a syntax pattern. typedef struct { proftime_T total; // total time used proftime_T slowest; // time of slowest call @@ -424,10 +404,8 @@ typedef struct { long match; // nr of times matched } syn_time_T; -/* - * These are items normally related to a buffer. But when using ":ownsyntax" - * a window may have its own instance. - */ +// These are items normally related to a buffer. But when using ":ownsyntax" +// a window may have its own instance. typedef struct { hashtab_T b_keywtab; // syntax keywords hash table hashtab_T b_keywtab_ic; // idem, ignore case @@ -514,13 +492,11 @@ EXTERN int curbuf_splice_pending INIT(= 0); // Maximum number of maphash blocks we will have #define MAX_MAPHASH 256 -/* - * buffer: structure that holds information about one file - * - * Several windows can share a single Buffer - * A buffer is unallocated if there is no memfile for it. - * A buffer is new if the associated file has never been loaded yet. - */ +// buffer: structure that holds information about one file +// +// Several windows can share a single Buffer +// A buffer is unallocated if there is no memfile for it. +// A buffer is new if the associated file has never been loaded yet. struct file_buffer { handle_T handle; // unique id for the buffer (buffer number) @@ -570,15 +546,13 @@ struct file_buffer { varnumber_T b_last_changedtick_pum; // b:changedtick when TextChangedP was // last triggered. - bool b_saving; /* Set to true if we are in the middle of - saving the buffer. */ + bool b_saving; // Set to true if we are in the middle of + // saving the buffer. - /* - * Changes to a buffer require updating of the display. To minimize the - * work, remember changes made and update everything at once. - */ - bool b_mod_set; /* true when there are changes since the last - time the display was updated */ + // Changes to a buffer require updating of the display. To minimize the + // work, remember changes made and update everything at once. + bool b_mod_set; // true when there are changes since the last + // time the display was updated linenr_T b_mod_top; // topmost lnum that was changed linenr_T b_mod_bot; // lnum below last changed line, AFTER the // change @@ -609,17 +583,13 @@ struct file_buffer { fmark_T b_last_insert; // where Insert mode was left fmark_T b_last_change; // position of last change: '. mark - /* - * the changelist contains old change positions - */ + // the changelist contains old change positions fmark_T b_changelist[JUMPLISTSIZE]; int b_changelistlen; // number of active entries bool b_new_change; // set by u_savecommon() - /* - * Character table, only used in charset.c for 'iskeyword' - * bitset with 4*64=256 bits: 1 bit per character 0-255. - */ + // Character table, only used in charset.c for 'iskeyword' + // bitset with 4*64=256 bits: 1 bit per character 0-255. uint64_t b_chartab[4]; // Table used for mappings local to a buffer. @@ -629,18 +599,14 @@ struct file_buffer { mapblock_T *b_first_abbr; // User commands local to the buffer. garray_T b_ucmds; - /* - * start and end of an operator, also used for '[ and '] - */ + // start and end of an operator, also used for '[ and '] pos_T b_op_start; pos_T b_op_start_orig; // used for Insstart_orig pos_T b_op_end; bool b_marks_read; // Have we read ShaDa marks yet? - /* - * The following only used in undo.c. - */ + // The following only used in undo.c. u_header_T *b_u_oldhead; // pointer to oldest header u_header_T *b_u_newhead; // pointer to newest header; may not be valid // if b_u_curhead is not NULL @@ -673,11 +639,9 @@ struct file_buffer { #define KEYMAP_LOADED 2 // 'keymap' mappings have been loaded garray_T b_kmap_ga; // the keymap table - /* - * Options local to a buffer. - * They are here because their value depends on the type of file - * or contents of the file being edited. - */ + // Options local to a buffer. + // They are here because their value depends on the type of file + // or contents of the file being edited. bool b_p_initialized; // set when options initialized LastSet b_p_script_ctx[BV_COUNT]; // SCTXs for buffer-local options @@ -834,19 +798,17 @@ struct file_buffer { ScopeDictDictItem b_bufvar; ///< Variable for "b:" Dictionary. dict_T *b_vars; ///< b: scope dictionary. - /* When a buffer is created, it starts without a swap file. b_may_swap is - * then set to indicate that a swap file may be opened later. It is reset - * if a swap file could not be opened. - */ + // When a buffer is created, it starts without a swap file. b_may_swap is + // then set to indicate that a swap file may be opened later. It is reset + // if a swap file could not be opened. bool b_may_swap; bool b_did_warn; /* Set to true if user has been warned on first change of a read-only file */ - /* Two special kinds of buffers: - * help buffer - used for help files, won't use a swap file. - * spell buffer - used for spell info, never displayed and doesn't have a - * file name. - */ + // Two special kinds of buffers: + // help buffer - used for help files, won't use a swap file. + // spell buffer - used for spell info, never displayed and doesn't have a + // file name. bool b_help; // true for help file buffer (when set b_p_bt // is "help") bool b_spell; // True for a spell file buffer, most fields @@ -906,25 +868,21 @@ struct file_buffer { int b_diff_failed; // internal diff failed for this buffer }; -/* - * Stuff for diff mode. - */ +// Stuff for diff mode. #define DB_COUNT 8 // up to four buffers can be diff'ed -/* - * Each diffblock defines where a block of lines starts in each of the buffers - * and how many lines it occupies in that buffer. When the lines are missing - * in the buffer the df_count[] is zero. This is all counted in - * buffer lines. - * There is always at least one unchanged line in between the diffs. - * Otherwise it would have been included in the diff above or below it. - * df_lnum[] + df_count[] is the lnum below the change. When in one buffer - * lines have been inserted, in the other buffer df_lnum[] is the line below - * the insertion and df_count[] is zero. When appending lines at the end of - * the buffer, df_lnum[] is one beyond the end! - * This is using a linked list, because the number of differences is expected - * to be reasonable small. The list is sorted on lnum. - */ +// Each diffblock defines where a block of lines starts in each of the buffers +// and how many lines it occupies in that buffer. When the lines are missing +// in the buffer the df_count[] is zero. This is all counted in +// buffer lines. +// There is always at least one unchanged line in between the diffs. +// Otherwise it would have been included in the diff above or below it. +// df_lnum[] + df_count[] is the lnum below the change. When in one buffer +// lines have been inserted, in the other buffer df_lnum[] is the line below +// the insertion and df_count[] is zero. When appending lines at the end of +// the buffer, df_lnum[] is one beyond the end! +// This is using a linked list, because the number of differences is expected +// to be reasonable small. The list is sorted on lnum. typedef struct diffblock_S diff_T; struct diffblock_S { diff_T *df_next; @@ -964,18 +922,16 @@ struct tabpage_S { char *tp_prevdir; ///< Previous directory. }; -/* - * Structure to cache info for displayed lines in w_lines[]. - * Each logical line has one entry. - * The entry tells how the logical line is currently displayed in the window. - * This is updated when displaying the window. - * When the display is changed (e.g., when clearing the screen) w_lines_valid - * is changed to exclude invalid entries. - * When making changes to the buffer, wl_valid is reset to indicate wl_size - * may not reflect what is actually in the buffer. When wl_valid is false, - * the entries can only be used to count the number of displayed lines used. - * wl_lnum and wl_lastlnum are invalid too. - */ +// Structure to cache info for displayed lines in w_lines[]. +// Each logical line has one entry. +// The entry tells how the logical line is currently displayed in the window. +// This is updated when displaying the window. +// When the display is changed (e.g., when clearing the screen) w_lines_valid +// is changed to exclude invalid entries. +// When making changes to the buffer, wl_valid is reset to indicate wl_size +// may not reflect what is actually in the buffer. When wl_valid is false, +// the entries can only be used to count the number of displayed lines used. +// wl_lnum and wl_lastlnum are invalid too. typedef struct w_line { linenr_T wl_lnum; // buffer line number for logical line uint16_t wl_size; // height in screen lines @@ -984,10 +940,8 @@ typedef struct w_line { linenr_T wl_lastlnum; // last buffer line number for logical line } wline_T; -/* - * Windows are kept in a tree of frames. Each frame has a column (FR_COL) - * or row (FR_ROW) layout or is a leaf, which has a window. - */ +// Windows are kept in a tree of frames. Each frame has a column (FR_COL) +// or row (FR_ROW) layout or is a leaf, which has a window. struct frame_S { char fr_layout; // FR_LEAF, FR_COL or FR_ROW int fr_width; @@ -1008,12 +962,10 @@ struct frame_S { #define FR_ROW 1 // frame with a row of windows #define FR_COL 2 // frame with a column of windows -/* - * Struct used for highlighting 'hlsearch' matches, matches defined by - * ":match" and matches defined by match functions. - * For 'hlsearch' there is one pattern for all windows. For ":match" and the - * match functions there is a different pattern for each window. - */ +// Struct used for highlighting 'hlsearch' matches, matches defined by +// ":match" and matches defined by match functions. +// For 'hlsearch' there is one pattern for all windows. For ":match" and the +// match functions there is a different pattern for each window. typedef struct { regmmatch_T rm; // points to the regexp program; contains last found // match (may continue in next line) @@ -1049,10 +1001,8 @@ struct posmatch { linenr_T botlnum; ///< bottom buffer line }; -/* - * matchitem_T provides a linked list for storing match items for ":match" and - * the match functions. - */ +// matchitem_T provides a linked list for storing match items for ":match" and +// the match functions. typedef struct matchitem matchitem_T; struct matchitem { matchitem_T *next; @@ -1221,12 +1171,10 @@ struct window_S { int eob; } w_p_fcs_chars; - /* - * "w_topline", "w_leftcol" and "w_skipcol" specify the offsets for - * displaying the buffer. - */ - linenr_T w_topline; /* buffer line number of the line at the - top of the window */ + // "w_topline", "w_leftcol" and "w_skipcol" specify the offsets for + // displaying the buffer. + linenr_T w_topline; // buffer line number of the line at the + // top of the window char w_topline_was_set; // flag set to true when topline is set, // e.g. by winrestview() int w_topfill; // number of filler lines above w_topline @@ -1279,15 +1227,12 @@ struct window_S { int w_height_outer; int w_width_outer; - /* - * === start of cached values ==== - */ - /* - * Recomputing is minimized by storing the result of computations. - * Use functions in screen.c to check if they are valid and to update. - * w_valid is a bitfield of flags, which indicate if specific values are - * valid or need to be recomputed. - */ + // === start of cached values ==== + + // Recomputing is minimized by storing the result of computations. + // Use functions in screen.c to check if they are valid and to update. + // w_valid is a bitfield of flags, which indicate if specific values are + // valid or need to be recomputed. int w_valid; pos_T w_valid_cursor; /* last known position of w_cursor, used to adjust w_valid */ @@ -1295,10 +1240,8 @@ struct window_S { bool w_viewport_invalid; - /* - * w_cline_height is the number of physical lines taken by the buffer line - * that the cursor is on. We use this to avoid extra calls to plines_win(). - */ + // w_cline_height is the number of physical lines taken by the buffer line + // that the cursor is on. We use this to avoid extra calls to plines_win(). int w_cline_height; // current size of cursor line bool w_cline_folded; // cursor line is folded @@ -1311,11 +1254,9 @@ struct window_S { // more than one screen line or when // w_leftcol is non-zero - /* - * w_wrow and w_wcol specify the cursor position in the window. - * This is related to positions in the window, not in the display or - * buffer, thus w_wrow is relative to w_winrow. - */ + // w_wrow and w_wcol specify the cursor position in the window. + // This is related to positions in the window, not in the display or + // buffer, thus w_wrow is relative to w_winrow. int w_wrow, w_wcol; // cursor position in window linenr_T w_botline; // number of the line below the bottom of @@ -1324,16 +1265,14 @@ struct window_S { int w_filler_rows; // number of filler rows at the end of the // window - /* - * Info about the lines currently in the window is remembered to avoid - * recomputing it every time. The allocated size of w_lines[] is Rows. - * Only the w_lines_valid entries are actually valid. - * When the display is up-to-date w_lines[0].wl_lnum is equal to w_topline - * and w_lines[w_lines_valid - 1].wl_lnum is equal to w_botline. - * Between changing text and updating the display w_lines[] represents - * what is currently displayed. wl_valid is reset to indicated this. - * This is used for efficient redrawing. - */ + // Info about the lines currently in the window is remembered to avoid + // recomputing it every time. The allocated size of w_lines[] is Rows. + // Only the w_lines_valid entries are actually valid. + // When the display is up-to-date w_lines[0].wl_lnum is equal to w_topline + // and w_lines[w_lines_valid - 1].wl_lnum is equal to w_botline. + // Between changing text and updating the display w_lines[] represents + // what is currently displayed. wl_valid is reset to indicated this. + // This is used for efficient redrawing. int w_lines_valid; // number of valid entries wline_T *w_lines; @@ -1346,9 +1285,7 @@ struct window_S { // column being used int w_scwidth; // width of 'signcolumn' - /* - * === end of cached values === - */ + // === end of cached values === int w_redr_type; // type of redraw to be performed on win int w_upd_rows; // number of window lines to update when @@ -1406,17 +1343,13 @@ struct window_S { ScopeDictDictItem w_winvar; ///< Variable for "w:" dictionary. dict_T *w_vars; ///< Dictionary with w: variables. - /* - * The w_prev_pcmark field is used to check whether we really did jump to - * a new line after setting the w_pcmark. If not, then we revert to - * using the previous w_pcmark. - */ + // The w_prev_pcmark field is used to check whether we really did jump to + // a new line after setting the w_pcmark. If not, then we revert to + // using the previous w_pcmark. pos_T w_pcmark; // previous context mark pos_T w_prev_pcmark; // previous w_pcmark - /* - * the jumplist contains old cursor positions - */ + // the jumplist contains old cursor positions xfmark_T w_jumplist[JUMPLISTSIZE]; int w_jumplistlen; // number of active entries int w_jumplistidx; // current position @@ -1426,12 +1359,10 @@ struct window_S { matchitem_T *w_match_head; // head of match list int w_next_match_id; // next match ID - /* - * the tagstack grows from 0 upwards: - * entry 0: older - * entry 1: newer - * entry 2: newest - */ + // the tagstack grows from 0 upwards: + // entry 0: older + // entry 1: newer + // entry 2: newest taggy_T w_tagstack[TAGSTACKSIZE]; // the tag stack int w_tagstackidx; // idx just below active entry int w_tagstacklen; // number of tags on stack @@ -1442,12 +1373,10 @@ struct window_S { bool w_floating; ///< whether the window is floating FloatConfig w_float_config; - /* - * w_fraction is the fractional row of the cursor within the window, from - * 0 at the top row to FRACTION_MULT at the last row. - * w_prev_fraction_row was the actual cursor row when w_fraction was last - * calculated. - */ + // w_fraction is the fractional row of the cursor within the window, from + // 0 at the top row to FRACTION_MULT at the last row. + // w_prev_fraction_row was the actual cursor row when w_fraction was last + // calculated. int w_fraction; int w_prev_fraction_row; diff --git a/src/nvim/edit.c b/src/nvim/edit.c index eac184c096..b85d349726 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * edit.c: functions for Insert mode - */ +// edit.c: functions for Insert mode #include #include @@ -1359,9 +1357,7 @@ void ins_redraw(bool ready) emsg_on_display = false; // may remove error message now } -/* - * Handle a CTRL-V or CTRL-Q typed in Insert mode. - */ +// Handle a CTRL-V or CTRL-Q typed in Insert mode. static void ins_ctrl_v(void) { int c; @@ -1391,10 +1387,8 @@ static void ins_ctrl_v(void) revins_legal++; } -/* - * Put a character directly onto the screen. It's not stored in a buffer. - * Used while handling CTRL-K, CTRL-V, etc. in Insert mode. - */ +// Put a character directly onto the screen. It's not stored in a buffer. +// Used while handling CTRL-K, CTRL-V, etc. in Insert mode. static int pc_status; #define PC_STATUS_UNSET 0 // pc_bytes was not set #define PC_STATUS_RIGHT 1 // right half of double-wide char @@ -1511,9 +1505,7 @@ bool prompt_curpos_editable(void) && curwin->w_cursor.col >= (int)STRLEN(prompt_text()); } -/* - * Undo the previous edit_putchar(). - */ +// Undo the previous edit_putchar(). void edit_unputchar(void) { if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled) { @@ -1528,10 +1520,8 @@ void edit_unputchar(void) } } -/* - * Called when p_dollar is set: display a '$' at the end of the changed text - * Only works when cursor is in the line that changes. - */ +// Called when p_dollar is set: display a '$' at the end of the changed text +// Only works when cursor is in the line that changes. void display_dollar(colnr_T col) { colnr_T save_col; @@ -1554,10 +1544,8 @@ void display_dollar(colnr_T col) curwin->w_cursor.col = save_col; } -/* - * Call this function before moving the cursor from the normal insert position - * in insert mode. - */ +// Call this function before moving the cursor from the normal insert position +// in insert mode. void undisplay_dollar(void) { if (dollar_vcol >= 0) { @@ -1600,11 +1588,9 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang vc = getvcol_nolist(&curwin->w_cursor); vcol = vc; - /* - * For Replace mode we need to fix the replace stack later, which is only - * possible when the cursor is in the indent. Remember the number of - * characters before the cursor if it's possible. - */ + // For Replace mode we need to fix the replace stack later, which is only + // possible when the cursor is in the indent. Remember the number of + // characters before the cursor if it's possible. start_col = curwin->w_cursor.col; // determine offset from first non-blank @@ -1614,10 +1600,8 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang insstart_less = curwin->w_cursor.col; - /* - * If the cursor is in the indent, compute how many screen columns the - * cursor is to the left of the first non-blank. - */ + // If the cursor is in the indent, compute how many screen columns the + // cursor is to the left of the first non-blank. if (new_cursor_col < 0) { vcol = get_indent() - vcol; } @@ -1626,9 +1610,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang start_col = -1; } - /* - * Set the new indent. The cursor will be put on the first non-blank. - */ + // Set the new indent. The cursor will be put on the first non-blank. if (type == INDENT_SET) { (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); } else { @@ -1643,20 +1625,16 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang } insstart_less -= curwin->w_cursor.col; - /* - * Try to put cursor on same character. - * If the cursor is at or after the first non-blank in the line, - * compute the cursor column relative to the column of the first - * non-blank character. - * If we are not in insert mode, leave the cursor on the first non-blank. - * If the cursor is before the first non-blank, position it relative - * to the first non-blank, counted in screen columns. - */ + // Try to put cursor on same character. + // If the cursor is at or after the first non-blank in the line, + // compute the cursor column relative to the column of the first + // non-blank character. + // If we are not in insert mode, leave the cursor on the first non-blank. + // If the cursor is before the first non-blank, position it relative + // to the first non-blank, counted in screen columns. if (new_cursor_col >= 0) { - /* - * When changing the indent while the cursor is touching it, reset - * Insstart_col to 0. - */ + // When changing the indent while the cursor is touching it, reset + // Insstart_col to 0. if (new_cursor_col == 0) { insstart_less = MAXCOL; } @@ -1687,10 +1665,8 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang new_cursor_col = (int)(cts.cts_ptr - cts.cts_line); clear_chartabsize_arg(&cts); - /* - * May need to insert spaces to be able to position the cursor on - * the right screen column. - */ + // May need to insert spaces to be able to position the cursor on + // the right screen column. if (vcol != (int)curwin->w_virtcol) { curwin->w_cursor.col = (colnr_T)new_cursor_col; size_t i = (size_t)(curwin->w_virtcol - vcol); @@ -1701,10 +1677,8 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang xfree(ptr); } - /* - * When changing the indent while the cursor is in it, reset - * Insstart_col to 0. - */ + // When changing the indent while the cursor is in it, reset + // Insstart_col to 0. insstart_less = MAXCOL; } @@ -1718,9 +1692,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang curwin->w_set_curswant = true; changed_cline_bef_curs(); - /* - * May have to adjust the start of the insert. - */ + // May have to adjust the start of the insert. if (State & MODE_INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { if ((int)Insstart.col <= insstart_less) { @@ -1998,15 +1970,13 @@ static void insert_special(int c, int allow_modmask, int ctrlv) } } -/* - * Special characters in this context are those that need processing other - * than the simple insertion that can be performed here. This includes ESC - * which terminates the insert, and CR/NL which need special processing to - * open up a new line. This routine tries to optimize insertions performed by - * the "redo", "undo" or "put" commands, so it needs to know when it should - * stop and defer processing to the "normal" mechanism. - * '0' and '^' are special, because they can be followed by CTRL-D. - */ +// Special characters in this context are those that need processing other +// than the simple insertion that can be performed here. This includes ESC +// which terminates the insert, and CR/NL which need special processing to +// open up a new line. This routine tries to optimize insertions performed by +// the "redo", "undo" or "put" commands, so it needs to know when it should +// stop and defer processing to the "normal" mechanism. +// '0' and '^' are special, because they can be followed by CTRL-D. #define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^') /// @@ -2207,9 +2177,7 @@ void insertchar(int c, int flags, int second_indent) } } -/* - * Put a character in the redo buffer, for when just after a CTRL-V. - */ +// Put a character in the redo buffer, for when just after a CTRL-V. static void redo_literal(int c) { char buf[10]; @@ -2259,10 +2227,8 @@ static void start_arrow_common(pos_T *end_insert_pos, bool end_change) check_spell_redraw(); } -/* - * If we skipped highlighting word at cursor, do it now. - * It may be skipped again, thus reset spell_redraw_lnum first. - */ +// If we skipped highlighting word at cursor, do it now. +// It may be skipped again, thus reset spell_redraw_lnum first. static void check_spell_redraw(void) { if (spell_redraw_lnum != 0) { @@ -2273,11 +2239,9 @@ static void check_spell_redraw(void) } } -/* - * stop_arrow() is called before a change is made in insert mode. - * If an arrow key has been used, start a new insertion. - * Returns FAIL if undo is impossible, shouldn't insert then. - */ +// stop_arrow() is called before a change is made in insert mode. +// If an arrow key has been used, start a new insertion. +// Returns FAIL if undo is impossible, shouldn't insert then. int stop_arrow(void) { if (arrow_used) { @@ -2327,11 +2291,9 @@ static void stop_insert(pos_T *end_insert_pos, int esc, int nomove) stop_redo_ins(); replace_flush(); // abandon replace stack - /* - * Save the inserted text for later redo with ^@ and CTRL-A. - * Don't do it when "restart_edit" was set and nothing was inserted, - * otherwise CTRL-O w and then will clear "last_insert". - */ + // Save the inserted text for later redo with ^@ and CTRL-A. + // Don't do it when "restart_edit" was set and nothing was inserted, + // otherwise CTRL-O w and then will clear "last_insert". ptr = get_inserted(); if (did_restart_edit == 0 || (ptr != NULL && (int)STRLEN(ptr) > new_insert_skip)) { @@ -2438,10 +2400,8 @@ static void stop_insert(pos_T *end_insert_pos, int esc, int nomove) } } -/* - * Set the last inserted text to a single character. - * Used for the replace command. - */ +// Set the last inserted text to a single character. +// Used for the replace command. void set_last_insert(int c) { char_u *s; @@ -2466,13 +2426,11 @@ void free_last_insert(void) } #endif -/* - * move cursor to start of line - * if flags & BL_WHITE move to first non-white - * if flags & BL_SOL move to first non-white if startofline is set, - * otherwise keep "curswant" column - * if flags & BL_FIX don't leave the cursor on a NUL. - */ +// move cursor to start of line +// if flags & BL_WHITE move to first non-white +// if flags & BL_SOL move to first non-white if startofline is set, +// otherwise keep "curswant" column +// if flags & BL_FIX don't leave the cursor on a NUL. void beginline(int flags) { if ((flags & BL_SOL) && !p_sol) { @@ -2493,13 +2451,11 @@ void beginline(int flags) } } -/* - * oneright oneleft cursor_down cursor_up - * - * Move one char {right,left,down,up}. - * Doesn't move onto the NUL past the end of the line, unless it is allowed. - * Return OK when successful, FAIL when we hit a line of file boundary. - */ +// oneright oneleft cursor_down cursor_up +// +// Move one char {right,left,down,up}. +// Doesn't move onto the NUL past the end of the line, unless it is allowed. +// Return OK when successful, FAIL when we hit a line of file boundary. int oneright(void) { @@ -2600,9 +2556,8 @@ int cursor_up(long n, int upd_topline) if (n >= lnum) { lnum = 1; } else if (hasAnyFolding(curwin)) { - /* - * Count each sequence of folded lines as one logical line. - */ + // Count each sequence of folded lines as one logical line. + // go to the start of the current fold (void)hasFolding(lnum, &lnum, NULL); @@ -2761,10 +2716,8 @@ char_u *get_last_insert(void) return last_insert + last_insert_skip; } -/* - * Get last inserted string, and remove trailing . - * Returns pointer to allocated memory (must be freed) or NULL. - */ +// Get last inserted string, and remove trailing . +// Returns pointer to allocated memory (must be freed) or NULL. char_u *get_last_insert_save(void) { char_u *s; @@ -2803,20 +2756,18 @@ static bool echeck_abbr(int c) curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); } -/* - * replace-stack functions - * - * When replacing characters, the replaced characters are remembered for each - * new character. This is used to re-insert the old text when backspacing. - * - * There is a NUL headed list of characters for each character that is - * currently in the file after the insertion point. When BS is used, one NUL - * headed list is put back for the deleted character. - * - * For a newline, there are two NUL headed lists. One contains the characters - * that the NL replaced. The extra one stores the characters after the cursor - * that were deleted (always white space). - */ +// replace-stack functions +// +// When replacing characters, the replaced characters are remembered for each +// new character. This is used to re-insert the old text when backspacing. +// +// There is a NUL headed list of characters for each character that is +// currently in the file after the insertion point. When BS is used, one NUL +// headed list is put back for the deleted character. +// +// For a newline, there are two NUL headed lists. One contains the characters +// that the NL replaced. The extra one stores the characters after the cursor +// that were deleted (always white space). static char_u *replace_stack = NULL; static ssize_t replace_stack_nr = 0; // next entry in replace stack @@ -2901,10 +2852,8 @@ static void replace_pop_ins(void) State = oldState; } -/* - * Insert bytes popped from the replace stack. "cc" is the first byte. If it - * indicates a multi-byte char, pop the other bytes too. - */ +// Insert bytes popped from the replace stack. "cc" is the first byte. If it +// indicates a multi-byte char, pop the other bytes too. static void mb_replace_pop_ins(int cc) { int n; @@ -2951,10 +2900,8 @@ static void mb_replace_pop_ins(int cc) } } -/* - * make the replace stack empty - * (called when exiting replace mode) - */ +// make the replace stack empty +// (called when exiting replace mode) static void replace_flush(void) { XFREE_CLEAR(replace_stack); @@ -2962,15 +2909,13 @@ static void replace_flush(void) replace_stack_nr = 0; } -/* - * Handle doing a BS for one character. - * cc < 0: replace stack empty, just move cursor - * cc == 0: character was inserted, delete it - * cc > 0: character was replaced, put cc (first byte of original char) back - * and check for more characters to be put back - * When "limit_col" is >= 0, don't delete before this column. Matters when - * using composing characters, use del_char_after_col() instead of del_char(). - */ +// Handle doing a BS for one character. +// cc < 0: replace stack empty, just move cursor +// cc == 0: character was inserted, delete it +// cc > 0: character was replaced, put cc (first byte of original char) back +// and check for more characters to be put back +// When "limit_col" is >= 0, don't delete before this column. Matters when +// using composing characters, use del_char_after_col() instead of del_char(). static void replace_do_bs(int limit_col) { int cc; @@ -3033,12 +2978,10 @@ bool cindent_on(void) return !p_paste && (curbuf->b_p_cin || *curbuf->b_p_inde != NUL); } -/* - * Re-indent the current line, based on the current contents of it and the - * surrounding lines. Fixing the cursor position seems really easy -- I'm very - * confused what all the part that handles Control-T is doing that I'm not. - * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent. - */ +// Re-indent the current line, based on the current contents of it and the +// surrounding lines. Fixing the cursor position seems really easy -- I'm very +// confused what all the part that handles Control-T is doing that I'm not. +// "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent. void fixthisline(IndentGetter get_the_indent) { int amount = get_the_indent(); @@ -3096,10 +3039,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) look = (char_u *)curbuf->b_p_cink; // 'indentexpr' empty: use 'cinkeys' } while (*look) { - /* - * Find out if we want to try a match with this key, depending on - * 'when' and a '*' or '!' before the key. - */ + // Find out if we want to try a match with this key, depending on + // 'when' and a '*' or '!' before the key. switch (when) { case '*': try_match = (*look == '*'); break; @@ -3286,9 +3227,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) return false; } -/* - * Map Hebrew keyboard when in hkmap mode. - */ +// Map Hebrew keyboard when in hkmap mode. int hkmap(int c) FUNC_ATTR_PURE { @@ -3390,9 +3329,7 @@ static void ins_reg(void) int literally = 0; int vis_active = VIsual_active; - /* - * If we are going to wait for a character, show a '"'. - */ + // If we are going to wait for a character, show a '"'. pc_status = PC_STATUS_UNSET; if (redrawing() && !char_avail()) { // may need to redraw when no more chars available now @@ -3474,9 +3411,7 @@ static void ins_reg(void) } } -/* - * CTRL-G commands in Insert mode. - */ +// CTRL-G commands in Insert mode. static void ins_ctrl_g(void) { int c; @@ -3530,9 +3465,7 @@ static void ins_ctrl_g(void) } } -/* - * CTRL-^ in Insert mode. - */ +// CTRL-^ in Insert mode. static void ins_ctrl_hat(void) { if (map_to_exists_mode("", MODE_LANGMAP, false)) { @@ -3576,10 +3509,8 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) AppendToRedobuff(ESC_STR); } - /* - * Repeating insert may take a long time. Check for - * interrupt now and then. - */ + // Repeating insert may take a long time. Check for + // interrupt now and then. if (*count > 0) { line_breakcheck(); if (got_int) { @@ -3622,10 +3553,8 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) RESET_FMARK(&curbuf->b_last_insert, curwin->w_cursor, curbuf->b_fnum, view); } - /* - * The cursor should end up on the last inserted character. - * Don't do it for CTRL-O, unless past the end of the line. - */ + // The cursor should end up on the last inserted character. + // Don't do it for CTRL-O, unless past the end of the line. if (!nomove && (curwin->w_cursor.col != 0 || curwin->w_cursor.coladd > 0) && (restart_edit == NUL || (gchar_cursor() == NUL && !VIsual_active)) @@ -3663,10 +3592,8 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) return true; } -/* - * Toggle language: hkmap and revins_on. - * Move to end of reverse inserted text. - */ +// Toggle language: hkmap and revins_on. +// Move to end of reverse inserted text. static void ins_ctrl_(void) { if (revins_on && revins_chars && revins_scol >= 0) { @@ -3733,9 +3660,7 @@ static bool ins_start_select(int c) return false; } -/* - * key in Insert mode: toggle insert/replace mode. - */ +// key in Insert mode: toggle insert/replace mode. static void ins_insert(int replaceState) { set_vim_var_string(VV_INSERTMODE, ((State & REPLACE_FLAG) ? "i" : @@ -3753,9 +3678,7 @@ static void ins_insert(int replaceState) ui_cursor_shape(); // may show different cursor shape } -/* - * Pressed CTRL-O in Insert mode. - */ +// Pressed CTRL-O in Insert mode. static void ins_ctrl_o(void) { if (State & VREPLACE_FLAG) { @@ -3772,13 +3695,11 @@ static void ins_ctrl_o(void) } } -/* - * If the cursor is on an indent, ^T/^D insert/delete one - * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>". - * Always round the indent to 'shiftwidth', this is compatible - * with vi. But vi only supports ^T and ^D after an - * autoindent, we support it everywhere. - */ +// If the cursor is on an indent, ^T/^D insert/delete one +// shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>". +// Always round the indent to 'shiftwidth', this is compatible +// with vi. But vi only supports ^T and ^D after an +// autoindent, we support it everywhere. static void ins_shift(int c, int lastc) { if (stop_arrow() == FAIL) { @@ -3786,9 +3707,7 @@ static void ins_shift(int c, int lastc) } AppendCharToRedobuff(c); - /* - * 0^D and ^^D: remove all indent. - */ + // 0^D and ^^D: remove all indent. if (c == Ctrl_D && (lastc == '0' || lastc == '^') && curwin->w_cursor.col > 0) { curwin->w_cursor.col--; @@ -3844,9 +3763,7 @@ static void ins_del(void) AppendCharToRedobuff(K_DEL); } -/* - * Delete one character for ins_bs(). - */ +// Delete one character for ins_bs(). static void ins_bs_one(colnr_T *vcolp) { dec_cursor(); @@ -3941,11 +3858,9 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) Insstart.lnum--; Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum)); } - /* - * In replace mode: - * cc < 0: NL was inserted, delete it - * cc >= 0: NL was replaced, put original characters back - */ + // In replace mode: + // cc < 0: NL was inserted, delete it + // cc >= 0: NL was replaced, put original characters back cc = -1; if (State & REPLACE_FLAG) { cc = replace_pop(); // returns -1 if NL was inserted @@ -4025,9 +3940,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) curwin->w_cursor.col = save_col; } - /* - * Handle deleting one 'shiftwidth' or 'softtabstop'. - */ + // Handle deleting one 'shiftwidth' or 'softtabstop'. if (mode == BACKSPACE_CHAR && ((p_sta && in_indent) || ((get_sts_value() != 0 @@ -4589,9 +4502,7 @@ static bool ins_tab(void) } } - /* - * When 'expandtab' not set: Replace spaces by TABs where possible. - */ + // When 'expandtab' not set: Replace spaces by TABs where possible. if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_array) > 0 || get_sts_value() > 0 || (p_sta && ind))) { @@ -4742,11 +4653,9 @@ bool ins_eol(int c) } undisplay_dollar(); - /* - * Strange Vi behaviour: In Replace mode, typing a NL will not delete the - * character under the cursor. Only push a NUL on the replace stack, - * nothing to put back when the NL is deleted. - */ + // Strange Vi behaviour: In Replace mode, typing a NL will not delete the + // character under the cursor. Only push a NUL on the replace stack, + // nothing to put back when the NL is deleted. if ((State & REPLACE_FLAG) && !(State & VREPLACE_FLAG)) { replace_push(NUL); @@ -4780,11 +4689,9 @@ bool ins_eol(int c) return i; } -/* - * Handle digraph in insert mode. - * Returns character still to be inserted, or NUL when nothing remaining to be - * done. - */ +// Handle digraph in insert mode. +// Returns character still to be inserted, or NUL when nothing remaining to be +// done. static int ins_digraph(void) { int c; @@ -4853,10 +4760,8 @@ static int ins_digraph(void) return NUL; } -/* - * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line. - * Returns the char to be inserted, or NUL if none found. - */ +// Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line. +// Returns the char to be inserted, or NUL if none found. int ins_copychar(linenr_T lnum) { int c; @@ -4894,9 +4799,7 @@ int ins_copychar(linenr_T lnum) return c; } -/* - * CTRL-Y or CTRL-E typed in Insert mode. - */ +// CTRL-Y or CTRL-E typed in Insert mode. static int ins_ctrl_ey(int tc) { int c = tc; @@ -4933,10 +4836,8 @@ static int ins_ctrl_ey(int tc) return c; } -/* - * Try to do some very smart auto-indenting. - * Used when inserting a "normal" character. - */ +// Try to do some very smart auto-indenting. +// Used when inserting a "normal" character. static void ins_try_si(int c) { pos_T *pos, old_pos; @@ -4944,20 +4845,16 @@ static void ins_try_si(int c) int i; bool temp; - /* - * do some very smart indenting when entering '{' or '}' - */ + // do some very smart indenting when entering '{' or '}' if (((did_si || can_si_back) && c == '{') || (can_si && c == '}' && inindent(0))) { // for '}' set indent equal to indent of line containing matching '{' if (c == '}' && (pos = findmatch(NULL, '{')) != NULL) { old_pos = curwin->w_cursor; - /* - * If the matching '{' has a ')' immediately before it (ignoring - * white-space), then line up with the start of the line - * containing the matching '(' if there is one. This handles the - * case where an "if (..\n..) {" statement continues over multiple - * lines -- webb - */ + // If the matching '{' has a ')' immediately before it (ignoring + // white-space), then line up with the start of the line + // containing the matching '(' if there is one. This handles the + // case where an "if (..\n..) {" statement continues over multiple + // lines -- webb ptr = (char_u *)ml_get(pos->lnum); i = pos->col; if (i > 0) { // skip blanks before '{' @@ -5001,9 +4898,7 @@ static void ins_try_si(int c) } } - /* - * set indent of '#' always to 0 - */ + // set indent of '#' always to 0 if (curwin->w_cursor.col > 0 && can_si && c == '#' && inindent(0)) { // remember current indent for next line old_indent = get_indent(); @@ -5016,10 +4911,8 @@ static void ins_try_si(int c) } } -/* - * Get the value that w_virtcol would have when 'list' is off. - * Unless 'cpo' contains the 'L' flag. - */ +// Get the value that w_virtcol would have when 'list' is off. +// Unless 'cpo' contains the 'L' flag. colnr_T get_nolist_virtcol(void) { // check validity of cursor in current buffer @@ -5034,12 +4927,10 @@ colnr_T get_nolist_virtcol(void) return curwin->w_virtcol; } -/* - * Handle the InsertCharPre autocommand. - * "c" is the character that was typed. - * Return a pointer to allocated memory with the replacement string. - * Return NULL to continue inserting "c". - */ +// Handle the InsertCharPre autocommand. +// "c" is the character that was typed. +// Return a pointer to allocated memory with the replacement string. +// Return NULL to continue inserting "c". static char_u *do_insert_char_pre(int c) { char buf[MB_MAXBYTES + 1]; diff --git a/src/nvim/eval.h b/src/nvim/eval.h index b0cb5fd8c1..afebdf5acb 100644 --- a/src/nvim/eval.h +++ b/src/nvim/eval.h @@ -11,33 +11,31 @@ #define COPYID_INC 2 #define COPYID_MASK (~0x1) -/* - * Structure returned by get_lval() and used by set_var_lval(). - * For a plain name: - * "name" points to the variable name. - * "exp_name" is NULL. - * "tv" is NULL - * For a magic braces name: - * "name" points to the expanded variable name. - * "exp_name" is non-NULL, to be freed later. - * "tv" is NULL - * For an index in a list: - * "name" points to the (expanded) variable name. - * "exp_name" NULL or non-NULL, to be freed later. - * "tv" points to the (first) list item value - * "li" points to the (first) list item - * "range", "n1", "n2" and "empty2" indicate what items are used. - * For an existing Dict item: - * "name" points to the (expanded) variable name. - * "exp_name" NULL or non-NULL, to be freed later. - * "tv" points to the dict item value - * "newkey" is NULL - * For a non-existing Dict item: - * "name" points to the (expanded) variable name. - * "exp_name" NULL or non-NULL, to be freed later. - * "tv" points to the Dictionary typval_T - * "newkey" is the key for the new item. - */ +// Structure returned by get_lval() and used by set_var_lval(). +// For a plain name: +// "name" points to the variable name. +// "exp_name" is NULL. +// "tv" is NULL +// For a magic braces name: +// "name" points to the expanded variable name. +// "exp_name" is non-NULL, to be freed later. +// "tv" is NULL +// For an index in a list: +// "name" points to the (expanded) variable name. +// "exp_name" NULL or non-NULL, to be freed later. +// "tv" points to the (first) list item value +// "li" points to the (first) list item +// "range", "n1", "n2" and "empty2" indicate what items are used. +// For an existing Dict item: +// "name" points to the (expanded) variable name. +// "exp_name" NULL or non-NULL, to be freed later. +// "tv" points to the dict item value +// "newkey" is NULL +// For a non-existing Dict item: +// "name" points to the (expanded) variable name. +// "exp_name" NULL or non-NULL, to be freed later. +// "tv" points to the Dictionary typval_T +// "newkey" is the key for the new item. typedef struct lval_S { const char *ll_name; ///< Start of variable name (can be NULL). size_t ll_name_len; ///< Length of the .ll_name. diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index 6611133ea4..3ab66c319f 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -1576,16 +1576,14 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t // Find the function name in the table, call its implementation. error = call_internal_func((char_u *)fname, argcount, argvars, rettv); } - /* - * The function call (or "FuncUndefined" autocommand sequence) might - * have been aborted by an error, an interrupt, or an explicitly thrown - * exception that has not been caught so far. This situation can be - * tested for by calling aborting(). For an error in an internal - * function or for the "E132" error in call_user_func(), however, the - * throw point at which the "force_abort" flag (temporarily reset by - * emsg()) is normally updated has not been reached yet. We need to - * update that flag first to make aborting() reliable. - */ + // The function call (or "FuncUndefined" autocommand sequence) might + // have been aborted by an error, an interrupt, or an explicitly thrown + // exception that has not been caught so far. This situation can be + // tested for by calling aborting(). For an error in an internal + // function or for the "E132" error in call_user_func(), however, the + // throw point at which the "force_abort" flag (temporarily reset by + // emsg()) is normally updated has not been reached yet. We need to + // update that flag first to make aborting() reliable. update_force_abort(); } if (error == ERROR_NONE) { @@ -1720,11 +1718,9 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { - /* - * Report an invalid expression in braces, unless the expression - * evaluation has been cancelled due to an aborting error, an - * interrupt, or an exception. - */ + // Report an invalid expression in braces, unless the expression + // evaluation has been cancelled due to an aborting error, an + // interrupt, or an exception. if (!aborting()) { if (end != NULL) { semsg(_(e_invarg2), start); @@ -1923,9 +1919,7 @@ void ex_function(exarg_T *eap) bool show_block = false; bool do_concat = true; - /* - * ":function" without argument: list functions. - */ + // ":function" without argument: list functions. if (ends_excmd(*eap->arg)) { if (!eap->skip) { todo = (int)func_hashtab.ht_used; @@ -1946,9 +1940,7 @@ void ex_function(exarg_T *eap) return; } - /* - * ":function /pat": list functions matching pattern. - */ + // ":function /pat": list functions matching pattern. if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', true, NULL); if (!eap->skip) { @@ -2000,11 +1992,9 @@ void ex_function(exarg_T *eap) name = (char *)trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { - /* - * Return on an invalid expression in braces, unless the expression - * evaluation has been cancelled due to an aborting error, an - * interrupt, or an exception. - */ + // Return on an invalid expression in braces, unless the expression + // evaluation has been cancelled due to an aborting error, an + // interrupt, or an exception. if (!aborting()) { if (fudi.fd_newkey != NULL) { semsg(_(e_dictkey), fudi.fd_newkey); @@ -2069,9 +2059,7 @@ void ex_function(exarg_T *eap) goto ret_free; } - /* - * ":function name(arg1, arg2)" Define function. - */ + // ":function name(arg1, arg2)" Define function. p = skipwhite(p); if (*p != '(') { if (!eap->skip) { @@ -2154,9 +2142,7 @@ void ex_function(exarg_T *eap) semsg(_(e_trailing_arg), p); } - /* - * Read the body of the function, until ":endfunction" is found. - */ + // Read the body of the function, until ":endfunction" is found. if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we @@ -2410,9 +2396,7 @@ void ex_function(exarg_T *eap) goto erret; } - /* - * If there are no errors, add the function - */ + // If there are no errors, add the function if (fudi.fd_dict == NULL) { v = find_var((const char *)name, STRLEN(name), &ht, false); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 126129b24d..8f256728e3 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * ex_cmds.c: some functions for command line commands - */ +// ex_cmds.c: some functions for command line commands #include #include @@ -249,11 +247,9 @@ void ex_align(exarg_T *eap) indent = width; } } else { - /* - * if 'textwidth' set, use it - * else if 'wrapmargin' set, use it - * if invalid value, use 80 - */ + // if 'textwidth' set, use it + // else if 'wrapmargin' set, use it + // if invalid value, use 80 if (width <= 0) { width = (int)curbuf->b_p_tw; } @@ -287,18 +283,14 @@ void ex_align(exarg_T *eap) } else { new_indent = width - len; // right align - /* - * Make sure that embedded TABs don't make the text go too far - * to the right. - */ + // Make sure that embedded TABs don't make the text go too far + // to the right. if (has_tab) { while (new_indent > 0) { (void)set_indent(new_indent, 0); if (linelen(NULL) <= width) { - /* - * Now try to move the line as much as possible to - * the right. Stop when it moves too far. - */ + // Now try to move the line as much as possible to + // the right. Stop when it moves too far. do { (void)set_indent(++new_indent, 0); } while (linelen(NULL) <= width); @@ -933,10 +925,8 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) num_lines = line2 - line1 + 1; - /* - * First we copy the old text to its new location -- webb - * Also copy the flag that ":global" command uses. - */ + // First we copy the old text to its new location -- webb + // Also copy the flag that ":global" command uses. if (u_save(dest, dest + 1) == FAIL) { return FAIL; } @@ -949,21 +939,19 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) } } - /* - * Now we must be careful adjusting our marks so that we don't overlap our - * mark_adjust() calls. - * - * We adjust the marks within the old text so that they refer to the - * last lines of the file (temporarily), because we know no other marks - * will be set there since these line numbers did not exist until we added - * our new lines. - * - * Then we adjust the marks on lines between the old and new text positions - * (either forwards or backwards). - * - * And Finally we adjust the marks we put at the end of the file back to - * their final destination at the new text position -- webb - */ + // Now we must be careful adjusting our marks so that we don't overlap our + // mark_adjust() calls. + // + // We adjust the marks within the old text so that they refer to the + // last lines of the file (temporarily), because we know no other marks + // will be set there since these line numbers did not exist until we added + // our new lines. + // + // Then we adjust the marks on lines between the old and new text positions + // (either forwards or backwards). + // + // And Finally we adjust the marks we put at the end of the file back to + // their final destination at the new text position -- webb last_line = curbuf->b_ml.ml_line_count; mark_adjust_nofold(line1, line2, last_line - line2, 0L, kExtmarkNOOP); @@ -1011,9 +999,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) // send update regarding the new lines that were added buf_updates_send_changes(curbuf, dest + 1, num_lines, 0); - /* - * Now we delete the original text -- webb - */ + // Now we delete the original text -- webb if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL) { return FAIL; } @@ -1030,9 +1016,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) dest + line_off, 0, dest_byte + byte_off, kExtmarkUndo); - /* - * Leave the cursor on the last of the moved lines. - */ + // Leave the cursor on the last of the moved lines. if (dest >= line1) { curwin->w_cursor.lnum = dest; } else { @@ -1069,17 +1053,15 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) curbuf->b_op_start.col = curbuf->b_op_end.col = 0; } - /* - * there are three situations: - * 1. destination is above line1 - * 2. destination is between line1 and line2 - * 3. destination is below line2 - * - * n = destination (when starting) - * curwin->w_cursor.lnum = destination (while copying) - * line1 = start of source (while copying) - * line2 = end of source (while copying) - */ + // there are three situations: + // 1. destination is above line1 + // 2. destination is between line1 and line2 + // 3. destination is below line2 + // + // n = destination (when starting) + // curwin->w_cursor.lnum = destination (while copying) + // line1 = start of source (while copying) + // line2 = end of source (while copying) if (u_save(n, n + 1) == FAIL) { return; } @@ -1155,10 +1137,8 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out msg_scroll = scroll_save; } - /* - * Try to find an embedded bang, like in :! ! [args] - * (:!! is indicated by the 'forceit' variable) - */ + // Try to find an embedded bang, like in :! ! [args] + // (:!! is indicated by the 'forceit' variable) bool ins_prevcmd = forceit; trailarg = arg; do { @@ -1187,10 +1167,8 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out xfree(newcmd); newcmd = t; - /* - * Scan the rest of the argument for '!', which is replaced by the - * previous command. "\!" is replaced by "!" (this is vi compatible). - */ + // Scan the rest of the argument for '!', which is replaced by the + // previous command. "\!" is replaced by "!" (this is vi compatible). trailarg = NULL; while (*p) { if (*p == '!') { @@ -1221,9 +1199,7 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out AppendToRedobuff("\n"); bangredo = false; } - /* - * Add quotes around the command, for shells that need them. - */ + // Add quotes around the command, for shells that need them. if (*p_shq != NUL) { newcmd = xmalloc(STRLEN(prevcmd) + 2 * STRLEN(p_shq) + 1); STRCPY(newcmd, p_shq); @@ -1298,18 +1274,16 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b changed_line_abv_curs(); invalidate_botline(); - /* - * When using temp files: - * 1. * Form temp file names - * 2. * Write the lines to a temp file - * 3. Run the filter command on the temp file - * 4. * Read the output of the command into the buffer - * 5. * Delete the original lines to be filtered - * 6. * Remove the temp files - * - * When writing the input with a pipe or when catching the output with a - * pipe only need to do 3. - */ + // When using temp files: + // 1. * Form temp file names + // 2. * Write the lines to a temp file + // 3. Run the filter command on the temp file + // 4. * Read the output of the command into the buffer + // 5. * Delete the original lines to be filtered + // 6. * Remove the temp files + // + // When writing the input with a pipe or when catching the output with a + // pipe only need to do 3. if (do_out) { shell_flags |= kShellOptDoOut; @@ -1337,10 +1311,8 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b goto filterend; } - /* - * The writing and reading of temp files will not be shown. - * Vi also doesn't do this and the messages are not very informative. - */ + // The writing and reading of temp files will not be shown. + // Vi also doesn't do this and the messages are not very informative. no_wait_return++; // don't call wait_return() while busy if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap, false, false, false, true) == FAIL) { @@ -1428,10 +1400,8 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b } } - /* - * Put cursor on first filtered line for ":range!cmd". - * Adjust '[ and '] (set by buf_write()). - */ + // Put cursor on first filtered line for ":range!cmd". + // Adjust '[ and '] (set by buf_write()). curwin->w_cursor.lnum = line1; del_lines(linecount, true); curbuf->b_op_start.lnum -= linecount; // adjust '[ @@ -1440,9 +1410,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b // for next write foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum); } else { - /* - * Put cursor on last new line for ":r !cmd". - */ + // Put cursor on last new line for ":r !cmd". linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1; curwin->w_cursor.lnum = curbuf->b_op_end.lnum; } @@ -1504,10 +1472,8 @@ void do_shell(char *cmd, int flags) return; } - /* - * For autocommands we want to get the output on the current screen, to - * avoid having to type return below. - */ + // For autocommands we want to get the output on the current screen, to + // avoid having to type return below. msg_putchar('\r'); // put cursor at start of line msg_putchar('\n'); // may shift screen one line up @@ -1740,13 +1706,11 @@ int rename_buffer(char *new_fname) if (aborting()) { // autocmds may abort script processing return FAIL; } - /* - * The name of the current buffer will be changed. - * A new (unlisted) buffer entry needs to be made to hold the old file - * name, which will become the alternate file name. - * But don't set the alternate file name if the buffer didn't have a - * name. - */ + // The name of the current buffer will be changed. + // A new (unlisted) buffer entry needs to be made to hold the old file + // name, which will become the alternate file name. + // But don't set the alternate file name if the buffer didn't have a + // name. fname = curbuf->b_ffname; sfname = curbuf->b_sfname; xfname = curbuf->b_fname; @@ -1860,9 +1824,7 @@ int do_write(exarg_T *eap) other = otherfile(ffname); } - /* - * If we have a new file, put its name in the list of alternate file names. - */ + // If we have a new file, put its name in the list of alternate file names. if (other) { if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL || eap->cmdidx == CMD_saveas) { @@ -2113,13 +2075,11 @@ void do_wqall(exarg_T *eap) } else if (!bufIsChanged(buf) || bt_dontwrite(buf)) { continue; } - /* - * Check if there is a reason the buffer cannot be written: - * 1. if the 'write' option is set - * 2. if there is no file name (even after browsing) - * 3. if the 'readonly' is set (even after a dialog) - * 4. if overwriting is allowed (even after a dialog) - */ + // Check if there is a reason the buffer cannot be written: + // 1. if the 'write' option is set + // 2. if there is no file name (even after browsing) + // 3. if the 'readonly' is set (even after a dialog) + // 4. if overwriting is allowed (even after a dialog) if (not_writing()) { error++; break; @@ -2405,10 +2365,8 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum goto theend; } - /* - * End Visual mode before switching to another buffer, so the text can be - * copied into the GUI selection buffer. - */ + // End Visual mode before switching to another buffer, so the text can be + // copied into the GUI selection buffer. reset_VIsual(); if ((command != NULL || newlnum > (linenr_T)0) @@ -2426,10 +2384,8 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum xfree(p); } - /* - * If we are starting to edit another file, open a (new) buffer. - * Otherwise we re-use the current buffer. - */ + // If we are starting to edit another file, open a (new) buffer. + // Otherwise we re-use the current buffer. if (other_file) { const int prev_alt_fnum = curwin->w_alt_fnum; @@ -2507,12 +2463,10 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum solcol = pos->col; } - /* - * Make the (new) buffer the one used by the current window. - * If the old buffer becomes unused, free it if ECMD_HIDE is false. - * If the current buffer was empty and has no file name, curbuf - * is returned by buflist_new(), nothing to do here. - */ + // Make the (new) buffer the one used by the current window. + // If the old buffer becomes unused, free it if ECMD_HIDE is false. + // If the current buffer was empty and has no file name, curbuf + // is returned by buflist_new(), nothing to do here. if (buf != curbuf) { const int save_cmdwin_type = cmdwin_type; @@ -2663,13 +2617,11 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum // highlighting to work in the other file. did_filetype = false; - /* - * other_file oldbuf - * false false re-edit same file, buffer is re-used - * false true re-edit same file, nothing changes - * true false start editing new file, new buffer - * true true start editing in existing buffer (nothing to do) - */ + // other_file oldbuf + // false false re-edit same file, buffer is re-used + // false true re-edit same file, nothing changes + // true false start editing new file, new buffer + // true true start editing in existing buffer (nothing to do) if (!other_file && !oldbuf) { // re-use the buffer set_last_cursor(curwin); // may set b_last_cursor if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL) { @@ -2728,9 +2680,7 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum curbuf->b_op_end.lnum = 0; } - /* - * If we get here we are sure to start editing - */ + // If we get here we are sure to start editing // Assume success now retval = OK; @@ -2741,17 +2691,13 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum curbuf->b_flags &= ~BF_NOTEDITED; } - /* - * Check if we are editing the w_arg_idx file in the argument list. - */ + // Check if we are editing the w_arg_idx file in the argument list. check_arg_idx(curwin); if (!auto_buf) { - /* - * Set cursor and init window before reading the file and executing - * autocommands. This allows for the autocommands to position the - * cursor. - */ + // Set cursor and init window before reading the file and executing + // autocommands. This allows for the autocommands to position the + // cursor. curwin_init(); // It's possible that all lines in the buffer changed. Need to update @@ -2765,19 +2711,15 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum // Change directories when the 'acd' option is set. do_autochdir(); - /* - * Careful: open_buffer() and apply_autocmds() may change the current - * buffer and window. - */ + // Careful: open_buffer() and apply_autocmds() may change the current + // buffer and window. orig_pos = curwin->w_cursor; topline = curwin->w_topline; if (!oldbuf) { // need to read the file swap_exists_action = SEA_DIALOG; curbuf->b_flags |= BF_CHECK_RO; // set/reset 'ro' flag - /* - * Open the buffer and read the file. - */ + // Open the buffer and read the file. if (flags & ECMD_NOWINENTER) { readfile_flags |= READ_NOWINENTER; } @@ -2868,10 +2810,8 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum // Check if cursors in other windows on the same buffer are still valid check_lnums(false); - /* - * Did not read the file, need to show some info about the file. - * Do this after setting the cursor. - */ + // Did not read the file, need to show some info about the file. + // Do this after setting the cursor. if (oldbuf && !auto_buf) { int msg_scroll_save = msg_scroll; @@ -3559,10 +3499,8 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T } } - /* - * Small incompatibility: vi sees '\n' as end of the command, but in - * Vim we want to use '\n' to find/substitute a NUL. - */ + // Small incompatibility: vi sees '\n' as end of the command, but in + // Vim we want to use '\n' to find/substitute a NUL. sub = cmd; // remember the start of the substitution while (cmd[0]) { @@ -3620,9 +3558,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T } } - /* - * check for trailing command or garbage - */ + // check for trailing command or garbage cmd = skipwhite(cmd); if (*cmd && *cmd != '"') { // if not end-of-line or comment eap->nextcmd = check_nextcmd(cmd); @@ -3711,50 +3647,48 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T bool skip_match = false; linenr_T sub_firstlnum; // nr of first sub line - /* - * The new text is build up step by step, to avoid too much - * copying. There are these pieces: - * sub_firstline The old text, unmodified. - * copycol Column in the old text where we started - * looking for a match; from here old text still - * needs to be copied to the new text. - * matchcol Column number of the old text where to look - * for the next match. It's just after the - * previous match or one further. - * prev_matchcol Column just after the previous match (if any). - * Mostly equal to matchcol, except for the first - * match and after skipping an empty match. - * regmatch.*pos Where the pattern matched in the old text. - * new_start The new text, all that has been produced so - * far. - * new_end The new text, where to append new text. - * - * lnum The line number where we found the start of - * the match. Can be below the line we searched - * when there is a \n before a \zs in the - * pattern. - * sub_firstlnum The line number in the buffer where to look - * for a match. Can be different from "lnum" - * when the pattern or substitute string contains - * line breaks. - * - * Special situations: - * - When the substitute string contains a line break, the part up - * to the line break is inserted in the text, but the copy of - * the original line is kept. "sub_firstlnum" is adjusted for - * the inserted lines. - * - When the matched pattern contains a line break, the old line - * is taken from the line at the end of the pattern. The lines - * in the match are deleted later, "sub_firstlnum" is adjusted - * accordingly. - * - * The new text is built up in new_start[]. It has some extra - * room to avoid using xmalloc()/free() too often. - * - * Make a copy of the old line, so it won't be taken away when - * updating the screen or handling a multi-line match. The "old_" - * pointers point into this copy. - */ + // The new text is build up step by step, to avoid too much + // copying. There are these pieces: + // sub_firstline The old text, unmodified. + // copycol Column in the old text where we started + // looking for a match; from here old text still + // needs to be copied to the new text. + // matchcol Column number of the old text where to look + // for the next match. It's just after the + // previous match or one further. + // prev_matchcol Column just after the previous match (if any). + // Mostly equal to matchcol, except for the first + // match and after skipping an empty match. + // regmatch.*pos Where the pattern matched in the old text. + // new_start The new text, all that has been produced so + // far. + // new_end The new text, where to append new text. + // + // lnum The line number where we found the start of + // the match. Can be below the line we searched + // when there is a \n before a \zs in the + // pattern. + // sub_firstlnum The line number in the buffer where to look + // for a match. Can be different from "lnum" + // when the pattern or substitute string contains + // line breaks. + // + // Special situations: + // - When the substitute string contains a line break, the part up + // to the line break is inserted in the text, but the copy of + // the original line is kept. "sub_firstlnum" is adjusted for + // the inserted lines. + // - When the matched pattern contains a line break, the old line + // is taken from the line at the end of the pattern. The lines + // in the match are deleted later, "sub_firstlnum" is adjusted + // accordingly. + // + // The new text is built up in new_start[]. It has some extra + // room to avoid using xmalloc()/free() too often. + // + // Make a copy of the old line, so it won't be taken away when + // updating the screen or handling a multi-line match. The "old_" + // pointers point into this copy. sub_firstlnum = lnum; copycol = 0; matchcol = 0; @@ -3765,14 +3699,12 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T got_match = true; } - /* - * Loop until nothing more to replace in this line. - * 1. Handle match with empty string. - * 2. If subflags.do_ask is set, ask for confirmation. - * 3. substitute the string. - * 4. if subflags.do_all is set, find next match - * 5. break if there isn't another match in this line - */ + // Loop until nothing more to replace in this line. + // 1. Handle match with empty string. + // 2. If subflags.do_ask is set, ask for confirmation. + // 3. substitute the string. + // 4. if subflags.do_all is set, find next match + // 5. break if there isn't another match in this line for (;;) { SubResult current_match = { .start = { 0, 0 }, @@ -3811,11 +3743,9 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T curwin->w_cursor.lnum = lnum; do_again = false; - /* - * 1. Match empty string does not count, except for first - * match. This reproduces the strange vi behaviour. - * This also catches endless loops. - */ + // 1. Match empty string does not count, except for first + // match. This reproduces the strange vi behaviour. + // This also catches endless loops. if (matchcol == prev_matchcol && regmatch.endpos[0].lnum == 0 && matchcol == regmatch.endpos[0].col) { @@ -3880,9 +3810,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T no_u_sync++; } - /* - * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. - */ + // Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. while (subflags.do_ask) { if (exmode_active) { char *prompt; @@ -4266,15 +4194,13 @@ skip: && !re_multiline(regmatch.regprog))); nmatch = -1; - /* - * Replace the line in the buffer when needed. This is - * skipped when there are more matches. - * The check for nmatch_tl is needed for when multi-line - * matching must replace the lines before trying to do another - * match, otherwise "\@<=" won't work. - * When the match starts below where we start searching also - * need to replace the line first (using \zs after \n). - */ + // Replace the line in the buffer when needed. This is + // skipped when there are more matches. + // The check for nmatch_tl is needed for when multi-line + // matching must replace the lines before trying to do another + // match, otherwise "\@<=" won't work. + // When the match starts below where we start searching also + // need to replace the line first (using \zs after \n). if (lastone || nmatch_tl > 0 || (nmatch = vim_regexec_multi(®match, curwin, @@ -4282,13 +4208,11 @@ skip: matchcol, NULL, NULL)) == 0 || regmatch.startpos[0].lnum > 0) { if (new_start != NULL) { - /* - * Copy the rest of the line, that didn't match. - * "matchcol" has to be adjusted, we use the end of - * the line as reference, because the substitute may - * have changed the number of characters. Same for - * "prev_matchcol". - */ + // Copy the rest of the line, that didn't match. + // "matchcol" has to be adjusted, we use the end of + // the line as reference, because the substitute may + // have changed the number of characters. Same for + // "prev_matchcol". STRCAT(new_start, sub_firstline + copycol); matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; prev_matchcol = (colnr_T)STRLEN(sub_firstline) @@ -4300,12 +4224,10 @@ skip: ml_replace(lnum, new_start, true); if (nmatch_tl > 0) { - /* - * Matched lines have now been substituted and are - * useless, delete them. The part after the match - * has been appended to new_start, we don't need - * it in the buffer. - */ + // Matched lines have now been substituted and are + // useless, delete them. The part after the match + // has been appended to new_start, we don't need + // it in the buffer. lnum++; if (u_savedel(lnum, nmatch_tl) != OK) { break; @@ -4348,9 +4270,7 @@ skip: sub_firstlnum, matchcol, NULL, NULL); } - /* - * 5. break if there isn't another match in this line - */ + // 5. break if there isn't another match in this line if (nmatch <= 0) { // If the match found didn't start where we were // searching, do the next search in the line where we @@ -4513,12 +4433,10 @@ skip: /// @return true if a message was given. bool do_sub_msg(bool count_only) { - /* - * Only report substitutions when: - * - more than 'report' substitutions - * - command was typed by user, or number of changed lines > 'report' - * - giving messages is not disabled by 'lazyredraw' - */ + // Only report substitutions when: + // - more than 'report' substitutions + // - command was typed by user, or number of changed lines > 'report' + // - giving messages is not disabled by 'lazyredraw' if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1)) || count_only) && messaging()) { @@ -4609,11 +4527,9 @@ void ex_global(exarg_T *eap) cmd = eap->arg; which_pat = RE_LAST; // default: use last used regexp - /* - * undocumented vi feature: - * "\/" and "\?": use previous search pattern. - * "\&": use previous substitute pattern. - */ + // undocumented vi feature: + // "\/" and "\?": use previous search pattern. + // "\&": use previous substitute pattern. if (*cmd == '\\') { cmd++; if (vim_strchr("/?&", *cmd) == NULL) { @@ -4752,9 +4668,7 @@ void free_old_sub(void) /// @return true when it was created. bool prepare_tagpreview(bool undo_sync) { - /* - * If there is already a preview window open, use that one. - */ + // If there is already a preview window open, use that one. if (!curwin->w_p_pvw) { bool found_win = false; FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { @@ -4765,9 +4679,7 @@ bool prepare_tagpreview(bool undo_sync) } } if (!found_win) { - /* - * There is no preview window open yet. Create one. - */ + // There is no preview window open yet. Create one. if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0) == FAIL) { return false; diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c index 6dddafcfcb..20725b81ee 100644 --- a/src/nvim/ex_eval.c +++ b/src/nvim/ex_eval.c @@ -79,15 +79,13 @@ static void discard_pending_return(typval_T *p) tv_free(p); } -/* - * When several errors appear in a row, setting "force_abort" is delayed until - * the failing command returned. "cause_abort" is set to true meanwhile, in - * order to indicate that situation. This is useful when "force_abort" was set - * during execution of a function call from an expression: the aborting of the - * expression evaluation is done without producing any error messages, but all - * error messages on parsing errors during the expression evaluation are given - * (even if a try conditional is active). - */ +// When several errors appear in a row, setting "force_abort" is delayed until +// the failing command returned. "cause_abort" is set to true meanwhile, in +// order to indicate that situation. This is useful when "force_abort" was set +// during execution of a function call from an expression: the aborting of the +// expression evaluation is done without producing any error messages, but all +// error messages on parsing errors during the expression evaluation are given +// (even if a try conditional is active). static int cause_abort = false; /// @return true when immediately aborting on error, or when an interrupt @@ -153,69 +151,57 @@ bool cause_errthrow(const char *mesg, bool severe, bool *ignore) msglist_T *elem; msglist_T **plist; - /* - * Do nothing when displaying the interrupt message or reporting an - * uncaught exception (which has already been discarded then) at the top - * level. Also when no exception can be thrown. The message will be - * displayed by emsg(). - */ + // Do nothing when displaying the interrupt message or reporting an + // uncaught exception (which has already been discarded then) at the top + // level. Also when no exception can be thrown. The message will be + // displayed by emsg(). if (suppress_errthrow) { return false; } - /* - * If emsg() has not been called previously, temporarily reset - * "force_abort" until the throw point for error messages has been - * reached. This ensures that aborting() returns the same value for all - * errors that appear in the same command. This means particularly that - * for parsing errors during expression evaluation emsg() will be called - * multiply, even when the expression is evaluated from a finally clause - * that was activated due to an aborting error, interrupt, or exception. - */ + // If emsg() has not been called previously, temporarily reset + // "force_abort" until the throw point for error messages has been + // reached. This ensures that aborting() returns the same value for all + // errors that appear in the same command. This means particularly that + // for parsing errors during expression evaluation emsg() will be called + // multiply, even when the expression is evaluated from a finally clause + // that was activated due to an aborting error, interrupt, or exception. if (!did_emsg) { cause_abort = force_abort; force_abort = false; } - /* - * If no try conditional is active and no exception is being thrown and - * there has not been an error in a try conditional or a throw so far, do - * nothing (for compatibility of non-EH scripts). The message will then - * be displayed by emsg(). When ":silent!" was used and we are not - * currently throwing an exception, do nothing. The message text will - * then be stored to v:errmsg by emsg() without displaying it. - */ + // If no try conditional is active and no exception is being thrown and + // there has not been an error in a try conditional or a throw so far, do + // nothing (for compatibility of non-EH scripts). The message will then + // be displayed by emsg(). When ":silent!" was used and we are not + // currently throwing an exception, do nothing. The message text will + // then be stored to v:errmsg by emsg() without displaying it. if (((trylevel == 0 && !cause_abort) || emsg_silent) && !did_throw) { return false; } - /* - * Ignore an interrupt message when inside a try conditional or when an - * exception is being thrown or when an error in a try conditional or - * throw has been detected previously. This is important in order that an - * interrupt exception is catchable by the innermost try conditional and - * not replaced by an interrupt message error exception. - */ + // Ignore an interrupt message when inside a try conditional or when an + // exception is being thrown or when an error in a try conditional or + // throw has been detected previously. This is important in order that an + // interrupt exception is catchable by the innermost try conditional and + // not replaced by an interrupt message error exception. if (mesg == _(e_interr)) { *ignore = true; return true; } - /* - * Ensure that all commands in nested function calls and sourced files - * are aborted immediately. - */ + // Ensure that all commands in nested function calls and sourced files + // are aborted immediately. cause_abort = true; - /* - * When an exception is being thrown, some commands (like conditionals) are - * not skipped. Errors in those commands may affect what of the subsequent - * commands are regarded part of catch and finally clauses. Catching the - * exception would then cause execution of commands not intended by the - * user, who wouldn't even get aware of the problem. Therefore, discard the - * exception currently being thrown to prevent it from being caught. Just - * execute finally clauses and terminate. - */ + // When an exception is being thrown, some commands (like conditionals) are + // not skipped. Errors in those commands may affect what of the subsequent + // commands are regarded part of catch and finally clauses. Catching the + // exception would then cause execution of commands not intended by the + // user, who wouldn't even get aware of the problem. Therefore, discard the + // exception currently being thrown to prevent it from being caught. Just + // execute finally clauses and terminate. if (did_throw) { // When discarding an interrupt exception, reset got_int to prevent the // same interrupt being converted to an exception again and discarding @@ -228,25 +214,21 @@ bool cause_errthrow(const char *mesg, bool severe, bool *ignore) #ifdef THROW_TEST if (!THROW_ON_ERROR) { - /* - * Print error message immediately without searching for a matching - * catch clause; just finally clauses are executed before the script - * is terminated. - */ + // Print error message immediately without searching for a matching + // catch clause; just finally clauses are executed before the script + // is terminated. return false; } else // NOLINT(readability/braces) #endif { - /* - * Prepare the throw of an error exception, so that everything will - * be aborted (except for executing finally clauses), until the error - * exception is caught; if still uncaught at the top level, the error - * message will be displayed and the script processing terminated - * then. - This function has no access to the conditional stack. - * Thus, the actual throw is made after the failing command has - * returned. - Throw only the first of several errors in a row, except - * a severe error is following. - */ + // Prepare the throw of an error exception, so that everything will + // be aborted (except for executing finally clauses), until the error + // exception is caught; if still uncaught at the top level, the error + // message will be displayed and the script processing terminated + // then. - This function has no access to the conditional stack. + // Thus, the actual throw is made after the failing command has + // returned. - Throw only the first of several errors in a row, except + // a severe error is following. if (msg_list != NULL) { plist = msg_list; while (*plist != NULL) { @@ -312,10 +294,8 @@ void free_global_msglist(void) /// has returned (see do_one_cmd()). void do_errthrow(cstack_T *cstack, char *cmdname) { - /* - * Ensure that all commands in nested function calls and sourced files - * are aborted immediately. - */ + // Ensure that all commands in nested function calls and sourced files + // are aborted immediately. if (cause_abort) { cause_abort = false; force_abort = true; @@ -455,11 +435,9 @@ static int throw_exception(void *value, except_type_T type, char *cmdname) except_T *excp; int should_free; - /* - * Disallow faking Interrupt or error exceptions as user exceptions. They - * would be treated differently from real interrupt or error exceptions - * when no active try block is found, see do_cmdline(). - */ + // Disallow faking Interrupt or error exceptions as user exceptions. They + // would be treated differently from real interrupt or error exceptions + // when no active try block is found, see do_cmdline(). if (type == ET_USER) { if (STRNCMP((char_u *)value, "Vim", 3) == 0 && (((char_u *)value)[3] == NUL || ((char_u *)value)[3] == ':' @@ -678,9 +656,7 @@ static void finish_exception(except_T *excp) discard_exception(excp, true); } -/* - * Flags specifying the message displayed by report_pending. - */ +// Flags specifying the message displayed by report_pending. #define RP_MAKE 0 #define RP_RESUME 1 #define RP_DISCARD 2 @@ -958,11 +934,9 @@ void ex_while(exarg_T *eap) if (cstack->cs_idx == CSTACK_LEN - 1) { eap->errmsg = _("E585: :while/:for nesting too deep"); } else { - /* - * The loop flag is set when we have jumped back from the matching - * ":endwhile" or ":endfor". When not set, need to initialise this - * cstack entry. - */ + // The loop flag is set when we have jumped back from the matching + // ":endwhile" or ":endfor". When not set, need to initialise this + // cstack entry. if ((cstack->cs_lflags & CSL_HAD_LOOP) == 0) { cstack->cs_idx++; cstack->cs_looplevel++; @@ -973,16 +947,12 @@ void ex_while(exarg_T *eap) skip = CHECK_SKIP; if (eap->cmdidx == CMD_while) { - /* - * ":while bool-expr" - */ + // ":while bool-expr" result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip); } else { void *fi; - /* - * ":for var in list-expr" - */ + // ":for var in list-expr" if ((cstack->cs_lflags & CSL_HAD_LOOP) != 0) { // Jumping here from a ":continue" or ":endfor": use the // previously evaluated list. @@ -1007,11 +977,9 @@ void ex_while(exarg_T *eap) } } - /* - * If this cstack entry was just initialised and is active, set the - * loop flag, so do_cmdline() will set the line number in cs_line[]. - * If executing the command a second time, clear the loop flag. - */ + // If this cstack entry was just initialised and is active, set the + // loop flag, so do_cmdline() will set the line number in cs_line[]. + // If executing the command a second time, clear the loop flag. if (!skip && !error && result) { cstack->cs_flags[cstack->cs_idx] |= (CSF_ACTIVE | CSF_TRUE); cstack->cs_lflags ^= CSL_HAD_LOOP; @@ -1046,10 +1014,8 @@ void ex_continue(exarg_T *eap) if (cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR)) { rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel); - /* - * Set CSL_HAD_CONT, so do_cmdline() will jump back to the - * matching ":while". - */ + // Set CSL_HAD_CONT, so do_cmdline() will jump back to the + // matching ":while". cstack->cs_lflags |= CSL_HAD_CONT; // let do_cmdline() handle it } else { // If a try conditional not in its finally clause is reached first, @@ -1147,10 +1113,8 @@ void ex_endwhile(exarg_T *eap) (void)do_intthrow(cstack); } - /* - * Set loop flag, so do_cmdline() will jump back to the matching - * ":while" or ":for". - */ + // Set loop flag, so do_cmdline() will jump back to the matching + // ":while" or ":for". cstack->cs_lflags |= CSL_HAD_ENDLOOP; } } @@ -1211,19 +1175,17 @@ void do_throw(cstack_T *cstack) #endif idx = cleanup_conditionals(cstack, 0, inactivate_try); if (idx >= 0) { - /* - * If this try conditional is active and we are before its first - * ":catch", set THROWN so that the ":catch" commands will check - * whether the exception matches. When the exception came from any of - * the catch clauses, it will be made pending at the ":finally" (if - * present) and rethrown at the ":endtry". This will also happen if - * the try conditional is inactive. This is the case when we are - * throwing an exception due to an error or interrupt on the way from - * a preceding ":continue", ":break", ":return", ":finish", error or - * interrupt (not converted to an exception) to the finally clause or - * from a preceding throw of a user or error or interrupt exception to - * the matching catch clause or the finally clause. - */ + // If this try conditional is active and we are before its first + // ":catch", set THROWN so that the ":catch" commands will check + // whether the exception matches. When the exception came from any of + // the catch clauses, it will be made pending at the ":finally" (if + // present) and rethrown at the ":endtry". This will also happen if + // the try conditional is inactive. This is the case when we are + // throwing an exception due to an error or interrupt on the way from + // a preceding ":continue", ":break", ":return", ":finish", error or + // interrupt (not converted to an exception) to the finally clause or + // from a preceding throw of a user or error or interrupt exception to + // the matching catch clause or the finally clause. if (!(cstack->cs_flags[idx] & CSF_CAUGHT)) { if (cstack->cs_flags[idx] & CSF_ACTIVE) { cstack->cs_flags[idx] |= CSF_THROWN; @@ -1263,22 +1225,20 @@ void ex_try(exarg_T *eap) // that the finally clause needs to be executed. cstack->cs_flags[cstack->cs_idx] |= CSF_ACTIVE | CSF_TRUE; - /* - * ":silent!", even when used in a try conditional, disables - * displaying of error messages and conversion of errors to - * exceptions. When the silent commands again open a try - * conditional, save "emsg_silent" and reset it so that errors are - * again converted to exceptions. The value is restored when that - * try conditional is left. If it is left normally, the commands - * following the ":endtry" are again silent. If it is left by - * a ":continue", ":break", ":return", or ":finish", the commands - * executed next are again silent. If it is left due to an - * aborting error, an interrupt, or an exception, restoring - * "emsg_silent" does not matter since we are already in the - * aborting state and/or the exception has already been thrown. - * The effect is then just freeing the memory that was allocated - * to save the value. - */ + // ":silent!", even when used in a try conditional, disables + // displaying of error messages and conversion of errors to + // exceptions. When the silent commands again open a try + // conditional, save "emsg_silent" and reset it so that errors are + // again converted to exceptions. The value is restored when that + // try conditional is left. If it is left normally, the commands + // following the ":endtry" are again silent. If it is left by + // a ":continue", ":break", ":return", or ":finish", the commands + // executed next are again silent. If it is left due to an + // aborting error, an interrupt, or an exception, restoring + // "emsg_silent" does not matter since we are already in the + // aborting state and/or the exception has already been thrown. + // The effect is then just freeing the memory that was allocated + // to save the value. if (emsg_silent) { eslist_T *elem = xmalloc(sizeof(*elem)); elem->saved_emsg_silent = emsg_silent; @@ -1342,20 +1302,16 @@ void ex_catch(exarg_T *eap) } if (!give_up) { - /* - * Don't do something when no exception has been thrown or when the - * corresponding try block never got active (because of an inactive - * surrounding conditional or after an error or interrupt or throw). - */ + // Don't do something when no exception has been thrown or when the + // corresponding try block never got active (because of an inactive + // surrounding conditional or after an error or interrupt or throw). if (!did_throw || !(cstack->cs_flags[idx] & CSF_TRUE)) { skip = true; } - /* - * Check for a match only if an exception is thrown but not caught by - * a previous ":catch". An exception that has replaced a discarded - * exception is not checked (THROWN is not set then). - */ + // Check for a match only if an exception is thrown but not caught by + // a previous ":catch". An exception that has replaced a discarded + // exception is not checked (THROWN is not set then). if (!skip && (cstack->cs_flags[idx] & CSF_THROWN) && !(cstack->cs_flags[idx] & CSF_CAUGHT)) { if (end != NULL && *end != NUL && !ends_excmd(*skipwhite(end + 1))) { @@ -1422,16 +1378,14 @@ void ex_catch(exarg_T *eap) internal_error("ex_catch()"); } } else { - /* - * If there is a preceding catch clause and it caught the exception, - * finish the exception now. This happens also after errors except - * when this ":catch" was after the ":finally" or not within - * a ":try". Make the try conditional inactive so that the - * following catch clauses are skipped. On an error or interrupt - * after the preceding try block or catch clause was left by - * a ":continue", ":break", ":return", or ":finish", discard the - * pending action. - */ + // If there is a preceding catch clause and it caught the exception, + // finish the exception now. This happens also after errors except + // when this ":catch" was after the ":finally" or not within + // a ":try". Make the try conditional inactive so that the + // following catch clauses are skipped. On an error or interrupt + // after the preceding try block or catch clause was left by + // a ":continue", ":break", ":return", or ":finish", discard the + // pending action. cleanup_conditionals(cstack, CSF_TRY, true); } } @@ -1495,14 +1449,12 @@ void ex_finally(exarg_T *eap) (void)do_intthrow(cstack); } - /* - * If there is a preceding catch clause and it caught the exception, - * finish the exception now. This happens also after errors except - * when this is a multiple ":finally" or one not within a ":try". - * After an error or interrupt, this also discards a pending - * ":continue", ":break", ":finish", or ":return" from the preceding - * try block or catch clause. - */ + // If there is a preceding catch clause and it caught the exception, + // finish the exception now. This happens also after errors except + // when this is a multiple ":finally" or one not within a ":try". + // After an error or interrupt, this also discards a pending + // ":continue", ":break", ":finish", or ":return" from the preceding + // try block or catch clause. cleanup_conditionals(cstack, CSF_TRY, false); // Make did_emsg, got_int, did_throw pending. If set, they overrule @@ -1606,12 +1558,10 @@ void ex_endtry(exarg_T *eap) } else { idx = cstack->cs_idx; - /* - * If we stopped with the exception currently being thrown at this - * try conditional since we didn't know that it doesn't have - * a finally clause, we need to rethrow it after closing the try - * conditional. - */ + // If we stopped with the exception currently being thrown at this + // try conditional since we didn't know that it doesn't have + // a finally clause, we need to rethrow it after closing the try + // conditional. if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE) && !(cstack->cs_flags[idx] & CSF_FINALLY)) { @@ -1645,12 +1595,10 @@ void ex_endtry(exarg_T *eap) } } - /* - * If a ":return" is pending, we need to resume it after closing the - * try conditional; remember the return value. If there was a finally - * clause making an exception pending, we need to rethrow it. Make it - * the exception currently being thrown. - */ + // If a ":return" is pending, we need to resume it after closing the + // try conditional; remember the return value. If there was a finally + // clause making an exception pending, we need to rethrow it. Make it + // the exception currently being thrown. if (!skip) { pending = cstack->cs_pending[idx]; cstack->cs_pending[idx] = CSTP_NONE; @@ -1661,16 +1609,14 @@ void ex_endtry(exarg_T *eap) } } - /* - * Discard anything pending on an error, interrupt, or throw in the - * finally clause. If there was no ":finally", discard a pending - * ":continue", ":break", ":return", or ":finish" if an error or - * interrupt occurred afterwards, but before the ":endtry" was reached. - * If an exception was caught by the last of the catch clauses and there - * was no finally clause, finish the exception now. This happens also - * after errors except when this ":endtry" is not within a ":try". - * Restore "emsg_silent" if it has been reset by this try conditional. - */ + // Discard anything pending on an error, interrupt, or throw in the + // finally clause. If there was no ":finally", discard a pending + // ":continue", ":break", ":return", or ":finish" if an error or + // interrupt occurred afterwards, but before the ":endtry" was reached. + // If an exception was caught by the last of the catch clauses and there + // was no finally clause, finish the exception now. This happens also + // after errors except when this ":endtry" is not within a ":try". + // Restore "emsg_silent" if it has been reset by this try conditional. (void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, true); if (cstack->cs_idx >= 0 && (cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) { @@ -1733,18 +1679,16 @@ void ex_endtry(exarg_T *eap) } } -/* - * enter_cleanup() and leave_cleanup() - * - * Functions to be called before/after invoking a sequence of autocommands for - * cleanup for a failed command. (Failure means here that a call to emsg() - * has been made, an interrupt occurred, or there is an uncaught exception - * from a previous autocommand execution of the same command.) - * - * Call enter_cleanup() with a pointer to a cleanup_T and pass the same - * pointer to leave_cleanup(). The cleanup_T structure stores the pending - * error/interrupt/exception state. - */ +// enter_cleanup() and leave_cleanup() +// +// Functions to be called before/after invoking a sequence of autocommands for +// cleanup for a failed command. (Failure means here that a call to emsg() +// has been made, an interrupt occurred, or there is an uncaught exception +// from a previous autocommand execution of the same command.) +// +// Call enter_cleanup() with a pointer to a cleanup_T and pass the same +// pointer to leave_cleanup(). The cleanup_T structure stores the pending +// error/interrupt/exception state. /// This function works a bit like ex_finally() except that there was not /// actually an extra try block around the part that failed and an error or @@ -1829,18 +1773,14 @@ void leave_cleanup(cleanup_T *csp) if (msg_list != NULL) { free_global_msglist(); } - } - /* - * If there was no new error, interrupt, or throw between the calls - * to enter_cleanup() and leave_cleanup(), restore the pending - * error/interrupt/exception state. - */ - else { - /* - * If there was an exception being thrown when enter_cleanup() was - * called, we need to rethrow it. Make it the exception currently - * being thrown. - */ + } else { + // If there was no new error, interrupt, or throw between the calls + // to enter_cleanup() and leave_cleanup(), restore the pending + // error/interrupt/exception state. + + // If there was an exception being thrown when enter_cleanup() was + // called, we need to rethrow it. Make it the exception currently + // being thrown. if (pending & CSTP_THROW) { current_exception = csp->exception; } else if (pending & CSTP_ERROR) { @@ -1893,12 +1833,10 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive) for (idx = cstack->cs_idx; idx >= 0; idx--) { if (cstack->cs_flags[idx] & CSF_TRY) { - /* - * Discard anything pending in a finally clause and continue the - * search. There may also be a pending ":continue", ":break", - * ":return", or ":finish" before the finally clause. We must not - * discard it, unless an error or interrupt occurred afterwards. - */ + // Discard anything pending in a finally clause and continue the + // search. There may also be a pending ":continue", ":break", + // ":return", or ":finish" before the finally clause. We must not + // discard it, unless an error or interrupt occurred afterwards. if (did_emsg || got_int || (cstack->cs_flags[idx] & CSF_FINALLY)) { switch (cstack->cs_pending[idx]) { case CSTP_NONE: @@ -1934,11 +1872,9 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive) } } - /* - * Stop at a try conditional not in its finally clause. If this try - * conditional is in an active catch clause, finish the caught - * exception. - */ + // Stop at a try conditional not in its finally clause. If this try + // conditional is in an active catch clause, finish the caught + // exception. if (!(cstack->cs_flags[idx] & CSF_FINALLY)) { if ((cstack->cs_flags[idx] & CSF_ACTIVE) && (cstack->cs_flags[idx] & CSF_CAUGHT) && !(cstack->cs_flags[idx] & CSF_FINISHED)) { @@ -1973,11 +1909,9 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive) break; } - /* - * When leaving a try conditional that reset "emsg_silent" on its - * entry after saving the original value, restore that value here and - * free the memory used to store it. - */ + // When leaving a try conditional that reset "emsg_silent" on its + // entry after saving the original value, restore that value here and + // free the memory used to store it. if ((cstack->cs_flags[idx] & CSF_TRY) && (cstack->cs_flags[idx] & CSF_SILENT)) { eslist_T *elem; diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 2112385533..da99a03c38 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * ex_getln.c: Functions for entering and editing an Ex command line. - */ +// ex_getln.c: Functions for entering and editing an Ex command line. #include #include @@ -2603,10 +2601,8 @@ bool text_locked(void) return textlock != 0; } -/* - * Give an error message for a command that isn't allowed while the cmdline - * window is open or editing the cmdline in another way. - */ +// Give an error message for a command that isn't allowed while the cmdline +// window is open or editing the cmdline in another way. void text_locked_msg(void) { emsg(_(get_text_locked_msg())); @@ -2738,15 +2734,11 @@ bool cmdline_at_end(void) return (ccline.cmdpos >= ccline.cmdlen); } -/* - * Allocate a new command line buffer. - * Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen. - */ +// Allocate a new command line buffer. +// Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen. static void alloc_cmdbuff(int len) { - /* - * give some extra space to avoid having to allocate all the time - */ + // give some extra space to avoid having to allocate all the time if (len < 80) { len = 100; } else { @@ -3088,10 +3080,8 @@ color_cmdline_error: #undef PRINT_ERRMSG } -/* - * Draw part of the cmdline at the current cursor position. But draw stars - * when cmdline_star is true. - */ +// Draw part of the cmdline at the current cursor position. But draw stars +// when cmdline_star is true. static void draw_cmdline(int start, int len) { if (!color_cmdline(&ccline)) { @@ -3342,11 +3332,9 @@ void cmdline_ui_flush(void) } } -/* - * Put a character on the command line. Shifts the following text to the - * right when "shift" is true. Used for CTRL-V, CTRL-K, etc. - * "c" must be printable (fit in one display cell)! - */ +// Put a character on the command line. Shifts the following text to the +// right when "shift" is true. Used for CTRL-V, CTRL-K, etc. +// "c" must be printable (fit in one display cell)! void putcmdline(char c, int shift) { if (cmd_silent) { @@ -3388,14 +3376,12 @@ void unputcmdline(void) ui_cursor_shape(); } -/* - * Put the given string, of the given length, onto the command line. - * If len is -1, then STRLEN() is used to calculate the length. - * If 'redraw' is true then the new part of the command line, and the remaining - * part will be redrawn, otherwise it will not. If this function is called - * twice in a row, then 'redraw' should be false and redrawcmd() should be - * called afterwards. - */ +// Put the given string, of the given length, onto the command line. +// If len is -1, then STRLEN() is used to calculate the length. +// If 'redraw' is true then the new part of the command line, and the remaining +// part will be redrawn, otherwise it will not. If this function is called +// twice in a row, then 'redraw' should be false and redrawcmd() should be +// called afterwards. void put_on_cmdline(char_u *str, int len, int redraw) { int i; @@ -3603,12 +3589,10 @@ static bool cmdline_paste(int regname, bool literally, bool remcr) return cmdline_paste_reg(regname, literally, remcr); } -/* - * Put a string on the command line. - * When "literally" is true, insert literally. - * When "literally" is false, insert as typed, but don't leave the command - * line. - */ +// Put a string on the command line. +// When "literally" is true, insert literally. +// When "literally" is false, insert as typed, but don't leave the command +// line. void cmdline_paste_str(char_u *s, int literally) { int c, cv; @@ -3675,9 +3659,7 @@ static void redrawcmdprompt(void) } } -/* - * Redraw what is currently on the command line. - */ +// Redraw what is currently on the command line. void redrawcmd(void) { if (cmd_silent) { @@ -3714,10 +3696,8 @@ void redrawcmd(void) putcmdline(ccline.special_char, ccline.special_shift); } - /* - * An emsg() before may have set msg_scroll. This is used in normal mode, - * in cmdline mode we can reset them now. - */ + // An emsg() before may have set msg_scroll. This is used in normal mode, + // in cmdline mode we can reset them now. msg_scroll = false; // next message overwrites cmdline // Typing ':' at the more prompt may set skip_redraw. We don't want this @@ -3794,12 +3774,10 @@ void gotocmdline(bool clr) cmd_cursor_goto(cmdline_row, 0); } -/* - * Check the word in front of the cursor for an abbreviation. - * Called when the non-id character "c" has been entered. - * When an abbreviation is recognized it is removed from the text with - * backspaces and the replacement string is inserted, followed by "c". - */ +// Check the word in front of the cursor for an abbreviation. +// Called when the non-id character "c" has been entered. +// When an abbreviation is recognized it is removed from the text with +// backspaces and the replacement string is inserted, followed by "c". static int ccheck_abbr(int c) { int spos = 0; @@ -4310,9 +4288,7 @@ static int open_cmdwin(void) RedrawingDisabled = 0; int save_count = save_batch_count(); - /* - * Call the main loop until or CTRL-C is typed. - */ + // Call the main loop until or CTRL-C is typed. normal_enter(true, false); RedrawingDisabled = i; diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c index f75dc51ca5..a604c5ff3e 100644 --- a/src/nvim/file_search.c +++ b/src/nvim/file_search.c @@ -71,9 +71,7 @@ static char_u *ff_expand_buffer = NULL; // used for expanding filenames -/* - * type for the directory search stack - */ +// type for the directory search stack typedef struct ff_stack { struct ff_stack *ffs_prev; @@ -104,9 +102,7 @@ typedef struct ff_stack { int ffs_star_star_empty; } ff_stack_T; -/* - * type for already visited directories or files. - */ +// type for already visited directories or files. typedef struct ff_visited { struct ff_visited *ffv_next; @@ -122,20 +118,18 @@ typedef struct ff_visited { char_u ffv_fname[1]; // actually longer } ff_visited_T; -/* - * We might have to manage several visited lists during a search. - * This is especially needed for the tags option. If tags is set to: - * "./++/tags,./++/TAGS,++/tags" (replace + with *) - * So we have to do 3 searches: - * 1) search from the current files directory downward for the file "tags" - * 2) search from the current files directory downward for the file "TAGS" - * 3) search from Vims current directory downwards for the file "tags" - * As you can see, the first and the third search are for the same file, so for - * the third search we can use the visited list of the first search. For the - * second search we must start from an empty visited list. - * The struct ff_visited_list_hdr is used to manage a linked list of already - * visited lists. - */ +// We might have to manage several visited lists during a search. +// This is especially needed for the tags option. If tags is set to: +// "./++/tags,./++/TAGS,++/tags" (replace + with *) +// So we have to do 3 searches: +// 1) search from the current files directory downward for the file "tags" +// 2) search from the current files directory downward for the file "TAGS" +// 3) search from Vims current directory downwards for the file "tags" +// As you can see, the first and the third search are for the same file, so for +// the third search we can use the visited list of the first search. For the +// second search we must start from an empty visited list. +// The struct ff_visited_list_hdr is used to manage a linked list of already +// visited lists. typedef struct ff_visited_list_hdr { struct ff_visited_list_hdr *ffvl_next; @@ -145,29 +139,25 @@ typedef struct ff_visited_list_hdr { ff_visited_T *ffvl_visited_list; } ff_visited_list_hdr_T; -/* - * '**' can be expanded to several directory levels. - * Set the default maximum depth. - */ +// '**' can be expanded to several directory levels. +// Set the default maximum depth. #define FF_MAX_STAR_STAR_EXPAND ((char_u)30) -/* - * The search context: - * ffsc_stack_ptr: the stack for the dirs to search - * ffsc_visited_list: the currently active visited list - * ffsc_dir_visited_list: the currently active visited list for search dirs - * ffsc_visited_lists_list: the list of all visited lists - * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs - * ffsc_file_to_search: the file to search for - * ffsc_start_dir: the starting directory, if search path was relative - * ffsc_fix_path: the fix part of the given path (without wildcards) - * Needed for upward search. - * ffsc_wc_path: the part of the given path containing wildcards - * ffsc_level: how many levels of dirs to search downwards - * ffsc_stopdirs_v: array of stop directories for upward search - * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE - * ffsc_tagfile: searching for tags file, don't use 'suffixesadd' - */ +// The search context: +// ffsc_stack_ptr: the stack for the dirs to search +// ffsc_visited_list: the currently active visited list +// ffsc_dir_visited_list: the currently active visited list for search dirs +// ffsc_visited_lists_list: the list of all visited lists +// ffsc_dir_visited_lists_list: the list of all visited lists for search dirs +// ffsc_file_to_search: the file to search for +// ffsc_start_dir: the starting directory, if search path was relative +// ffsc_fix_path: the fix part of the given path (without wildcards) +// Needed for upward search. +// ffsc_wc_path: the part of the given path containing wildcards +// ffsc_level: how many levels of dirs to search downwards +// ffsc_stopdirs_v: array of stop directories for upward search +// ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE +// ffsc_tagfile: searching for tags file, don't use 'suffixesadd' typedef struct ff_search_ctx_T { ff_stack_T *ffsc_stack_ptr; ff_visited_list_hdr_T *ffsc_visited_list; @@ -341,15 +331,13 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i #endif } - /* - * If stopdirs are given, split them into an array of pointers. - * If this fails (mem allocation), there is no upward search at all or a - * stop directory is not recognized -> continue silently. - * If stopdirs just contains a ";" or is empty, - * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This - * is handled as unlimited upward search. See function - * ff_path_in_stoplist() for details. - */ + // If stopdirs are given, split them into an array of pointers. + // If this fails (mem allocation), there is no upward search at all or a + // stop directory is not recognized -> continue silently. + // If stopdirs just contains a ";" or is empty, + // search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This + // is handled as unlimited upward search. See function + // ff_path_in_stoplist() for details. if (stopdirs != NULL) { char *walker = stopdirs; @@ -401,15 +389,13 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i assert(wc_part - path >= 0); search_ctx->ffsc_fix_path = xstrnsave(path, (size_t)(wc_part - path)); - /* - * copy wc_path and add restricts to the '**' wildcard. - * The octet after a '**' is used as a (binary) counter. - * So '**3' is transposed to '**^C' ('^C' is ASCII value 3) - * or '**76' is transposed to '**N'( 'N' is ASCII value 76). - * If no restrict is given after '**' the default is used. - * Due to this technique the path looks awful if you print it as a - * string. - */ + // copy wc_path and add restricts to the '**' wildcard. + // The octet after a '**' is used as a (binary) counter. + // So '**3' is transposed to '**^C' ('^C' is ASCII value 3) + // or '**76' is transposed to '**N'( 'N' is ASCII value 76). + // If no restrict is given after '**' the default is used. + // Due to this technique the path looks awful if you print it as a + // string. len = 0; while (*wc_part != NUL) { if (len + 5 >= MAXPATHL) { @@ -513,11 +499,9 @@ void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, i return search_ctx; error_return: - /* - * We clear the search context now! - * Even when the caller gave us a (perhaps valid) context we free it here, - * as we might have already destroyed it. - */ + // We clear the search context now! + // Even when the caller gave us a (perhaps valid) context we free it here, + // as we might have already destroyed it. vim_findfile_cleanup(search_ctx); return NULL; } @@ -587,10 +571,8 @@ char_u *vim_findfile(void *search_ctx_arg) search_ctx = (ff_search_ctx_T *)search_ctx_arg; - /* - * filepath is used as buffer for various actions and as the storage to - * return a found filename. - */ + // filepath is used as buffer for various actions and as the storage to + // return a found filename. file_path = xmalloc(MAXPATHL); // store the end of the start dir -- needed for upward search @@ -614,25 +596,23 @@ char_u *vim_findfile(void *search_ctx_arg) break; } - /* - * TODO: decide if we leave this test in - * - * GOOD: don't search a directory(-tree) twice. - * BAD: - check linked list for every new directory entered. - * - check for double files also done below - * - * Here we check if we already searched this directory. - * We already searched a directory if: - * 1) The directory is the same. - * 2) We would use the same wildcard string. - * - * Good if you have links on same directory via several ways - * or you have selfreferences in directories (e.g. SuSE Linux 6.3: - * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop) - * - * This check is only needed for directories we work on for the - * first time (hence stackp->ff_filearray == NULL) - */ + // TODO(vim): decide if we leave this test in + // + // GOOD: don't search a directory(-tree) twice. + // BAD: - check linked list for every new directory entered. + // - check for double files also done below + // + // Here we check if we already searched this directory. + // We already searched a directory if: + // 1) The directory is the same. + // 2) We would use the same wildcard string. + // + // Good if you have links on same directory via several ways + // or you have selfreferences in directories (e.g. SuSE Linux 6.3: + // /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop) + // + // This check is only needed for directories we work on for the + // first time (hence stackp->ff_filearray == NULL) if (stackp->ffs_filearray == NULL && ff_check_visited(&search_ctx->ffsc_dir_visited_list->ffvl_visited_list, stackp->ffs_fix_path, stackp->ffs_wc_path) == FAIL) { @@ -666,12 +646,10 @@ char_u *vim_findfile(void *search_ctx_arg) file_path[0] = NUL; - /* - * If no filearray till now expand wildcards - * The function expand_wildcards() can handle an array of paths - * and all possible expands are returned in one array. We use this - * to handle the expansion of '**' into an empty string. - */ + // If no filearray till now expand wildcards + // The function expand_wildcards() can handle an array of paths + // and all possible expands are returned in one array. We use this + // to handle the expansion of '**' into an empty string. if (stackp->ffs_filearray == NULL) { char *dirptrs[2]; @@ -737,13 +715,11 @@ char_u *vim_findfile(void *search_ctx_arg) } } - /* - * Here we copy until the next path separator or the end of - * the path. If we stop at a path separator, there is - * still something else left. This is handled below by - * pushing every directory returned from expand_wildcards() - * on the stack again for further search. - */ + // Here we copy until the next path separator or the end of + // the path. If we stop at a path separator, there is + // still something else left. This is handled below by + // pushing every directory returned from expand_wildcards() + // on the stack again for further search. while (*rest_of_wildcards && !vim_ispathsep(*rest_of_wildcards)) { if (len + 1 >= MAXPATHL) { @@ -759,10 +735,8 @@ char_u *vim_findfile(void *search_ctx_arg) } } - /* - * Expand wildcards like "*" and "$VAR". - * If the path is a URL don't try this. - */ + // Expand wildcards like "*" and "$VAR". + // If the path is a URL don't try this. if (path_with_url(dirptrs[0])) { stackp->ffs_filearray = xmalloc(sizeof(char *)); stackp->ffs_filearray[0] = xstrdup(dirptrs[0]); @@ -786,10 +760,8 @@ char_u *vim_findfile(void *search_ctx_arg) if (stackp->ffs_stage == 0) { // this is the first time we work on this directory if (*rest_of_wildcards == NUL) { - /* - * We don't have further wildcards to expand, so we have to - * check for the final file now. - */ + // We don't have further wildcards to expand, so we have to + // check for the final file now. for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) { if (!path_with_url(stackp->ffs_filearray[i]) && !os_isdir(stackp->ffs_filearray[i])) { @@ -808,10 +780,8 @@ char_u *vim_findfile(void *search_ctx_arg) } STRCAT(file_path, search_ctx->ffsc_file_to_search); - /* - * Try without extra suffix and then with suffixes - * from 'suffixesadd'. - */ + // Try without extra suffix and then with suffixes + // from 'suffixesadd'. len = STRLEN(file_path); if (search_ctx->ffsc_tagfile) { suf = ""; @@ -894,10 +864,8 @@ char_u *vim_findfile(void *search_ctx_arg) stackp->ffs_stage = 1; } - /* - * if wildcards contains '**' we have to descent till we reach the - * leaves of the directory tree. - */ + // if wildcards contains '**' we have to descent till we reach the + // leaves of the directory tree. if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0) { for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) { @@ -1048,9 +1016,7 @@ static ff_visited_list_hdr_T *ff_get_visited_list(char_u *filename, } #endif - /* - * if we reach this we didn't find a list and we have to allocate new list - */ + // if we reach this we didn't find a list and we have to allocate new list retptr = xmalloc(sizeof(*retptr)); retptr->ffvl_visited_list = NULL; @@ -1136,9 +1102,7 @@ static int ff_check_visited(ff_visited_T **visited_list, char_u *fname, char_u * } } - /* - * New file/dir. Add it to the list of visited files/dirs. - */ + // New file/dir. Add it to the list of visited files/dirs. vp = xmalloc(sizeof(ff_visited_T) + STRLEN(ff_expand_buffer)); if (!url) { @@ -1434,11 +1398,9 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':') #endif ) { - /* - * Absolute path, no need to use "path_option". - * If this is not a first call, return NULL. We already returned a - * filename on the first call. - */ + // Absolute path, no need to use "path_option". + // If this is not a first call, return NULL. We already returned a + // filename on the first call. if (first == true) { if (path_with_url((char *)ff_file_to_find)) { file_name = vim_strsave(ff_file_to_find); @@ -1483,11 +1445,9 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first } } } else { - /* - * Loop over all paths in the 'path' or 'cdpath' option. - * When "first" is set, first setup to the start of the option. - * Otherwise continue to find the next match. - */ + // Loop over all paths in the 'path' or 'cdpath' option. + // When "first" is set, first setup to the start of the option. + // Otherwise continue to find the next match. if (first == true) { // vim_findfile_free_visited can handle a possible NULL pointer vim_findfile_free_visited(fdip_search_ctx); diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 889e569672..a29a0efe40 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -90,9 +90,7 @@ * with iconv() to be able to allocate a buffer. */ #define ICONV_MULT 8 -/* - * Structure to pass arguments from buf_write() to buf_write_bytes(). - */ +// Structure to pass arguments from buf_write() to buf_write_bytes(). struct bw_info { int bw_fd; // file descriptor char_u *bw_buf; // buffer with data to be written @@ -257,12 +255,10 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read - /* - * If there is no file name yet, use the one for the read file. - * BF_NOTEDITED is set to reflect this. - * Don't do this for a read from a filter. - * Only do this when 'cpoptions' contains the 'f' flag. - */ + // If there is no file name yet, use the one for the read file. + // BF_NOTEDITED is set to reflect this. + // Don't do this for a read from a filter. + // Only do this when 'cpoptions' contains the 'f' flag. if (curbuf->b_ffname == NULL && !filtering && fname != NULL @@ -401,12 +397,10 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, // Set default or forced 'fileformat' and 'binary'. set_file_options(set_options, eap); - /* - * When opening a new file we take the readonly flag from the file. - * Default is r/w, can be set to r/o below. - * Don't reset it when in readonly mode - * Only set/reset b_p_ro when BF_CHECK_RO is set. - */ + // When opening a new file we take the readonly flag from the file. + // Default is r/w, can be set to r/o below. + // Don't reset it when in readonly mode + // Only set/reset b_p_ro when BF_CHECK_RO is set. check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO)); if (check_readonly && !readonlymode) { curbuf->b_p_ro = false; @@ -419,17 +413,15 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, curbuf->b_mtime_read = curbuf->b_mtime; curbuf->b_mtime_read_ns = curbuf->b_mtime_ns; #ifdef UNIX - /* - * Use the protection bits of the original file for the swap file. - * This makes it possible for others to read the name of the - * edited file from the swapfile, but only if they can read the - * edited file. - * Remove the "write" and "execute" bits for group and others - * (they must not write the swapfile). - * Add the "read" and "write" bits for the user, otherwise we may - * not be able to write to the file ourselves. - * Setting the bits is done below, after creating the swap file. - */ + // Use the protection bits of the original file for the swap file. + // This makes it possible for others to read the name of the + // edited file from the swapfile, but only if they can read the + // edited file. + // Remove the "write" and "execute" bits for group and others + // (they must not write the swapfile). + // Add the "read" and "write" bits for the user, otherwise we may + // not be able to write to the file ourselves. + // Setting the bits is done below, after creating the swap file. swap_mode = ((int)file_info.stat.st_mode & 0644) | 0600; #endif } else { @@ -520,10 +512,8 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, return FAIL; } - /* - * Only set the 'ro' flag for readonly files the first time they are - * loaded. Help files always get readonly mode - */ + // Only set the 'ro' flag for readonly files the first time they are + // loaded. Help files always get readonly mode if ((check_readonly && file_readonly) || curbuf->b_help) { curbuf->b_p_ro = true; } @@ -645,13 +635,11 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, curbuf->b_p_ro = true; // must use "w!" now return FAIL; } - /* - * Don't allow the autocommands to change the current buffer. - * Try to re-open the file. - * - * Don't allow the autocommands to change the buffer name either - * (cd for example) if it invalidates fname or sfname. - */ + // Don't allow the autocommands to change the current buffer. + // Try to re-open the file. + // + // Don't allow the autocommands to change the buffer name either + // (cd for example) if it invalidates fname or sfname. if (!read_stdin && (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) || (using_b_fname && (old_b_fname != curbuf->b_fname)) @@ -679,10 +667,8 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, msg_scroll = false; // overwrite the file message - /* - * Set linecnt now, before the "retry" caused by a wrong guess for - * fileformat, and after the autocommands, which may change them. - */ + // Set linecnt now, before the "retry" caused by a wrong guess for + // fileformat, and after the autocommands, which may change them. linecnt = curbuf->b_ml.ml_line_count; // "++bad=" argument. @@ -695,9 +681,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, curbuf->b_bad_char = 0; } - /* - * Decide which 'encoding' to use or use first. - */ + // Decide which 'encoding' to use or use first. if (eap != NULL && eap->force_enc != 0) { fenc = enc_canonize(eap->cmd + eap->force_enc); fenc_alloced = true; @@ -722,25 +706,23 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip, fenc = next_fenc(&fenc_next, &fenc_alloced); } - /* - * Jump back here to retry reading the file in different ways. - * Reasons to retry: - * - encoding conversion failed: try another one from "fenc_next" - * - BOM detected and fenc was set, need to setup conversion - * - "fileformat" check failed: try another - * - * Variables set for special retry actions: - * "file_rewind" Rewind the file to start reading it again. - * "advance_fenc" Advance "fenc" using "fenc_next". - * "skip_read" Re-use already read bytes (BOM detected). - * "did_iconv" iconv() conversion failed, try 'charconvert'. - * "keep_fileformat" Don't reset "fileformat". - * - * Other status indicators: - * "tmpname" When != NULL did conversion with 'charconvert'. - * Output file has to be deleted afterwards. - * "iconv_fd" When != -1 did conversion with iconv(). - */ + // Jump back here to retry reading the file in different ways. + // Reasons to retry: + // - encoding conversion failed: try another one from "fenc_next" + // - BOM detected and fenc was set, need to setup conversion + // - "fileformat" check failed: try another + // + // Variables set for special retry actions: + // "file_rewind" Rewind the file to start reading it again. + // "advance_fenc" Advance "fenc" using "fenc_next". + // "skip_read" Re-use already read bytes (BOM detected). + // "did_iconv" iconv() conversion failed, try 'charconvert'. + // "keep_fileformat" Don't reset "fileformat". + // + // Other status indicators: + // "tmpname" When != NULL did conversion with 'charconvert'. + // Output file has to be deleted afterwards. + // "iconv_fd" When != -1 did conversion with iconv(). retry: if (file_rewind) { @@ -764,10 +746,8 @@ retry: conv_error = 0; } - /* - * When retrying with another "fenc" and the first time "fileformat" - * will be reset. - */ + // When retrying with another "fenc" and the first time "fileformat" + // will be reset. if (keep_fileformat) { keep_fileformat = false; } else { @@ -793,9 +773,7 @@ retry: #endif if (advance_fenc) { - /* - * Try the next entry in 'fileencodings'. - */ + // Try the next entry in 'fileencodings'. advance_fenc = false; if (eap != NULL && eap->force_enc != 0) { @@ -825,10 +803,8 @@ retry: } } - /* - * Conversion may be required when the encoding of the file is different - * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4. - */ + // Conversion may be required when the encoding of the file is different + // from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4. fio_flags = 0; converted = need_conversion((char_u *)fenc); if (converted) { @@ -855,10 +831,8 @@ retry: } #endif - /* - * Use the 'charconvert' expression when conversion is required - * and we can't do it internally or with iconv(). - */ + // Use the 'charconvert' expression when conversion is required + // and we can't do it internally or with iconv(). if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL && !read_fifo #ifdef HAVE_ICONV @@ -922,12 +896,10 @@ retry: } while (!error && !got_int) { - /* - * We allocate as much space for the file as we can get, plus - * space for the old line plus room for one terminating NUL. - * The amount is limited by the fact that read() only can read - * up to max_unsigned characters (and other things). - */ + // We allocate as much space for the file as we can get, plus + // space for the old line plus room for one terminating NUL. + // The amount is limited by the fact that read() only can read + // up to max_unsigned characters (and other things). { if (!skip_read) { // Use buffer >= 64K. Add linerest to double the size if the @@ -999,10 +971,8 @@ retry: } if (read_buffer) { - /* - * Read bytes from curbuf. Used for converting text read - * from stdin. - */ + // Read bytes from curbuf. Used for converting text read + // from stdin. if (read_buf_lnum > from) { size = 0; } else { @@ -1052,9 +1022,7 @@ retry: } } } else { - /* - * Read bytes from the file. - */ + // Read bytes from the file. size = read_eintr(fd, ptr, (size_t)size); } @@ -1062,10 +1030,8 @@ retry: if (size < 0) { // read error error = true; } else if (conv_restlen > 0) { - /* - * Reached end-of-file but some trailing bytes could - * not be converted. Truncated file? - */ + // Reached end-of-file but some trailing bytes could + // not be converted. Truncated file? // When we did a conversion report an error. if (fio_flags != 0 @@ -1118,12 +1084,10 @@ retry: skip_read = false; - /* - * At start of file: Check for BOM. - * Also check for a BOM for other Unicode encodings, but not after - * converting with 'charconvert' or when a BOM has already been - * found. - */ + // At start of file: Check for BOM. + // Also check for a BOM for other Unicode encodings, but not after + // converting with 'charconvert' or when a BOM has already been + // found. if ((filesize == 0) && (fio_flags == FIO_UCSBOM || (!curbuf->b_p_bomb @@ -1172,9 +1136,7 @@ retry: ptr -= conv_restlen; size += conv_restlen; conv_restlen = 0; - /* - * Break here for a read error or end-of-file. - */ + // Break here for a read error or end-of-file. if (size <= 0) { break; } @@ -1188,11 +1150,9 @@ retry: char *top = ptr; size_t to_size = (size_t)(real_size - size); - /* - * If there is conversion error or not enough room try using - * another conversion. Except for when there is no - * alternative (help files). - */ + // If there is conversion error or not enough room try using + // another conversion. Except for when there is no + // alternative (help files). while ((iconv(iconv_fd, (void *)&fromp, &from_size, &top, &to_size) == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) @@ -1493,9 +1453,7 @@ rewind_retry: // count the number of characters (after conversion!) filesize += size; - /* - * when reading the first part of a file: guess EOL type - */ + // when reading the first part of a file: guess EOL type if (fileformat == EOL_UNKNOWN) { // First try finding a NL, for Dos and Unix if (try_dos || try_unix) { @@ -1560,10 +1518,8 @@ rewind_retry: } } - /* - * This loop is executed once for every character read. - * Keep it fast! - */ + // This loop is executed once for every character read. + // Keep it fast! if (fileformat == EOL_MAC) { ptr--; while (++ptr, --size >= 0) { @@ -1665,11 +1621,9 @@ failed: error = false; } - /* - * If we get EOF in the middle of a line, note the fact and - * complete the line ourselves. - * In Dos format ignore a trailing CTRL-Z, unless 'binary' set. - */ + // If we get EOF in the middle of a line, note the fact and + // complete the line ourselves. + // In Dos format ignore a trailing CTRL-Z, unless 'binary' set. if (!error && !got_int && linerest != 0 @@ -1738,9 +1692,7 @@ failed: } no_wait_return--; // may wait for return now - /* - * In recovery mode everything but autocommands is skipped. - */ + // In recovery mode everything but autocommands is skipped. if (!recoverymode) { // need to delete the last line, which comes from the empty buffer if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY)) { @@ -1767,11 +1719,9 @@ failed: appended_lines_mark(from, linecnt); } - /* - * If we were reading from the same terminal as where messages go, - * the screen will have been messed up. - * Switch on raw mode now and clear the screen. - */ + // If we were reading from the same terminal as where messages go, + // the screen will have been messed up. + // Switch on raw mode now and clear the screen. if (read_stdin) { screenclear(); } @@ -1878,10 +1828,8 @@ failed: u_clearline(); // cannot use "U" command after adding lines - /* - * In Ex mode: cursor at last new line. - * Otherwise: cursor at first new line. - */ + // In Ex mode: cursor at last new line. + // Otherwise: cursor at first new line. if (exmode_active) { curwin->w_cursor.lnum = from + linecnt; } else { @@ -1900,17 +1848,13 @@ failed: } msg_scroll = msg_save; - /* - * Get the marks before executing autocommands, so they can be used there. - */ + // Get the marks before executing autocommands, so they can be used there. check_marks_read(); - /* - * We remember if the last line of the read didn't have - * an eol even when 'binary' is off, to support turning 'fixeol' off, - * or writing the read again with 'binary' on. The latter is required - * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work. - */ + // We remember if the last line of the read didn't have + // an eol even when 'binary' is off, to support turning 'fixeol' off, + // or writing the read again with 'binary' on. The latter is required + // for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work. curbuf->b_no_eol_lnum = read_no_eol_lnum; // When reloading a buffer put the cursor at the first line that is @@ -1919,9 +1863,7 @@ failed: u_find_first_changed(); } - /* - * When opening a new file locate undo info and read it. - */ + // When opening a new file locate undo info and read it. if (read_undo_file) { char_u hash[UNDO_HASH_SIZE]; @@ -1939,11 +1881,9 @@ failed: save_file_ff(curbuf); } - /* - * The output from the autocommands should not overwrite anything and - * should not be overwritten: Set msg_scroll, restore its value if no - * output was done. - */ + // The output from the autocommands should not overwrite anything and + // should not be overwritten: Set msg_scroll, restore its value if no + // output was done. msg_scroll = true; if (filtering) { apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname, @@ -2256,10 +2196,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en return FAIL; } - /* - * Disallow writing from .exrc and .vimrc in current directory for - * security reasons. - */ + // Disallow writing from .exrc and .vimrc in current directory for + // security reasons. if (check_secure()) { return FAIL; } @@ -2283,13 +2221,11 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en * the line. */ ex_no_reprint = true; - /* - * If there is no file name yet, use the one for the written file. - * BF_NOTEDITED is set to reflect this (in case the write fails). - * Don't do this when the write is for a filter command. - * Don't do this when appending. - * Only do this when 'cpoptions' contains the 'F' flag. - */ + // If there is no file name yet, use the one for the written file. + // BF_NOTEDITED is set to reflect this (in case the write fails). + // Don't do this when the write is for a filter command. + // Don't do this when appending. + // Only do this when 'cpoptions' contains the 'F' flag. if (buf->b_ffname == NULL && reset_changed && whole @@ -2325,9 +2261,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en no_wait_return++; // don't wait for return yet - /* - * Set '[ and '] marks to the lines to be written. - */ + // Set '[ and '] marks to the lines to be written. buf->b_op_start.lnum = start; buf->b_op_start.col = 0; buf->b_op_end.lnum = end; @@ -2344,11 +2278,9 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en int empty_memline = (buf->b_ml.ml_mfp == NULL); bufref_T bufref; - /* - * Apply PRE autocommands. - * Set curbuf to the buffer to be written. - * Careful: The autocommands may call buf_write() recursively! - */ + // Apply PRE autocommands. + // Set curbuf to the buffer to be written. + // Careful: The autocommands may call buf_write() recursively! if (ffname == buf->b_ffname) { buf_ffname = true; } @@ -2471,12 +2403,10 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en return FAIL; } - /* - * The autocommands may have changed the number of lines in the file. - * When writing the whole file, adjust the end. - * When writing part of the file, assume that the autocommands only - * changed the number of lines that are to be written (tricky!). - */ + // The autocommands may have changed the number of lines in the file. + // When writing the whole file, adjust the end. + // When writing part of the file, assume that the autocommands only + // changed the number of lines that are to be written (tricky!). if (buf->b_ml.ml_line_count != old_line_count) { if (whole) { // write all end = buf->b_ml.ml_line_count; @@ -2493,10 +2423,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en } } - /* - * The autocommands may have changed the name of the buffer, which may - * be kept in fname, ffname and sfname. - */ + // The autocommands may have changed the name of the buffer, which may + // be kept in fname, ffname and sfname. if (buf_ffname) { ffname = buf->b_ffname; } @@ -2543,9 +2471,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en bufsize = BUFSIZE; } - /* - * Get information about original file (if there is one). - */ + // Get information about original file (if there is one). FileInfo file_info_old; #if defined(UNIX) perm = -1; @@ -2595,10 +2521,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en #endif // !UNIX if (!device && !newfile) { - /* - * Check if the file is really writable (when renaming the file to - * make a backup we won't discover it later). - */ + // Check if the file is really writable (when renaming the file to + // make a backup we won't discover it later). file_readonly = !os_file_is_writable(fname); if (!forceit && file_readonly) { @@ -2610,9 +2534,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en goto fail; } - /* - * Check if the timestamp hasn't changed since reading the file. - */ + // Check if the timestamp hasn't changed since reading the file. if (overwriting) { retval = check_mtime(buf, &file_info_old); if (retval == FAIL) { @@ -2622,41 +2544,33 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en } #ifdef HAVE_ACL - /* - * For systems that support ACL: get the ACL from the original file. - */ + // For systems that support ACL: get the ACL from the original file. if (!newfile) { acl = mch_get_acl((char_u *)fname); } #endif - /* - * If 'backupskip' is not empty, don't make a backup for some files. - */ + // If 'backupskip' is not empty, don't make a backup for some files. dobackup = (p_wb || p_bk || *p_pm != NUL); if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, (char_u *)sfname, (char_u *)ffname)) { dobackup = false; } - /* - * Save the value of got_int and reset it. We don't want a previous - * interruption cancel writing, only hitting CTRL-C while writing should - * abort it. - */ + // Save the value of got_int and reset it. We don't want a previous + // interruption cancel writing, only hitting CTRL-C while writing should + // abort it. prev_got_int = got_int; got_int = false; // Mark the buffer as 'being saved' to prevent changed buffer warnings buf->b_saving = true; - /* - * If we are not appending or filtering, the file exists, and the - * 'writebackup', 'backup' or 'patchmode' option is set, need a backup. - * When 'patchmode' is set also make a backup when appending. - * - * Do not make any backup, if 'writebackup' and 'backup' are both switched - * off. This helps when editing large files on almost-full disks. - */ + // If we are not appending or filtering, the file exists, and the + // 'writebackup', 'backup' or 'patchmode' option is set, need a backup. + // When 'patchmode' is set also make a backup when appending. + // + // Do not make any backup, if 'writebackup' and 'backup' are both switched + // off. This helps when editing large files on almost-full disks. if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup) { FileInfo file_info; const bool no_prepend_dot = false; @@ -2666,23 +2580,19 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en } else if ((bkc & BKC_AUTO)) { // "auto" int i; - /* - * Don't rename the file when: - * - it's a hard link - * - it's a symbolic link - * - we don't have write permission in the directory - */ + // Don't rename the file when: + // - it's a hard link + // - it's a symbolic link + // - we don't have write permission in the directory if (os_fileinfo_hardlinks(&file_info_old) > 1 || !os_fileinfo_link(fname, &file_info) || !os_fileinfo_id_equal(&file_info, &file_info_old)) { backup_copy = true; } else { - /* - * Check if we can create a file and set the owner/group to - * the ones from the original file. - * First find a file name that doesn't exist yet (use some - * arbitrary numbers). - */ + // Check if we can create a file and set the owner/group to + // the ones from the original file. + // First find a file name that doesn't exist yet (use some + // arbitrary numbers). STRCPY(IObuff, fname); for (i = 4913;; i += 123) { char *tail = path_tail((char *)IObuff); @@ -2714,9 +2624,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en } } - /* - * Break symlinks and/or hardlinks if we've been asked to. - */ + // Break symlinks and/or hardlinks if we've been asked to. if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK)) { #ifdef UNIX bool file_info_link_ok = os_fileinfo_link(fname, &file_info); @@ -2752,23 +2660,19 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en char *rootname; char *p; - /* - * Try to make the backup in each directory in the 'bdir' option. - * - * Unix semantics has it, that we may have a writable file, - * that cannot be recreated with a simple open(..., O_CREAT, ) e.g: - * - the directory is not writable, - * - the file may be a symbolic link, - * - the file may belong to another user/group, etc. - * - * For these reasons, the existing writable file must be truncated - * and reused. Creation of a backup COPY will be attempted. - */ + // Try to make the backup in each directory in the 'bdir' option. + // + // Unix semantics has it, that we may have a writable file, + // that cannot be recreated with a simple open(..., O_CREAT, ) e.g: + // - the directory is not writable, + // - the file may be a symbolic link, + // - the file may belong to another user/group, etc. + // + // For these reasons, the existing writable file must be truncated + // and reused. Creation of a backup COPY will be attempted. dirp = p_bdir; while (*dirp) { - /* - * Isolate one directory name, using an entry in 'bdir'. - */ + // Isolate one directory name, using an entry in 'bdir'. size_t dir_len = copy_option_part(&dirp, (char *)IObuff, IOSIZE, ","); p = (char *)IObuff + dir_len; bool trailing_pathseps = after_pathsep((char *)IObuff, p) && p[-1] == p[-2]; @@ -2814,9 +2718,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en goto nobackup; } - /* - * Check if backup file already exists. - */ + // Check if backup file already exists. if (os_fileinfo(backup, &file_info_new)) { if (os_fileinfo_id_equal(&file_info_new, &file_info_old)) { // @@ -2848,9 +2750,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en } xfree(rootname); - /* - * Try to create the backup file - */ + // Try to create the backup file if (backup != NULL) { // remove old backup, if present os_remove(backup); @@ -2906,30 +2806,22 @@ nobackup: char *p; char *rootname; - /* - * Make a backup by renaming the original file. - */ - /* - * If 'cpoptions' includes the "W" flag, we don't want to - * overwrite a read-only file. But rename may be possible - * anyway, thus we need an extra check here. - */ + // Make a backup by renaming the original file. + + // If 'cpoptions' includes the "W" flag, we don't want to + // overwrite a read-only file. But rename may be possible + // anyway, thus we need an extra check here. if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL) { SET_ERRMSG_NUM("E504", _(err_readonly)); goto fail; } - /* - * - * Form the backup file name - change path/fo.o.h to - * path/fo.o.h.bak Try all directories in 'backupdir', first one - * that works is used. - */ + // Form the backup file name - change path/fo.o.h to + // path/fo.o.h.bak Try all directories in 'backupdir', first one + // that works is used. dirp = p_bdir; while (*dirp) { - /* - * Isolate one directory name and make the backup file name. - */ + // Isolate one directory name and make the backup file name. size_t dir_len = copy_option_part(&dirp, (char *)IObuff, IOSIZE, ","); p = (char *)IObuff + dir_len; bool trailing_pathseps = after_pathsep((char *)IObuff, p) && p[-1] == p[-2]; @@ -2965,11 +2857,9 @@ nobackup: } if (backup != NULL) { - /* - * If we are not going to keep the backup file, don't - * delete an existing one, try to use another name. - * Change one character, just before the extension. - */ + // If we are not going to keep the backup file, don't + // delete an existing one, try to use another name. + // Change one character, just before the extension. if (!p_bk && os_path_exists(backup)) { p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext); if (p < backup) { // empty file name ??? @@ -3099,11 +2989,9 @@ nobackup: } else { #endif - /* - * When the file needs to be converted with 'charconvert' after - * writing, write to a temp file instead and let the conversion - * overwrite the original file. - */ + // When the file needs to be converted with 'charconvert' after + // writing, write to a temp file instead and let the conversion + // overwrite the original file. if (*p_ccv != NUL) { wfname = (char *)vim_tempname(); if (wfname == NULL) { // Can't write without a tempfile! @@ -3561,10 +3449,8 @@ restore_backup: u_update_save_nr(buf); } - /* - * If written to the current file, update the timestamp of the swap file - * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime. - */ + // If written to the current file, update the timestamp of the swap file + // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime. if (overwriting) { ml_timestamp(buf); if (append) { @@ -3574,18 +3460,14 @@ restore_backup: } } - /* - * If we kept a backup until now, and we are in patch mode, then we make - * the backup file our 'original' file. - */ + // If we kept a backup until now, and we are in patch mode, then we make + // the backup file our 'original' file. if (*p_pm && dobackup) { char *const org = modname(fname, p_pm, false); if (backup != NULL) { - /* - * If the original file does not exist yet - * the current backup file becomes the original file - */ + // If the original file does not exist yet + // the current backup file becomes the original file if (org == NULL) { emsg(_("E205: Patchmode: can't save original file")); } else if (!os_path_exists(org)) { @@ -3597,12 +3479,9 @@ restore_backup: (double)file_info_old.stat.st_mtim.tv_sec); #endif } - } - /* - * If there is no backup file, remember that a (new) file was - * created. - */ - else { + } else { + // If there is no backup file, remember that a (new) file was + // created. int empty_fd; if (org == NULL @@ -3620,9 +3499,7 @@ restore_backup: } } - /* - * Remove the backup unless 'backup' option is set - */ + // Remove the backup unless 'backup' option is set if (!p_bk && backup != NULL && !write_info.bw_conv_error && os_remove(backup) != 0) { @@ -3631,9 +3508,7 @@ restore_backup: goto nofail; - /* - * Finish up. We get here either after failure or success. - */ + // Finish up. We get here either after failure or success. fail: no_wait_return--; // may wait for return now nofail: @@ -3698,10 +3573,8 @@ nofail: } msg_scroll = msg_save; - /* - * When writing the whole file and 'undofile' is set, also write the undo - * file. - */ + // When writing the whole file and 'undofile' is set, also write the undo + // file. if (retval == OK && write_undo_file) { char hash[UNDO_HASH_SIZE]; @@ -3714,10 +3587,8 @@ nofail: curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read - /* - * Apply POST autocommands. - * Careful: The autocommands may call buf_write() recursively! - */ + // Apply POST autocommands. + // Careful: The autocommands may call buf_write() recursively! aucmd_prepbuf(&aco, buf); if (append) { @@ -3918,18 +3789,14 @@ static int buf_write_bytes(struct bw_info *ip) int flags = ip->bw_flags; // extra flags #endif - /* - * Skip conversion when writing the BOM. - */ + // Skip conversion when writing the BOM. if (!(flags & FIO_NOCONVERT)) { char_u *p; unsigned c; int n; if (flags & FIO_UTF8) { - /* - * Convert latin1 in the buffer to UTF-8 in the file. - */ + // Convert latin1 in the buffer to UTF-8 in the file. p = ip->bw_conv_buf; // translate to buffer for (wlen = 0; wlen < len; wlen++) { p += utf_char2bytes(buf[wlen], (char *)p); @@ -3937,10 +3804,8 @@ static int buf_write_bytes(struct bw_info *ip) buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) { - /* - * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or - * Latin1 chars in the file. - */ + // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or + // Latin1 chars in the file. if (flags & FIO_LATIN1) { p = buf; // translate in-place (can only get shorter) } else { @@ -4063,9 +3928,7 @@ static int buf_write_bytes(struct bw_info *ip) ip->bw_first = false; } - /* - * If iconv() has an error or there is not enough room, fail. - */ + // If iconv() has an error or there is not enough room, fail. if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen) == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) || fromlen > CONV_RESTLEN) { @@ -4633,11 +4496,9 @@ int vim_rename(const char_u *from, const char_u *to) #endif bool use_tmp_file = false; - /* - * When the names are identical, there is nothing to do. When they refer - * to the same file (ignoring case and slash/backslash differences) but - * the file name differs we need to go through a temp file. - */ + // When the names are identical, there is nothing to do. When they refer + // to the same file (ignoring case and slash/backslash differences) but + // the file name differs we need to go through a temp file. if (FNAMECMP(from, to) == 0) { if (p_fic && (STRCMP(path_tail((char *)from), path_tail((char *)to)) != 0)) { @@ -4665,10 +4526,8 @@ int vim_rename(const char_u *from, const char_u *to) if (use_tmp_file) { char_u tempname[MAXPATHL + 1]; - /* - * Find a name that doesn't exist and is in the same directory. - * Rename "from" to "tempname" and then rename "tempname" to "to". - */ + // Find a name that doesn't exist and is in the same directory. + // Rename "from" to "tempname" and then rename "tempname" to "to". if (STRLEN(from) >= MAXPATHL - 5) { return -1; } @@ -4695,24 +4554,18 @@ int vim_rename(const char_u *from, const char_u *to) return -1; } - /* - * Delete the "to" file, this is required on some systems to make the - * os_rename() work, on other systems it makes sure that we don't have - * two files when the os_rename() fails. - */ + // Delete the "to" file, this is required on some systems to make the + // os_rename() work, on other systems it makes sure that we don't have + // two files when the os_rename() fails. os_remove((char *)to); - /* - * First try a normal rename, return if it works. - */ + // First try a normal rename, return if it works. if (os_rename(from, to) == OK) { return 0; } - /* - * Rename() failed, try copying the file. - */ + // Rename() failed, try copying the file. perm = os_getperm((const char *)from); #ifdef HAVE_ACL // For systems that support ACL: get the ACL from the original file. @@ -5553,12 +5406,10 @@ bool match_file_pat(char *pattern, regprog_T **prog, char *fname, char *sfname, } } - /* - * Try for a match with the pattern with: - * 1. the full file name, when the pattern has a '/'. - * 2. the short file name, when the pattern has a '/'. - * 3. the tail of the file name, when the pattern has no '/'. - */ + // Try for a match with the pattern with: + // 1. the full file name, when the pattern has a '/'. + // 2. the short file name, when the pattern has a '/'. + // 3. the tail of the file name, when the pattern has no '/'. if (regmatch.regprog != NULL && ((allow_dirs && (vim_regexec(®match, fname, (colnr_T)0) diff --git a/src/nvim/fold.h b/src/nvim/fold.h index f34e6d43c3..395cd8e30a 100644 --- a/src/nvim/fold.h +++ b/src/nvim/fold.h @@ -8,10 +8,8 @@ #include "nvim/pos.h" #include "nvim/types.h" -/* - * Info used to pass info about a fold from the fold-detection code to the - * code that displays the foldcolumn. - */ +// Info used to pass info about a fold from the fold-detection code to the +// code that displays the foldcolumn. typedef struct foldinfo { linenr_T fi_lnum; // line number where fold starts int fi_level; // level of the fold; when this is zero the diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index 97c3b1c61f..22c350d36b 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -87,25 +87,23 @@ static int block_redo = false; static int KeyNoremap = 0; // remapping flags -/* - * Variables used by vgetorpeek() and flush_buffers() - * - * typebuf.tb_buf[] contains all characters that are not consumed yet. - * typebuf.tb_buf[typebuf.tb_off] is the first valid character. - * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char. - * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL. - * The head of the buffer may contain the result of mappings, abbreviations - * and @a commands. The length of this part is typebuf.tb_maplen. - * typebuf.tb_silent is the part where applies. - * After the head are characters that come from the terminal. - * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that - * should not be considered for abbreviations. - * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered - * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and - * contains RM_NONE for the characters that are not to be remapped. - * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag. - * (typebuf has been put in globals.h, because check_termcode() needs it). - */ +// Variables used by vgetorpeek() and flush_buffers() +// +// typebuf.tb_buf[] contains all characters that are not consumed yet. +// typebuf.tb_buf[typebuf.tb_off] is the first valid character. +// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char. +// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL. +// The head of the buffer may contain the result of mappings, abbreviations +// and @a commands. The length of this part is typebuf.tb_maplen. +// typebuf.tb_silent is the part where applies. +// After the head are characters that come from the terminal. +// typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that +// should not be considered for abbreviations. +// Some parts of typebuf.tb_buf may not be mapped. These parts are remembered +// in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and +// contains RM_NONE for the characters that are not to be remapped. +// typebuf.tb_noremap[typebuf.tb_off] is the first valid flag. +// (typebuf has been put in globals.h, because check_termcode() needs it). #define RM_YES 0 // tb_noremap: remap #define RM_NONE 1 // tb_noremap: don't remap #define RM_SCRIPT 2 // tb_noremap: remap local script mappings @@ -124,9 +122,7 @@ static size_t last_recorded_len = 0; // number of last recorded chars # include "getchar.c.generated.h" #endif -/* - * Free and clear a buffer. - */ +// Free and clear a buffer. void free_buff(buffheader_T *buf) { buffblock_T *p, *np; @@ -180,20 +176,16 @@ char_u *get_recorded(void) p = get_buffcont(&recordbuff, true); free_buff(&recordbuff); - /* - * Remove the characters that were added the last time, these must be the - * (possibly mapped) characters that stopped the recording. - */ + // Remove the characters that were added the last time, these must be the + // (possibly mapped) characters that stopped the recording. len = STRLEN(p); if (len >= last_recorded_len) { len -= last_recorded_len; p[len] = NUL; } - /* - * When stopping recording from Insert mode with CTRL-O q, also remove the - * CTRL-O. - */ + // When stopping recording from Insert mode with CTRL-O q, also remove the + // CTRL-O. if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O) { p[len - 1] = NUL; } @@ -351,9 +343,7 @@ static int read_readbuf(buffheader_T *buf, int advance) return c; } -/* - * Prepare the read buffers for reading (if they contain something). - */ +// Prepare the read buffers for reading (if they contain something). static void start_stuff(void) { if (readbuf1.bh_first.b_next != NULL) { @@ -381,19 +371,15 @@ int readbuf1_empty(void) return (readbuf1.bh_first.b_next == NULL); } -/* - * Set a typeahead character that won't be flushed. - */ +// Set a typeahead character that won't be flushed. void typeahead_noflush(int c) { typeahead_char = c; } -/* - * Remove the contents of the stuff buffer and the mapped characters in the - * typeahead buffer (used in case of an error). If "flush_typeahead" is true, - * flush all typeahead characters (used when interrupted by a CTRL-C). - */ +// Remove the contents of the stuff buffer and the mapped characters in the +// typeahead buffer (used in case of an error). If "flush_typeahead" is true, +// flush all typeahead characters (used when interrupted by a CTRL-C). void flush_buffers(flush_buffers_T flush_typeahead) { init_typebuf(); @@ -437,10 +423,8 @@ void beep_flush(void) } } -/* - * The previous contents of the redo buffer is kept in old_redobuffer. - * This is used for the CTRL-O <.> command in insert mode. - */ +// The previous contents of the redo buffer is kept in old_redobuffer. +// This is used for the CTRL-O <.> command in insert mode. void ResetRedobuff(void) { if (!block_redo) { @@ -450,10 +434,8 @@ void ResetRedobuff(void) } } -/* - * Discard the contents of the redo buffer and restore the previous redo - * buffer. - */ +// Discard the contents of the redo buffer and restore the previous redo +// buffer. void CancelRedo(void) { if (!block_redo) { @@ -559,9 +541,7 @@ void AppendCharToRedobuff(int c) } } -/* - * Append a number to the redo buffer. - */ +// Append a number to the redo buffer. void AppendNumberToRedobuff(long n) { if (!block_redo) { @@ -615,9 +595,7 @@ void stuffcharReadbuff(int c) add_char_buff(&readbuf1, c); } -/* - * Append a number to the stuff buffer. - */ +// Append a number to the stuff buffer. void stuffnumReadbuff(long n) { add_num_buff(&readbuf1, n); @@ -783,11 +761,9 @@ int start_redo(long count, bool old_redo) return OK; } -/* - * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing - * the redo buffer into readbuf2. - * return FAIL for failure, OK otherwise - */ +// Repeat the last insert (R, o, O, a, A, i or I command) by stuffing +// the redo buffer into readbuf2. +// return FAIL for failure, OK otherwise int start_redo_ins(void) { int c; @@ -818,11 +794,9 @@ void stop_redo_ins(void) block_redo = false; } -/* - * Initialize typebuf.tb_buf to point to typebuf_init. - * alloc() cannot be used here: In out-of-memory situations it would - * be impossible to type anything. - */ +// Initialize typebuf.tb_buf to point to typebuf_init. +// alloc() cannot be used here: In out-of-memory situations it would +// be impossible to type anything. static void init_typebuf(void) { if (typebuf.tb_buf == NULL) { @@ -939,14 +913,12 @@ int ins_typebuf(char *str, int noremap, int offset, bool nottyped, bool silent) val = RM_NONE; } - /* - * Adjust typebuf.tb_noremap[] for the new characters: - * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are - * (sometimes) not remappable - * If noremap == REMAP_YES: all the new characters are mappable - * If noremap > 0: "noremap" characters are not remappable, the rest - * mappable - */ + // Adjust typebuf.tb_noremap[] for the new characters: + // If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are + // (sometimes) not remappable + // If noremap == REMAP_YES: all the new characters are mappable + // If noremap > 0: "noremap" characters are not remappable, the rest + // mappable if (noremap == REMAP_SKIP) { nrm = 1; } else if (noremap < 0) { @@ -1016,18 +988,14 @@ int typebuf_typed(void) return typebuf.tb_maplen == 0; } -/* - * Return the number of characters that are mapped (or not typed). - */ +// Return the number of characters that are mapped (or not typed). int typebuf_maplen(void) FUNC_ATTR_PURE { return typebuf.tb_maplen; } -/* - * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset] - */ +// remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset] void del_typebuf(int len, int offset) { int i; @@ -1038,21 +1006,14 @@ void del_typebuf(int len, int offset) typebuf.tb_len -= len; - /* - * Easy case: Just increase typebuf.tb_off. - */ + // Easy case: Just increase typebuf.tb_off. if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len) >= 3 * MAXMAPLEN + 3) { typebuf.tb_off += len; - } - /* - * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[] - */ - else { + } else { + // Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[] i = typebuf.tb_off + offset; - /* - * Leave some extra room at the end to avoid reallocation. - */ + // Leave some extra room at the end to avoid reallocation. if (typebuf.tb_off > MAXMAPLEN) { memmove(typebuf.tb_buf + MAXMAPLEN, typebuf.tb_buf + typebuf.tb_off, (size_t)offset); @@ -1101,10 +1062,8 @@ void del_typebuf(int len, int offset) } } -/* - * Write typed characters to script file. - * If recording is on put the character in the recordbuffer. - */ +// Write typed characters to script file. +// If recording is on put the character in the recordbuffer. static void gotchars(const char_u *chars, size_t len) FUNC_ATTR_NONNULL_ALL { @@ -1161,14 +1120,12 @@ void ungetchars(int len) } } -/* - * Sync undo. Called when typed characters are obtained from the typeahead - * buffer, or when a menu is used. - * Do not sync: - * - In Insert mode, unless cursor key has been used. - * - While reading a script file. - * - When no_u_sync is non-zero. - */ +// Sync undo. Called when typed characters are obtained from the typeahead +// buffer, or when a menu is used. +// Do not sync: +// - In Insert mode, unless cursor key has been used. +// - While reading a script file. +// - When no_u_sync is non-zero. void may_sync_undo(void) { if ((!(State & (MODE_INSERT | MODE_CMDLINE)) || arrow_used) @@ -1177,9 +1134,7 @@ void may_sync_undo(void) } } -/* - * Make "typebuf" empty and allocate new buffers. - */ +// Make "typebuf" empty and allocate new buffers. void alloc_typebuf(void) { typebuf.tb_buf = xmalloc(TYPELEN_INIT); @@ -1195,9 +1150,7 @@ void alloc_typebuf(void) } } -/* - * Free the buffers of "typebuf". - */ +// Free the buffers of "typebuf". void free_typebuf(void) { if (typebuf.tb_buf == typebuf_init) { @@ -1212,10 +1165,8 @@ void free_typebuf(void) } } -/* - * When doing ":so! file", the current typeahead needs to be saved, and - * restored when "file" has been read completely. - */ +// When doing ":so! file", the current typeahead needs to be saved, and +// restored when "file" has been read completely. static typebuf_T saved_typebuf[NSCRIPT]; void save_typebuf(void) @@ -1239,9 +1190,7 @@ static bool can_get_old_char(void) return old_char != -1 && (old_KeyStuffed || stuff_empty()); } -/* - * Save all three kinds of typeahead, so that the user must type at a prompt. - */ +// Save all three kinds of typeahead, so that the user must type at a prompt. void save_typeahead(tasave_T *tp) { tp->save_typebuf = typebuf; @@ -1257,10 +1206,8 @@ void save_typeahead(tasave_T *tp) readbuf2.bh_first.b_next = NULL; } -/* - * Restore the typeahead to what it was before calling save_typeahead(). - * The allocated memory is freed, can only be called once! - */ +// Restore the typeahead to what it was before calling save_typeahead(). +// The allocated memory is freed, can only be called once! void restore_typeahead(tasave_T *tp) { if (tp->typebuf_valid) { @@ -1314,12 +1261,10 @@ void openscript(char *name, bool directly) } save_typebuf(); - /* - * Execute the commands from the file right now when using ":source!" - * after ":global" or ":argdo" or in a loop. Also when another command - * follows. This means the display won't be updated. Don't do this - * always, "make test" would fail. - */ + // Execute the commands from the file right now when using ":source!" + // after ":global" or ":argdo" or in a loop. Also when another command + // follows. This means the display won't be updated. Don't do this + // always, "make test" would fail. if (directly) { oparg_T oa; int oldcurscript; @@ -1348,9 +1293,7 @@ void openscript(char *name, bool directly) } } -/* - * Close the currently active input script. - */ +// Close the currently active input script. static void closescript(void) { free_typebuf(); @@ -1452,10 +1395,8 @@ int vgetc(void) garbage_collect(false); } - /* - * If a character was put back with vungetc, it was already processed. - * Return it directly. - */ + // If a character was put back with vungetc, it was already processed. + // Return it directly. if (can_get_old_char()) { c = old_char; old_char = -1; @@ -1628,11 +1569,9 @@ int vgetc(void) last_vgetc_recorded_len = last_recorded_len; } - /* - * In the main loop "may_garbage_collect" can be set to do garbage - * collection in the first next vgetc(). It's disabled after that to - * avoid internally used Lists and Dicts to be freed. - */ + // In the main loop "may_garbage_collect" can be set to do garbage + // collection in the first next vgetc(). It's disabled after that to + // avoid internally used Lists and Dicts to be freed. may_garbage_collect = false; // Execute Lua on_key callbacks. @@ -1641,10 +1580,8 @@ int vgetc(void) return c; } -/* - * Like vgetc(), but never return a NUL when called recursively, get a key - * directly from the user (ignoring typeahead). - */ +// Like vgetc(), but never return a NUL when called recursively, get a key +// directly from the user (ignoring typeahead). int safe_vgetc(void) { int c; @@ -1656,10 +1593,8 @@ int safe_vgetc(void) return c; } -/* - * Like safe_vgetc(), but loop to handle K_IGNORE. - * Also ignore scrollbar events. - */ +// Like safe_vgetc(), but loop to handle K_IGNORE. +// Also ignore scrollbar events. int plain_vgetc(void) { int c; @@ -1672,12 +1607,10 @@ int plain_vgetc(void) return c; } -/* - * Check if a character is available, such that vgetc() will not block. - * If the next character is a special character or multi-byte, the returned - * character is not valid!. - * Returns NUL if no character is available. - */ +// Check if a character is available, such that vgetc() will not block. +// If the next character is a special character or multi-byte, the returned +// character is not valid!. +// Returns NUL if no character is available. int vpeekc(void) { if (can_get_old_char()) { @@ -1686,11 +1619,9 @@ int vpeekc(void) return vgetorpeek(false); } -/* - * Check if any character is available, also half an escape sequence. - * Trick: when no typeahead found, but there is something in the typeahead - * buffer, it must be an ESC that is recognized as the start of a key code. - */ +// Check if any character is available, also half an escape sequence. +// Trick: when no typeahead found, but there is something in the typeahead +// buffer, it must be an ESC that is recognized as the start of a key code. int vpeekc_any(void) { int c; @@ -1702,10 +1633,8 @@ int vpeekc_any(void) return c; } -/* - * Call vpeekc() without causing anything to be mapped. - * Return true if a character is available, false otherwise. - */ +// Call vpeekc() without causing anything to be mapped. +// Return true if a character is available, false otherwise. int char_avail(void) { int retval; @@ -2851,11 +2780,9 @@ int inchar(char_u *buf, int maxlen, long wait_time) ui_flush(); } - /* - * Don't reset these when at the hit-return prompt, otherwise an endless - * recursive loop may result (write error in swapfile, hit-return, timeout - * on char wait, flush swapfile, write error....). - */ + // Don't reset these when at the hit-return prompt, otherwise an endless + // recursive loop may result (write error in swapfile, hit-return, timeout + // on char wait, flush swapfile, write error....). if (State != MODE_HITRETURN) { did_outofmem_msg = false; // display out of memory message (again) did_swapwrite_msg = false; // display swap file write error again diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c index d7f5730943..e280648fd2 100644 --- a/src/nvim/hardcopy.c +++ b/src/nvim/hardcopy.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * hardcopy.c: printing to paper - */ +// hardcopy.c: printing to paper #include #include @@ -36,64 +34,62 @@ #include "nvim/version.h" #include "nvim/vim.h" -/* - * To implement printing on a platform, the following functions must be - * defined: - * - * int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) - * Called once. Code should display printer dialogue (if appropriate) and - * determine printer font and margin settings. Reset has_color if the printer - * doesn't support colors at all. - * Returns FAIL to abort. - * - * int mch_print_begin(prt_settings_T *settings) - * Called to start the print job. - * Return false to abort. - * - * int mch_print_begin_page(char_u *msg) - * Called at the start of each page. - * "msg" indicates the progress of the print job, can be NULL. - * Return false to abort. - * - * int mch_print_end_page() - * Called at the end of each page. - * Return false to abort. - * - * int mch_print_blank_page() - * Called to generate a blank page for collated, duplex, multiple copy - * document. Return false to abort. - * - * void mch_print_end(prt_settings_T *psettings) - * Called at normal end of print job. - * - * void mch_print_cleanup() - * Called if print job ends normally or is abandoned. Free any memory, close - * devices and handles. Also called when mch_print_begin() fails, but not - * when mch_print_init() fails. - * - * void mch_print_set_font(int Bold, int Italic, int Underline); - * Called whenever the font style changes. - * - * void mch_print_set_bg(uint32_t bgcol); - * Called to set the background color for the following text. Parameter is an - * RGB value. - * - * void mch_print_set_fg(uint32_t fgcol); - * Called to set the foreground color for the following text. Parameter is an - * RGB value. - * - * mch_print_start_line(int margin, int page_line) - * Sets the current position at the start of line "page_line". - * If margin is true start in the left margin (for header and line number). - * - * int mch_print_text_out(char_u *p, size_t len); - * Output one character of text p[len] at the current position. - * Return true if there is no room for another character in the same line. - * - * Note that the generic code has no idea of margins. The machine code should - * simply make the page look smaller! The header and the line numbers are - * printed in the margin. - */ +// To implement printing on a platform, the following functions must be +// defined: +// +// int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) +// Called once. Code should display printer dialogue (if appropriate) and +// determine printer font and margin settings. Reset has_color if the printer +// doesn't support colors at all. +// Returns FAIL to abort. +// +// int mch_print_begin(prt_settings_T *settings) +// Called to start the print job. +// Return false to abort. +// +// int mch_print_begin_page(char_u *msg) +// Called at the start of each page. +// "msg" indicates the progress of the print job, can be NULL. +// Return false to abort. +// +// int mch_print_end_page() +// Called at the end of each page. +// Return false to abort. +// +// int mch_print_blank_page() +// Called to generate a blank page for collated, duplex, multiple copy +// document. Return false to abort. +// +// void mch_print_end(prt_settings_T *psettings) +// Called at normal end of print job. +// +// void mch_print_cleanup() +// Called if print job ends normally or is abandoned. Free any memory, close +// devices and handles. Also called when mch_print_begin() fails, but not +// when mch_print_init() fails. +// +// void mch_print_set_font(int Bold, int Italic, int Underline); +// Called whenever the font style changes. +// +// void mch_print_set_bg(uint32_t bgcol); +// Called to set the background color for the following text. Parameter is an +// RGB value. +// +// void mch_print_set_fg(uint32_t fgcol); +// Called to set the foreground color for the following text. Parameter is an +// RGB value. +// +// mch_print_start_line(int margin, int page_line) +// Sets the current position at the start of line "page_line". +// If margin is true start in the left margin (for header and line number). +// +// int mch_print_text_out(char_u *p, size_t len); +// Output one character of text p[len] at the current position. +// Return true if there is no room for another character in the same line. +// +// Note that the generic code has no idea of margins. The machine code should +// simply make the page look smaller! The header and the line numbers are +// printed in the margin. static option_table_T printer_opts[OPT_PRINT_NUM_OPTIONS] = { { "top", true, 0, NULL, 0, false }, @@ -154,9 +150,7 @@ static option_table_T mbfont_opts[OPT_MBFONT_NUM_OPTIONS] = { "o", false, 0, NULL, 0, false }, }; -/* - * These values determine the print position on a page. - */ +// These values determine the print position on a page. typedef struct { int lead_spaces; // remaining spaces for a TAB int print_pos; // virtual column for computing TABs @@ -255,33 +249,27 @@ struct prt_resfile_buffer_S { # include "hardcopy.c.generated.h" #endif -/* - * Parse 'printoptions' and set the flags in "printer_opts". - * Returns an error message or NULL; - */ +// Parse 'printoptions' and set the flags in "printer_opts". +// Returns an error message or NULL; char *parse_printoptions(void) { return parse_list_options((char_u *)p_popt, printer_opts, OPT_PRINT_NUM_OPTIONS); } -/* - * Parse 'printoptions' and set the flags in "printer_opts". - * Returns an error message or NULL; - */ +// Parse 'printoptions' and set the flags in "printer_opts". +// Returns an error message or NULL; char *parse_printmbfont(void) { return parse_list_options((char_u *)p_pmfn, mbfont_opts, OPT_MBFONT_NUM_OPTIONS); } -/* - * Parse a list of options in the form - * option:value,option:value,option:value - * - * "value" can start with a number which is parsed out, e.g. margin:12mm - * - * Returns an error message for an illegal option, NULL otherwise. - * Only used for the printer at the moment... - */ +// Parse a list of options in the form +// option:value,option:value,option:value +// +// "value" can start with a number which is parsed out, e.g. margin:12mm +// +// Returns an error message for an illegal option, NULL otherwise. +// Only used for the printer at the moment... static char *parse_list_options(char_u *option_str, option_table_T *table, size_t table_size) { option_table_T *old_opts; @@ -301,9 +289,7 @@ static char *parse_list_options(char_u *option_str, option_table_T *table, size_ table[idx].present = false; } - /* - * Repeat for all comma separated parts. - */ + // Repeat for all comma separated parts. stringp = option_str; while (*stringp) { colonp = (char_u *)vim_strchr((char *)stringp, ':'); @@ -361,10 +347,8 @@ static char *parse_list_options(char_u *option_str, option_table_T *table, size_ return ret; } -/* - * If using a dark background, the colors will probably be too bright to show - * up well on white paper, so reduce their brightness. - */ +// If using a dark background, the colors will probably be too bright to show +// up well on white paper, so reduce their brightness. static uint32_t darken_rgb(uint32_t rgb) { return ((rgb >> 17) << 16) @@ -489,9 +473,7 @@ static void prt_line_number(prt_settings_T *const psettings, const int page_line } } -/* - * Get the currently effective header height. - */ +// Get the currently effective header height. int prt_header_height(void) { if (printer_opts[OPT_PRINT_HEADERHEIGHT].present) { @@ -507,10 +489,8 @@ int prt_use_number(void) && TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y'; } -/* - * Return the unit used in a margin item in 'printoptions'. - * Returns PRT_UNIT_NONE if not recognized. - */ +// Return the unit used in a margin item in 'printoptions'. +// Returns PRT_UNIT_NONE if not recognized. int prt_get_unit(int idx) { int u = PRT_UNIT_NONE; @@ -546,12 +526,10 @@ static void prt_header(prt_settings_T *const psettings, const int pagenum, const linenr_T tmp_lnum, tmp_topline, tmp_botline; int use_sandbox = false; - /* - * Need to (temporarily) set current line number and first/last line - * number on the 'window'. Since we don't know how long the page is, - * set the first and current line number to the top line, and guess - * that the page length is 64. - */ + // Need to (temporarily) set current line number and first/last line + // number on the 'window'. Since we don't know how long the page is, + // set the first and current line number to the top line, and guess + // that the page length is 64. tmp_lnum = curwin->w_cursor.lnum; tmp_topline = curwin->w_topline; tmp_botline = curwin->w_botline; @@ -606,9 +584,7 @@ static void prt_header(prt_settings_T *const psettings, const int pagenum, const } } -/* - * Display a print status message. - */ +// Display a print status message. static void prt_message(char_u *s) { // TODO(bfredl): delete this @@ -644,13 +620,11 @@ void ex_hardcopy(exarg_T *eap) settings.arguments = (char_u *)eap->arg; } - /* - * Initialise for printing. Ask the user for settings, unless forceit is - * set. - * The mch_print_init() code should set up margins if applicable. (It may - * not be a real printer - for example the engine might generate HTML or - * PS.) - */ + // Initialise for printing. Ask the user for settings, unless forceit is + // set. + // The mch_print_init() code should set up margins if applicable. (It may + // not be a real printer - for example the engine might generate HTML or + // PS.) if (mch_print_init(&settings, curbuf->b_fname == NULL ? (char_u *)buf_spname(curbuf) : curbuf->b_sfname == NULL ? (char_u *)curbuf->b_fname : (char_u *)curbuf->b_sfname, @@ -687,9 +661,7 @@ void ex_hardcopy(exarg_T *eap) prt_get_attr(id, &settings.number, settings.modec); } - /* - * Estimate the total lines to be printed - */ + // Estimate the total lines to be printed for (lnum = eap->line1; lnum <= eap->line2; lnum++) { bytes_to_print += STRLEN(skipwhite((char *)ml_get(lnum))); } @@ -717,9 +689,7 @@ void ex_hardcopy(exarg_T *eap) goto print_fail_no_begin; } - /* - * Loop over collated copies: 1 2 3, 1 2 3, ... - */ + // Loop over collated copies: 1 2 3, 1 2 3, ... page_count = 0; for (collated_copies = 0; collated_copies < settings.n_collated_copies; @@ -740,9 +710,7 @@ void ex_hardcopy(exarg_T *eap) } } - /* - * Loop over all pages in the print job: 1 2 3 ... - */ + // Loop over all pages in the print job: 1 2 3 ... for (page_count = 0; prtpos.file_line <= eap->line2; page_count++) { // Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ... // For duplex: 12 12 12 34 34 34, ... @@ -752,9 +720,7 @@ void ex_hardcopy(exarg_T *eap) // Set the print position to the start of this page. prtpos = page_prtpos; - /* - * Do front and rear side of a page. - */ + // Do front and rear side of a page. for (side = 0; side <= settings.duplex; side++) { // Print one page. @@ -780,9 +746,7 @@ void ex_hardcopy(exarg_T *eap) } prt_message(IObuff); - /* - * Output header if required - */ + // Output header if required if (prt_header_height() > 0) { prt_header(&settings, page_count + 1 + side, prtpos.file_line); @@ -814,10 +778,8 @@ void ex_hardcopy(exarg_T *eap) } } - /* - * Extra blank page for duplexing with odd number of pages and - * more copies to come. - */ + // Extra blank page for duplexing with odd number of pages and + // more copies to come. if (prtpos.file_line > eap->line2 && settings.duplex && side == 0 && uncollated_copies + 1 < settings.n_uncollated_copies) { @@ -850,10 +812,8 @@ print_fail_no_begin: mch_print_cleanup(); } -/* - * Print one page line. - * Return the next column to print, or zero if the line is finished. - */ +// Print one page line. +// Return the next column to print, or zero if the line is finished. static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T *ppos) { colnr_T col; @@ -881,9 +841,7 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T mch_print_start_line(false, page_line); line = (char_u *)ml_get(ppos->file_line); - /* - * Loop over the columns until the end of the file line or right margin. - */ + // Loop over the columns until the end of the file line or right margin. for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen) { if ((outputlen = utfc_ptr2len((char *)line + col)) < 1) { outputlen = 1; @@ -908,9 +866,7 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T } } - /* - * Appropriately expand any tabs to spaces. - */ + // Appropriately expand any tabs to spaces. if (line[col] == TAB || tab_spaces != 0) { if (tab_spaces == 0) { tab_spaces = tabstop_padding(print_pos, @@ -945,10 +901,8 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T ppos->lead_spaces = tab_spaces; ppos->print_pos = print_pos; - /* - * Start next line of file if we clip lines, or have reached end of the - * line, unless we are doing a formfeed. - */ + // Start next line of file if we clip lines, or have reached end of the + // line, unless we are doing a formfeed. if (!ppos->ff && (line[col] == NUL || (printer_opts[OPT_PRINT_WRAP].present @@ -959,34 +913,32 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T return col; } -/* - * PS printer stuff. - * - * Sources of information to help maintain the PS printing code: - * - * 1. PostScript Language Reference, 3rd Edition, - * Addison-Wesley, 1999, ISBN 0-201-37922-8 - * 2. PostScript Language Program Design, - * Addison-Wesley, 1988, ISBN 0-201-14396-8 - * 3. PostScript Tutorial and Cookbook, - * Addison Wesley, 1985, ISBN 0-201-10179-3 - * 4. PostScript Language Document Structuring Conventions Specification, - * version 3.0, - * Adobe Technote 5001, 25th September 1992 - * 5. PostScript Printer Description File Format Specification, Version 4.3, - * Adobe technote 5003, 9th February 1996 - * 6. Adobe Font Metrics File Format Specification, Version 4.1, - * Adobe Technote 5007, 7th October 1998 - * 7. Adobe CMap and CIDFont Files Specification, Version 1.0, - * Adobe Technote 5014, 8th October 1996 - * 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts, - * Adoboe Technote 5094, 8th September, 2001 - * 9. CJKV Information Processing, 2nd Edition, - * O'Reilly, 2002, ISBN 1-56592-224-7 - * - * Some of these documents can be found in PDF form on Adobe's web site - - * http://www.adobe.com - */ +// PS printer stuff. +// +// Sources of information to help maintain the PS printing code: +// +// 1. PostScript Language Reference, 3rd Edition, +// Addison-Wesley, 1999, ISBN 0-201-37922-8 +// 2. PostScript Language Program Design, +// Addison-Wesley, 1988, ISBN 0-201-14396-8 +// 3. PostScript Tutorial and Cookbook, +// Addison Wesley, 1985, ISBN 0-201-10179-3 +// 4. PostScript Language Document Structuring Conventions Specification, +// version 3.0, +// Adobe Technote 5001, 25th September 1992 +// 5. PostScript Printer Description File Format Specification, Version 4.3, +// Adobe technote 5003, 9th February 1996 +// 6. Adobe Font Metrics File Format Specification, Version 4.1, +// Adobe Technote 5007, 7th October 1998 +// 7. Adobe CMap and CIDFont Files Specification, Version 1.0, +// Adobe Technote 5014, 8th October 1996 +// 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts, +// Adoboe Technote 5094, 8th September, 2001 +// 9. CJKV Information Processing, 2nd Edition, +// O'Reilly, 2002, ISBN 1-56592-224-7 +// +// Some of these documents can be found in PDF form on Adobe's web site - +// http://www.adobe.com #define PRT_PS_DEFAULT_DPI (72) // Default user space resolution #define PRT_PS_DEFAULT_FONTSIZE (10) @@ -1251,17 +1203,13 @@ static struct prt_dsc_comment_S prt_dsc_table[] = PRT_DSC_ENDCOMMENTS_TYPE } }; -/* - * Variables for the output PostScript file. - */ +// Variables for the output PostScript file. static FILE *prt_ps_fd; static bool prt_file_error; static char_u *prt_ps_file_name = NULL; -/* - * Various offsets and dimensions in default PostScript user space (points). - * Used for text positioning calculations - */ +// Various offsets and dimensions in default PostScript user space (points). +// Used for text positioning calculations static double prt_page_width; static double prt_page_height; static double prt_left_margin; @@ -1276,10 +1224,8 @@ static double prt_bgcol_offset; static double prt_pos_x_moveto = 0.0; static double prt_pos_y_moveto = 0.0; -/* - * Various control variables used to decide when and how to change the - * PostScript graphics state. - */ +// Various control variables used to decide when and how to change the +// PostScript graphics state. static bool prt_need_moveto; static bool prt_do_moveto; static bool prt_need_font; @@ -1298,9 +1244,7 @@ static double prt_text_run; static int prt_page_num; static int prt_bufsiz; -/* - * Variables controlling physical printing. - */ +// Variables controlling physical printing. static int prt_media; static int prt_portrait; static int prt_num_copies; @@ -1308,9 +1252,7 @@ static int prt_duplex; static int prt_tumble; static int prt_collate; -/* - * Buffers used when generating PostScript output - */ +// Buffers used when generating PostScript output static char prt_line_buffer[257]; static garray_T prt_ps_buffer = GA_EMPTY_INIT_VALUE; @@ -1345,36 +1287,28 @@ static void prt_write_file_len(char_u *buffer, size_t bytes) prt_write_file_raw_len(buffer, bytes); } -/* - * Write a string. - */ +// Write a string. static void prt_write_string(char *s) { vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer), "%s", s); prt_write_file(prt_line_buffer); } -/* - * Write an int and a space. - */ +// Write an int and a space. static void prt_write_int(int i) { snprintf(prt_line_buffer, sizeof(prt_line_buffer), "%d ", i); prt_write_file(prt_line_buffer); } -/* - * Write a boolean and a space. - */ +// Write a boolean and a space. static void prt_write_boolean(int b) { snprintf(prt_line_buffer, sizeof(prt_line_buffer), "%s ", (b ? "T" : "F")); prt_write_file(prt_line_buffer); } -/* - * Write PostScript to re-encode and define the font. - */ +// Write PostScript to re-encode and define the font. static void prt_def_font(char *new_name, char *encoding, int height, char *font) { vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer), @@ -1390,9 +1324,7 @@ static void prt_def_font(char *new_name, char *encoding, int height, char *font) prt_write_file(prt_line_buffer); } -/* - * Write a line to define the CID font. - */ +// Write a line to define the CID font. static void prt_def_cidfont(char *new_name, int height, char *cidfont) { vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer), @@ -1403,9 +1335,7 @@ static void prt_def_cidfont(char *new_name, int height, char *cidfont) prt_write_file(prt_line_buffer); } -/* - * Write a line to define a duplicate of a CID font - */ +// Write a line to define a duplicate of a CID font static void prt_dup_cidfont(char *original_name, char *new_name) { vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer), @@ -1413,11 +1343,9 @@ static void prt_dup_cidfont(char *original_name, char *new_name) prt_write_file(prt_line_buffer); } -/* - * Convert a real value into an integer and fractional part as integers, with - * the fractional part being in the range [0,10^precision). The fractional part - * is also rounded based on the precision + 1'th fractional digit. - */ +// Convert a real value into an integer and fractional part as integers, with +// the fractional part being in the range [0,10^precision). The fractional part +// is also rounded based on the precision + 1'th fractional digit. static void prt_real_bits(double real, int precision, int *pinteger, int *pfraction) { int integer = (int)real; @@ -1433,11 +1361,9 @@ static void prt_real_bits(double real, int precision, int *pinteger, int *pfract *pfraction = (int)(fraction + 0.5); } -/* - * Write a real and a space. Save bytes if real value has no fractional part! - * We use prt_real_bits() as %f in sprintf uses the locale setting to decide - * what decimal point character to use, but PS always requires a '.'. - */ +// Write a real and a space. Save bytes if real value has no fractional part! +// We use prt_real_bits() as %f in sprintf uses the locale setting to decide +// what decimal point character to use, but PS always requires a '.'. static void prt_write_real(double val, int prec) { int integer; @@ -1463,9 +1389,7 @@ static void prt_write_real(double val, int prec) prt_write_file(prt_line_buffer); } -/* - * Write a line to define a numeric variable. - */ +// Write a line to define a numeric variable. static void prt_def_var(char *name, double value, int prec) { vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer), @@ -2020,9 +1944,7 @@ static double to_device_units(int idx, double physsize, int def_number) return ret; } -/* - * Calculate margins for given width and height from printoptions settings. - */ +// Calculate margins for given width and height from printoptions settings. static void prt_page_margins(double width, double height, double *left, double *right, double *top, double *bottom) { @@ -2062,18 +1984,14 @@ static void prt_build_cid_fontname(int font, char_u *name, int name_len) prt_ps_mb_font.ps_fontname[font] = fontname; } -/* - * Get number of lines of text that fit on a page (excluding the header). - */ +// Get number of lines of text that fit on a page (excluding the header). static int prt_get_lpp(void) { int lpp; - /* - * Calculate offset to lower left corner of background rect based on actual - * font height (based on its bounding box) and the line height, handling the - * case where the font height can exceed the line height. - */ + // Calculate offset to lower left corner of background rect based on actual + // font height (based on its bounding box) and the line height, handling the + // case where the font height can exceed the line height. prt_bgcol_offset = PRT_PS_FONT_TO_USER(prt_line_height, prt_ps_font->bbox_min_y); if ((prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y) < 1000.0) { @@ -2270,9 +2188,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) prt_ps_font = &prt_ps_courier_font; } - /* - * Find the size of the paper and set the margins. - */ + // Find the size of the paper and set the margins. prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present || TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) == 'y'); @@ -2295,13 +2211,11 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) } prt_media = i; - /* - * Set PS pagesize based on media dimensions and print orientation. - * Note: Media and page sizes have defined meanings in PostScript and should - * be kept distinct. Media is the paper (or transparency, or ...) that is - * printed on, whereas the page size is the area that the PostScript - * interpreter renders into. - */ + // Set PS pagesize based on media dimensions and print orientation. + // Note: Media and page sizes have defined meanings in PostScript and should + // be kept distinct. Media is the paper (or transparency, or ...) that is + // printed on, whereas the page size is the area that the PostScript + // interpreter renders into. if (prt_portrait) { prt_page_width = prt_mediasize[i].width; prt_page_height = prt_mediasize[i].height; @@ -2320,9 +2234,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) prt_top_margin = top; prt_bottom_margin = bottom; - /* - * Set up the font size. - */ + // Set up the font size. fontsize = PRT_PS_DEFAULT_FONTSIZE; for (p = (char_u *)p_pfn; (p = (char_u *)vim_strchr((char *)p, ':')) != NULL; p++) { if (p[1] == 'h' && ascii_isdigit(p[2])) { @@ -2331,10 +2243,8 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) } prt_font_metrics(fontsize); - /* - * Return the number of characters per line, and lines per page for the - * generic print code. - */ + // Return the number of characters per line, and lines per page for the + // generic print code. psettings->chars_per_line = prt_get_cpl(); psettings->lines_per_page = prt_get_lpp(); @@ -2343,12 +2253,10 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) return FAIL; } - /* - * Sort out the number of copies to be printed. PS by default will do - * uncollated copies for you, so once we know how many uncollated copies are - * wanted cache it away and lie to the generic code that we only want one - * uncollated copy. - */ + // Sort out the number of copies to be printed. PS by default will do + // uncollated copies for you, so once we know how many uncollated copies are + // wanted cache it away and lie to the generic code that we only want one + // uncollated copy. psettings->n_collated_copies = 1; psettings->n_uncollated_copies = 1; prt_num_copies = 1; @@ -2364,10 +2272,8 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) psettings->jobname = jobname; - /* - * Set up printer duplex and tumble based on Duplex option setting - default - * is long sided duplex printing (i.e. no tumble). - */ + // Set up printer duplex and tumble based on Duplex option setting - default + // is long sided duplex printing (i.e. no tumble). prt_duplex = true; prt_tumble = false; psettings->duplex = 1; @@ -2491,9 +2397,7 @@ bool mch_print_begin(prt_settings_T *psettings) struct prt_ps_resource_S res_cidfont; struct prt_ps_resource_S res_cmap; - /* - * PS DSC Header comments - no PS code! - */ + // PS DSC Header comments - no PS code! prt_dsc_start(); prt_dsc_textline("Title", (char *)psettings->jobname); if (os_get_username(buffer, 256) == FAIL) { @@ -2685,9 +2589,7 @@ bool mch_print_begin(prt_settings_T *psettings) prt_num_copies); prt_dsc_noarg("EndComments"); - /* - * PS Document page defaults - */ + // PS Document page defaults prt_dsc_noarg("BeginDefaults"); // List font resources most likely common to all pages @@ -2707,9 +2609,7 @@ bool mch_print_begin(prt_settings_T *psettings) prt_dsc_noarg("EndDefaults"); - /* - * PS Document prolog inclusion - all required procsets. - */ + // PS Document prolog inclusion - all required procsets. prt_dsc_noarg("BeginProlog"); // Add required procsets - NOTE: order is important! @@ -2736,9 +2636,7 @@ bool mch_print_begin(prt_settings_T *psettings) prt_dsc_noarg("EndProlog"); - /* - * PS Document setup - must appear after the prolog - */ + // PS Document setup - must appear after the prolog prt_dsc_noarg("BeginSetup"); // Device setup - page size and number of uncollated copies @@ -2847,9 +2745,7 @@ void mch_print_end(prt_settings_T *psettings) { prt_dsc_noarg("Trailer"); - /* - * Output any info we don't know in toto until we finish - */ + // Output any info we don't know in toto until we finish prt_dsc_ints("Pages", 1, &prt_page_num); prt_dsc_noarg("EOF"); diff --git a/src/nvim/hardcopy.h b/src/nvim/hardcopy.h index 9ef4eb0074..ce562cd3e6 100644 --- a/src/nvim/hardcopy.h +++ b/src/nvim/hardcopy.h @@ -8,9 +8,7 @@ #include "nvim/globals.h" // for TriState #include "nvim/types.h" // for char_u -/* - * Structure to hold printing color and font attributes. - */ +// Structure to hold printing color and font attributes. typedef struct { uint32_t fg_color; uint32_t bg_color; @@ -23,9 +21,7 @@ typedef struct { int underdashed; } prt_text_attr_T; -/* - * Structure passed back to the generic printer code. - */ +// Structure passed back to the generic printer code. typedef struct { int n_collated_copies; int n_uncollated_copies; @@ -42,9 +38,7 @@ typedef struct { char_u *arguments; } prt_settings_T; -/* - * Generic option table item, only used for printer at the moment. - */ +// Generic option table item, only used for printer at the moment. typedef struct { const char *name; int hasnum; diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index e54bffb587..85534ebcff 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -1,13 +1,11 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * CSCOPE support for Vim added by Andy Kahn - * Ported to Win32 by Sergey Khorev - * - * The basic idea/structure of cscope for Vim was borrowed from Nvi. There - * might be a few lines of code that look similar to what Nvi has. - */ +// CSCOPE support for Vim added by Andy Kahn +// Ported to Win32 by Sergey Khorev +// +// The basic idea/structure of cscope for Vim was borrowed from Nvi. There +// might be a few lines of code that look similar to what Nvi has. #include #include @@ -78,10 +76,8 @@ static enum { EXP_CSCOPE_KILL, // expand ":cscope kill" arguments } expand_what; -/* - * Function given to ExpandGeneric() to obtain the cscope command - * expansion. - */ +// Function given to ExpandGeneric() to obtain the cscope command +// expansion. char *get_cscope_name(expand_T *xp, int idx) { int current_idx; @@ -140,9 +136,7 @@ char *get_cscope_name(expand_T *xp, int idx) } } -/* - * Handle command line completion for :cscope command. - */ +// Handle command line completion for :cscope command. void set_context_in_cscope_cmd(expand_T *xp, const char *arg, cmdidx_T cmdidx) { // Default: expand subcommands. @@ -304,33 +298,31 @@ void cs_print_tags(void) cs_manage_matches(NULL, NULL, 0, Print); } -/* - * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function - * - * Checks for the existence of a |cscope| connection. If no - * parameters are specified, then the function returns: - * - * 0, if cscope was not available (not compiled in), or if there - * are no cscope connections; or - * 1, if there is at least one cscope connection. - * - * If parameters are specified, then the value of {num} - * determines how existence of a cscope connection is checked: - * - * {num} Description of existence check - * ----- ------------------------------ - * 0 Same as no parameters (e.g., "cscope_connection()"). - * 1 Ignore {prepend}, and use partial string matches for - * {dbpath}. - * 2 Ignore {prepend}, and use exact string matches for - * {dbpath}. - * 3 Use {prepend}, use partial string matches for both - * {dbpath} and {prepend}. - * 4 Use {prepend}, use exact string matches for both - * {dbpath} and {prepend}. - * - * Note: All string comparisons are case sensitive! - */ +// "cscope_connection([{num} , {dbpath} [, {prepend}]])" function +// +// Checks for the existence of a |cscope| connection. If no +// parameters are specified, then the function returns: +// +// 0, if cscope was not available (not compiled in), or if there +// are no cscope connections; or +// 1, if there is at least one cscope connection. +// +// If parameters are specified, then the value of {num} +// determines how existence of a cscope connection is checked: +// +// {num} Description of existence check +// ----- ------------------------------ +// 0 Same as no parameters (e.g., "cscope_connection()"). +// 1 Ignore {prepend}, and use partial string matches for +// {dbpath}. +// 2 Ignore {prepend}, and use exact string matches for +// {dbpath}. +// 3 Use {prepend}, use partial string matches for both +// {dbpath} and {prepend}. +// 4 Use {prepend}, use exact string matches for both +// {dbpath} and {prepend}. +// +// Note: All string comparisons are case sensitive! bool cs_connection(int num, char_u *dbpath, char_u *ppath) { if (num < 0 || num > 4 || (num > 0 && !dbpath)) { @@ -379,9 +371,8 @@ bool cs_connection(int num, char_u *dbpath, char_u *ppath) return false; } // cs_connection -/* - * PRIVATE functions - ****************************************************************************/ +// PRIVATE functions +// ************************************************************************** /// Add cscope database or a directory name (to look for cscope.out) /// to the cscope connection list. @@ -684,10 +675,8 @@ static int cs_create_connection(size_t i) char *prog, *cmd, *ppath = NULL; #if defined(UNIX) - /* - * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from - * from_cs[0] and writes to to_cs[1]. - */ + // Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from + // from_cs[0] and writes to to_cs[1]. to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1; if (pipe(to_cs) < 0 || pipe(from_cs) < 0) { (void)emsg(_("E566: Could not create cscope pipes")); @@ -896,10 +885,8 @@ static int cs_find(exarg_T *eap) return false; } - /* - * Let's replace the NULs written by strtok() with spaces - we need the - * spaces to correctly display the quickfix/location list window's title. - */ + // Let's replace the NULs written by strtok() with spaces - we need the + // spaces to correctly display the quickfix/location list window's title. for (int i = 0; i < eap_arg_len; i++) { if (NUL == eap->arg[i]) { eap->arg[i] = ' '; @@ -1041,10 +1028,8 @@ static bool cs_find_common(char *opt, char *pat, int forceit, int verbose, bool apply_autocmds(EVENT_QUICKFIXCMDPOST, "cscope", curbuf->b_fname, true, curbuf); if (use_ll) { - /* - * In the location list window, use the displayed location - * list. Otherwise, use the location list for the window. - */ + // In the location list window, use the displayed location + // list. Otherwise, use the location list for the window. qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL) ? wp->w_llist_ref : wp->w_llist; } @@ -1431,11 +1416,9 @@ retry: } *p = '\0'; - /* - * cscope output is in the following format: - * - * - */ + // cscope output is in the following format: + // + // char *saveptr = NULL; if ((name = os_strtok(buf, (const char *)" ", &saveptr)) == NULL) { return NULL; @@ -1786,9 +1769,7 @@ static int cs_read_prompt(size_t i) } #if defined(UNIX) && defined(SIGALRM) -/* - * Used to catch and ignore SIGALRM below. - */ +// Used to catch and ignore SIGALRM below. static void sig_handler(int s) { // do nothing @@ -1847,25 +1828,21 @@ static void cs_release_csp(size_t i, bool freefnpp) os_delay(50L, false); // sleep 50 ms } # endif - /* - * If the cscope process is still running: kill it. - * Safety check: If the PID would be zero here, the entire X session - * would be killed. -1 and 1 are dangerous as well. - */ + // If the cscope process is still running: kill it. + // Safety check: If the PID would be zero here, the entire X session + // would be killed. -1 and 1 are dangerous as well. if (pid < 0 && csinfo[i].pid > 1) { # ifdef ECHILD bool alive = true; if (waitpid_errno == ECHILD) { - /* - * When using 'vim -g', vim is forked and cscope process is - * no longer a child process but a sibling. So waitpid() - * fails with errno being ECHILD (No child processes). - * Don't send SIGKILL to cscope immediately but wait - * (polling) for it to exit normally as result of sending - * the "q" command, hence giving it a chance to clean up - * its temporary files. - */ + // When using 'vim -g', vim is forked and cscope process is + // no longer a child process but a sibling. So waitpid() + // fails with errno being ECHILD (No child processes). + // Don't send SIGKILL to cscope immediately but wait + // (polling) for it to exit normally as result of sending + // the "q" command, hence giving it a chance to clean up + // its temporary files. int waited; sleep(0); @@ -1974,11 +1951,9 @@ static char *cs_resolve_file(size_t i, char *name) char *fullname; char_u *csdir = NULL; - /* - * Ppath is freed when we destroy the cscope connection. - * Fullname is freed after cs_make_vim_style_matches, after it's been - * copied into the tag buffer used by Vim. - */ + // Ppath is freed when we destroy the cscope connection. + // Fullname is freed after cs_make_vim_style_matches, after it's been + // copied into the tag buffer used by Vim. size_t len = strlen(name) + 2; if (csinfo[i].ppath != NULL) { len += strlen(csinfo[i].ppath); diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c index 7dcc9e3c27..5941473825 100644 --- a/src/nvim/indent_c.c +++ b/src/nvim/indent_c.c @@ -27,11 +27,9 @@ typedef struct { #ifdef INCLUDE_GENERATED_DECLARATIONS # include "indent_c.c.generated.h" #endif -/* - * Find the start of a comment, not knowing if we are in a comment right now. - * Search starts at w_cursor.lnum and goes backwards. - * Return NULL when not inside a comment. - */ +// Find the start of a comment, not knowing if we are in a comment right now. +// Search starts at w_cursor.lnum and goes backwards. +// Return NULL when not inside a comment. static pos_T *ind_find_start_comment(void) // XXX { return find_start_comment(curbuf->b_ind_maxcomment); @@ -48,10 +46,8 @@ pos_T *find_start_comment(int ind_maxcomment) // XXX break; } - /* - * Check if the comment start we found is inside a string. - * If it is then restrict the search to below this line and try again. - */ + // Check if the comment start we found is inside a string. + // If it is then restrict the search to below this line and try again. if (!is_pos_in_string((char_u *)ml_get(pos->lnum), pos->col)) { break; } @@ -97,11 +93,9 @@ static pos_T *ind_find_start_CORS(linenr_T *is_raw) return comment_pos; } -/* - * Find the start of a raw string, not knowing if we are in one right now. - * Search starts at w_cursor.lnum and goes backwards. - * Return NULL when not inside a raw string. - */ +// Find the start of a raw string, not knowing if we are in one right now. +// Search starts at w_cursor.lnum and goes backwards. +// Return NULL when not inside a raw string. static pos_T *find_start_rawstring(int ind_maxcomment) // XXX { pos_T *pos; @@ -127,17 +121,13 @@ static pos_T *find_start_rawstring(int ind_maxcomment) // XXX return pos; } -/* - * Skip to the end of a "string" and a 'c' character. - * If there is no string or character, return argument unmodified. - */ +// Skip to the end of a "string" and a 'c' character. +// If there is no string or character, return argument unmodified. static const char_u *skip_string(const char_u *p) { int i; - /* - * We loop, because strings may be concatenated: "date""time". - */ + // We loop, because strings may be concatenated: "date""time". for (;; p++) { if (p[0] == '\'') { // 'c' or '\n' or '\000' if (p[1] == NUL) { // ' at end of line @@ -204,13 +194,10 @@ int is_pos_in_string(const char_u *line, colnr_T col) return !((colnr_T)(p - line) <= col); } -/* - * Functions for C-indenting. - * Most of this originally comes from Eric Fischer. - */ -/* - * Below "XXX" means that this function may unlock the current line. - */ +// Functions for C-indenting. +// Most of this originally comes from Eric Fischer. + +// Below "XXX" means that this function may unlock the current line. /// @return true if the string "line" starts with a word from 'cinwords'. bool cin_is_cinword(const char *line) @@ -235,10 +222,8 @@ bool cin_is_cinword(const char *line) return retval; } -/* - * Skip over white space and C comments within the line. - * Also skip over Perl/shell comments if desired. - */ +// Skip over white space and C comments within the line. +// Also skip over Perl/shell comments if desired. static const char_u *cin_skipcomment(const char_u *s) { while (*s) { @@ -246,8 +231,8 @@ static const char_u *cin_skipcomment(const char_u *s) s = (char_u *)skipwhite((char *)s); - /* Perl/shell # comment comment continues until eol. Require a space - * before # to avoid recognizing $#array. */ + // Perl/shell # comment comment continues until eol. Require a space + // before # to avoid recognizing $#array. if (curbuf->b_ind_hash_comment != 0 && s != prev_s && *s == '#') { s += STRLEN(s); break; @@ -280,9 +265,7 @@ static int cin_nocode(const char_u *s) return *cin_skipcomment(s) == NUL; } -/* - * Check previous lines for a "//" line comment, skipping over blank lines. - */ +// Check previous lines for a "//" line comment, skipping over blank lines. static pos_T *find_line_comment(void) // XXX { static pos_T pos; @@ -369,10 +352,8 @@ bool cin_islabel(void) // XXX return false; } - /* - * Only accept a label if the previous line is terminated or is a case - * label. - */ + // Only accept a label if the previous line is terminated or is a case + // label. pos_T cursor_save; pos_T *trypos; const char_u *line; @@ -381,10 +362,8 @@ bool cin_islabel(void) // XXX while (curwin->w_cursor.lnum > 1) { curwin->w_cursor.lnum--; - /* - * If we're in a comment or raw string now, skip to the start of - * it. - */ + // If we're in a comment or raw string now, skip to the start of + // it. curwin->w_cursor.col = 0; if ((trypos = ind_find_start_CORS(NULL)) != NULL) { // XXX curwin->w_cursor = *trypos; @@ -411,11 +390,9 @@ bool cin_islabel(void) // XXX return true; // label at start of file??? } -/* - * Recognize structure initialization and enumerations: - * "[typedef] [static|public|protected|private] enum" - * "[typedef] [static|public|protected|private] = {" - */ +// Recognize structure initialization and enumerations: +// "[typedef] [static|public|protected|private] enum" +// "[typedef] [static|public|protected|private] = {" static int cin_isinit(void) { const char_u *s; @@ -495,9 +472,7 @@ bool cin_iscase(const char_u *s, bool strict) return false; } -/* - * Recognize a "default" switch label. - */ +// Recognize a "default" switch label. static int cin_isdefault(const char_u *s) { return STRNCMP(s, "default", 7) == 0 @@ -576,12 +551,10 @@ static bool cin_is_cpp_namespace(const char_u *s) return false; } -/* - * Return a pointer to the first non-empty non-comment character after a ':'. - * Return NULL if not found. - * case 234: a = b; - * ^ - */ +// Return a pointer to the first non-empty non-comment character after a ':'. +// Return NULL if not found. +// case 234: a = b; +// ^ static const char_u *after_label(const char_u *l) { for (; *l; l++) { @@ -605,10 +578,8 @@ static const char_u *after_label(const char_u *l) return l; } -/* - * Get indent of line "lnum", skipping a label. - * Return 0 if there is nothing after the label. - */ +// Get indent of line "lnum", skipping a label. +// Return 0 if there is nothing after the label. static int get_indent_nolabel(linenr_T lnum) // XXX { const char_u *l; @@ -628,12 +599,10 @@ static int get_indent_nolabel(linenr_T lnum) // XXX return (int)col; } -/* - * Find indent for line "lnum", ignoring any case or jump label. - * Also return a pointer to the text (after the label) in "pp". - * label: if (asdf && asdfasdf) - * ^ - */ +// Find indent for line "lnum", ignoring any case or jump label. +// Also return a pointer to the text (after the label) in "pp". +// label: if (asdf && asdfasdf) +// ^ static int skip_label(linenr_T lnum, const char_u **pp) { const char_u *l; @@ -660,13 +629,11 @@ static int skip_label(linenr_T lnum, const char_u **pp) return amount; } -/* - * Return the indent of the first variable name after a type in a declaration. - * int a, indent of "a" - * static struct foo b, indent of "b" - * enum bla c, indent of "c" - * Returns zero when it doesn't look like a declaration. - */ +// Return the indent of the first variable name after a type in a declaration. +// int a, indent of "a" +// static struct foo b, indent of "b" +// enum bla c, indent of "c" +// Returns zero when it doesn't look like a declaration. static int cin_first_id_amount(void) { char_u *line, *p, *s; @@ -707,15 +674,13 @@ static int cin_first_id_amount(void) return (int)col; } -/* - * Return the indent of the first non-blank after an equal sign. - * char *foo = "here"; - * Return zero if no (useful) equal sign found. - * Return -1 if the line above "lnum" ends in a backslash. - * foo = "asdf\ - * asdf\ - * here"; - */ +// Return the indent of the first non-blank after an equal sign. +// char *foo = "here"; +// Return zero if no (useful) equal sign found. +// Return -1 if the line above "lnum" ends in a backslash. +// foo = "asdf{backslash} +// asdf{backslash} +// here"; static int cin_get_equal_amount(linenr_T lnum) { const char_u *line; @@ -758,9 +723,7 @@ static int cin_get_equal_amount(linenr_T lnum) return (int)col; } -/* - * Recognize a preprocessor statement: Any line that starts with '#'. - */ +// Recognize a preprocessor statement: Any line that starts with '#'. static int cin_ispreproc(const char_u *s) { if (*skipwhite((char *)s) == '#') { @@ -808,17 +771,13 @@ static int cin_ispreproc_cont(const char_u **pp, linenr_T *lnump, int *amount) return retval; } -/* - * Recognize the start of a C or C++ comment. - */ +// Recognize the start of a C or C++ comment. static int cin_iscomment(const char_u *p) { return p[0] == '/' && (p[1] == '*' || p[1] == '/'); } -/* - * Recognize the start of a "//" comment. - */ +// Recognize the start of a "//" comment. static int cin_islinecomment(const char_u *p) { return p[0] == '/' && p[1] == '/'; @@ -957,10 +916,10 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s)) { int comma = (*s == ','); - /* ',' at the end: continue looking in the next line. - * At the end: check for ',' in the next line, for this style: - * func(arg1 - * , arg2) */ + // ',' at the end: continue looking in the next line. + // At the end: check for ',' in the next line, for this style: + // func(arg1 + // , arg2) for (;;) { if (lnum >= curbuf->b_ml.ml_line_count) { break; @@ -1014,11 +973,9 @@ static int cin_isdo(const char_u *p) return STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]); } -/* - * Check if this is a "while" that should have a matching "do". - * We only accept a "while (condition) ;", with only white space between the - * ')' and ';'. The condition may be spread over several lines. - */ +// Check if this is a "while" that should have a matching "do". +// We only accept a "while (condition) ;", with only white space between the +// ')' and ';'. The condition may be spread over several lines. static int cin_iswhileofdo(const char_u *p, linenr_T lnum) // XXX { pos_T cursor_save; @@ -1047,12 +1004,10 @@ static int cin_iswhileofdo(const char_u *p, linenr_T lnum) // XXX return retval; } -/* - * Check whether in "p" there is an "if", "for" or "while" before "*poffset". - * Return 0 if there is none. - * Otherwise return !0 and update "*poffset" to point to the place where the - * string was found. - */ +// Check whether in "p" there is an "if", "for" or "while" before "*poffset". +// Return 0 if there is none. +// Otherwise return !0 and update "*poffset" to point to the place where the +// string was found. static int cin_is_if_for_while_before_offset(const char_u *line, int *poffset) { int offset = *poffset; @@ -1116,8 +1071,8 @@ static int cin_iswhileofdo_end(int terminated) if (*p == ')') { s = (char_u *)skipwhite((char *)p + 1); if (*s == ';' && cin_nocode(s + 1)) { - /* Found ");" at end of the line, now check there is "while" - * before the matching '('. XXX */ + // Found ");" at end of the line, now check there is "while" + // before the matching '('. XXX i = (int)(p - line); curwin->w_cursor.col = i; trypos = find_match_paren(curbuf->b_ind_maxparen); @@ -1149,19 +1104,17 @@ static int cin_isbreak(const char_u *p) return STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]); } -/* - * Find the position of a C++ base-class declaration or - * constructor-initialization. eg: - * - * class MyClass : - * baseClass <-- here - * class MyClass : public baseClass, - * anotherBaseClass <-- here (should probably lineup ??) - * MyClass::MyClass(...) : - * baseClass(...) <-- here (constructor-initialization) - * - * This is a lot of guessing. Watch out for "cond ? func() : foo". - */ +// Find the position of a C++ base-class declaration or +// constructor-initialization. eg: +// +// class MyClass : +// baseClass <-- here +// class MyClass : public baseClass, +// anotherBaseClass <-- here (should probably lineup ??) +// MyClass::MyClass(...) : +// baseClass(...) <-- here (constructor-initialization) +// +// This is a lot of guessing. Watch out for "cond ? func() : foo". static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) { lpos_T *pos = &cached->lpos; // find position @@ -1187,19 +1140,18 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) cpp_base_class = lookfor_ctor_init = class_or_struct = false; - /* Search for a line starting with '#', empty, ending in ';' or containing - * '{' or '}' and start below it. This handles the following situations: - * a = cond ? - * func() : - * asdf; - * func::foo() - * : something - * {} - * Foo::Foo (int one, int two) - * : something(4), - * somethingelse(3) - * {} - */ + // Search for a line starting with '#', empty, ending in ';' or containing + // '{' or '}' and start below it. This handles the following situations: + // a = cond ? + // func() : + // asdf; + // func::foo() + // : something + // {} + // Foo::Foo (int one, int two) + // : something(4), + // somethingelse(3) + // {} while (lnum > 1) { line = (char_u *)ml_get(lnum - 1); s = (char_u *)skipwhite((char *)line); @@ -1249,13 +1201,13 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) s = skip_string(s) + 1; } else if (s[0] == ':') { if (s[1] == ':') { - /* skip double colon. It can't be a constructor - * initialization any more */ + // skip double colon. It can't be a constructor + // initialization any more lookfor_ctor_init = false; s = cin_skipcomment(s + 2); } else if (lookfor_ctor_init || class_or_struct) { - /* we have something found, that looks like the start of - * cpp-base-class-declaration or constructor-initialization */ + // we have something found, that looks like the start of + // cpp-base-class-declaration or constructor-initialization cpp_base_class = true; lookfor_ctor_init = class_or_struct = false; pos->col = 0; @@ -1277,8 +1229,8 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached) if (s[0] == '{' || s[0] == '}' || s[0] == ';') { cpp_base_class = lookfor_ctor_init = class_or_struct = false; } else if (s[0] == ')') { - /* Constructor-initialization is assumed if we come across - * something like "):" */ + // Constructor-initialization is assumed if we come across + // something like "):" class_or_struct = false; lookfor_ctor_init = true; } else if (s[0] == '?') { @@ -1411,10 +1363,8 @@ static int cin_is_cpp_extern_c(const char_u *s) return false; } -/* - * Skip strings, chars and comments until at or past "trypos". - * Return the column found. - */ +// Skip strings, chars and comments until at or past "trypos". +// Return the column found. static int cin_skip2pos(pos_T *trypos) { const char_u *line; @@ -1438,11 +1388,10 @@ static int cin_skip2pos(pos_T *trypos) return (int)(p - line); } -/* - * Find the '{' at the start of the block we are in. - * Return NULL if no match found. - * Ignore a '{' that is in a comment, makes indenting the next three lines - * work. */ +// Find the '{' at the start of the block we are in. +// Return NULL if no match found. +// Ignore a '{' that is in a comment, makes indenting the next three lines +// work. // foo() // { // } @@ -1542,12 +1491,10 @@ static pos_T *find_match_paren_after_brace(int ind_maxparen) return trypos; } -/* - * Return ind_maxparen corrected for the difference in line number between the - * cursor position and "startpos". This makes sure that searching for a - * matching paren above the cursor line doesn't find a match because of - * looking a few lines further. - */ +// Return ind_maxparen corrected for the difference in line number between the +// cursor position and "startpos". This makes sure that searching for a +// matching paren above the cursor line doesn't find a match because of +// looking a few lines further. static int corr_ind_maxparen(pos_T *startpos) { long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum; @@ -1558,10 +1505,8 @@ static int corr_ind_maxparen(pos_T *startpos) return curbuf->b_ind_maxparen; } -/* - * Set w_cursor.col to the column number of the last unmatched ')' or '{' in - * line "l". "l" must point to the start of the line. - */ +// Set w_cursor.col to the column number of the last unmatched ')' or '{' in +// line "l". "l" must point to the start of the line. static int find_last_paren(const char_u *l, int start, int end) { int i; @@ -1587,10 +1532,8 @@ static int find_last_paren(const char_u *l, int start, int end) return retval; } -/* - * Parse 'cinoptions' and set the values in "curbuf". - * Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes. - */ +// Parse 'cinoptions' and set the values in "curbuf". +// Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes. void parse_cino(buf_T *buf) { char *p; @@ -1599,39 +1542,37 @@ void parse_cino(buf_T *buf) int fraction = 0; int sw = get_sw_value(buf); - /* - * Set the default values. - */ - /* Spaces from a block's opening brace the prevailing indent for that - * block should be. */ + // Set the default values. + // Spaces from a block's opening brace the prevailing indent for that + // block should be. buf->b_ind_level = sw; - /* Spaces from the edge of the line an open brace that's at the end of a - * line is imagined to be. */ + // Spaces from the edge of the line an open brace that's at the end of a + // line is imagined to be. buf->b_ind_open_imag = 0; - /* Spaces from the prevailing indent for a line that is not preceded by - * an opening brace. */ + // Spaces from the prevailing indent for a line that is not preceded by + // an opening brace. buf->b_ind_no_brace = 0; // Column where the first { of a function should be located }. buf->b_ind_first_open = 0; - /* Spaces from the prevailing indent a leftmost open brace should be - * located. */ + // Spaces from the prevailing indent a leftmost open brace should be + // located. buf->b_ind_open_extra = 0; - /* Spaces from the matching open brace (real location for one at the left - * edge; imaginary location from one that ends a line) the matching close - * brace should be located. */ + // Spaces from the matching open brace (real location for one at the left + // edge; imaginary location from one that ends a line) the matching close + // brace should be located. buf->b_ind_close_extra = 0; - /* Spaces from the edge of the line an open brace sitting in the leftmost - * column is imagined to be. */ + // Spaces from the edge of the line an open brace sitting in the leftmost + // column is imagined to be. buf->b_ind_open_left_imag = 0; - /* Spaces jump labels should be shifted to the left if N is non-negative, - * otherwise the jump label will be put to column 1. */ + // Spaces jump labels should be shifted to the left if N is non-negative, + // otherwise the jump label will be put to column 1. buf->b_ind_jump_label = -1; // Spaces from the switch() indent a "case xx" label should be located. @@ -1643,8 +1584,8 @@ void parse_cino(buf_T *buf) // Lineup break at end of case in switch() with case label. buf->b_ind_case_break = 0; - /* Spaces from the class declaration indent a scope declaration label - * should be located. */ + // Spaces from the class declaration indent a scope declaration label + // should be located. buf->b_ind_scopedecl = sw; // Spaces from the scope declaration label code should be located. @@ -1656,32 +1597,32 @@ void parse_cino(buf_T *buf) // Amount a function type spec should be indented. buf->b_ind_func_type = sw; - /* Amount a cpp base class declaration or constructor initialization - * should be indented. */ + // Amount a cpp base class declaration or constructor initialization + // should be indented. buf->b_ind_cpp_baseclass = sw; - /* additional spaces beyond the prevailing indent a continuation line - * should be located. */ + // additional spaces beyond the prevailing indent a continuation line + // should be located. buf->b_ind_continuation = sw; // Spaces from the indent of the line with an unclosed parentheses. buf->b_ind_unclosed = sw * 2; - /* Spaces from the indent of the line with an unclosed parentheses, which - * itself is also unclosed. */ + // Spaces from the indent of the line with an unclosed parentheses, which + // itself is also unclosed. buf->b_ind_unclosed2 = sw; // Suppress ignoring spaces from the indent of a line starting with an // unclosed parenthesis. buf->b_ind_unclosed_noignore = 0; - /* If the opening paren is the last nonwhite character on the line, and - * b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer - * context (for very long lines). */ + // If the opening paren is the last nonwhite character on the line, and + // b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer + // context (for very long lines). buf->b_ind_unclosed_wrapped = 0; - /* Suppress ignoring white space when lining up with the character after - * an unclosed parentheses. */ + // Suppress ignoring white space when lining up with the character after + // an unclosed parentheses. buf->b_ind_unclosed_whiteok = 0; // Indent a closing parenthesis under the line start of the matching @@ -1697,8 +1638,8 @@ void parse_cino(buf_T *buf) // Spaces from the comment opener when there is nothing after it. buf->b_ind_in_comment = 3; - /* Boolean: if non-zero, use b_ind_in_comment even if there is something - * after the comment opener. */ + // Boolean: if non-zero, use b_ind_in_comment even if there is something + // after the comment opener. buf->b_ind_in_comment2 = 0; // Max lines to search for an open paren. @@ -1719,8 +1660,8 @@ void parse_cino(buf_T *buf) // Handle C++ namespace. buf->b_ind_cpp_namespace = 0; - /* Handle continuation lines containing conditions of if(), for() and - * while(). */ + // Handle continuation lines containing conditions of if(), for() and + // while(). buf->b_ind_if_for_while = 0; // indentation for # comments @@ -1766,8 +1707,8 @@ void parse_cino(buf_T *buf) n = -n; } - /* When adding an entry here, also update the default 'cinoptions' in - * doc/indent.txt, and add explanation for it! */ + // When adding an entry here, also update the default 'cinoptions' in + // doc/indent.txt, and add explanation for it! switch (*l) { case '>': buf->b_ind_level = n; @@ -1887,10 +1828,8 @@ void parse_cino(buf_T *buf) } } -/* - * Return the desired indent for C code. - * Return -1 if the indent should be left alone (inside a raw string). - */ +// Return the desired indent for C code. +// Return -1 if the indent should be left alone (inside a raw string). int get_c_indent(void) { pos_T cur_curpos; @@ -1951,18 +1890,16 @@ int get_c_indent(void) return 0; } - /* Get a copy of the current contents of the line. - * This is required, because only the most recent line obtained with - * ml_get is valid! */ + // Get a copy of the current contents of the line. + // This is required, because only the most recent line obtained with + // ml_get is valid! linecopy = vim_strsave((char_u *)ml_get(cur_curpos.lnum)); - /* - * In insert mode and the cursor is on a ')' truncate the line at the - * cursor position. We don't want to line up with the matching '(' when - * inserting new stuff. - * For unknown reasons the cursor might be past the end of the line, thus - * check for that. - */ + // In insert mode and the cursor is on a ')' truncate the line at the + // cursor position. We don't want to line up with the matching '(' when + // inserting new stuff. + // For unknown reasons the cursor might be past the end of the line, thus + // check for that. if ((State & MODE_INSERT) && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy) && linecopy[curwin->w_cursor.col] == ')') { @@ -1977,10 +1914,8 @@ int get_c_indent(void) original_line_islabel = cin_islabel(); // XXX - /* - * If we are inside a raw string don't change the indent. - * Ignore a raw string inside a comment. - */ + // If we are inside a raw string don't change the indent. + // Ignore a raw string inside a comment. comment_pos = ind_find_start_comment(); if (comment_pos != NULL) { // findmatchlimit() static pos is overwritten, make a copy @@ -2010,10 +1945,8 @@ int get_c_indent(void) amount = 0; goto theend; } - /* - * If we're inside a "//" comment and there is a "//" comment in a - * previous line, lineup with that one. - */ + // If we're inside a "//" comment and there is a "//" comment in a + // previous line, lineup with that one. if (cin_islinecomment(theline)) { pos_T linecomment_pos; @@ -2034,10 +1967,8 @@ int get_c_indent(void) goto theend; } } - /* - * If we're inside a comment and not looking at the start of the - * comment, try using the 'comments' option. - */ + // If we're inside a comment and not looking at the start of the + // comment, try using the 'comments' option. if (!cin_iscomment(theline) && comment_pos != NULL) { // XXX int lead_start_len = 2; int lead_middle_len = 1; @@ -2086,16 +2017,16 @@ int get_c_indent(void) STRCPY(lead_middle, lead_end); lead_middle_len = (int)STRLEN(lead_middle); } else if (what == COM_END) { - /* If our line starts with the middle comment string, line it - * up with the comment opener per the 'comments' option. */ + // If our line starts with the middle comment string, line it + // up with the comment opener per the 'comments' option. if (STRNCMP(theline, lead_middle, lead_middle_len) == 0 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0) { done = true; if (curwin->w_cursor.lnum > 1) { - /* If the start comment string matches in the previous - * line, use the indent of that line plus offset. If - * the middle comment string matches in the previous - * line, use the indent of that line. XXX */ + // If the start comment string matches in the previous + // line, use the indent of that line plus offset. If + // the middle comment string matches in the previous + // line, use the indent of that line. XXX look = (char_u *)skipwhite(ml_get(curwin->w_cursor.lnum - 1)); if (STRNCMP(look, lead_start, lead_start_len) == 0) { amount = get_indent_lnum(curwin->w_cursor.lnum - 1); @@ -2117,8 +2048,8 @@ int get_c_indent(void) break; } - /* If our line starts with the end comment string, line it up - * with the middle comment */ + // If our line starts with the end comment string, line it up + // with the middle comment if (STRNCMP(theline, lead_middle, lead_middle_len) != 0 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0) { amount = get_indent_lnum(curwin->w_cursor.lnum - 1); @@ -2134,10 +2065,9 @@ int get_c_indent(void) } } - /* If our line starts with an asterisk, line up with the - * asterisk in the comment opener; otherwise, line up - * with the first character of the comment text. - */ + // If our line starts with an asterisk, line up with the + // asterisk in the comment opener; otherwise, line up + // with the first character of the comment text. if (done) { // skip } else if (theline[0] == '*') { @@ -2187,8 +2117,8 @@ int get_c_indent(void) || (tryposBrace = find_start_brace()) != NULL || trypos != NULL) { if (trypos != NULL && tryposBrace != NULL) { - /* Both an unmatched '(' and '{' is found. Use the one which is - * closer to the current cursor position, set the other to NULL. */ + // Both an unmatched '(' and '{' is found. Use the one which is + // closer to the current cursor position, set the other to NULL. if (trypos->lnum != tryposBrace->lnum ? trypos->lnum < tryposBrace->lnum : trypos->col < tryposBrace->col) { @@ -2200,10 +2130,8 @@ int get_c_indent(void) if (trypos != NULL) { our_paren_pos = *trypos; - /* - * If the matching paren is more than one line away, use the indent of - * a previous non-empty line that matches the same paren. - */ + // If the matching paren is more than one line away, use the indent of + // a previous non-empty line that matches the same paren. if (theline[0] == ')' && curbuf->b_ind_paren_prev) { // Line up with the start of the matching paren line. amount = get_indent_lnum(curwin->w_cursor.lnum - 1); // XXX @@ -2243,18 +2171,16 @@ int get_c_indent(void) } } - /* - * Line up with line where the matching paren is. XXX - * If the line starts with a '(' or the indent for unclosed - * parentheses is zero, line up with the unclosed parentheses. - */ + // Line up with line where the matching paren is. XXX + // If the line starts with a '(' or the indent for unclosed + // parentheses is zero, line up with the unclosed parentheses. if (amount == -1) { int ignore_paren_col = 0; int is_if_for_while = 0; if (curbuf->b_ind_if_for_while) { - /* Look for the outermost opening parenthesis on this line - * and check whether it belongs to an "if", "for" or "while". */ + // Look for the outermost opening parenthesis on this line + // and check whether it belongs to an "if", "for" or "while". pos_T cursor_save = curwin->w_cursor; pos_T outermost; @@ -2284,8 +2210,8 @@ int get_c_indent(void) char_u *line; int look_col; - /* Ignore a '(' in front of the line that has a match before - * our matching '('. */ + // Ignore a '(' in front of the line that has a match before + // our matching '('. curwin->w_cursor.lnum = our_paren_pos.lnum; line = (char_u *)get_cursor_line_ptr(); look_col = (int)(look - line); @@ -2305,22 +2231,20 @@ int get_c_indent(void) && is_if_for_while == 0) || (!curbuf->b_ind_unclosed_noignore && *look == '(' && ignore_paren_col == 0)) { - /* - * If we're looking at a close paren, line up right there; - * otherwise, line up with the next (non-white) character. - * When b_ind_unclosed_wrapped is set and the matching paren is - * the last nonwhite character of the line, use either the - * indent of the current line or the indentation of the next - * outer paren and add b_ind_unclosed_wrapped (for very long - * lines). - */ + // If we're looking at a close paren, line up right there; + // otherwise, line up with the next (non-white) character. + // When b_ind_unclosed_wrapped is set and the matching paren is + // the last nonwhite character of the line, use either the + // indent of the current line or the indentation of the next + // outer paren and add b_ind_unclosed_wrapped (for very long + // lines). if (theline[0] != ')') { cur_amount = MAXCOL; l = (char_u *)ml_get(our_paren_pos.lnum); if (curbuf->b_ind_unclosed_wrapped && cin_ends_in(l, (char_u *)"(", NULL)) { - /* look for opening unmatched paren, indent one level - * for each additional level */ + // look for opening unmatched paren, indent one level + // for each additional level n = 1; for (col = 0; col < our_paren_pos.col; col++) { switch (l[col]) { @@ -2355,10 +2279,8 @@ int get_c_indent(void) } } - /* - * Find how indented the paren is, or the character after it - * if we did the above "if". - */ + // Find how indented the paren is, or the character after it + // if we did the above "if". if (our_paren_pos.col > 0) { getvcol(curwin, &our_paren_pos, &col, NULL, NULL); if (cur_amount > (int)col) { @@ -2376,8 +2298,8 @@ int get_c_indent(void) amount = cur_amount; } } else { - /* Add b_ind_unclosed2 for each '(' before our matching one, - * but ignore (void) before the line (ignore_paren_col). */ + // Add b_ind_unclosed2 for each '(' before our matching one, + // but ignore (void) before the line (ignore_paren_col). col = our_paren_pos.col; while ((int)our_paren_pos.col > ignore_paren_col) { our_paren_pos.col--; @@ -2393,8 +2315,8 @@ int get_c_indent(void) } } - /* Use b_ind_unclosed once, when the first '(' is not inside - * braces */ + // Use b_ind_unclosed once, when the first '(' is not inside + // braces if (col == MAXCOL) { amount += curbuf->b_ind_unclosed; } else { @@ -2410,14 +2332,12 @@ int get_c_indent(void) } } } - /* - * For a line starting with ')' use the minimum of the two - * positions, to avoid giving it more indent than the previous - * lines: - * func_long_name( if (x - * arg && yy - * ) ^ not here ) ^ not here - */ + // For a line starting with ')' use the minimum of the two + // positions, to avoid giving it more indent than the previous + // lines: + // func_long_name( if (x + // arg && yy + // ) ^ not here ) ^ not here if (cur_amount < amount) { amount = cur_amount; } @@ -2439,12 +2359,10 @@ int get_c_indent(void) ourscope = trypos->lnum; start = (char_u *)ml_get(ourscope); - /* - * Now figure out how indented the line is in general. - * If the brace was at the start of the line, we use that; - * otherwise, check out the indentation of the line as - * a whole and then add the "imaginary indent" to that. - */ + // Now figure out how indented the line is in general. + // If the brace was at the start of the line, we use that; + // otherwise, check out the indentation of the line as + // a whole and then add the "imaginary indent" to that. look = (char_u *)skipwhite((char *)start); if (*look == '{') { getvcol(curwin, trypos, &col, NULL, NULL); @@ -2490,18 +2408,14 @@ int get_c_indent(void) // we want to be. Otherwise, add the amount of room // that an indent is supposed to be. if (theline[0] == '}') { - /* - * they may want closing braces to line up with something - * other than the open brace. indulge them, if so. - */ + // they may want closing braces to line up with something + // other than the open brace. indulge them, if so. amount += curbuf->b_ind_close_extra; } else { - /* - * If we're looking at an "else", try to find an "if" - * to match it with. - * If we're looking at a "while", try to find a "do" - * to match it with. - */ + // If we're looking at an "else", try to find an "if" + // to match it with. + // If we're looking at a "while", try to find a "do" + // to match it with. lookfor = LOOKFOR_INITIAL; if (cin_iselse(theline)) { lookfor = LOOKFOR_IF; @@ -2516,18 +2430,14 @@ int get_c_indent(void) } } - /* - * We get here if we are not on an "while-of-do" or "else" (or - * failed to find a matching "if"). - * Search backwards for something to line up with. - * First set amount for when we don't find anything. - */ + // We get here if we are not on an "while-of-do" or "else" (or + // failed to find a matching "if"). + // Search backwards for something to line up with. + // First set amount for when we don't find anything. - /* - * if the '{' is _really_ at the left margin, use the imaginary - * location of a left-margin brace. Otherwise, correct the - * location for b_ind_open_extra. - */ + // if the '{' is _really_ at the left margin, use the imaginary + // location of a left-margin brace. Otherwise, correct the + // location for b_ind_open_extra. if (start_brace == BRACE_IN_COL0) { // '{' is in column 0 amount = curbuf->b_ind_open_left_imag; @@ -2586,10 +2496,8 @@ int get_c_indent(void) curwin->w_cursor.lnum--; curwin->w_cursor.col = 0; - /* - * If we went all the way back to the start of our scope, line - * up with it. - */ + // If we went all the way back to the start of our scope, line + // up with it. if (curwin->w_cursor.lnum <= ourscope) { // We reached end of scope: // If looking for a enum or structure initialization @@ -2603,9 +2511,9 @@ int get_c_indent(void) if (curwin->w_cursor.lnum == 0 || curwin->w_cursor.lnum < ourscope - curbuf->b_ind_maxparen) { - /* nothing found (abuse curbuf->b_ind_maxparen as - * limit) assume terminated line (i.e. a variable - * initialization) */ + // nothing found (abuse curbuf->b_ind_maxparen as + // limit) assume terminated line (i.e. a variable + // initialization) if (cont_amount > 0) { amount = cont_amount; } else if (!curbuf->b_ind_js) { @@ -2616,10 +2524,8 @@ int get_c_indent(void) l = (char_u *)get_cursor_line_ptr(); - /* - * If we're in a comment or raw string now, skip to - * the start of it. - */ + // If we're in a comment or raw string now, skip to + // the start of it. trypos = ind_find_start_CORS(NULL); if (trypos != NULL) { curwin->w_cursor.lnum = trypos->lnum + 1; @@ -2640,27 +2546,23 @@ int get_c_indent(void) terminated = cin_isterminated(l, false, true); - /* - * If we are at top level and the line looks like a - * function declaration, we are done - * (it's a variable declaration). - */ + // If we are at top level and the line looks like a + // function declaration, we are done + // (it's a variable declaration). if (start_brace != BRACE_IN_COL0 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0)) { - /* if the line is terminated with another ',' - * it is a continued variable initialization. - * don't add extra indent. - * TODO: does not work, if a function - * declaration is split over multiple lines: - * cin_isfuncdecl returns false then. - */ + // if the line is terminated with another ',' + // it is a continued variable initialization. + // don't add extra indent. + // TODO(vim): does not work, if a function + // declaration is split over multiple lines: + // cin_isfuncdecl returns false then. if (terminated == ',') { break; } - /* if it is an enum declaration or an assignment, - * we are done. - */ + // if it is an enum declaration or an assignment, + // we are done. if (terminated != ';' && cin_isinit()) { break; } @@ -2692,11 +2594,10 @@ int get_c_indent(void) } } - /* it's a variable declaration, add indentation - * like in - * int a, - * b; - */ + // it's a variable declaration, add indentation + // like in + // int a, + // b; if (cont_amount > 0) { amount = cont_amount; } else { @@ -2720,10 +2621,8 @@ int get_c_indent(void) } if (lookfor_cpp_namespace) { - /* - * Looking for C++ namespace, need to look further - * back. - */ + // Looking for C++ namespace, need to look further + // back. if (curwin->w_cursor.lnum == ourscope) { continue; } @@ -2736,8 +2635,8 @@ int get_c_indent(void) l = (char_u *)get_cursor_line_ptr(); - /* If we're in a comment or raw string now, skip - * to the start of it. */ + // If we're in a comment or raw string now, skip + // to the start of it. trypos = ind_find_start_CORS(NULL); if (trypos != NULL) { curwin->w_cursor.lnum = trypos->lnum + 1; @@ -2779,20 +2678,18 @@ int get_c_indent(void) l = (char_u *)get_cursor_line_ptr(); - /* - * If this is a switch() label, may line up relative to that. - * If this is a C++ scope declaration, do the same. - */ + // If this is a switch() label, may line up relative to that. + // If this is a C++ scope declaration, do the same. bool iscase = cin_iscase(l, false); if (iscase || cin_isscopedecl(l)) { - /* we are only looking for cpp base class - * declaration/initialization any longer */ + // we are only looking for cpp base class + // declaration/initialization any longer if (lookfor == LOOKFOR_CPP_BASECLASS) { break; } - /* When looking for a "do" we are not interested in - * labels. */ + // When looking for a "do" we are not interested in + // labels. if (whilelevel > 0) { continue; } @@ -2865,14 +2762,12 @@ int get_c_indent(void) break; } - /* - * Try to get the indent of a statement before the switch - * label. If nothing is found, line up relative to the - * switch label. - * break; <- may line up with this line - * case xx: - * -> y = 1; - */ + // Try to get the indent of a statement before the switch + // label. If nothing is found, line up relative to the + // switch label. + // break; <- may line up with this line + // case xx: + // -> y = 1; scope_amount = get_indent() + (iscase // XXX ? curbuf->b_ind_case_code : curbuf->b_ind_scopedecl_code); @@ -2881,10 +2776,8 @@ int get_c_indent(void) continue; } - /* - * Looking for a switch() label or C++ scope declaration, - * ignore other lines, skip {}-blocks. - */ + // Looking for a switch() label or C++ scope declaration, + // ignore other lines, skip {}-blocks. if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL) { if (find_last_paren(l, '{', '}') && (trypos = find_start_brace()) != NULL) { @@ -2894,9 +2787,7 @@ int get_c_indent(void) continue; } - /* - * Ignore jump labels with nothing after them. - */ + // Ignore jump labels with nothing after them. if (!curbuf->b_ind_js && cin_islabel()) { l = after_label((char_u *)get_cursor_line_ptr()); if (l == NULL || cin_nocode(l)) { @@ -2904,12 +2795,10 @@ int get_c_indent(void) } } - /* - * Ignore #defines, #if, etc. - * Ignore comment and empty lines. - * (need to get the line again, cin_islabel() may have - * unlocked it) - */ + // Ignore #defines, #if, etc. + // Ignore comment and empty lines. + // (need to get the line again, cin_islabel() may have + // unlocked it) l = (char_u *)get_cursor_line_ptr(); if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount) || cin_nocode(l)) { @@ -2942,9 +2831,8 @@ int get_c_indent(void) } break; } else if (lookfor == LOOKFOR_CPP_BASECLASS) { - /* only look, whether there is a cpp base class - * declaration or initialization before the opening brace. - */ + // only look, whether there is a cpp base class + // declaration or initialization before the opening brace. if (cin_isterminated(l, true, false)) { break; } else { @@ -2952,17 +2840,15 @@ int get_c_indent(void) } } - /* - * What happens next depends on the line being terminated. - * If terminated with a ',' only consider it terminating if - * there is another unterminated statement behind, eg: - * 123, - * sizeof - * here - * Otherwise check whether it is an enumeration or structure - * initialisation (not indented) or a variable declaration - * (indented). - */ + // What happens next depends on the line being terminated. + // If terminated with a ',' only consider it terminating if + // there is another unterminated statement behind, eg: + // 123, + // sizeof + // here + // Otherwise check whether it is an enumeration or structure + // initialisation (not indented) or a variable declaration + // (indented). terminated = cin_isterminated(l, false, true); if (js_cur_has_key) { @@ -3032,12 +2918,10 @@ int get_c_indent(void) } if (trypos != NULL) { - /* - * Check if we are on a case label now. This is - * handled above. - * case xx: if ( asdf && - * asdf) - */ + // Check if we are on a case label now. This is + // handled above. + // case xx: if ( asdf && + // asdf) curwin->w_cursor = *trypos; l = (char_u *)get_cursor_line_ptr(); if (cin_iscase(l, false) || cin_isscopedecl(l)) { @@ -3047,13 +2931,11 @@ int get_c_indent(void) } } - /* - * Skip over continuation lines to find the one to get the - * indent from - * char *usethis = "bla\ - * bla", - * here; - */ + // Skip over continuation lines to find the one to get the + // indent from + // char *usethis = "bla{backslash} + // bla", + // here; if (terminated == ',') { while (curwin->w_cursor.lnum > 1) { l = (char_u *)ml_get(curwin->w_cursor.lnum - 1); @@ -3065,49 +2947,41 @@ int get_c_indent(void) } } - /* - * Get indent and pointer to text for current line, - * ignoring any jump label. XXX - */ + // Get indent and pointer to text for current line, + // ignoring any jump label. XXX if (curbuf->b_ind_js) { cur_amount = get_indent(); } else { cur_amount = skip_label(curwin->w_cursor.lnum, &l); } - /* - * If this is just above the line we are indenting, and it - * starts with a '{', line it up with this line. - * while (not) - * -> { - * } - */ + // If this is just above the line we are indenting, and it + // starts with a '{', line it up with this line. + // while (not) + // -> { + // } if (terminated != ',' && lookfor != LOOKFOR_TERM && theline[0] == '{') { amount = cur_amount; - /* - * Only add b_ind_open_extra when the current line - * doesn't start with a '{', which must have a match - * in the same line (scope is the same). Probably: - * { 1, 2 }, - * -> { 3, 4 } - */ + // Only add b_ind_open_extra when the current line + // doesn't start with a '{', which must have a match + // in the same line (scope is the same). Probably: + // { 1, 2 }, + // -> { 3, 4 } if (*skipwhite((char *)l) != '{') { amount += curbuf->b_ind_open_extra; } if (curbuf->b_ind_cpp_baseclass && !curbuf->b_ind_js) { - /* have to look back, whether it is a cpp base - * class declaration or initialization */ + // have to look back, whether it is a cpp base + // class declaration or initialization lookfor = LOOKFOR_CPP_BASECLASS; continue; } break; } - /* - * Check if we are after an "if", "while", etc. - * Also allow " } else". - */ + // Check if we are after an "if", "while", etc. + // Also allow " } else". if (cin_is_cinword((char *)l) || cin_iselse((char_u *)skipwhite((char *)l))) { // Found an unterminated line after an if (), line up // with the last one. @@ -3124,19 +2998,17 @@ int get_c_indent(void) break; } - /* - * If this is just above the line we are indenting, we - * are finished. - * while (not) - * -> here; - * Otherwise this indent can be used when the line - * before this is terminated. - * yyy; - * if (stat) - * while (not) - * xxx; - * -> here; - */ + // If this is just above the line we are indenting, we + // are finished. + // while (not) + // -> here; + // Otherwise this indent can be used when the line + // before this is terminated. + // yyy; + // if (stat) + // while (not) + // xxx; + // -> here; amount = cur_amount; if (theline[0] == '{') { amount += curbuf->b_ind_open_extra; @@ -3147,13 +3019,11 @@ int get_c_indent(void) break; } - /* - * Special trick: when expecting the while () after a - * do, line up with the while() - * do - * x = 1; - * -> here - */ + // Special trick: when expecting the while () after a + // do, line up with the while() + // do + // x = 1; + // -> here l = (char_u *)skipwhite(get_cursor_line_ptr()); if (cin_isdo(l)) { if (whilelevel == 0) { @@ -3162,16 +3032,14 @@ int get_c_indent(void) whilelevel--; } - /* - * When searching for a terminated line, don't use the - * one between the "if" and the matching "else". - * Need to use the scope of this "else". XXX - * If whilelevel != 0 continue looking for a "do {". - */ + // When searching for a terminated line, don't use the + // one between the "if" and the matching "else". + // Need to use the scope of this "else". XXX + // If whilelevel != 0 continue looking for a "do {". if (cin_iselse(l) && whilelevel == 0) { - /* If we're looking at "} else", let's make sure we - * find the opening brace of the enclosing scope, - * not the one from "if () {". */ + // If we're looking at "} else", let's make sure we + // find the opening brace of the enclosing scope, + // not the one from "if () {". if (*l == '}') { curwin->w_cursor.col = (colnr_T)(l - (char_u *)get_cursor_line_ptr()) + 1; @@ -3183,21 +3051,17 @@ int get_c_indent(void) break; } } - } - /* - * If we're below an unterminated line that is not an - * "if" or something, we may line up with this line or - * add something for a continuation line, depending on - * the line before this one. - */ - else { - /* - * Found two unterminated lines on a row, line up with - * the last one. - * c = 99 + - * 100 + - * -> here; - */ + } else { + // If we're below an unterminated line that is not an + // "if" or something, we may line up with this line or + // add something for a continuation line, depending on + // the line before this one. + + // Found two unterminated lines on a row, line up with + // the last one. + // c = 99 + + // 100 + + // -> here; if (lookfor == LOOKFOR_UNTERM) { // When line ends in a comma add extra indent if (terminated == ',') { @@ -3207,11 +3071,11 @@ int get_c_indent(void) } if (lookfor == LOOKFOR_ENUM_OR_INIT) { - /* Found two lines ending in ',', lineup with the - * lowest one, but check for cpp base class - * declaration/initialization, if it is an - * opening brace or we are looking just for - * enumerations/initializations. */ + // Found two lines ending in ',', lineup with the + // lowest one, but check for cpp base class + // declaration/initialization, if it is an + // opening brace or we are looking just for + // enumerations/initializations. if (terminated == ',') { if (curbuf->b_ind_cpp_baseclass == 0) { break; @@ -3296,19 +3160,14 @@ int get_c_indent(void) } } } - } - /* - * Check if we are after a while (cond); - * If so: Ignore until the matching "do". - */ - else if (cin_iswhileofdo_end(terminated)) { // XXX - /* - * Found an unterminated line after a while ();, line up - * with the last one. - * while (cond); - * 100 + <- line up with this one - * -> here; - */ + // Check if we are after a while (cond); + // If so: Ignore until the matching "do". + } else if (cin_iswhileofdo_end(terminated)) { // XXX + // Found an unterminated line after a while ();, line up + // with the last one. + // while (cond); + // 100 + <- line up with this one + // -> here; if (lookfor == LOOKFOR_UNTERM || lookfor == LOOKFOR_ENUM_OR_INIT) { if (cont_amount > 0) { @@ -3327,28 +3186,22 @@ int get_c_indent(void) } } whilelevel++; - } - /* - * We are after a "normal" statement. - * If we had another statement we can stop now and use the - * indent of that other statement. - * Otherwise the indent of the current statement may be used, - * search backwards for the next "normal" statement. - */ - else { - /* - * Skip single break line, if before a switch label. It - * may be lined up with the case label. - */ + } else { + // We are after a "normal" statement. + // If we had another statement we can stop now and use the + // indent of that other statement. + // Otherwise the indent of the current statement may be used, + // search backwards for the next "normal" statement. + + // Skip single break line, if before a switch label. It + // may be lined up with the case label. if (lookfor == LOOKFOR_NOBREAK && cin_isbreak((char_u *)skipwhite(get_cursor_line_ptr()))) { lookfor = LOOKFOR_ANY; continue; } - /* - * Handle "do {" line. - */ + // Handle "do {" line. if (whilelevel > 0) { l = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_isdo(l)) { @@ -3358,17 +3211,15 @@ int get_c_indent(void) } } - /* - * Found a terminated line above an unterminated line. Add - * the amount for a continuation line. - * x = 1; - * y = foo + - * -> here; - * or - * int x = 1; - * int foo, - * -> here; - */ + // Found a terminated line above an unterminated line. Add + // the amount for a continuation line. + // x = 1; + // y = foo + + // -> here; + // or + // int x = 1; + // int foo, + // -> here; if (lookfor == LOOKFOR_UNTERM || lookfor == LOOKFOR_ENUM_OR_INIT) { if (cont_amount > 0) { @@ -3379,34 +3230,28 @@ int get_c_indent(void) break; } - /* - * Found a terminated line above a terminated line or "if" - * etc. line. Use the amount of the line below us. - * x = 1; x = 1; - * if (asdf) y = 2; - * while (asdf) ->here; - * here; - * ->foo; - */ + // Found a terminated line above a terminated line or "if" + // etc. line. Use the amount of the line below us. + // x = 1; x = 1; + // if (asdf) y = 2; + // while (asdf) ->here; + // here; + // ->foo; if (lookfor == LOOKFOR_TERM) { if (!lookfor_break && whilelevel == 0) { break; } - } - /* - * First line above the one we're indenting is terminated. - * To know what needs to be done look further backward for - * a terminated line. - */ - else { - /* - * position the cursor over the rightmost paren, so - * that matching it will take us back to the start of - * the line. Helps for: - * func(asdr, - * asdfasdf); - * here; - */ + } else { + // First line above the one we're indenting is terminated. + // To know what needs to be done look further backward for + // a terminated line. + + // position the cursor over the rightmost paren, so + // that matching it will take us back to the start of + // the line. Helps for: + // func(asdr, + // asdfasdf); + // here; term_again: l = (char_u *)get_cursor_line_ptr(); if (find_last_paren(l, '(', ')') @@ -3424,21 +3269,18 @@ term_again: } } - /* When aligning with the case statement, don't align - * with a statement after it. - * case 1: { <-- don't use this { position - * stat; - * } - * case 2: - * stat; - * } - */ + // When aligning with the case statement, don't align + // with a statement after it. + // case 1: { <-- don't use this { position + // stat; + // } + // case 2: + // stat; + // } iscase = curbuf->b_ind_keep_case_label && cin_iscase(l, false); - /* - * Get indent and pointer to text for current line, - * ignoring any jump label. - */ + // Get indent and pointer to text for current line, + // ignoring any jump label. amount = skip_label(curwin->w_cursor.lnum, &l); if (theline[0] == '{') { @@ -3451,14 +3293,12 @@ term_again: } lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM; - /* - * When a terminated line starts with "else" skip to - * the matching "if": - * else 3; - * indent this; - * Need to use the scope of this "else". XXX - * If whilelevel != 0 continue looking for a "do {". - */ + // When a terminated line starts with "else" skip to + // the matching "if": + // else 3; + // indent this; + // Need to use the scope of this "else". XXX + // If whilelevel != 0 continue looking for a "do {". if (lookfor == LOOKFOR_TERM && *l != '}' && cin_iselse(l) @@ -3471,10 +3311,8 @@ term_again: continue; } - /* - * If we're at the end of a block, skip to the start of - * that block. - */ + // If we're at the end of a block, skip to the start of + // that block. l = (char_u *)get_cursor_line_ptr(); if (find_last_paren(l, '{', '}') // XXX && (trypos = find_start_brace()) != NULL) { @@ -3521,13 +3359,11 @@ term_again: amount = curbuf->b_ind_first_open; goto theend; } - /* - * If the NEXT line is a function declaration, the current - * line needs to be indented as a function type spec. - * Don't do this if the current line looks like a comment or if the - * current line is terminated, ie. ends in ';', or if the current line - * contains { or }: "void f() {\n if (1)" - */ + // If the NEXT line is a function declaration, the current + // line needs to be indented as a function type spec. + // Don't do this if the current line looks like a comment or if the + // current line is terminated, ie. ends in ';', or if the current line + // contains { or }: "void f() {\n if (1)" if (cur_curpos.lnum < curbuf->b_ml.ml_line_count && !cin_nocode(theline) && vim_strchr((char *)theline, '{') == NULL @@ -3582,18 +3418,16 @@ term_again: continue; } - /* - * If the previous line ends in ',', use one level of - * indentation: - * int foo, - * bar; - * do this before checking for '}' in case of eg. - * enum foobar - * { - * ... - * } foo, - * bar; - */ + // If the previous line ends in ',', use one level of + // indentation: + // int foo, + // bar; + // do this before checking for '}' in case of eg. + // enum foobar + // { + // ... + // } foo, + // bar; if (cin_ends_in(l, (char_u *)",", NULL) || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\')) { // take us back to opening paren @@ -3602,12 +3436,11 @@ term_again: curwin->w_cursor = *trypos; } - /* For a line ending in ',' that is a continuation line go - * back to the first line with a backslash: - * char *foo = "bla\ - * bla", - * here; - */ + // For a line ending in ',' that is a continuation line go + // back to the first line with a backslash: + // char *foo = "bla{backslash} + // bla", + // here; while (n == 0 && curwin->w_cursor.lnum > 1) { l = (char_u *)ml_get(curwin->w_cursor.lnum - 1); if (*l == NUL || l[STRLEN(l) - 1] != '\\') { @@ -3628,19 +3461,15 @@ term_again: break; } - /* - * If the line looks like a function declaration, and we're - * not in a comment, put it the left margin. - */ + // If the line looks like a function declaration, and we're + // not in a comment, put it the left margin. if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0)) { // XXX break; } l = (char_u *)get_cursor_line_ptr(); - /* - * Finding the closing '}' of a previous function. Put - * current line at the left margin. For when 'cino' has "fs". - */ + // Finding the closing '}' of a previous function. Put + // current line at the left margin. For when 'cino' has "fs". if (*skipwhite((char *)l) == '}') { break; } @@ -3663,11 +3492,9 @@ term_again: break; } - /* - * Find a line only has a semicolon that belongs to a previous - * line ending in '}', e.g. before an #endif. Don't increase - * indent then. - */ + // Find a line only has a semicolon that belongs to a previous + // line ending in '}', e.g. before an #endif. Don't increase + // indent then. if (*(look = (char_u *)skipwhite((char *)l)) == ';' && cin_nocode(look + 1)) { pos_T curpos_save = curwin->w_cursor; @@ -3686,23 +3513,19 @@ term_again: curwin->w_cursor = curpos_save; } - /* - * If the PREVIOUS line is a function declaration, the current - * line (and the ones that follow) needs to be indented as - * parameters. - */ + // If the PREVIOUS line is a function declaration, the current + // line (and the ones that follow) needs to be indented as + // parameters. if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0)) { amount = curbuf->b_ind_param; break; } - /* - * If the previous line ends in ';' and the line before the - * previous line ends in ',' or '\', ident to column zero: - * int foo, - * bar; - * indent_to_0 here; - */ + // If the previous line ends in ';' and the line before the + // previous line ends in ',' or '\', ident to column zero: + // int foo, + // bar; + // indent_to_0 here; if (cin_ends_in(l, (char_u *)";", NULL)) { l = (char_u *)ml_get(curwin->w_cursor.lnum - 1); if (cin_ends_in(l, (char_u *)",", NULL) @@ -3712,13 +3535,11 @@ term_again: l = (char_u *)get_cursor_line_ptr(); } - /* - * Doesn't look like anything interesting -- so just - * use the indent of this line. - * - * Position the cursor over the rightmost paren, so that - * matching it will take us back to the start of the line. - */ + // Doesn't look like anything interesting -- so just + // use the indent of this line. + // + // Position the cursor over the rightmost paren, so that + // matching it will take us back to the start of the line. (void)find_last_paren(l, '(', ')'); if ((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) { @@ -3794,38 +3615,30 @@ static int find_match(int lookfor, linenr_T ourscope) continue; } - /* - * if we've gone outside the braces entirely, - * we must be out of scope... - */ + // if we've gone outside the braces entirely, + // we must be out of scope... theirscope = find_start_brace(); // XXX if (theirscope == NULL) { break; } - /* - * and if the brace enclosing this is further - * back than the one enclosing the else, we're - * out of luck too. - */ + // and if the brace enclosing this is further + // back than the one enclosing the else, we're + // out of luck too. if (theirscope->lnum < ourscope) { break; } - /* - * and if they're enclosed in a *deeper* brace, - * then we can ignore it because it's in a - * different scope... - */ + // and if they're enclosed in a *deeper* brace, + // then we can ignore it because it's in a + // different scope... if (theirscope->lnum > ourscope) { continue; } - /* - * if it was an "else" (that's not an "else if") - * then we need to go back to another if, so - * increment elselevel - */ + // if it was an "else" (that's not an "else if") + // then we need to go back to another if, so + // increment elselevel look = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_iselse(look)) { mightbeif = cin_skipcomment(look + 4); @@ -3835,10 +3648,8 @@ static int find_match(int lookfor, linenr_T ourscope) continue; } - /* - * if it was a "while" then we need to go back to - * another "do", so increment whilelevel. XXX - */ + // if it was a "while" then we need to go back to + // another "do", so increment whilelevel. XXX if (cin_iswhileofdo(look, curwin->w_cursor.lnum)) { whilelevel++; continue; @@ -3847,11 +3658,9 @@ static int find_match(int lookfor, linenr_T ourscope) // If it's an "if" decrement elselevel look = cin_skipcomment((char_u *)get_cursor_line_ptr()); if (cin_isif(look)) { - elselevel--; - /* - * When looking for an "if" ignore "while"s that - * get in the way. - */ + elselevel--; // NOLINT(readability/braces) + // When looking for an "if" ignore "while"s that + // get in the way. if (elselevel == 0 && lookfor == LOOKFOR_IF) { whilelevel = 0; } @@ -3862,11 +3671,9 @@ static int find_match(int lookfor, linenr_T ourscope) whilelevel--; } - /* - * if we've used up all the elses, then - * this must be the if that we want! - * match the indent level of that if. - */ + // if we've used up all the elses, then + // this must be the if that we want! + // match the indent level of that if. if (elselevel <= 0 && whilelevel <= 0) { return OK; } @@ -3874,9 +3681,7 @@ static int find_match(int lookfor, linenr_T ourscope) return FAIL; } -/* - * Do C or expression indenting on the current line. - */ +// Do C or expression indenting on the current line. void do_c_expr_indent(void) { if (*curbuf->b_p_inde != NUL) { diff --git a/src/nvim/main.c b/src/nvim/main.c index 1c7cfea768..a73c465042 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -1390,10 +1390,9 @@ scripterror: TIME_MSG("parsing arguments"); } -/* - * Many variables are in "params" so that we can pass them to invoked - * functions without a lot of arguments. "argc" and "argv" are also - * copied, so that they can be changed. */ +// Many variables are in "params" so that we can pass them to invoked +// functions without a lot of arguments. "argc" and "argv" are also +// copied, so that they can be changed. static void init_params(mparm_T *paramp, int argc, char **argv) { CLEAR_POINTER(paramp); @@ -1465,9 +1464,7 @@ static char_u *get_fname(mparm_T *parmp, char_u *cwd) return (char_u *)alist_name(&GARGLIST[0]); } -/* - * Decide about window layout for diff mode after reading vimrc. - */ +// Decide about window layout for diff mode after reading vimrc. static void set_window_layout(mparm_T *paramp) { if (paramp->diff_mode && paramp->window_layout == 0) { @@ -1479,10 +1476,8 @@ static void set_window_layout(mparm_T *paramp) } } -/* - * "-q errorfile": Load the error file now. - * If the error file can't be read, exit before doing anything else. - */ +// "-q errorfile": Load the error file now. +// If the error file can't be read, exit before doing anything else. static void handle_quickfix(mparm_T *paramp) { if (paramp->edit_type == EDIT_QF) { @@ -1498,10 +1493,8 @@ static void handle_quickfix(mparm_T *paramp) } } -/* - * Need to jump to the tag before executing the '-c command'. - * Makes "vim -c '/return' -t main" work. - */ +// Need to jump to the tag before executing the '-c command'. +// Makes "vim -c '/return' -t main" work. static void handle_tag(char_u *tagname) { if (tagname != NULL) { @@ -1540,18 +1533,14 @@ static void read_stdin(void) check_swap_exists_action(); } -/* - * Create the requested number of windows and edit buffers in them. - * Also does recovery if "recoverymode" set. - */ +// Create the requested number of windows and edit buffers in them. +// Also does recovery if "recoverymode" set. static void create_windows(mparm_T *parmp) { int dorewind; int done = 0; - /* - * Create the number of windows that was requested. - */ + // Create the number of windows that was requested. if (parmp->window_count == -1) { // was not set parmp->window_count = 1; } @@ -1670,9 +1659,7 @@ static void edit_buffers(mparm_T *parmp, char_u *cwd) win_T *win; char *p_shm_save = NULL; - /* - * Don't execute Win/Buf Enter/Leave autocommands here - */ + // Don't execute Win/Buf Enter/Leave autocommands here autocmd_no_enter++; autocmd_no_leave++; @@ -1781,9 +1768,7 @@ static void edit_buffers(mparm_T *parmp, char_u *cwd) } } -/* - * Execute the commands from --cmd arguments "cmds[cnt]". - */ +// Execute the commands from --cmd arguments "cmds[cnt]". static void exe_pre_commands(mparm_T *parmp) { char **cmds = parmp->pre_commands; @@ -1803,18 +1788,14 @@ static void exe_pre_commands(mparm_T *parmp) } } -/* - * Execute "+", "-c" and "-S" arguments. - */ +// Execute "+", "-c" and "-S" arguments. static void exe_commands(mparm_T *parmp) { int i; - /* - * We start commands on line 0, make "vim +/pat file" match a - * pattern on line 1. But don't move the cursor when an autocommand - * with g`" was used. - */ + // We start commands on line 0, make "vim +/pat file" match a + // pattern on line 1. But don't move the cursor when an autocommand + // with g`" was used. msg_scroll = true; if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1) { curwin->w_cursor.lnum = 0; @@ -2137,11 +2118,9 @@ static void usage(void) mch_msg(_("\nSee \":help startup-options\" for all options.\n")); } -/* - * Check the result of the ATTENTION dialog: - * When "Quit" selected, exit Vim. - * When "Recover" selected, recover the file. - */ +// Check the result of the ATTENTION dialog: +// When "Quit" selected, exit Vim. +// When "Recover" selected, recover the file. static void check_swap_exists_action(void) { if (swap_exists_action == SEA_QUIT) { diff --git a/src/nvim/mark.c b/src/nvim/mark.c index c6d08eb689..7838986edd 100644 --- a/src/nvim/mark.c +++ b/src/nvim/mark.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * mark.c: functions for setting marks and jumping to them - */ +// mark.c: functions for setting marks and jumping to them #include #include @@ -39,17 +37,13 @@ #include "nvim/ui.h" #include "nvim/vim.h" -/* - * This file contains routines to maintain and manipulate marks. - */ +// This file contains routines to maintain and manipulate marks. -/* - * If a named file mark's lnum is non-zero, it is valid. - * If a named file mark's fnum is non-zero, it is for an existing buffer, - * otherwise it is from .shada and namedfm[n].fname is the file name. - * There are marks 'A - 'Z (set by user) and '0 to '9 (set when writing - * shada). - */ +// If a named file mark's lnum is non-zero, it is valid. +// If a named file mark's fnum is non-zero, it is for an existing buffer, +// otherwise it is from .shada and namedfm[n].fname is the file name. +// There are marks 'A - 'Z (set by user) and '0 to '9 (set when writing +// shada). /// Global marks (marks with file number or name) static xfmark_T namedfm[NGLOBALMARKS]; @@ -57,10 +51,9 @@ static xfmark_T namedfm[NGLOBALMARKS]; #ifdef INCLUDE_GENERATED_DECLARATIONS # include "mark.c.generated.h" #endif -/* - * Set named mark "c" at current cursor position. - * Returns OK on success, FAIL if bad name given. - */ + +// Set named mark "c" at current cursor position. +// Returns OK on success, FAIL if bad name given. int setmark(int c) { fmarkv_T view = mark_view_make(curwin->w_topline, curwin->w_cursor); @@ -88,11 +81,9 @@ void clear_fmark(fmark_T *fm) CLEAR_POINTER(fm); } -/* - * Set named mark "c" to position "pos". - * When "c" is upper case use file "fnum". - * Returns OK on success, FAIL if bad name given. - */ +// Set named mark "c" to position "pos". +// When "c" is upper case use file "fnum". +// Returns OK on success, FAIL if bad name given. int setmark_pos(int c, pos_T *pos, int fnum, fmarkv_T *view_pt) { int i; @@ -166,10 +157,8 @@ int setmark_pos(int c, pos_T *pos, int fnum, fmarkv_T *view_pt) return FAIL; } -/* - * Set the previous context mark to the current position and add it to the - * jump list. - */ +// Set the previous context mark to the current position and add it to the +// jump list. void setpcmark(void) { xfmark_T *fm; @@ -210,12 +199,10 @@ void setpcmark(void) SET_XFMARK(fm, curwin->w_pcmark, curbuf->b_fnum, view, NULL); } -/* - * To change context, call setpcmark(), then move the current position to - * where ever, then call checkpcmark(). This ensures that the previous - * context will only be changed if the cursor moved to a different line. - * If pcmark was deleted (with "dG") the previous mark is restored. - */ +// To change context, call setpcmark(), then move the current position to +// where ever, then call checkpcmark(). This ensures that the previous +// context will only be changed if the cursor moved to a different line. +// If pcmark was deleted (with "dG") the previous mark is restored. void checkpcmark(void) { if (curwin->w_prev_pcmark.lnum != 0 @@ -653,20 +640,16 @@ fmark_T *getnextmark(pos_T *startpos, int dir, int begin_line) return result; } -/* - * For an xtended filemark: set the fnum from the fname. - * This is used for marks obtained from the .shada file. It's postponed - * until the mark is used to avoid a long startup delay. - */ +// For an xtended filemark: set the fnum from the fname. +// This is used for marks obtained from the .shada file. It's postponed +// until the mark is used to avoid a long startup delay. static void fname2fnum(xfmark_T *fm) { char_u *p; if (fm->fname != NULL) { - /* - * First expand "~/" in the file name to the home directory. - * Don't expand the whole name, it may contain other '~' chars. - */ + // First expand "~/" in the file name to the home directory. + // Don't expand the whole name, it may contain other '~' chars. if (fm->fname[0] == '~' && (fm->fname[1] == '/' #ifdef BACKSLASH_IN_FILENAME || fm->fname[1] == '\\' @@ -690,11 +673,9 @@ static void fname2fnum(xfmark_T *fm) } } -/* - * Check all file marks for a name that matches the file name in buf. - * May replace the name with an fnum. - * Used for marks that come from the .shada file. - */ +// Check all file marks for a name that matches the file name in buf. +// May replace the name with an fnum. +// Used for marks that come from the .shada file. void fmarks_check_names(buf_T *buf) { char_u *name = (char_u *)buf->b_ffname; @@ -792,11 +773,9 @@ void clrallmarks(buf_T *const buf) buf->b_changelistlen = 0; } -/* - * Get name of file from a filemark. - * When it's in the current buffer, return the text at the mark. - * Returns an allocated string. - */ +// Get name of file from a filemark. +// When it's in the current buffer, return the text at the mark. +// Returns an allocated string. char_u *fm_getname(fmark_T *fmark, int lead_len) { if (fmark->fnum == curbuf->b_fnum) { // current buffer @@ -831,9 +810,7 @@ static char *mark_line(pos_T *mp, int lead_len) return s; } -/* - * print the marks - */ +// print the marks void ex_marks(exarg_T *eap) { char_u *arg = (char_u *)eap->arg; @@ -930,9 +907,7 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu } } -/* - * ":delmarks[!] [marks]" - */ +// ":delmarks[!] [marks]" void ex_delmarks(exarg_T *eap) { char_u *p; @@ -1013,9 +988,7 @@ void ex_delmarks(exarg_T *eap) } } -/* - * print the jumplist - */ +// print the jumplist void ex_jumps(exarg_T *eap) { int i; @@ -1068,9 +1041,7 @@ void ex_clearjumps(exarg_T *eap) curwin->w_jumplistidx = 0; } -/* - * print the changelist - */ +// print the changelist void ex_changes(exarg_T *eap) { int i; @@ -1132,17 +1103,15 @@ void ex_changes(exarg_T *eap) *lp += amount_after; \ } -/* - * Adjust marks between line1 and line2 (inclusive) to move 'amount' lines. - * Must be called before changed_*(), appended_lines() or deleted_lines(). - * May be called before or after changing the text. - * When deleting lines line1 to line2, use an 'amount' of MAXLNUM: The marks - * within this range are made invalid. - * If 'amount_after' is non-zero adjust marks after line2. - * Example: Delete lines 34 and 35: mark_adjust(34, 35, MAXLNUM, -2); - * Example: Insert two lines below 55: mark_adjust(56, MAXLNUM, 2, 0); - * or: mark_adjust(56, 55, MAXLNUM, 2); - */ +// Adjust marks between line1 and line2 (inclusive) to move 'amount' lines. +// Must be called before changed_*(), appended_lines() or deleted_lines(). +// May be called before or after changing the text. +// When deleting lines line1 to line2, use an 'amount' of MAXLNUM: The marks +// within this range are made invalid. +// If 'amount_after' is non-zero adjust marks after line2. +// Example: Delete lines 34 and 35: mark_adjust(34, 35, MAXLNUM, -2); +// Example: Insert two lines below 55: mark_adjust(56, MAXLNUM, 2, 0); +// or: mark_adjust(56, 55, MAXLNUM, 2); void mark_adjust(linenr_T line1, linenr_T line2, linenr_T amount, linenr_T amount_after, ExtmarkOp op) { @@ -1237,9 +1206,7 @@ static void mark_adjust_internal(linenr_T line1, linenr_T line2, linenr_T amount ONE_ADJUST_NODEL(&(saved_cursor.lnum)); } - /* - * Adjust items in all windows related to the current buffer. - */ + // Adjust items in all windows related to the current buffer. FOR_ALL_TAB_WINDOWS(tab, win) { if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Marks in the jumplist. When deleting lines, this may create @@ -1381,9 +1348,7 @@ void mark_col_adjust(linenr_T lnum, colnr_T mincol, linenr_T lnum_amount, long c // saved cursor for formatting COL_ADJUST(&saved_cursor); - /* - * Adjust items in all windows related to the current buffer. - */ + // Adjust items in all windows related to the current buffer. FOR_ALL_WINDOWS_IN_TAB(win, curtab) { // marks in the jumplist for (i = 0; i < win->w_jumplistlen; i++) { @@ -1481,9 +1446,7 @@ void cleanup_jumplist(win_T *wp, bool checktail) } } -/* - * Copy the jumplist from window "from" to window "to". - */ +// Copy the jumplist from window "from" to window "to". void copy_jumplist(win_T *from, win_T *to) { int i; @@ -1705,9 +1668,7 @@ bool mark_set_local(const char name, buf_T *const buf, const fmark_T fm, const b return true; } -/* - * Free items in the jumplist of window "wp". - */ +// Free items in the jumplist of window "wp". void free_jumplist(win_T *wp) { int i; diff --git a/src/nvim/mark_defs.h b/src/nvim/mark_defs.h index a78056c5f9..3e3a46cd20 100644 --- a/src/nvim/mark_defs.h +++ b/src/nvim/mark_defs.h @@ -5,10 +5,8 @@ #include "nvim/os/time.h" #include "nvim/pos.h" -/* - * marks: positions in a file - * (a normal mark is a lnum/col pair, the same as a file position) - */ +// marks: positions in a file +// (a normal mark is a lnum/col pair, the same as a file position) /// Flags for outcomes when moving to a mark. typedef enum { diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index 0a4182a892..116a66e773 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -132,10 +132,8 @@ const uint8_t utf8len_tab_zero[] = { 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // F? }; -/* - * Canonical encoding names and their properties. - * "iso-8859-n" is handled by enc_canonize() directly. - */ +// Canonical encoding names and their properties. +// "iso-8859-n" is handled by enc_canonize() directly. static struct { const char *name; int prop; int codepage; } enc_canon_table[] = @@ -269,9 +267,7 @@ enc_canon_table[] = #define IDX_COUNT 59 }; -/* - * Aliases for encoding names. - */ +// Aliases for encoding names. static struct { const char *name; int canon; } enc_alias_table[] = @@ -342,10 +338,8 @@ enc_alias_table[] = { NULL, 0 } }; -/* - * Find encoding "name" in the list of canonical encoding names. - * Returns -1 if not found. - */ +// Find encoding "name" in the list of canonical encoding names. +// Returns -1 if not found. static int enc_canon_search(const char_u *name) FUNC_ATTR_PURE { @@ -357,10 +351,8 @@ static int enc_canon_search(const char_u *name) return -1; } -/* - * Find canonical encoding "name" in the list and return its properties. - * Returns 0 if not found. - */ +// Find canonical encoding "name" in the list and return its properties. +// Returns 0 if not found. int enc_canon_props(const char_u *name) FUNC_ATTR_PURE { @@ -375,13 +367,11 @@ int enc_canon_props(const char_u *name) return 0; } -/* - * Return the size of the BOM for the current buffer: - * 0 - no BOM - * 2 - UCS-2 or UTF-16 BOM - * 4 - UCS-4 BOM - * 3 - UTF-8 BOM - */ +// Return the size of the BOM for the current buffer: +// 0 - no BOM +// 2 - UCS-2 or UTF-16 BOM +// 4 - UCS-4 BOM +// 3 - UTF-8 BOM int bomb_size(void) FUNC_ATTR_PURE { @@ -401,9 +391,7 @@ int bomb_size(void) return n; } -/* - * Remove all BOM from "s" by moving remaining text. - */ +// Remove all BOM from "s" by moving remaining text. void remove_bom(char_u *s) { char *p = (char *)s; @@ -417,13 +405,11 @@ void remove_bom(char_u *s) } } -/* - * Get class of pointer: - * 0 for blank or NUL - * 1 for punctuation - * 2 for an (ASCII) word character - * >2 for other word characters - */ +// Get class of pointer: +// 0 for blank or NUL +// 1 for punctuation +// 2 for an (ASCII) word character +// >2 for other word characters int mb_get_class(const char_u *p) FUNC_ATTR_PURE { @@ -445,9 +431,7 @@ int mb_get_class_tab(const char_u *p, const uint64_t *const chartab) return utf_class_tab(utf_ptr2char((char *)p), chartab); } -/* - * Return true if "c" is in "table". - */ +// Return true if "c" is in "table". static bool intable(const struct interval *table, size_t n_items, int c) FUNC_ATTR_PURE { @@ -646,22 +630,20 @@ int utf_ptr2char(const char *const p_in) return p[0]; } -/* - * Convert a UTF-8 byte sequence to a wide character. - * String is assumed to be terminated by NUL or after "n" bytes, whichever - * comes first. - * The function is safe in the sense that it never accesses memory beyond the - * first "n" bytes of "s". - * - * On success, returns decoded codepoint, advances "s" to the beginning of - * next character and decreases "n" accordingly. - * - * If end of string was reached, returns 0 and, if "n" > 0, advances "s" past - * NUL byte. - * - * If byte sequence is illegal or incomplete, returns -1 and does not advance - * "s". - */ +// Convert a UTF-8 byte sequence to a wide character. +// String is assumed to be terminated by NUL or after "n" bytes, whichever +// comes first. +// The function is safe in the sense that it never accesses memory beyond the +// first "n" bytes of "s". +// +// On success, returns decoded codepoint, advances "s" to the beginning of +// next character and decreases "n" accordingly. +// +// If end of string was reached, returns 0 and, if "n" > 0, advances "s" past +// NUL byte. +// +// If byte sequence is illegal or incomplete, returns -1 and does not advance +// "s". static int utf_safe_read_char_adv(const char_u **s, size_t *n) { int c; @@ -701,10 +683,8 @@ static int utf_safe_read_char_adv(const char_u **s, size_t *n) return -1; } -/* - * Get character at **pp and advance *pp to the next character. - * Note: composing characters are skipped! - */ +// Get character at **pp and advance *pp to the next character. +// Note: composing characters are skipped! int mb_ptr2char_adv(const char_u **const pp) { int c; @@ -714,10 +694,8 @@ int mb_ptr2char_adv(const char_u **const pp) return c; } -/* - * Get character at **pp and advance *pp to the next character. - * Note: composing characters are returned as separate characters. - */ +// Get character at **pp and advance *pp to the next character. +// Note: composing characters are returned as separate characters. int mb_cptr2char_adv(const char_u **pp) { int c; @@ -784,12 +762,10 @@ int utfc_ptr2char(const char *p_in, int *pcc) return c; } -/* - * Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO - * composing characters. Use no more than p[maxlen]. - * - * @param [out] pcc: composing chars, last one is 0 - */ +// Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO +// composing characters. Use no more than p[maxlen]. +// +// @param [out] pcc: composing chars, last one is 0 int utfc_ptr2char_len(const char_u *p, int *pcc, int maxlen) { assert(maxlen > 0); @@ -845,24 +821,20 @@ int utf_ptr2len(const char *const p_in) return len; } -/* - * Return length of UTF-8 character, obtained from the first byte. - * "b" must be between 0 and 255! - * Returns 1 for an invalid first byte value. - */ +// Return length of UTF-8 character, obtained from the first byte. +// "b" must be between 0 and 255! +// Returns 1 for an invalid first byte value. int utf_byte2len(int b) { return utf8len_tab[b]; } -/* - * Get the length of UTF-8 byte sequence "p[size]". Does not include any - * following composing characters. - * Returns 1 for "". - * Returns 1 for an illegal byte sequence (also in incomplete byte seq.). - * Returns number > "size" for an incomplete byte sequence. - * Never returns zero. - */ +// Get the length of UTF-8 byte sequence "p[size]". Does not include any +// following composing characters. +// Returns 1 for "". +// Returns 1 for an illegal byte sequence (also in incomplete byte seq.). +// Returns number > "size" for an incomplete byte sequence. +// Never returns zero. int utf_ptr2len_len(const char_u *p, int size) { int len; @@ -948,10 +920,8 @@ int utfc_ptr2len_len(const char *p, int size) return 1; } - /* - * Check for composing characters. We can handle only the first six, but - * skip all of them (otherwise the cursor would get stuck). - */ + // Check for composing characters. We can handle only the first six, but + // skip all of them (otherwise the cursor would get stuck). prevlen = 0; while (len < size) { int len_next_char; @@ -960,10 +930,8 @@ int utfc_ptr2len_len(const char *p, int size) break; } - /* - * Next character length should not go beyond size to ensure that - * utf_composinglike(...) does not read beyond size. - */ + // Next character length should not go beyond size to ensure that + // utf_composinglike(...) does not read beyond size. len_next_char = utf_ptr2len_len((char_u *)p + len, size - len); if (len_next_char > size - len) { break; @@ -1042,20 +1010,16 @@ int utf_char2bytes(const int c, char *const buf) } } -/* - * Return true if "c" is a composing UTF-8 character. This means it will be - * drawn on top of the preceding character. - * Based on code from Markus Kuhn. - */ +// Return true if "c" is a composing UTF-8 character. This means it will be +// drawn on top of the preceding character. +// Based on code from Markus Kuhn. bool utf_iscomposing(int c) { return intable(combining, ARRAY_SIZE(combining), c); } -/* - * Return true for characters that can be displayed in a normal way. - * Only for characters of 0x100 and above! - */ +// Return true for characters that can be displayed in a normal way. +// Only for characters of 0x100 and above! bool utf_printable(int c) { // Sorted list of non-overlapping intervals. @@ -1070,12 +1034,10 @@ bool utf_printable(int c) return !intable(nonprint, ARRAY_SIZE(nonprint), c); } -/* - * Get class of a Unicode character. - * 0: white space - * 1: punctuation - * 2 or bigger: some class of word character. - */ +// Get class of a Unicode character. +// 0: white space +// 1: punctuation +// 2 or bigger: some class of word character. int utf_class(const int c) { return utf_class_tab(c, curbuf->b_chartab); @@ -1204,11 +1166,9 @@ bool utf_ambiguous_width(int c) || intable(emoji_all, ARRAY_SIZE(emoji_all), c)); } -/* - * Generic conversion function for case operations. - * Return the converted equivalent of "a", which is a UCS-4 character. Use - * the given conversion "table". Uses binary search on "table". - */ +// Generic conversion function for case operations. +// Return the converted equivalent of "a", which is a UCS-4 character. Use +// the given conversion "table". Uses binary search on "table". static int utf_convert(int a, const convertStruct *const table, size_t n_items) { size_t start, mid, end; // indices into table @@ -1234,10 +1194,8 @@ static int utf_convert(int a, const convertStruct *const table, size_t n_items) } } -/* - * Return the folded-case equivalent of "a", which is a UCS-4 character. Uses - * simple case folding. - */ +// Return the folded-case equivalent of "a", which is a UCS-4 character. Uses +// simple case folding. int utf_fold(int a) { if (a < 0x80) { @@ -1566,10 +1524,8 @@ int mb_stricmp(const char *s1, const char *s2) return mb_strnicmp(s1, s2, MAXCOL); } -/* - * "g8": show bytes of the UTF-8 char under the cursor. Doesn't matter what - * 'encoding' has been set to. - */ +// "g8": show bytes of the UTF-8 char under the cursor. Doesn't matter what +// 'encoding' has been set to. void show_utf8(void) { int len; @@ -1916,9 +1872,7 @@ int utf_cp_head_off(const char_u *base, const char_u *p) return i; } -/* - * Find the next illegal byte sequence. - */ +// Find the next illegal byte sequence. void utf_find_illegal(void) { pos_T pos = curwin->w_cursor; @@ -2008,10 +1962,8 @@ bool utf_valid_string(const char_u *s, const char_u *end) return true; } -/* - * If the cursor moves on an trail byte, set the cursor on the lead byte. - * Thus it moves left if necessary. - */ +// If the cursor moves on an trail byte, set the cursor on the lead byte. +// Thus it moves left if necessary. void mb_adjust_cursor(void) { mark_mb_adjustpos(curbuf, &curwin->w_cursor); @@ -2238,10 +2190,8 @@ static int enc_alias_search(const char_u *name) # include #endif -/* - * Get the canonicalized encoding of the current locale. - * Returns an allocated string when successful, NULL when not. - */ +// Get the canonicalized encoding of the current locale. +// Returns an allocated string when successful, NULL when not. char_u *enc_locale(void) { int i; @@ -2307,12 +2257,10 @@ enc_locale_copy_enc: #if defined(HAVE_ICONV) -/* - * Call iconv_open() with a check if iconv() works properly (there are broken - * versions). - * Returns (void *)-1 if failed. - * (should return iconv_t, but that causes problems with prototypes). - */ +// Call iconv_open() with a check if iconv() works properly (there are broken +// versions). +// Returns (void *)-1 if failed. +// (should return iconv_t, but that causes problems with prototypes). void *my_iconv_open(char_u *to, char_u *from) { iconv_t fd; @@ -2328,13 +2276,11 @@ void *my_iconv_open(char_u *to, char_u *from) fd = iconv_open(enc_skip((char *)to), enc_skip((char *)from)); if (fd != (iconv_t)-1 && iconv_working == kUnknown) { - /* - * Do a dummy iconv() call to check if it actually works. There is a - * version of iconv() on Linux that is broken. We can't ignore it, - * because it's wide-spread. The symptoms are that after outputting - * the initial shift state the "to" pointer is NULL and conversion - * stops for no apparent reason after about 8160 characters. - */ + // Do a dummy iconv() call to check if it actually works. There is a + // version of iconv() on Linux that is broken. We can't ignore it, + // because it's wide-spread. The symptoms are that after outputting + // the initial shift state the "to" pointer is NULL and conversion + // stops for no apparent reason after about 8160 characters. p = (char *)tobuf; tolen = ICONV_TESTLEN; (void)iconv(fd, NULL, NULL, &p, &tolen); @@ -2350,13 +2296,11 @@ void *my_iconv_open(char_u *to, char_u *from) return (void *)fd; } -/* - * Convert the string "str[slen]" with iconv(). - * If "unconvlenp" is not NULL handle the string ending in an incomplete - * sequence and set "*unconvlenp" to the length of it. - * Returns the converted string in allocated memory. NULL for an error. - * If resultlenp is not NULL, sets it to the result length in bytes. - */ +// Convert the string "str[slen]" with iconv(). +// If "unconvlenp" is not NULL handle the string ending in an incomplete +// sequence and set "*unconvlenp" to the length of it. +// Returns the converted string in allocated memory. NULL for an error. +// If resultlenp is not NULL, sets it to the result length in bytes. static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen, size_t *unconvlenp, size_t *resultlenp) { @@ -2529,11 +2473,9 @@ char *string_convert(const vimconv_T *const vcp, char *ptr, size_t *lenp) return (char *)string_convert_ext(vcp, (char_u *)ptr, lenp, NULL); } -/* - * Like string_convert(), but when "unconvlenp" is not NULL and there are is - * an incomplete sequence at the end it is not converted and "*unconvlenp" is - * set to the number of remaining bytes. - */ +// Like string_convert(), but when "unconvlenp" is not NULL and there are is +// an incomplete sequence at the end it is not converted and "*unconvlenp" is +// set to the number of remaining bytes. char_u *string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp, size_t *unconvlenp) { diff --git a/src/nvim/mbyte.h b/src/nvim/mbyte.h index 2a9afcbd03..b499f33cc6 100644 --- a/src/nvim/mbyte.h +++ b/src/nvim/mbyte.h @@ -11,12 +11,10 @@ #include "nvim/os/os_defs.h" // For indirect #include "nvim/types.h" // for char_u -/* - * Return byte length of character that starts with byte "b". - * Returns 1 for a single-byte character. - * MB_BYTE2LEN_CHECK() can be used to count a special key as one byte. - * Don't call MB_BYTE2LEN(b) with b < 0 or b > 255! - */ +// Return byte length of character that starts with byte "b". +// Returns 1 for a single-byte character. +// MB_BYTE2LEN_CHECK() can be used to count a special key as one byte. +// Don't call MB_BYTE2LEN(b) with b < 0 or b > 255! #define MB_BYTE2LEN(b) utf8len_tab[b] #define MB_BYTE2LEN_CHECK(b) (((b) < 0 || (b) > 255) ? 1 : utf8len_tab[b]) diff --git a/src/nvim/memline.c b/src/nvim/memline.c index cd143bd52c..35650755b4 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -5,36 +5,34 @@ // #define CHECK(c, s) do { if (c) emsg(s); } while (0) #define CHECK(c, s) do {} while (0) -/* - * memline.c: Contains the functions for appending, deleting and changing the - * text lines. The memfile functions are used to store the information in - * blocks of memory, backed up by a file. The structure of the information is - * a tree. The root of the tree is a pointer block. The leaves of the tree - * are data blocks. In between may be several layers of pointer blocks, - * forming branches. - * - * Three types of blocks are used: - * - Block nr 0 contains information for recovery - * - Pointer blocks contain list of pointers to other blocks. - * - Data blocks contain the actual text. - * - * Block nr 0 contains the block0 structure (see below). - * - * Block nr 1 is the first pointer block. It is the root of the tree. - * Other pointer blocks are branches. - * - * If a line is too big to fit in a single page, the block containing that - * line is made big enough to hold the line. It may span several pages. - * Otherwise all blocks are one page. - * - * A data block that was filled when starting to edit a file and was not - * changed since then, can have a negative block number. This means that it - * has not yet been assigned a place in the file. When recovering, the lines - * in this data block can be read from the original file. When the block is - * changed (lines appended/deleted/changed) or when it is flushed it gets a - * positive number. Use mf_trans_del() to get the new number, before calling - * mf_get(). - */ +// memline.c: Contains the functions for appending, deleting and changing the +// text lines. The memfile functions are used to store the information in +// blocks of memory, backed up by a file. The structure of the information is +// a tree. The root of the tree is a pointer block. The leaves of the tree +// are data blocks. In between may be several layers of pointer blocks, +// forming branches. +// +// Three types of blocks are used: +// - Block nr 0 contains information for recovery +// - Pointer blocks contain list of pointers to other blocks. +// - Data blocks contain the actual text. +// +// Block nr 0 contains the block0 structure (see below). +// +// Block nr 1 is the first pointer block. It is the root of the tree. +// Other pointer blocks are branches. +// +// If a line is too big to fit in a single page, the block containing that +// line is made big enough to hold the line. It may span several pages. +// Otherwise all blocks are one page. +// +// A data block that was filled when starting to edit a file and was not +// changed since then, can have a negative block number. This means that it +// has not yet been assigned a place in the file. When recovering, the lines +// in this data block can be read from the original file. When the block is +// changed (lines appended/deleted/changed) or when it is flushed it gets a +// positive number. Use mf_trans_del() to get the new number, before calling +// mf_get(). #include #include @@ -90,9 +88,7 @@ typedef struct pointer_entry PTR_EN; // block/line-count pair #define BLOCK0_ID0 'b' // block 0 id 0 #define BLOCK0_ID1 '0' // block 0 id 1 -/* - * pointer to a block, used in a pointer block - */ +// pointer to a block, used in a pointer block struct pointer_entry { blocknr_T pe_bnum; // block number linenr_T pe_line_count; // number of lines in this branch @@ -100,9 +96,7 @@ struct pointer_entry { int pe_page_count; // number of pages in block pe_bnum }; -/* - * A pointer block contains a list of branches in the tree. - */ +// A pointer block contains a list of branches in the tree. struct pointer_block { uint16_t pb_id; // ID for pointer block: PTR_ID uint16_t pb_count; // number of pointers in this block @@ -111,13 +105,11 @@ struct pointer_block { // followed by empty space until end of page }; -/* - * A data block is a leaf in the tree. - * - * The text of the lines is at the end of the block. The text of the first line - * in the block is put at the end, the text of the second line in front of it, - * etc. Thus the order of the lines is the opposite of the line number. - */ +// A data block is a leaf in the tree. +// +// The text of the lines is at the end of the block. The text of the first line +// in the block is put at the end, the text of the second line in front of it, +// etc. Thus the order of the lines is the opposite of the line number. struct data_block { uint16_t db_id; // ID for data block: DATA_ID unsigned db_free; // free space available @@ -130,14 +122,12 @@ struct data_block { // end of page }; -/* - * The low bits of db_index hold the actual index. The topmost bit is - * used for the global command to be able to mark a line. - * This method is not clean, but otherwise there would be at least one extra - * byte used for each line. - * The mark has to be in this place to keep it with the correct line when other - * lines are inserted or deleted. - */ +// The low bits of db_index hold the actual index. The topmost bit is +// used for the global command to be able to mark a line. +// This method is not clean, but otherwise there would be at least one extra +// byte used for each line. +// The mark has to be in this place to keep it with the correct line when other +// lines are inserted or deleted. #define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1)) #define DB_INDEX_MASK (~DB_MARKED) @@ -149,28 +139,24 @@ struct data_block { #define B0_FNAME_SIZE_CRYPT 890 // 10 bytes used for other things #define B0_UNAME_SIZE 40 #define B0_HNAME_SIZE 40 -/* - * Restrict the numbers to 32 bits, otherwise most compilers will complain. - * This won't detect a 64 bit machine that only swaps a byte in the top 32 - * bits, but that is crazy anyway. - */ +// Restrict the numbers to 32 bits, otherwise most compilers will complain. +// This won't detect a 64 bit machine that only swaps a byte in the top 32 +// bits, but that is crazy anyway. #define B0_MAGIC_LONG 0x30313233L #define B0_MAGIC_INT 0x20212223L #define B0_MAGIC_SHORT 0x10111213L #define B0_MAGIC_CHAR 0x55 -/* - * Block zero holds all info about the swap file. - * - * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing - * swap files unusable! - * - * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!! - * - * This block is built up of single bytes, to make it portable across - * different machines. b0_magic_* is used to check the byte order and size of - * variables, because the rest of the swap file is not portable. - */ +// Block zero holds all info about the swap file. +// +// NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing +// swap files unusable! +// +// If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!! +// +// This block is built up of single bytes, to make it portable across +// different machines. b0_magic_* is used to check the byte order and size of +// variables, because the rest of the swap file is not portable. struct block0 { char_u b0_id[2]; ///< ID for block 0: BLOCK0_ID0 and BLOCK0_ID1. char_u b0_version[10]; // Vim version string @@ -187,18 +173,14 @@ struct block0 { char_u b0_magic_char; // check for last char }; -/* - * Note: b0_dirty and b0_flags are put at the end of the file name. For very - * long file names in older versions of Vim they are invalid. - * The 'fileencoding' comes before b0_flags, with a NUL in front. But only - * when there is room, for very long file names it's omitted. - */ +// Note: b0_dirty and b0_flags are put at the end of the file name. For very +// long file names in older versions of Vim they are invalid. +// The 'fileencoding' comes before b0_flags, with a NUL in front. But only +// when there is room, for very long file names it's omitted. #define B0_DIRTY 0x55 #define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1] -/* - * The b0_flags field is new in Vim 7.0. - */ +// The b0_flags field is new in Vim 7.0. #define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2] // The lowest two bits contain the fileformat. Zero means it's not set @@ -216,17 +198,13 @@ struct block0 { #define STACK_INCR 5 // nr of entries added to ml_stack at a time -/* - * The line number where the first mark may be is remembered. - * If it is 0 there are no marks at all. - * (always used for the current buffer only, no buffer change possible while - * executing a global command). - */ +// The line number where the first mark may be is remembered. +// If it is 0 there are no marks at all. +// (always used for the current buffer only, no buffer change possible while +// executing a global command). static linenr_T lowest_marked = 0; -/* - * arguments for ml_find_line() - */ +// arguments for ml_find_line() #define ML_DELETE 0x11 // delete line #define ML_INSERT 0x12 // insert line #define ML_FIND 0x13 // just find the line @@ -253,9 +231,7 @@ int ml_open(buf_T *buf) PTR_BL *pp; DATA_BL *dp; - /* - * init fields in memline struct - */ + // init fields in memline struct buf->b_ml.ml_stack_size = 0; // no stack yet buf->b_ml.ml_stack = NULL; // no stack yet buf->b_ml.ml_stack_top = 0; // nothing in the stack @@ -269,9 +245,7 @@ int ml_open(buf_T *buf) buf->b_p_swf = false; } - /* - * When 'updatecount' is non-zero swap file may be opened later. - */ + // When 'updatecount' is non-zero swap file may be opened later. if (!buf->terminal && p_uc && buf->b_p_swf) { buf->b_may_swap = true; } else { @@ -289,9 +263,7 @@ int ml_open(buf_T *buf) buf->b_ml.ml_line_count = 1; curwin->w_nrwidth_line_count = 0; - /* - * fill block0 struct and write page 0 - */ + // fill block0 struct and write page 0 hp = mf_new(mfp, false, 1); if (hp->bh_bnum != 0) { iemsg(_("E298: Didn't get block nr 0?")); @@ -319,21 +291,17 @@ int ml_open(buf_T *buf) long_to_char(os_get_pid(), b0p->b0_pid); } - /* - * Always sync block number 0 to disk, so we can check the file name in - * the swap file in findswapname(). Don't do this for a help files or - * a spell buffer though. - * Only works when there's a swapfile, otherwise it's done when the file - * is created. - */ + // Always sync block number 0 to disk, so we can check the file name in + // the swap file in findswapname(). Don't do this for a help files or + // a spell buffer though. + // Only works when there's a swapfile, otherwise it's done when the file + // is created. mf_put(mfp, hp, true, false); if (!buf->b_help && !B_SPELL(buf)) { (void)mf_sync(mfp, 0); } - /* - * Fill in root pointer block and write page 1. - */ + // Fill in root pointer block and write page 1. if ((hp = ml_new_ptr(mfp)) == NULL) { goto error; } @@ -349,9 +317,7 @@ int ml_open(buf_T *buf) pp->pb_pointer[0].pe_line_count = 1; // line count after insertion mf_put(mfp, hp, true, false); - /* - * Allocate first data block and create an empty line 1. - */ + // Allocate first data block and create an empty line 1. hp = ml_new_data(mfp, false, 1); if (hp->bh_bnum != 2) { iemsg(_("E298: Didn't get block nr 2?")); @@ -388,10 +354,8 @@ void ml_setname(buf_T *buf) mfp = buf->b_ml.ml_mfp; if (mfp->mf_fd < 0) { // there is no swap file yet - /* - * When 'updatecount' is 0 and 'noswapfile' there is no swap file. - * For help files we will make a swap file now. - */ + // When 'updatecount' is 0 and 'noswapfile' there is no swap file. + // For help files we will make a swap file now. if (p_uc != 0 && (cmdmod.cmod_flags & CMOD_NOSWAPFILE) == 0) { ml_open_file(buf); // create a swap file } @@ -653,13 +617,11 @@ static void set_b0_fname(ZERO_BL *b0p, buf_T *buf) } else { char uname[B0_UNAME_SIZE]; - /* - * For a file under the home directory of the current user, we try to - * replace the home directory path with "~user". This helps when - * editing the same file on different machines over a network. - * First replace home dir path with "~/" with home_replace(). - * Then insert the user name to get "~user/". - */ + // For a file under the home directory of the current user, we try to + // replace the home directory path with "~user". This helps when + // editing the same file on different machines over a network. + // First replace home dir path with "~/" with home_replace(). + // Then insert the user name to get "~user/". home_replace(NULL, buf->b_ffname, (char *)b0p->b0_fname, B0_FNAME_SIZE_CRYPT, true); if (b0p->b0_fname[0] == '~') { @@ -813,15 +775,11 @@ void ml_recover(bool checkext) getout(1); } - /* - * Allocate a buffer structure for the swap file that is used for recovery. - * Only the memline in it is really used. - */ + // Allocate a buffer structure for the swap file that is used for recovery. + // Only the memline in it is really used. buf = xmalloc(sizeof(buf_T)); - /* - * init fields in memline struct - */ + // init fields in memline struct buf->b_ml.ml_stack_size = 0; // no stack yet buf->b_ml.ml_stack = NULL; // no stack yet buf->b_ml.ml_stack_top = 0; // nothing in the stack @@ -830,9 +788,7 @@ void ml_recover(bool checkext) buf->b_ml.ml_locked = NULL; // no locked block buf->b_ml.ml_flags = 0; - /* - * open the memfile from the old swap file - */ + // open the memfile from the old swap file p = xstrdup(fname_used); // save "fname_used" for the message: // mf_open() will consume "fname_used"! mfp = mf_open(fname_used, O_RDONLY); @@ -843,17 +799,13 @@ void ml_recover(bool checkext) } buf->b_ml.ml_mfp = mfp; - /* - * The page size set in mf_open() might be different from the page size - * used in the swap file, we must get it from block 0. But to read block - * 0 we need a page size. Use the minimal size for block 0 here, it will - * be set to the real value below. - */ + // The page size set in mf_open() might be different from the page size + // used in the swap file, we must get it from block 0. But to read block + // 0 we need a page size. Use the minimal size for block 0 here, it will + // be set to the real value below. mfp->mf_page_size = MIN_SWAP_PAGE_SIZE; - /* - * try to read block 0 - */ + // try to read block 0 if ((hp = mf_get(mfp, 0, 1)) == NULL) { msg_start(); msg_puts_attr(_("Unable to read block 0 from "), attr | MSG_HIST); @@ -891,10 +843,8 @@ void ml_recover(bool checkext) goto theend; } - /* - * If we guessed the wrong page size, we have to recalculate the - * highest block number in the file. - */ + // If we guessed the wrong page size, we have to recalculate the + // highest block number in the file. if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size)) { unsigned previous_page_size = mfp->mf_page_size; @@ -941,9 +891,7 @@ void ml_recover(bool checkext) smsg(_("Original file \"%s\""), NameBuff); msg_putchar('\n'); - /* - * check date of swap file and original file - */ + // check date of swap file and original file FileInfo org_file_info; FileInfo swp_file_info; mtime = char_to_long(b0p->b0_mtime); @@ -969,18 +917,14 @@ void ml_recover(bool checkext) mf_put(mfp, hp, false, false); // release block 0 hp = NULL; - /* - * Now that we are sure that the file is going to be recovered, clear the - * contents of the current buffer. - */ + // Now that we are sure that the file is going to be recovered, clear the + // contents of the current buffer. while (!(curbuf->b_ml.ml_flags & ML_EMPTY)) { ml_delete((linenr_T)1, false); } - /* - * Try reading the original file to obtain the values of 'fileformat', - * 'fileencoding', etc. Ignore errors. The text itself is not used. - */ + // Try reading the original file to obtain the values of 'fileformat', + // 'fileencoding', etc. Ignore errors. The text itself is not used. if (curbuf->b_ffname != NULL) { orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW, false); @@ -1017,9 +961,7 @@ void ml_recover(bool checkext) if (hp != NULL) { mf_put(mfp, hp, false, false); // release previous block } - /* - * get block - */ + // get block if ((hp = mf_get(mfp, bnum, page_count)) == NULL) { if (bnum == 1) { semsg(_("E309: Unable to read block 1 from %s"), mfp->mf_fname); @@ -1049,11 +991,9 @@ void ml_recover(bool checkext) error++; } else if (idx < (int)pp->pb_count) { // go a block deeper if (pp->pb_pointer[idx].pe_bnum < 0) { - /* - * Data block with negative block number. - * Try to read lines from the original file. - * This is slow, but it works. - */ + // Data block with negative block number. + // Try to read lines from the original file. + // This is slow, but it works. if (!cannot_open) { line_count = pp->pb_pointer[idx].pe_line_count; if (readfile(curbuf->b_ffname, NULL, lnum, @@ -1073,9 +1013,7 @@ void ml_recover(bool checkext) continue; } - /* - * going one block deeper in the tree - */ + // going one block deeper in the tree top = ml_add_stack(buf); // new entry in stack ip = &(buf->b_ml.ml_stack[top]); ip->ip_bnum = bnum; @@ -1116,10 +1054,8 @@ void ml_recover(bool checkext) // make sure there is a NUL at the end of the block *((char_u *)dp + dp->db_txt_end - 1) = NUL; - /* - * check number of lines in block - * if wrong, use count in data block - */ + // check number of lines in block + // if wrong, use count in data block if (line_count != dp->db_line_count) { ml_append(lnum++, _("??? from here until ???END lines" @@ -1151,22 +1087,18 @@ void ml_recover(bool checkext) break; } - /* - * go one block up in the tree - */ + // go one block up in the tree ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]); bnum = ip->ip_bnum; idx = ip->ip_index + 1; // go to next index page_count = 1; } - /* - * Compare the buffer contents with the original file. When they differ - * set the 'modified' flag. - * Lines 1 - lnum are the new contents. - * Lines lnum + 1 to ml_line_count are the original contents. - * Line ml_line_count + 1 in the dummy empty line. - */ + // Compare the buffer contents with the original file. When they differ + // set the 'modified' flag. + // Lines 1 - lnum are the new contents. + // Lines lnum + 1 to ml_line_count are the original contents. + // Line ml_line_count + 1 in the dummy empty line. if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1) { // Recovering an empty file results in two lines and the first line is // empty. Don't set the modified flag then. @@ -1188,10 +1120,8 @@ void ml_recover(bool checkext) } } - /* - * Delete the lines from the original file and the dummy line from the - * empty buffer. These will now be after the last line in the buffer. - */ + // Delete the lines from the original file and the dummy line from the + // empty buffer. These will now be after the last line in the buffer. while (curbuf->b_ml.ml_line_count > lnum && !(curbuf->b_ml.ml_flags & ML_EMPTY)) { ml_delete(curbuf->b_ml.ml_line_count, false); @@ -1343,11 +1273,9 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) num_files = 0; } - /* - * When no swap file found, wildcard expansion might have failed (e.g. - * not able to execute the shell). - * Try finding a swap file by simply adding ".swp" to the file name. - */ + // When no swap file found, wildcard expansion might have failed (e.g. + // not able to execute the shell). + // 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); if (swapname != NULL) { @@ -1361,9 +1289,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out) } } - /* - * remove swapfile name of the current buffer, it must be ignored - */ + // remove swapfile name of the current buffer, it must be ignored if (curbuf->b_ml.ml_mfp != NULL && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL) { for (int i = 0; i < num_files; i++) { @@ -1522,9 +1448,7 @@ static time_t swapfile_info(char_u *fname) msg_puts(os_ctime_r(&x, ctime_buf, sizeof(ctime_buf))); } - /* - * print the original file name - */ + // print the original file name fd = os_open((char *)fname, O_RDONLY, 0); if (fd >= 0) { if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) { @@ -1681,10 +1605,8 @@ void ml_sync_all(int check_file, int check_char, bool do_fsync) (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp) && buf->b_ffname != NULL) { - /* - * If the original file does not exist anymore or has been changed - * call ml_preserve() to get rid of all negative numbered blocks. - */ + // If the original file does not exist anymore or has been changed + // call ml_preserve() to get rid of all negative numbered blocks. FileInfo file_info; if (!os_fileinfo(buf->b_ffname, &file_info) || file_info.stat.st_mtim.tv_sec != buf->b_mtime_read @@ -1739,18 +1661,16 @@ void ml_preserve(buf_T *buf, int message, bool do_fsync) // stack is invalid after mf_sync(.., MFS_ALL) buf->b_ml.ml_stack_top = 0; - /* - * Some of the data blocks may have been changed from negative to - * positive block number. In that case the pointer blocks need to be - * updated. - * - * We don't know in which pointer block the references are, so we visit - * all data blocks until there are no more translations to be done (or - * we hit the end of the file, which can only happen in case a write fails, - * e.g. when file system if full). - * ml_find_line() does the work by translating the negative block numbers - * when getting the first line of each data block. - */ + // Some of the data blocks may have been changed from negative to + // positive block number. In that case the pointer blocks need to be + // updated. + // + // We don't know in which pointer block the references are, so we visit + // all data blocks until there are no more translations to be done (or + // we hit the end of the file, which can only happen in case a write fails, + // e.g. when file system if full). + // ml_find_line() does the work by translating the negative block numbers + // when getting the first line of each data block. if (mf_need_trans(mfp) && !got_int) { lnum = 1; while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count) { @@ -1781,13 +1701,11 @@ theend: } } -/* - * NOTE: The pointer returned by the ml_get_*() functions only remains valid - * until the next call! - * line1 = ml_get(1); - * line2 = ml_get(2); // line1 is now invalid! - * Make a copy of the line if necessary. - */ +// NOTE: The pointer returned by the ml_get_*() functions only remains valid +// until the next call! +// line1 = ml_get(1); +// line2 = ml_get(2); // line1 is now invalid! +// Make a copy of the line if necessary. /// @return a pointer to a (read-only copy of a) line. /// @@ -1851,20 +1769,16 @@ errorret: return (char_u *)""; } - /* - * See if it is the same line as requested last time. - * Otherwise may need to flush last used line. - * Don't use the last used line when 'swapfile' is reset, need to load all - * blocks. - */ + // See if it is the same line as requested last time. + // Otherwise may need to flush last used line. + // Don't use the last used line when 'swapfile' is reset, need to load all + // blocks. if (buf->b_ml.ml_line_lnum != lnum) { ml_flush_line(buf); - /* - * Find the data block containing the line. - * This also fills the stack with the blocks from the root to the data - * block and releases any locked block. - */ + // Find the data block containing the line. + // This also fills the stack with the blocks from the root to the data + // block and releases any locked block. if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL) { if (recursive == 0) { // Avoid giving this message for a recursive call, may happen @@ -1986,11 +1900,9 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b memfile_T *mfp = buf->b_ml.ml_mfp; int page_size = (int)mfp->mf_page_size; - /* - * find the data block containing the previous line - * This also fills the stack with the blocks from the root to the data block - * This also releases any locked block. - */ + // find the data block containing the previous line + // This also fills the stack with the blocks from the root to the data block + // This also releases any locked block. if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum, ML_INSERT)) == NULL) { return FAIL; @@ -2008,22 +1920,18 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b dp = hp->bh_data; - /* - * If - * - there is not enough room in the current block - * - appending to the last line in the block - * - not appending to the last line in the file - * insert in front of the next block. - */ + // If + // - there is not enough room in the current block + // - appending to the last line in the block + // - not appending to the last line in the file + // insert in front of the next block. if ((int)dp->db_free < space_needed && db_idx == line_count - 1 && lnum < buf->b_ml.ml_line_count) { - /* - * Now that the line is not going to be inserted in the block that we - * expected, the line count has to be adjusted in the pointer blocks - * by using ml_locked_lineadd. - */ - --(buf->b_ml.ml_locked_lineadd); - --(buf->b_ml.ml_locked_high); + // Now that the line is not going to be inserted in the block that we + // expected, the line count has to be adjusted in the pointer blocks + // by using ml_locked_lineadd. + (buf->b_ml.ml_locked_lineadd)--; + (buf->b_ml.ml_locked_high)--; if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL) { return FAIL; } @@ -2039,22 +1947,16 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b buf->b_ml.ml_line_count++; if ((int)dp->db_free >= space_needed) { // enough room in data block - /* - * Insert new line in existing data block, or in data block allocated above. - */ + // Insert new line in existing data block, or in data block allocated above. dp->db_txt_start -= (unsigned)len; dp->db_free -= (unsigned)space_needed; dp->db_line_count++; - /* - * move the text of the lines that follow to the front - * adjust the indexes of the lines that follow - */ + // move the text of the lines that follow to the front + // adjust the indexes of the lines that follow if (line_count > db_idx + 1) { // if there are following lines - /* - * Offset is the start of the previous line. - * This will become the character just after the new line. - */ + // Offset is the start of the previous line. + // This will become the character just after the new line. if (db_idx < 0) { offset = (int)dp->db_txt_end; } else { @@ -2071,31 +1973,25 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b dp->db_index[db_idx + 1] = dp->db_txt_start; } - /* - * copy the text into the block - */ + // copy the text into the block memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len); if (mark) { dp->db_index[db_idx + 1] |= DB_MARKED; } - /* - * Mark the block dirty. - */ + // Mark the block dirty. buf->b_ml.ml_flags |= ML_LOCKED_DIRTY; if (!newfile) { buf->b_ml.ml_flags |= ML_LOCKED_POS; } } else { // not enough space in data block - /* - * If there is not enough room we have to create a new data block and copy some - * lines into it. - * Then we have to insert an entry in the pointer block. - * If this pointer block also is full, we go up another block, and so on, up - * to the root if necessary. - * The line counts in the pointer blocks have already been adjusted by - * ml_find_line(). - */ + // If there is not enough room we have to create a new data block and copy some + // lines into it. + // Then we have to insert an entry in the pointer block. + // If this pointer block also is full, we go up another block, and so on, up + // to the root if necessary. + // The line counts in the pointer blocks have already been adjusted by + // ml_find_line(). int line_count_left, line_count_right; int page_count_left, page_count_right; bhdr_T *hp_left; @@ -2113,14 +2009,12 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b int pb_idx; PTR_BL *pp_new; - /* - * We are going to allocate a new data block. Depending on the - * situation it will be put to the left or right of the existing - * block. If possible we put the new line in the left block and move - * the lines after it to the right block. Otherwise the new line is - * also put in the right block. This method is more efficient when - * inserting a lot of lines at one place. - */ + // We are going to allocate a new data block. Depending on the + // situation it will be put to the left or right of the existing + // block. If possible we put the new line in the left block and move + // the lines after it to the right block. Otherwise the new line is + // also put in the right block. This method is more efficient when + // inserting a lot of lines at one place. if (db_idx < 0) { // left block is new, right block is existing lines_moved = 0; in_left = true; @@ -2164,9 +2058,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b page_count_left = (int)hp_left->bh_page_count; page_count_right = (int)hp_right->bh_page_count; - /* - * May move the new line into the right/new block. - */ + // May move the new line into the right/new block. if (!in_left) { dp_right->db_txt_start -= (unsigned)len; dp_right->db_free -= (unsigned)len + (unsigned)INDEX_SIZE; @@ -2179,12 +2071,8 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b line, (size_t)len); line_count_right++; } - /* - * may move lines from the left/old block to the right/new one. - */ + // may move lines from the left/old block to the right/new one. if (lines_moved) { - /* - */ dp_right->db_txt_start -= (unsigned)data_moved; dp_right->db_free -= (unsigned)total_moved; memmove((char *)dp_right + dp_right->db_txt_start, @@ -2194,9 +2082,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b dp_left->db_txt_start += (unsigned)data_moved; dp_left->db_free += (unsigned)total_moved; - /* - * update indexes in the new block - */ + // update indexes in the new block for (to = line_count_right, from = db_idx + 1; from < line_count_left; from++, to++) { dp_right->db_index[to] = dp->db_index[from] + (unsigned)offset; @@ -2205,9 +2091,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b line_count_left -= lines_moved; } - /* - * May move the new line into the left (old or new) block. - */ + // May move the new line into the left (old or new) block. if (in_left) { dp_left->db_txt_start -= (unsigned)len; dp_left->db_free -= (unsigned)len + (unsigned)INDEX_SIZE; @@ -2234,12 +2118,10 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b dp_left->db_line_count = line_count_left; dp_right->db_line_count = line_count_right; - /* - * release the two data blocks - * The new one (hp_new) already has a correct blocknumber. - * The old one (hp, in ml_locked) gets a positive blocknumber if - * we changed it and we are not editing a new file. - */ + // release the two data blocks + // The new one (hp_new) already has a correct blocknumber. + // The old one (hp, in ml_locked) gets a positive blocknumber if + // we changed it and we are not editing a new file. if (lines_moved || in_left) { buf->b_ml.ml_flags |= ML_LOCKED_DIRTY; } @@ -2248,18 +2130,14 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b } mf_put(mfp, hp_new, true, false); - /* - * flush the old data block - * set ml_locked_lineadd to 0, because the updating of the - * pointer blocks is done below - */ + // flush the old data block + // set ml_locked_lineadd to 0, because the updating of the + // pointer blocks is done below lineadd = buf->b_ml.ml_locked_lineadd; buf->b_ml.ml_locked_lineadd = 0; (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); // flush data block - /* - * update pointer blocks for the new data block - */ + // update pointer blocks for the new data block for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx) { ip = &(buf->b_ml.ml_stack[stack_idx]); @@ -2273,10 +2151,8 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b mf_put(mfp, hp, false, false); return FAIL; } - /* - * TODO: If the pointer block is full and we are adding at the end - * try to insert in front of the next block - */ + // TODO(vim): If the pointer block is full and we are adding at the end + // try to insert in front of the next block // block not full, add one entry if (pp->pb_count < pp->pb_count_max) { if (pb_idx + 1 < (int)pp->pb_count) { @@ -2312,9 +2188,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b ++(buf->b_ml.ml_stack_top); } - /* - * We are finished, break the loop here. - */ + // We are finished, break the loop here. break; } // pointer block full @@ -2400,9 +2274,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b mf_put(mfp, hp_new, true, false); } - /* - * Safety check: fallen out of for loop? - */ + // Safety check: fallen out of for loop? if (stack_idx < 0) { iemsg(_("E318: Updated too many blocks?")); buf->b_ml.ml_stack_top = 0; // invalidate stack @@ -2526,9 +2398,7 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message) lowest_marked--; } - /* - * If the file becomes empty the last line is replaced by an empty line. - */ + // If the file becomes empty the last line is replaced by an empty line. if (buf->b_ml.ml_line_count == 1) { // file becomes empty if (message) { set_keep_msg(_(no_lines_msg), 0); @@ -2540,11 +2410,9 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message) return i; } - /* - * find the data block containing the line - * This also fills the stack with the blocks from the root to the data block - * This also releases any locked block. - */ + // find the data block containing the line + // This also fills the stack with the blocks from the root to the data block + // This also releases any locked block. mfp = buf->b_ml.ml_mfp; if (mfp == NULL) { return FAIL; @@ -2573,14 +2441,12 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message) assert(line_size >= 1); ml_add_deleted_len_buf(buf, (char_u *)dp + line_start, line_size - 1); - /* - * special case: If there is only one line in the data block it becomes empty. - * Then we have to remove the entry, pointing to this data block, from the - * pointer block. If this pointer block also becomes empty, we go up another - * block, and so on, up to the root if necessary. - * The line counts in the pointer blocks have already been adjusted by - * ml_find_line(). - */ + // special case: If there is only one line in the data block it becomes empty. + // Then we have to remove the entry, pointing to this data block, from the + // pointer block. If this pointer block also becomes empty, we go up another + // block, and so on, up to the root if necessary. + // The line counts in the pointer blocks have already been adjusted by + // ml_find_line(). if (count == 1) { mf_free(mfp, hp); // free the data block buf->b_ml.ml_locked = NULL; @@ -2638,9 +2504,7 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message) dp->db_txt_start += (unsigned)line_size; dp->db_line_count--; - /* - * mark the block dirty and make sure it is in the file (for recovery) - */ + // mark the block dirty and make sure it is in the file (for recovery) buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS); } @@ -2662,11 +2526,9 @@ void ml_setmarked(linenr_T lnum) lowest_marked = lnum; } - /* - * find the data block containing the line - * This also fills the stack with the blocks from the root to the data block - * This also releases any locked block. - */ + // find the data block containing the line + // This also fills the stack with the blocks from the root to the data block + // This also releases any locked block. if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) { return; // give error message? } @@ -2687,16 +2549,12 @@ linenr_T ml_firstmarked(void) return (linenr_T)0; } - /* - * The search starts with lowest_marked line. This is the last line where - * a mark was found, adjusted by inserting/deleting lines. - */ + // The search starts with lowest_marked line. This is the last line where + // a mark was found, adjusted by inserting/deleting lines. for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count;) { - /* - * Find the data block containing the line. - * This also fills the stack with the blocks from the root to the data - * block This also releases any locked block. - */ + // Find the data block containing the line. + // This also fills the stack with the blocks from the root to the data + // block This also releases any locked block. if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) { return (linenr_T)0; // give error message? } @@ -2728,15 +2586,11 @@ void ml_clearmarked(void) return; } - /* - * The search starts with line lowest_marked. - */ + // The search starts with line lowest_marked. for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count;) { - /* - * Find the data block containing the line. - * This also fills the stack with the blocks from the root to the data - * block and releases any locked block. - */ + // Find the data block containing the line. + // This also fills the stack with the blocks from the root to the data + // block and releases any locked block. if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) { return; // give error message? } @@ -2813,9 +2667,7 @@ static void ml_flush_line(buf_T *buf) new_len = (colnr_T)STRLEN(new_line) + 1; extra = new_len - old_len; // negative if lines gets smaller - /* - * if new line fits in data block, replace directly - */ + // if new line fits in data block, replace directly if ((int)dp->db_free >= extra) { // if the length changes and there are following lines count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1; @@ -2918,13 +2770,11 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) mfp = buf->b_ml.ml_mfp; - /* - * If there is a locked block check if the wanted line is in it. - * If not, flush and release the locked block. - * Don't do this for ML_INSERT_SAME, because the stack need to be updated. - * Don't do this for ML_FLUSH, because we want to flush the locked block. - * Don't do this when 'swapfile' is reset, we want to load all the blocks. - */ + // If there is a locked block check if the wanted line is in it. + // If not, flush and release the locked block. + // Don't do this for ML_INSERT_SAME, because the stack need to be updated. + // Don't do this for ML_FLUSH, because we want to flush the locked block. + // Don't do this when 'swapfile' is reset, we want to load all the blocks. if (buf->b_ml.ml_locked) { if (ML_SIMPLE(action) && buf->b_ml.ml_locked_low <= lnum @@ -2944,10 +2794,8 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) buf->b_ml.ml_flags & ML_LOCKED_POS); buf->b_ml.ml_locked = NULL; - /* - * If lines have been added or deleted in the locked block, need to - * update the line count in pointer blocks. - */ + // If lines have been added or deleted in the locked block, need to + // update the line count in pointer blocks. if (buf->b_ml.ml_locked_lineadd != 0) { ml_lineadd(buf, buf->b_ml.ml_locked_lineadd); } @@ -2979,17 +2827,13 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) } else { // ML_DELETE or ML_INSERT buf->b_ml.ml_stack_top = 0; // start at the root } - /* - * search downwards in the tree until a data block is found - */ + // search downwards in the tree until a data block is found for (;;) { if ((hp = mf_get(mfp, bnum, (unsigned)page_count)) == NULL) { goto error_noblock; } - /* - * update high for insert/delete - */ + // update high for insert/delete if (action == ML_INSERT) { high++; } else if (action == ML_DELETE) { @@ -3030,9 +2874,7 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) high = low - 1; low -= t; - /* - * a negative block number may have been changed - */ + // a negative block number may have been changed if (bnum < 0) { bnum2 = mf_trans_del(mfp, bnum); if (bnum != bnum2) { @@ -3067,11 +2909,9 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action) error_block: mf_put(mfp, hp, false, false); error_noblock: - /* - * If action is ML_DELETE or ML_INSERT we have to correct the tree for - * the incremented/decremented line counts, because there won't be a line - * inserted/deleted after all. - */ + // If action is ML_DELETE or ML_INSERT we have to correct the tree for + // the incremented/decremented line counts, because there won't be a line + // inserted/deleted after all. if (action == ML_DELETE) { ml_lineadd(buf, 1); } else if (action == ML_INSERT) { @@ -3196,11 +3036,9 @@ int resolve_symlink(const char *fname, char *buf) } } - /* - * Try to resolve the full name of the file so that the swapfile name will - * be consistent even when opening a relative symlink from different - * working directories. - */ + // Try to resolve the full name of the file so that the swapfile name will + // be consistent even when opening a relative symlink from different + // working directories. return vim_FullName(tmp, buf, MAXPATHL, true); } #endif @@ -3407,17 +3245,13 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ char *dir_name; char *buf_fname = buf->b_fname; - /* - * Isolate a directory name from *dirp and put it in dir_name. - * First allocate some memory to put the directory name in. - */ + // Isolate a directory name from *dirp and put it in dir_name. + // First allocate some memory to put the directory name in. const size_t dir_len = strlen(*dirp) + 1; dir_name = xmalloc(dir_len); (void)copy_option_part(dirp, dir_name, dir_len, ","); - /* - * we try different names until we find one that does not exist yet - */ + // we try different names until we find one that does not exist yet fname = (char *)makeswapname((char_u *)buf_fname, (char_u *)buf->b_ffname, buf, (char_u *)dir_name); @@ -3596,12 +3430,10 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_ } } - /* - * Change the ".swp" extension to find another file that can be used. - * First decrement the last char: ".swo", ".swn", etc. - * If that still isn't enough decrement the last but one char: ".svz" - * Can happen when editing many "No Name" buffers. - */ + // Change the ".swp" extension to find another file that can be used. + // First decrement the last char: ".swo", ".swn", etc. + // If that still isn't enough decrement the last but one char: ".svz" + // Can happen when editing many "No Name" buffers. if (fname[n - 1] == 'a') { // ".s?a" if (fname[n - 2] == 'a') { // ".saa": tried enough, give up emsg(_("E326: Too many swap files found")); @@ -3701,11 +3533,9 @@ static bool fnamecmp_ino(char_u *fname_c, char_u *fname_s, long ino_block0) ino_c = os_fileinfo_inode(&file_info); } - /* - * First we try to get the inode from the file name, because the inode in - * the swap file may be outdated. If that fails (e.g. this path is not - * valid on this machine), use the inode from block 0. - */ + // First we try to get the inode from the file name, because the inode in + // the swap file may be outdated. If that fails (e.g. this path is not + // valid on this machine), use the inode from block 0. if (os_fileinfo((char *)fname_s, &file_info)) { ino_s = os_fileinfo_inode(&file_info); } else { @@ -3716,21 +3546,17 @@ static bool fnamecmp_ino(char_u *fname_c, char_u *fname_s, long ino_block0) return ino_c != ino_s; } - /* - * One of the inode numbers is unknown, try a forced vim_FullName() and - * compare the file names. - */ + // One of the inode numbers is unknown, try a forced vim_FullName() and + // compare the file names. retval_c = vim_FullName((char *)fname_c, (char *)buf_c, MAXPATHL, true); retval_s = vim_FullName((char *)fname_s, (char *)buf_s, MAXPATHL, true); if (retval_c == OK && retval_s == OK) { return STRCMP(buf_c, buf_s) != 0; } - /* - * Can't compare inodes or file names, guess that the files are different, - * unless both appear not to exist at all, then compare with the file name - * in the swap file. - */ + // Can't compare inodes or file names, guess that the files are different, + // unless both appear not to exist at all, then compare with the file name + // in the swap file. if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL) { return STRCMP(fname_c, fname_s) != 0; } @@ -3827,9 +3653,7 @@ static void ml_updatechunk(buf_T *buf, linenr_T line, long len, int updtype) } if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1) { - /* - * First line in empty buffer from ml_flush_line() -- reset - */ + // First line in empty buffer from ml_flush_line() -- reset buf->b_ml.ml_usedchunks = 1; buf->b_ml.ml_chunksize[0].mlcs_numlines = 1; buf->b_ml.ml_chunksize[0].mlcs_totalsize = @@ -3837,10 +3661,8 @@ static void ml_updatechunk(buf_T *buf, linenr_T line, long len, int updtype) return; } - /* - * Find chunk that our line belongs to, curline will be at start of the - * chunk. - */ + // Find chunk that our line belongs to, curline will be at start of the + // chunk. if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1 || updtype != ML_CHNK_ADDLINE) { for (curline = 1, curix = 0; @@ -3928,10 +3750,8 @@ static void ml_updatechunk(buf_T *buf, linenr_T line, long len, int updtype) curchnk->mlcs_numlines = 0; curchnk->mlcs_totalsize = 0; } else { - /* - * Line is just prior to last, move count for last - * This is the common case when loading a new file - */ + // Line is just prior to last, move count for last + // This is the common case when loading a new file hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND); if (hp == NULL) { buf->b_ml.ml_usedchunks = -1; @@ -4044,10 +3864,8 @@ long ml_find_line_or_offset(buf_T *buf, linenr_T lnum, long *offp, bool no_ff) if (lnum == 0 && offset <= 0) { return 1; // Not a "find offset" and offset 0 _must_ be in line 1 } - /* - * Find the last chunk before the one containing our line. Last chunk is - * special because it will never qualify - */ + // Find the last chunk before the one containing our line. Last chunk is + // special because it will never qualify curline = 1; curix = 0; size = 0; diff --git a/src/nvim/memory.c b/src/nvim/memory.c index acd2478c81..e5fea027cb 100644 --- a/src/nvim/memory.c +++ b/src/nvim/memory.c @@ -502,10 +502,8 @@ bool striequal(const char *a, const char *b) return (a == NULL && b == NULL) || (a && b && STRICMP(a, b) == 0); } -/* - * Avoid repeating the error message many times (they take 1 second each). - * Did_outofmem_msg is reset when a character is read. - */ +// Avoid repeating the error message many times (they take 1 second each). +// Did_outofmem_msg is reset when a character is read. void do_outofmem_msg(size_t size) { if (!did_outofmem_msg) { @@ -675,13 +673,11 @@ char *arena_memdupz(Arena *arena, const char *buf, size_t size) # include "nvim/tag.h" # include "nvim/window.h" -/* - * Free everything that we allocated. - * Can be used to detect memory leaks, e.g., with ccmalloc. - * NOTE: This is tricky! Things are freed that functions depend on. Don't be - * surprised if Vim crashes... - * Some things can't be freed, esp. things local to a library function. - */ +// Free everything that we allocated. +// Can be used to detect memory leaks, e.g., with ccmalloc. +// NOTE: This is tricky! Things are freed that functions depend on. Don't be +// surprised if Vim crashes... +// Some things can't be freed, esp. things local to a library function. void free_all_mem(void) { buf_T *buf, *nextbuf; diff --git a/src/nvim/menu.c b/src/nvim/menu.c index 84a1defbe0..7a08a4d6f6 100644 --- a/src/nvim/menu.c +++ b/src/nvim/menu.c @@ -1,10 +1,8 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * Code for menus. Used for the GUI and 'wildmenu'. - * GUI/Motif support by Robert Webb - */ +// Code for menus. Used for the GUI and 'wildmenu'. +// GUI/Motif support by Robert Webb #include #include @@ -141,9 +139,7 @@ void ex_menu(exarg_T *eap) } pri_tab[MENUDEPTH] = -1; // mark end of the table - /* - * Check for "disable" or "enable" argument. - */ + // Check for "disable" or "enable" argument. if (STRNCMP(arg, "enable", 6) == 0 && ascii_iswhite(arg[6])) { enable = kTrue; arg = skipwhite(arg + 6); @@ -152,9 +148,7 @@ void ex_menu(exarg_T *eap) arg = skipwhite(arg + 7); } - /* - * If there is no argument, display all menus. - */ + // If there is no argument, display all menus. if (*arg == NUL) { show_menus(arg, modes); return; @@ -168,9 +162,7 @@ void ex_menu(exarg_T *eap) map_to = menu_translate_tab_and_shift(arg); - /* - * If there is only a menu name, display menus with that name. - */ + // If there is only a menu name, display menus with that name. if (*map_to == NUL && !unmenu && enable == kNone) { show_menus(menu_path, modes); goto theend; @@ -200,16 +192,12 @@ void ex_menu(exarg_T *eap) } menu_enable_recurse(*root_menu_ptr, menu_path, modes, enable); } else if (unmenu) { - /* - * Delete menu(s). - */ + // Delete menu(s). if (STRCMP(menu_path, "*") == 0) { // meaning: remove all menus menu_path = ""; } - /* - * For the PopUp menu, remove a menu for each mode separately. - */ + // For the PopUp menu, remove a menu for each mode separately. if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; i++) { if (modes & (1 << i)) { @@ -223,10 +211,8 @@ void ex_menu(exarg_T *eap) // Careful: remove_menu() changes menu_path remove_menu(root_menu_ptr, menu_path, modes, false); } else { - /* - * Add menu(s). - * Replace special key codes. - */ + // Add menu(s). + // Replace special key codes. if (STRICMP(map_to, "") == 0) { // "" means nothing map_to = ""; map_buf = NULL; @@ -242,9 +228,7 @@ void ex_menu(exarg_T *eap) menuarg.silent[0] = silent; add_menu_path(menu_path, &menuarg, pri_tab, map_to); - /* - * For the PopUp menu, add a menu for each mode separately. - */ + // For the PopUp menu, add a menu for each mode separately. if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; i++) { if (modes & (1 << i)) { @@ -384,11 +368,9 @@ static int add_menu_path(const char *const menu_path, vimmenu_T *menuarg, const } else { old_modes = menu->modes; - /* - * If this menu option was previously only available in other - * modes, then make sure it's available for this one now - * Also enable a menu when it's created or changed. - */ + // If this menu option was previously only available in other + // modes, then make sure it's available for this one now + // Also enable a menu when it's created or changed. { menu->modes |= modes; menu->enabled |= modes; @@ -405,10 +387,8 @@ static int add_menu_path(const char *const menu_path, vimmenu_T *menuarg, const } xfree(path_name); - /* - * Only add system menu items which have not been defined yet. - * First check if this was an ":amenu". - */ + // Only add system menu items which have not been defined yet. + // First check if this was an ":amenu". amenu = ((modes & (MENU_NORMAL_MODE | MENU_INSERT_MODE)) == (MENU_NORMAL_MODE | MENU_INSERT_MODE)); if (sys_menu) { @@ -491,10 +471,8 @@ erret: return FAIL; } -/* - * Set the (sub)menu with the given name to enabled or disabled. - * Called recursively. - */ +// Set the (sub)menu with the given name to enabled or disabled. +// Called recursively. static int menu_enable_recurse(vimmenu_T *menu, char *name, int modes, int enable) { char *p; @@ -522,11 +500,9 @@ static int menu_enable_recurse(vimmenu_T *menu, char *name, int modes, int enabl menu->enabled &= ~modes; } - /* - * When name is empty, we are doing all menu items for the given - * modes, so keep looping, otherwise we are just doing the named - * menu item (which has been found) so break here. - */ + // When name is empty, we are doing all menu items for the given + // modes, so keep looping, otherwise we are just doing the named + // menu item (which has been found) so break here. if (*name != NUL && *name != '*') { break; } @@ -577,11 +553,9 @@ static int remove_menu(vimmenu_T **menup, char *name, int modes, bool silent) return FAIL; } - /* - * When name is empty, we are removing all menu items for the given - * modes, so keep looping, otherwise we are just removing the named - * menu item (which has been found) so break here. - */ + // When name is empty, we are removing all menu items for the given + // modes, so keep looping, otherwise we are just removing the named + // menu item (which has been found) so break here. if (*name != NUL) { break; } @@ -628,9 +602,7 @@ static int remove_menu(vimmenu_T **menup, char *name, int modes, bool silent) return OK; } -/* - * Free the given menu structure and remove it from the linked list. - */ +// Free the given menu structure and remove it from the linked list. static void free_menu(vimmenu_T **menup) { int i; @@ -652,9 +624,7 @@ static void free_menu(vimmenu_T **menup) xfree(menu); } -/* - * Free the menu->string with the given index. - */ +// Free the menu->string with the given index. static void free_menu_string(vimmenu_T *menu, int idx) { int count = 0; @@ -909,16 +879,12 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth) } } -/* - * Used when expanding menu names. - */ +// Used when expanding menu names. static vimmenu_T *expand_menu = NULL; static int expand_modes = 0x0; static int expand_emenu; // true for ":emenu" command -/* - * Work out what to complete when doing command line completion of menu names. - */ +// Work out what to complete when doing command line completion of menu names. char *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char *arg, bool forceit) FUNC_ATTR_NONNULL_ALL { @@ -994,10 +960,8 @@ char *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char *arg, bool for // Found menu if ((*p != NUL && menu->children == NULL) || ((menu->modes & expand_modes) == 0x0)) { - /* - * Menu path continues, but we have reached a leaf. - * Or menu exists only in another mode. - */ + // Menu path continues, but we have reached a leaf. + // Or menu exists only in another mode. xfree(path_name); return NULL; } @@ -1024,10 +988,8 @@ char *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char *arg, bool for return NULL; } -/* - * Function given to ExpandGeneric() to obtain the list of (sub)menus (not - * entries). - */ +// Function given to ExpandGeneric() to obtain the list of (sub)menus (not +// entries). char *get_menu_name(expand_T *xp, int idx) { static vimmenu_T *menu = NULL; @@ -1073,10 +1035,8 @@ char *get_menu_name(expand_T *xp, int idx) return str; } -/* - * Function given to ExpandGeneric() to obtain the list of menus and menu - * entries. - */ +// Function given to ExpandGeneric() to obtain the list of menus and menu +// entries. char *get_menu_names(expand_T *xp, int idx) { static vimmenu_T *menu = NULL; @@ -1312,10 +1272,8 @@ static char *get_menu_mode_str(int modes) return ""; } -/* - * Modify a menu name starting with "PopUp" to include the mode character. - * Returns the name in allocated memory. - */ +// Modify a menu name starting with "PopUp" to include the mode character. +// Returns the name in allocated memory. static char *popup_mode_name(char *name, int idx) { size_t len = STRLEN(name); @@ -1730,9 +1688,7 @@ theend: return menu; } -/* - * Translation of menu names. Just a simple lookup table. - */ +// Translation of menu names. Just a simple lookup table. typedef struct { char *from; // English name @@ -1748,11 +1704,9 @@ static garray_T menutrans_ga = GA_EMPTY_INIT_VALUE; xfree(_mt->from_noamp); \ xfree(_mt->to) -/* - * ":menutrans". - * This function is also defined without the +multi_lang feature, in which - * case the commands are ignored. - */ +// ":menutrans". +// This function is also defined without the +multi_lang feature, in which +// case the commands are ignored. void ex_menutranslate(exarg_T *eap) { char *arg = eap->arg; @@ -1762,9 +1716,7 @@ void ex_menutranslate(exarg_T *eap) ga_init(&menutrans_ga, (int)sizeof(menutrans_T), 5); } - /* - * ":menutrans clear": clear all translations. - */ + // ":menutrans clear": clear all translations. if (STRNCMP(arg, "clear", 5) == 0 && ends_excmd(*skipwhite(arg + 5))) { GA_DEEP_CLEAR(&menutrans_ga, menutrans_T, FREE_MENUTRANS); @@ -1796,9 +1748,7 @@ void ex_menutranslate(exarg_T *eap) } } -/* - * Find the character just after one part of a menu name. - */ +// Find the character just after one part of a menu name. static char *menu_skip_part(char *p) { while (*p != NUL && *p != '.' && !ascii_iswhite(*p)) { @@ -1810,10 +1760,8 @@ static char *menu_skip_part(char *p) return p; } -/* - * Lookup part of a menu name in the translations. - * Return a pointer to the translation or NULL if not found. - */ +// Lookup part of a menu name in the translations. +// Return a pointer to the translation or NULL if not found. static char *menutrans_lookup(char *name, int len) { menutrans_T *tp = (menutrans_T *)menutrans_ga.ga_data; @@ -1841,9 +1789,7 @@ static char *menutrans_lookup(char *name, int len) return NULL; } -/* - * Unescape the name in the translate dictionary table. - */ +// Unescape the name in the translate dictionary table. static void menu_unescape_name(char *name) { char *p; @@ -1855,10 +1801,8 @@ static void menu_unescape_name(char *name) } } -/* - * Isolate the menu name. - * Skip the menu name, and translate into a real TAB. - */ +// Isolate the menu name. +// Skip the menu name, and translate into a real TAB. static char *menu_translate_tab_and_shift(char *arg_start) { char *arg = arg_start; diff --git a/src/nvim/message.c b/src/nvim/message.c index 87cfe06edc..d43c04b652 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * message.c: functions for displaying messages on the command line - */ +// message.c: functions for displaying messages on the command line #include #include @@ -48,10 +46,8 @@ #include "nvim/ui_compositor.h" #include "nvim/vim.h" -/* - * To be able to scroll back at the "more" and "hit-enter" prompts we need to - * store the displayed text and remember where screen lines start. - */ +// To be able to scroll back at the "more" and "hit-enter" prompts we need to +// store the displayed text and remember where screen lines start. typedef struct msgchunk_S msgchunk_T; struct msgchunk_S { msgchunk_T *sb_next; @@ -82,41 +78,39 @@ static int verbose_did_open = false; bool keep_msg_more = false; // keep_msg was set by msgmore() -/* - * When writing messages to the screen, there are many different situations. - * A number of variables is used to remember the current state: - * msg_didany true when messages were written since the last time the - * user reacted to a prompt. - * Reset: After hitting a key for the hit-return prompt, - * hitting for the command line or input(). - * Set: When any message is written to the screen. - * msg_didout true when something was written to the current line. - * Reset: When advancing to the next line, when the current - * text can be overwritten. - * Set: When any message is written to the screen. - * msg_nowait No extra delay for the last drawn message. - * Used in normal_cmd() before the mode message is drawn. - * emsg_on_display There was an error message recently. Indicates that there - * should be a delay before redrawing. - * msg_scroll The next message should not overwrite the current one. - * msg_scrolled How many lines the screen has been scrolled (because of - * messages). Used in update_screen() to scroll the screen - * back. Incremented each time the screen scrolls a line. - * msg_scrolled_ign true when msg_scrolled is non-zero and msg_puts_attr() - * writes something without scrolling should not make - * need_wait_return to be set. This is a hack to make ":ts" - * work without an extra prompt. - * lines_left Number of lines available for messages before the - * more-prompt is to be given. -1 when not set. - * need_wait_return true when the hit-return prompt is needed. - * Reset: After giving the hit-return prompt, when the user - * has answered some other prompt. - * Set: When the ruler or typeahead display is overwritten, - * scrolling the screen for some message. - * keep_msg Message to be displayed after redrawing the screen, in - * main_loop(). - * This is an allocated string or NULL when not used. - */ +// When writing messages to the screen, there are many different situations. +// A number of variables is used to remember the current state: +// msg_didany true when messages were written since the last time the +// user reacted to a prompt. +// Reset: After hitting a key for the hit-return prompt, +// hitting for the command line or input(). +// Set: When any message is written to the screen. +// msg_didout true when something was written to the current line. +// Reset: When advancing to the next line, when the current +// text can be overwritten. +// Set: When any message is written to the screen. +// msg_nowait No extra delay for the last drawn message. +// Used in normal_cmd() before the mode message is drawn. +// emsg_on_display There was an error message recently. Indicates that there +// should be a delay before redrawing. +// msg_scroll The next message should not overwrite the current one. +// msg_scrolled How many lines the screen has been scrolled (because of +// messages). Used in update_screen() to scroll the screen +// back. Incremented each time the screen scrolls a line. +// msg_scrolled_ign true when msg_scrolled is non-zero and msg_puts_attr() +// writes something without scrolling should not make +// need_wait_return to be set. This is a hack to make ":ts" +// work without an extra prompt. +// lines_left Number of lines available for messages before the +// more-prompt is to be given. -1 when not set. +// need_wait_return true when the hit-return prompt is needed. +// Reset: After giving the hit-return prompt, when the user +// has answered some other prompt. +// Set: When the ruler or typeahead display is overwritten, +// scrolling the screen for some message. +// keep_msg Message to be displayed after redrawing the screen, in +// main_loop(). +// This is an allocated string or NULL when not used. // Extended msg state, currently used for external UIs with ext_messages static const char *msg_ext_kind = NULL; @@ -313,11 +307,9 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline) set_vim_var_string(VV_STATUSMSG, s, -1); } - /* - * It is possible that displaying a messages causes a problem (e.g., - * when redrawing the window), which causes another message, etc.. To - * break this loop, limit the recursiveness to 3 levels. - */ + // It is possible that displaying a messages causes a problem (e.g., + // when redrawing the window), which causes another message, etc.. To + // break this loop, limit the recursiveness to 3 levels. if (entered >= 3) { return true; } @@ -483,10 +475,8 @@ void trunc_string(char *s, char *buf, int room_in, int buflen) } } -/* - * Note: Caller of smsg() and smsg_attr() must check the resulting string is - * shorter than IOSIZE!!! - */ +// Note: Caller of smsg() and smsg_attr() must check the resulting string is +// shorter than IOSIZE!!! int smsg(const char *s, ...) FUNC_ATTR_PRINTF(1, 2) @@ -522,10 +512,8 @@ int smsg_attr_keep(int attr, const char *s, ...) return msg_attr_keep((const char *)IObuff, attr, true, false); } -/* - * Remember the last sourcing name/lnum used in an error message, so that it - * isn't printed each time when it didn't change. - */ +// Remember the last sourcing name/lnum used in an error message, so that it +// isn't printed each time when it didn't change. static int last_sourcing_lnum = 0; static char *last_sourcing_name = NULL; @@ -681,10 +669,8 @@ static bool emsg_multiline(const char *s, bool multiline) // set "v:errmsg", also when using ":silent! cmd" set_vim_var_string(VV_ERRMSG, s, -1); - /* - * When using ":silent! cmd" ignore error messages. - * But do write it to the redirection file. - */ + // When using ":silent! cmd" ignore error messages. + // But do write it to the redirection file. if (emsg_silent != 0) { if (!emsg_noredir) { msg_start(); @@ -1156,12 +1142,10 @@ void wait_return(int redraw) return; } - /* - * When inside vgetc(), we can't wait for a typed character at all. - * With the global command (and some others) we only need one return at - * the end. Adjust cmdline_row to avoid the next message overwriting the - * last one. - */ + // When inside vgetc(), we can't wait for a typed character at all. + // With the global command (and some others) we only need one return at + // the end. Adjust cmdline_row to avoid the next message overwriting the + // last one. if (vgetc_busy > 0) { return; } @@ -1226,12 +1210,10 @@ void wait_return(int redraw) reg_recording = save_reg_recording; scriptout = save_scriptout; - /* - * Allow scrolling back in the messages. - * Also accept scroll-down commands when messages fill the screen, - * to avoid that typing one 'j' too many makes the messages - * disappear. - */ + // Allow scrolling back in the messages. + // Also accept scroll-down commands when messages fill the screen, + // to avoid that typing one 'j' too many makes the messages + // disappear. if (p_more) { if (c == 'b' || c == 'k' || c == 'u' || c == 'g' || c == K_UP || c == K_PAGEUP) { @@ -1268,9 +1250,7 @@ void wait_return(int redraw) || c == K_MOUSEDOWN || c == K_MOUSEUP || c == K_MOUSEMOVE); os_breakcheck(); - /* - * Avoid that the mouse-up event causes visual mode to start. - */ + // Avoid that the mouse-up event causes visual mode to start. if (c == K_LEFTMOUSE || c == K_MIDDLEMOUSE || c == K_RIGHTMOUSE || c == K_X1MOUSE || c == K_X2MOUSE) { (void)jump_to_mouse(MOUSE_SETPOS, NULL, 0); @@ -1575,10 +1555,8 @@ int msg_outtrans_len_attr(const char *msgstr, int len, int attr) msg_puts_attr(" ", attr); } - /* - * Go over the string. Special characters are translated and printed. - * Normal characters are printed several at a time. - */ + // Go over the string. Special characters are translated and printed. + // Normal characters are printed several at a time. while (--len >= 0 && !got_int) { // Don't include composing chars after the end. mb_l = utfc_ptr2len_len(str, len + 1); @@ -2250,10 +2228,8 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse) cmdline_row--; } - /* - * If screen is completely filled and 'more' is set then wait - * for a character. - */ + // If screen is completely filled and 'more' is set then wait + // for a character. if (lines_left > 0) { lines_left--; } @@ -2828,9 +2804,7 @@ static int do_more_prompt(int typed_char) msg_moremsg(false); } for (;;) { - /* - * Get a typed character directly from the user. - */ + // Get a typed character directly from the user. if (used_typed_char != NUL) { c = used_typed_char; // was typed at hit-enter prompt used_typed_char = NUL; @@ -3170,12 +3144,10 @@ void msg_clr_cmdline(void) /// @return true if wait_return() not called. int msg_end(void) { - /* - * If the string is larger than the window, - * or the ruler option is set and we run into it, - * we have to redraw the window. - * Do not do this if we are abandoning the file or editing the command line. - */ + // If the string is larger than the window, + // or the ruler option is set and we run into it, + // we have to redraw the window. + // Do not do this if we are abandoning the file or editing the command line. if (!exiting && need_wait_return && !(State & MODE_CMDLINE)) { wait_return(false); return false; @@ -3545,10 +3517,8 @@ int do_dialog(int type, char *title, char *message, char *buttons, int dfltbutto State = MODE_CONFIRM; setmouse(); - /* - * Since we wait for a keypress, don't make the - * user press RETURN as well afterwards. - */ + // Since we wait for a keypress, don't make the + // user press RETURN as well afterwards. no_wait_return++; hotkeys = msg_show_console_dialog(message, buttons, dfltbutton); diff --git a/src/nvim/message.h b/src/nvim/message.h index 2de2890213..4dba26f958 100644 --- a/src/nvim/message.h +++ b/src/nvim/message.h @@ -11,9 +11,7 @@ #include "nvim/macros.h" #include "nvim/types.h" -/* - * Types of dialogs passed to do_dialog(). - */ +// Types of dialogs passed to do_dialog(). #define VIM_GENERIC 0 #define VIM_ERROR 1 #define VIM_WARNING 2 @@ -21,9 +19,7 @@ #define VIM_QUESTION 4 #define VIM_LAST_TYPE 4 // sentinel value -/* - * Return values for functions like vim_dialogyesno() - */ +// Return values for functions like vim_dialogyesno() #define VIM_YES 2 #define VIM_NO 3 #define VIM_CANCEL 4 diff --git a/src/nvim/move.c b/src/nvim/move.c index b3ec3a8e7a..0e2550352d 100644 --- a/src/nvim/move.c +++ b/src/nvim/move.c @@ -1,16 +1,14 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * move.c: Functions for moving the cursor and scrolling text. - * - * There are two ways to move the cursor: - * 1. Move the cursor directly, the text is scrolled to keep the cursor in the - * window. - * 2. Scroll the text, the cursor is moved into the text visible in the - * window. - * The 'scrolloff' option makes this a bit complicated. - */ +// move.c: Functions for moving the cursor and scrolling text. +// +// There are two ways to move the cursor: +// 1. Move the cursor directly, the text is scrolled to keep the cursor in the +// window. +// 2. Scroll the text, the cursor is moved into the text visible in the +// window. +// The 'scrolloff' option makes this a bit complicated. #include #include @@ -47,19 +45,15 @@ typedef struct { # include "move.c.generated.h" #endif -/* - * Compute wp->w_botline for the current wp->w_topline. Can be called after - * wp->w_topline changed. - */ +// Compute wp->w_botline for the current wp->w_topline. Can be called after +// wp->w_topline changed. static void comp_botline(win_T *wp) { linenr_T lnum; int done; - /* - * If w_cline_row is valid, start there. - * Otherwise have to start at w_topline. - */ + // If w_cline_row is valid, start there. + // Otherwise have to start at w_topline. check_cursor_moved(wp); if (wp->w_valid & VALID_CROW) { lnum = wp->w_cursor.lnum; @@ -133,10 +127,8 @@ static void redraw_for_cursorcolumn(win_T *wp) } } -/* - * Update curwin->w_topline and redraw if necessary. - * Used to update the screen before printing a message. - */ +// Update curwin->w_topline and redraw if necessary. +// Used to update the screen before printing a message. void update_topline_redraw(void) { update_topline(curwin); @@ -145,9 +137,7 @@ void update_topline_redraw(void) } } -/* - * Update curwin->w_topline to move the cursor onto the screen. - */ +// Update curwin->w_topline to move the cursor onto the screen. void update_topline(win_T *wp) { linenr_T old_topline; @@ -250,14 +240,12 @@ void update_topline(win_T *wp) } } - /* - * If the cursor is below the bottom of the window, scroll the window - * to put the cursor on the window. - * When w_botline is invalid, recompute it first, to avoid a redraw later. - * If w_botline was approximated, we might need a redraw later in a few - * cases, but we don't want to spend (a lot of) time recomputing w_botline - * for every small change. - */ + // If the cursor is below the bottom of the window, scroll the window + // to put the cursor on the window. + // When w_botline is invalid, recompute it first, to avoid a redraw later. + // If w_botline was approximated, we might need a redraw later in a few + // cases, but we don't want to spend (a lot of) time recomputing w_botline + // for every small change. if (check_botline) { if (!(wp->w_valid & VALID_BOTLINE_AP)) { validate_botline(wp); @@ -328,9 +316,7 @@ void update_topline(win_T *wp) wp->w_viewport_invalid = true; win_check_anchored_floats(wp); - /* - * Need to redraw when topline changed. - */ + // Need to redraw when topline changed. if (wp->w_topline != old_topline || wp->w_topfill != old_topfill) { dollar_vcol = -1; @@ -349,9 +335,7 @@ void update_topline(win_T *wp) *so_ptr = save_so; } -/* - * Update win->w_topline to move the cursor onto the screen. - */ +// Update win->w_topline to move the cursor onto the screen. void update_topline_win(win_T *win) { switchwin_T switchwin; @@ -360,11 +344,9 @@ void update_topline_win(win_T *win) restore_win(&switchwin, true); } -/* - * Return the scrolljump value to use for the current window. - * When 'scrolljump' is positive use it as-is. - * When 'scrolljump' is negative use it as a percentage of the window height. - */ +// Return the scrolljump value to use for the current window. +// When 'scrolljump' is positive use it as-is. +// When 'scrolljump' is negative use it as a percentage of the window height. static int scrolljump_value(void) { long result = p_sj >= 0 ? p_sj : (curwin->w_height_inner * -p_sj) / 100; @@ -372,10 +354,8 @@ static int scrolljump_value(void) return (int)result; } -/* - * Return true when there are not 'scrolloff' lines above the cursor for the - * current window. - */ +// Return true when there are not 'scrolloff' lines above the cursor for the +// current window. static bool check_top_offset(void) { long so = get_scrolloff_value(curwin); @@ -412,9 +392,7 @@ void update_curswant(void) } } -/* - * Check if the cursor has moved. Set the w_valid flag accordingly. - */ +// Check if the cursor has moved. Set the w_valid flag accordingly. void check_cursor_moved(win_T *wp) { if (wp->w_cursor.lnum != wp->w_valid_cursor.lnum) { @@ -435,11 +413,9 @@ void check_cursor_moved(win_T *wp) } } -/* - * Call this function when some window settings have changed, which require - * the cursor position, botline and topline to be recomputed and the window to - * be redrawn. E.g, when changing the 'wrap' option or folding. - */ +// Call this function when some window settings have changed, which require +// the cursor position, botline and topline to be recomputed and the window to +// be redrawn. E.g, when changing the 'wrap' option or folding. void changed_window_setting(void) { changed_window_setting_win(curwin); @@ -453,9 +429,7 @@ void changed_window_setting_win(win_T *wp) redraw_later(wp, UPD_NOT_VALID); } -/* - * Set wp->w_topline to a certain number. - */ +// Set wp->w_topline to a certain number. void set_topline(win_T *wp, linenr_T lnum) { linenr_T prev_topline = wp->w_topline; @@ -475,11 +449,9 @@ void set_topline(win_T *wp, linenr_T lnum) redraw_later(wp, UPD_VALID); } -/* - * Call this function when the length of the cursor line (in screen - * characters) has changed, and the change is before the cursor. - * Need to take care of w_botline separately! - */ +// Call this function when the length of the cursor line (in screen +// characters) has changed, and the change is before the cursor. +// Need to take care of w_botline separately! void changed_cline_bef_curs(void) { curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL @@ -492,11 +464,9 @@ void changed_cline_bef_curs_win(win_T *wp) |VALID_CHEIGHT|VALID_TOPLINE); } -/* - * Call this function when the length of a line (in screen characters) above - * the cursor have changed. - * Need to take care of w_botline separately! - */ +// Call this function when the length of a line (in screen characters) above +// the cursor have changed. +// Need to take care of w_botline separately! void changed_line_abv_curs(void) { curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL|VALID_CROW @@ -509,9 +479,7 @@ void changed_line_abv_curs_win(win_T *wp) |VALID_CHEIGHT|VALID_TOPLINE); } -/* - * Make sure the value of curwin->w_botline is valid. - */ +// Make sure the value of curwin->w_botline is valid. void validate_botline(win_T *wp) { if (!(wp->w_valid & VALID_BOTLINE)) { @@ -519,9 +487,7 @@ void validate_botline(win_T *wp) } } -/* - * Mark curwin->w_botline as invalid (because of some change in the buffer). - */ +// Mark curwin->w_botline as invalid (because of some change in the buffer). void invalidate_botline(void) { curwin->w_valid &= ~(VALID_BOTLINE|VALID_BOTLINE_AP); @@ -537,9 +503,7 @@ void approximate_botline_win(win_T *wp) wp->w_valid &= ~VALID_BOTLINE; } -/* - * Return true if curwin->w_wrow and curwin->w_wcol are valid. - */ +// Return true if curwin->w_wrow and curwin->w_wcol are valid. int cursor_valid(void) { check_cursor_moved(curwin); @@ -547,10 +511,8 @@ int cursor_valid(void) (VALID_WROW|VALID_WCOL); } -/* - * Validate cursor position. Makes sure w_wrow and w_wcol are valid. - * w_topline must be valid, you may need to call update_topline() first! - */ +// Validate cursor position. Makes sure w_wrow and w_wcol are valid. +// w_topline must be valid, you may need to call update_topline() first! void validate_cursor(void) { check_cursor_moved(curwin); @@ -559,10 +521,8 @@ void validate_cursor(void) } } -/* - * Compute wp->w_cline_row and wp->w_cline_height, based on the current value - * of wp->w_topline. - */ +// Compute wp->w_cline_row and wp->w_cline_height, based on the current value +// of wp->w_topline. static void curs_rows(win_T *wp) { // Check if wp->w_lines[].wl_size is invalid @@ -633,17 +593,13 @@ static void curs_rows(win_T *wp) wp->w_valid |= VALID_CROW|VALID_CHEIGHT; } -/* - * Validate curwin->w_virtcol only. - */ +// Validate curwin->w_virtcol only. void validate_virtcol(void) { validate_virtcol_win(curwin); } -/* - * Validate wp->w_virtcol only. - */ +// Validate wp->w_virtcol only. void validate_virtcol_win(win_T *wp) { check_cursor_moved(wp); @@ -654,9 +610,7 @@ void validate_virtcol_win(win_T *wp) } } -/* - * Validate curwin->w_cline_height only. - */ +// Validate curwin->w_cline_height only. void validate_cheight(void) { check_cursor_moved(curwin); @@ -668,9 +622,7 @@ void validate_cheight(void) } } -/* - * Validate w_wcol and w_virtcol only. - */ +// Validate w_wcol and w_virtcol only. void validate_cursor_col(void) { validate_virtcol(); @@ -697,10 +649,8 @@ void validate_cursor_col(void) } } -/* - * Compute offset of a window, occupied by absolute or relative line number, - * fold column and sign column (these don't move when scrolling horizontally). - */ +// Compute offset of a window, occupied by absolute or relative line number, +// fold column and sign column (these don't move when scrolling horizontally). int win_col_off(win_T *wp) { return ((wp->w_p_nu || wp->w_p_rnu) ? number_width(wp) + 1 : 0) @@ -714,11 +664,9 @@ int curwin_col_off(void) return win_col_off(curwin); } -/* - * Return the difference in column offset for the second screen line of a - * wrapped line. It's 8 if 'number' or 'relativenumber' is on and 'n' is in - * 'cpoptions'. - */ +// Return the difference in column offset for the second screen line of a +// wrapped line. It's 8 if 'number' or 'relativenumber' is on and 'n' is in +// 'cpoptions'. int win_col_off2(win_T *wp) { if ((wp->w_p_nu || wp->w_p_rnu) && vim_strchr(p_cpo, CPO_NUMCOL) != NULL) { @@ -746,9 +694,7 @@ void curs_columns(win_T *wp, int may_scroll) long so = get_scrolloff_value(wp); long siso = get_sidescrolloff_value(wp); - /* - * First make sure that w_topline is valid (after moving the cursor). - */ + // First make sure that w_topline is valid (after moving the cursor). update_topline(wp); // Next make sure that w_cline_row is valid. @@ -756,9 +702,7 @@ void curs_columns(win_T *wp, int may_scroll) curs_rows(wp); } - /* - * Compute the number of virtual columns. - */ + // Compute the number of virtual columns. if (wp->w_cline_folded) { // In a folded line the cursor is always in the first column startcol = wp->w_virtcol = endcol = wp->w_leftcol; @@ -1079,10 +1023,8 @@ bool scrolldown(long line_count, int byfold) } check_topfill(curwin, true); - /* - * Compute the row number of the last row of the cursor line - * and move the cursor onto the displayed part of the window. - */ + // Compute the row number of the last row of the cursor line + // and move the cursor onto the displayed part of the window. int wrow = curwin->w_wrow; if (curwin->w_p_wrap && curwin->w_width_inner != 0) { validate_virtcol(); @@ -1200,10 +1142,8 @@ void check_topfill(win_T *wp, bool down) win_check_anchored_floats(curwin); } -/* - * Use as many filler lines as possible for w_topline. Make sure w_topline - * is still visible. - */ +// Use as many filler lines as possible for w_topline. Make sure w_topline +// is still visible. static void max_topfill(void) { int n = plines_win_nofill(curwin, curwin->w_topline, true); @@ -1217,10 +1157,8 @@ static void max_topfill(void) } } -/* - * Scroll the screen one line down, but don't do it if it would move the - * cursor off the screen. - */ +// Scroll the screen one line down, but don't do it if it would move the +// cursor off the screen. void scrolldown_clamp(void) { int can_fill = (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline)); @@ -1261,10 +1199,8 @@ void scrolldown_clamp(void) } } -/* - * Scroll the screen one line up, but don't do it if it would move the cursor - * off the screen. - */ +// Scroll the screen one line up, but don't do it if it would move the cursor +// off the screen. void scrollup_clamp(void) { if (curwin->w_topline == curbuf->b_ml.ml_line_count @@ -1296,12 +1232,10 @@ void scrollup_clamp(void) } } -/* - * Add one line above "lp->lnum". This can be a filler line, a closed fold or - * a (wrapped) text line. Uses and sets "lp->fill". - * Returns the height of the added line in "lp->height". - * Lines above the first one are incredibly high: MAXCOL. - */ +// Add one line above "lp->lnum". This can be a filler line, a closed fold or +// a (wrapped) text line. Uses and sets "lp->fill". +// Returns the height of the added line in "lp->height". +// Lines above the first one are incredibly high: MAXCOL. static void topline_back(win_T *wp, lineoff_T *lp) { if (lp->fill < win_get_fill(wp, lp->lnum)) { @@ -1322,12 +1256,10 @@ static void topline_back(win_T *wp, lineoff_T *lp) } } -/* - * Add one line below "lp->lnum". This can be a filler line, a closed fold or - * a (wrapped) text line. Uses and sets "lp->fill". - * Returns the height of the added line in "lp->height". - * Lines below the last one are incredibly high. - */ +// Add one line below "lp->lnum". This can be a filler line, a closed fold or +// a (wrapped) text line. Uses and sets "lp->fill". +// Returns the height of the added line in "lp->height". +// Lines below the last one are incredibly high. static void botline_forw(win_T *wp, lineoff_T *lp) { if (lp->fill < win_get_fill(wp, lp->lnum + 1)) { @@ -1349,11 +1281,9 @@ static void botline_forw(win_T *wp, lineoff_T *lp) } } -/* - * Switch from including filler lines below lp->lnum to including filler - * lines above loff.lnum + 1. This keeps pointing to the same line. - * When there are no filler lines nothing changes. - */ +// Switch from including filler lines below lp->lnum to including filler +// lines above loff.lnum + 1. This keeps pointing to the same line. +// When there are no filler lines nothing changes. static void botline_topline(lineoff_T *lp) { if (lp->fill > 0) { @@ -1362,11 +1292,9 @@ static void botline_topline(lineoff_T *lp) } } -/* - * Switch from including filler lines above lp->lnum to including filler - * lines below loff.lnum - 1. This keeps pointing to the same line. - * When there are no filler lines nothing changes. - */ +// Switch from including filler lines above lp->lnum to including filler +// lines below loff.lnum - 1. This keeps pointing to the same line. +// When there are no filler lines nothing changes. static void topline_botline(lineoff_T *lp) { if (lp->fill > 0) { @@ -1375,11 +1303,9 @@ static void topline_botline(lineoff_T *lp) } } -/* - * Recompute topline to put the cursor at the top of the window. - * Scroll at least "min_scroll" lines. - * If "always" is true, always set topline (for "zt"). - */ +// Recompute topline to put the cursor at the top of the window. +// Scroll at least "min_scroll" lines. +// If "always" is true, always set topline (for "zt"). void scroll_cursor_top(int min_scroll, int always) { int scrolled = 0; @@ -1394,13 +1320,11 @@ void scroll_cursor_top(int min_scroll, int always) off = mouse_dragging - 1; } - /* - * Decrease topline until: - * - it has become 1 - * - (part of) the cursor line is moved off the screen or - * - moved at least 'scrolljump' lines and - * - at least 'scrolloff' lines above and below the cursor - */ + // Decrease topline until: + // - it has become 1 + // - (part of) the cursor line is moved off the screen or + // - moved at least 'scrolljump' lines and + // - at least 'scrolloff' lines above and below the cursor validate_cheight(); int used = curwin->w_cline_height; // includes filler lines above if (curwin->w_cursor.lnum < curwin->w_topline) { @@ -1421,10 +1345,8 @@ void scroll_cursor_top(int min_scroll, int always) // Hide filler lines above cursor line by adding them to "extra". int extra = win_get_fill(curwin, curwin->w_cursor.lnum); - /* - * Check if the lines from "top" to "bot" fit in the window. If they do, - * set new_topline and advance "top" and "bot" to include more lines. - */ + // Check if the lines from "top" to "bot" fit in the window. If they do, + // set new_topline and advance "top" and "bot" to include more lines. while (top > 0) { int i = hasFolding(top, &top, NULL) ? 1 // count one logical line for a sequence of folded lines @@ -1445,9 +1367,7 @@ void scroll_cursor_top(int min_scroll, int always) scrolled += i; } - /* - * If scrolling is needed, scroll at least 'sj' lines. - */ + // If scrolling is needed, scroll at least 'sj' lines. if ((new_topline >= curwin->w_topline || scrolled > min_scroll) && extra >= off) { break; @@ -1459,18 +1379,14 @@ void scroll_cursor_top(int min_scroll, int always) bot++; } - /* - * If we don't have enough space, put cursor in the middle. - * This makes sure we get the same position when using "k" and "j" - * in a small window. - */ + // If we don't have enough space, put cursor in the middle. + // This makes sure we get the same position when using "k" and "j" + // in a small window. if (used > curwin->w_height_inner) { scroll_cursor_halfway(false); } else { - /* - * If "always" is false, only adjust topline to a lower value, higher - * value may happen with wrapping lines - */ + // If "always" is false, only adjust topline to a lower value, higher + // value may happen with wrapping lines if (new_topline < curwin->w_topline || always) { curwin->w_topline = new_topline; } @@ -1495,10 +1411,8 @@ void scroll_cursor_top(int min_scroll, int always) } } -/* - * Set w_empty_rows and w_filler_rows for window "wp", having used up "used" - * screen lines for text lines. - */ +// Set w_empty_rows and w_filler_rows for window "wp", having used up "used" +// screen lines for text lines. void set_empty_rows(win_T *wp, int used) { wp->w_filler_rows = 0; @@ -1577,13 +1491,11 @@ void scroll_cursor_bot(int min_scroll, int set_topbot) } } - /* - * Stop counting lines to scroll when - * - hitting start of the file - * - scrolled nothing or at least 'sj' lines - * - at least 'so' lines below the cursor - * - lines between botline and cursor have been counted - */ + // Stop counting lines to scroll when + // - hitting start of the file + // - scrolled nothing or at least 'sj' lines + // - at least 'so' lines below the cursor + // - lines between botline and cursor have been counted if (!hasFolding(curwin->w_cursor.lnum, &loff.lnum, &boff.lnum)) { loff.lnum = cln; boff.lnum = cln; @@ -1673,21 +1585,17 @@ void scroll_cursor_bot(int min_scroll, int set_topbot) } } - /* - * Scroll up if the cursor is off the bottom of the screen a bit. - * Otherwise put it at 1/2 of the screen. - */ + // Scroll up if the cursor is off the bottom of the screen a bit. + // Otherwise put it at 1/2 of the screen. if (line_count >= curwin->w_height_inner && line_count > min_scroll) { scroll_cursor_halfway(false); } else { scrollup(line_count, true); } - /* - * If topline didn't change we need to restore w_botline and w_empty_rows - * (we changed them). - * If topline did change, update_screen() will set botline. - */ + // If topline didn't change we need to restore w_botline and w_empty_rows + // (we changed them). + // If topline did change, update_screen() will set botline. if (curwin->w_topline == old_topline && set_topbot) { curwin->w_botline = old_botline; curwin->w_empty_rows = old_empty_rows; @@ -1760,18 +1668,14 @@ void scroll_cursor_halfway(int atend) curwin->w_valid |= VALID_TOPLINE; } -/* - * Correct the cursor position so that it is in a part of the screen at least - * 'so' lines from the top and bottom, if possible. - * If not possible, put it at the same position as scroll_cursor_halfway(). - * When called topline must be valid! - */ +// Correct the cursor position so that it is in a part of the screen at least +// 'so' lines from the top and bottom, if possible. +// If not possible, put it at the same position as scroll_cursor_halfway(). +// When called topline must be valid! void cursor_correct(void) { - /* - * How many lines we would like to have above/below the cursor depends on - * whether the first/last line of the file is on screen. - */ + // How many lines we would like to have above/below the cursor depends on + // whether the first/last line of the file is on screen. int above_wanted = (int)get_scrolloff_value(curwin); int below_wanted = (int)get_scrolloff_value(curwin); if (mouse_dragging > 0) { @@ -1795,10 +1699,8 @@ void cursor_correct(void) } } - /* - * If there are sufficient file-lines above and below the cursor, we can - * return now. - */ + // If there are sufficient file-lines above and below the cursor, we can + // return now. linenr_T cln = curwin->w_cursor.lnum; // Cursor Line Number if (cln >= curwin->w_topline + above_wanted && cln < curwin->w_botline - below_wanted @@ -1806,12 +1708,10 @@ void cursor_correct(void) return; } - /* - * Narrow down the area where the cursor can be put by taking lines from - * the top and the bottom until: - * - the desired context lines are found - * - the lines from the top is past the lines from the bottom - */ + // Narrow down the area where the cursor can be put by taking lines from + // the top and the bottom until: + // - the desired context lines are found + // - the lines from the top is past the lines from the bottom linenr_T topline = curwin->w_topline; linenr_T botline = curwin->w_botline - 1; // count filler lines as context @@ -1860,11 +1760,9 @@ void cursor_correct(void) curwin->w_viewport_invalid = true; } -/* - * move screen 'count' pages up or down and update screen - * - * return FAIL for failure, OK otherwise - */ +// move screen 'count' pages up or down and update screen +// +// return FAIL for failure, OK otherwise int onepage(Direction dir, long count) { long n; @@ -2044,18 +1942,16 @@ int onepage(Direction dir, long count) return retval; } -/* - * Decide how much overlap to use for page-up or page-down scrolling. - * This is symmetric, so that doing both keeps the same lines displayed. - * Three lines are examined: - * - * before CTRL-F after CTRL-F / before CTRL-B - * etc. l1 - * l1 last but one line ------------ - * l2 last text line l2 top text line - * ------------- l3 second text line - * l3 etc. - */ +// Decide how much overlap to use for page-up or page-down scrolling. +// This is symmetric, so that doing both keeps the same lines displayed. +// Three lines are examined: +// +// before CTRL-F after CTRL-F / before CTRL-B +// etc. l1 +// l1 last but one line ------------ +// l2 last text line l2 top text line +// ------------- l3 second text line +// l3 etc. static void get_scroll_overlap(lineoff_T *lp, int dir) { int min_height = curwin->w_height_inner - 2; @@ -2125,9 +2021,7 @@ void halfpage(bool flag, linenr_T Prenum) validate_botline(curwin); int room = curwin->w_empty_rows + curwin->w_filler_rows; if (flag) { - /* - * scroll the text up - */ + // scroll the text up while (n > 0 && curwin->w_botline <= curbuf->b_ml.ml_line_count) { if (curwin->w_topfill > 0) { i = 1; @@ -2185,9 +2079,7 @@ void halfpage(bool flag, linenr_T Prenum) check_cursor_lnum(); } } else { - /* - * scroll the text down - */ + // scroll the text down while (n > 0 && curwin->w_topline > 1) { if (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline)) { i = 1; @@ -2247,9 +2139,7 @@ void do_check_cursorbind(void) int old_VIsual_select = VIsual_select; int old_VIsual_active = VIsual_active; - /* - * loop through the cursorbound windows - */ + // loop through the cursorbound windows VIsual_select = VIsual_active = 0; FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { curwin = wp; @@ -2294,9 +2184,7 @@ void do_check_cursorbind(void) } } - /* - * reset current-window - */ + // reset current-window VIsual_select = old_VIsual_select; VIsual_active = old_VIsual_active; curwin = old_curwin; diff --git a/src/nvim/normal.h b/src/nvim/normal.h index 13ea233658..0317080f4f 100644 --- a/src/nvim/normal.h +++ b/src/nvim/normal.h @@ -22,9 +22,7 @@ typedef enum { kMTUnknown = -1, ///< Unknown or invalid motion type } MotionType; -/* - * Arguments for operators. - */ +// Arguments for operators. typedef struct oparg_S { int op_type; // current pending operator type int regname; // register to use for the operator @@ -53,9 +51,7 @@ typedef struct oparg_S { // block } oparg_T; -/* - * Arguments for Normal mode commands. - */ +// Arguments for Normal mode commands. typedef struct cmdarg_S { oparg_T *oap; // Operator arguments int prechar; // prefix character (optional, always 'g') diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 01fd4bb9a7..25b957e3b9 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -1,10 +1,8 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * ops.c: implementation of various operators: op_shift, op_delete, op_tilde, - * op_change, op_yank, do_put, do_join - */ +// ops.c: implementation of various operators: op_shift, op_delete, op_tilde, +// op_change, op_yank, do_put, do_join #include #include @@ -67,10 +65,8 @@ static bool clipboard_delay_update = false; // delay clipboard update static bool clipboard_needs_update = false; // clipboard was updated static bool clipboard_didwarn = false; -/* - * structure used by block_prep, op_delete and op_yank for blockwise operators - * also op_change, op_shift, op_insert, op_replace - AKelly - */ +// structure used by block_prep, op_delete and op_yank for blockwise operators +// also op_change, op_shift, op_insert, op_replace - AKelly struct block_def { int startspaces; // 'extra' cols before first char int endspaces; // 'extra' cols after last char @@ -96,11 +92,9 @@ struct block_def { #define OPF_LINES 1 // operator always works on lines #define OPF_CHANGE 2 // operator changes text -/* - * The names of operators. - * IMPORTANT: Index must correspond with defines in vim.h!!! - * The third field indicates whether the operator always works on lines. - */ +// The names of operators. +// IMPORTANT: Index must correspond with defines in vim.h!!! +// The third field indicates whether the operator always works on lines. static char opchars[][3] = { { NUL, NUL, 0 }, // OP_NOP @@ -361,12 +355,10 @@ static void shift_block(oparg_T *oap, int amount) int startcol, oldlen, newlen; if (!left) { - /* - * 1. Get start vcol - * 2. Total ws vcols - * 3. Divvy into TABs & spp - * 4. Construct new string - */ + // 1. Get start vcol + // 2. Total ws vcols + // 3. Divvy into TABs & spp + // 4. Construct new string total += bd.pre_whitesp; // all virtual WS up to & incl a split TAB colnr_T ws_vcol = bd.start_vcol - bd.pre_whitesp; char_u *old_textstart = bd.textstart; @@ -428,13 +420,11 @@ static void shift_block(oparg_T *oap, int amount) // block shift char_u *non_white = bd.textstart; - /* - * Firstly, let's find the first non-whitespace character that is - * displayed after the block's start column and the character's column - * number. Also, let's calculate the width of all the whitespace - * characters that are displayed in the block and precede the searched - * non-whitespace character. - */ + // Firstly, let's find the first non-whitespace character that is + // displayed after the block's start column and the character's column + // number. Also, let's calculate the width of all the whitespace + // characters that are displayed in the block and precede the searched + // non-whitespace character. // If "bd.startspaces" is set, "bd.textstart" points to the character, // the part of which is displayed at the block's beginning. Let's start @@ -715,9 +705,7 @@ void op_reindent(oparg_T *oap, Indenter how) } } -/* - * Keep the last expression line here, for repeating. - */ +// Keep the last expression line here, for repeating. static char_u *expr_line = NULL; /// Get an expression for the "\"=expr1" or "CTRL-R =expr1" @@ -1165,9 +1153,7 @@ int do_execreg(int regname, int colon, int addcr, int silent) // Disallow remapping for ":@r". int remap = colon ? REMAP_NONE : REMAP_YES; - /* - * Insert lines into typeahead buffer, from last one to first one. - */ + // Insert lines into typeahead buffer, from last one to first one. put_reedit_in_typebuf(silent); char *escaped; for (size_t i = reg->y_size; i-- > 0;) { // from y_size - 1 to 0 included @@ -1277,11 +1263,9 @@ int insert_reg(int regname, bool literally_arg) bool allocated; const bool literally = literally_arg || is_literal_register(regname); - /* - * It is possible to get into an endless loop by having CTRL-R a in - * register a and then, in insert mode, doing CTRL-R a. - * If you hit CTRL-C, the loop will be broken here. - */ + // It is possible to get into an endless loop by having CTRL-R a in + // register a and then, in insert mode, doing CTRL-R a. + // If you hit CTRL-C, the loop will be broken here. os_breakcheck(); if (got_int) { return FAIL; @@ -1503,11 +1487,9 @@ int op_delete(oparg_T *oap) mb_adjust_opend(oap); - /* - * Imitate the strange Vi behaviour: If the delete spans more than one - * line and motion_type == kMTCharWise and the result is a blank line, make the - * delete linewise. Don't do this for the change command or Visual mode. - */ + // Imitate the strange Vi behaviour: If the delete spans more than one + // line and motion_type == kMTCharWise and the result is a blank line, make the + // delete linewise. Don't do this for the change command or Visual mode. if (oap->motion_type == kMTCharWise && !oap->is_VIsual && oap->line_count > 1 @@ -1523,10 +1505,8 @@ int op_delete(oparg_T *oap) } } - /* - * Check for trying to delete (e.g. "D") in an empty line. - * Note: For the change operator it is ok. - */ + // Check for trying to delete (e.g. "D") in an empty line. + // Note: For the change operator it is ok. if (oap->motion_type != kMTLineWise && oap->line_count == 1 && oap->op_type == OP_DELETE @@ -1544,11 +1524,9 @@ int op_delete(oparg_T *oap) return OK; } - /* - * Do a yank of whatever we're about to delete. - * If a yank register was specified, put the deleted text into that - * register. For the black hole register '_' don't yank anything. - */ + // Do a yank of whatever we're about to delete. + // If a yank register was specified, put the deleted text into that + // register. For the black hole register '_' don't yank anything. if (oap->regname != '_') { yankreg_T *reg = NULL; int did_yank = false; @@ -1592,9 +1570,7 @@ int op_delete(oparg_T *oap) } } - /* - * block mode delete - */ + // block mode delete if (oap->motion_type == kMTBlockWise) { if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) { @@ -1873,9 +1849,7 @@ static int op_replace(oparg_T *oap, int c) return FAIL; } - /* - * block mode replace - */ + // block mode replace if (oap->motion_type == kMTBlockWise) { bd.is_MAX = (curwin->w_curswant == MAXCOL); for (; curwin->w_cursor.lnum <= oap->end.lnum; curwin->w_cursor.lnum++) { @@ -2409,10 +2383,8 @@ void op_insert(oparg_T *oap, long count1) bd.textlen = bd2.textlen; } - /* - * Subsequent calls to ml_get() flush the firstline data - take a - * copy of the required string. - */ + // Subsequent calls to ml_get() flush the firstline data - take a + // copy of the required string. firstline = ml_get(oap->start.lnum); const size_t len = STRLEN(firstline); colnr_T add = bd.textcol; @@ -2510,11 +2482,9 @@ int op_change(oparg_T *oap) retval = edit(NUL, false, (linenr_T)1); - /* - * In Visual block mode, handle copying the new text to all lines of the - * block. - * Don't repeat the insert when Insert mode ended with CTRL-C. - */ + // In Visual block mode, handle copying the new text to all lines of the + // block. + // Don't repeat the insert when Insert mode ended with CTRL-C. if (oap->motion_type == kMTBlockWise && oap->start.lnum != oap->end.lnum && !got_int) { // Auto-indenting may have changed the indent. If the cursor was past @@ -2973,10 +2943,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) curbuf->b_op_start = curwin->w_cursor; // default for '[ mark curbuf->b_op_end = curwin->w_cursor; // default for '] mark - /* - * Using inserted text works differently, because the register includes - * special characters (newlines, etc.). - */ + // Using inserted text works differently, because the register includes + // special characters (newlines, etc.). if (regname == '.' && !reg) { bool non_linewise_vis = (VIsual_active && VIsual_mode != 'V'); @@ -3056,10 +3024,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) return; } - /* - * For special registers '%' (file name), '#' (alternate file name) and - * ':' (last command line), etc. we have to create a fake yank register. - */ + // For special registers '%' (file name), '#' (alternate file name) and + // ':' (last command line), etc. we have to create a fake yank register. if (!reg && get_spec_reg(regname, &insert_string, &allocated, true)) { if (insert_string == NULL) { return; @@ -3232,9 +3198,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) lnum = curwin->w_cursor.lnum; col = curwin->w_cursor.col; - /* - * Block mode - */ + // Block mode if (y_type == kMTBlockWise) { int c = gchar_cursor(); colnr_T endcol2 = 0; @@ -4129,13 +4093,11 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions cend = newp + sumsize; *cend = 0; - /* - * Move affected lines to the new long one. - * - * Move marks from each deleted line to the joined line, adjusting the - * column. This is not Vi compatible, but Vi deletes the marks, thus that - * should not really be a problem. - */ + // Move affected lines to the new long one. + // + // Move marks from each deleted line to the joined line, adjusting the + // column. This is not Vi compatible, but Vi deletes the marks, thus that + // should not really be a problem. curbuf_splice_pending++; @@ -4185,11 +4147,9 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions changed_lines(curwin->w_cursor.lnum, currsize, curwin->w_cursor.lnum + 1, 0L, true); - /* - * Delete following lines. To do this we move the cursor there - * briefly, and then move it back. After del_lines() the cursor may - * have moved up (last line deleted), so the current lnum is kept in t. - */ + // Delete following lines. To do this we move the cursor there + // briefly, and then move it back. After del_lines() the cursor may + // have moved up (last line deleted), so the current lnum is kept in t. t = curwin->w_cursor.lnum; curwin->w_cursor.lnum++; del_lines((long)count - 1, false); @@ -4197,11 +4157,9 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions curbuf_splice_pending--; curbuf->deleted_bytes2 = 0; - /* - * Set the cursor column: - * Vi compatible: use the column of the first join - * vim: use the column of the last join - */ + // Set the cursor column: + // Vi compatible: use the column of the first join + // vim: use the column of the last join curwin->w_cursor.col = (vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col); check_cursor_col(); @@ -4963,16 +4921,12 @@ void *get_reg_contents(int regname, int flags) return list; } - /* - * Compute length of resulting string. - */ + // Compute length of resulting string. size_t len = 0; for (size_t i = 0; i < reg->y_size; i++) { len += STRLEN(reg->y_array[i]); - /* - * Insert a newline between lines and after last line if - * y_type is kMTLineWise. - */ + // Insert a newline between lines and after last line if + // y_type is kMTLineWise. if (reg->y_type == kMTLineWise || i < reg->y_size - 1) { len++; } @@ -4980,18 +4934,14 @@ void *get_reg_contents(int regname, int flags) retval = xmalloc(len + 1); - /* - * Copy the lines of the yank register into the string. - */ + // Copy the lines of the yank register into the string. len = 0; for (size_t i = 0; i < reg->y_size; i++) { STRCPY(retval + len, reg->y_array[i]); len += STRLEN(retval + len); - /* - * Insert a NL between lines and after the last line if y_type is - * kMTLineWise. - */ + // Insert a NL between lines and after the last line if y_type is + // kMTLineWise. if (reg->y_type == kMTLineWise || i < reg->y_size - 1) { retval[len++] = '\n'; } diff --git a/src/nvim/ops.h b/src/nvim/ops.h index 05893c9940..840e33a48c 100644 --- a/src/nvim/ops.h +++ b/src/nvim/ops.h @@ -23,15 +23,13 @@ typedef int (*Indenter)(void); #define PUT_LINE_FORWARD 32 // put linewise register below Visual sel. #define PUT_BLOCK_INNER 64 // in block mode, do not add trailing spaces -/* - * Registers: - * 0 = register for latest (unnamed) yank - * 1..9 = registers '1' to '9', for deletes - * 10..35 = registers 'a' to 'z' - * 36 = delete register '-' - * 37 = selection register '*' - * 38 = clipboard register '+' - */ +// Registers: +// 0 = register for latest (unnamed) yank +// 1..9 = registers '1' to '9', for deletes +// 10..35 = registers 'a' to 'z' +// 36 = delete register '-' +// 37 = selection register '*' +// 38 = clipboard register '+' #define DELETION_REGISTER 36 #define NUM_SAVED_REGISTERS 37 // The following registers should not be saved in ShaDa file: diff --git a/src/nvim/option.c b/src/nvim/option.c index f8b7d96305..12c2888f5c 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -106,14 +106,12 @@ static char e_number_required_after_equal[] static char e_preview_window_already_exists[] = N_("E590: A preview window already exists"); -/* - * The options that are local to a window or buffer have "indir" set to one of - * these values. Special values: - * PV_NONE: global option. - * PV_WIN is added: window-local option - * PV_BUF is added: buffer-local option - * PV_BOTH is added: global option which also has a local value. - */ +// The options that are local to a window or buffer have "indir" set to one of +// these values. Special values: +// PV_NONE: global option. +// PV_WIN is added: window-local option +// PV_BUF is added: buffer-local option +// PV_BOTH is added: global option which also has a local value. #define PV_BOTH 0x1000 #define PV_WIN 0x2000 #define PV_BUF 0x4000 @@ -128,10 +126,8 @@ typedef enum { PV_MAXVAL = 0xffff, // to avoid warnings for value out of range } idopt_T; -/* - * Options local to a window have a value local to a buffer and global to all - * buffers. Indicate this by setting "var" to VAR_WIN. - */ +// Options local to a window have a value local to a buffer and global to all +// buffers. Indicate this by setting "var" to VAR_WIN. #define VAR_WIN ((char_u *)-1) static char *p_term = NULL; @@ -164,14 +160,12 @@ typedef struct vimoption { LastSet last_set; // script in which the option was last set } vimoption_T; -/* - * options[] is initialized here. - * The order of the options MUST be alphabetic for ":set all" and findoption(). - * All option names MUST start with a lowercase letter (for findoption()). - * Exception: "t_" options are at the end. - * The options with a NULL variable are 'hidden': a set command for them is - * ignored and they are not printed. - */ +// options[] is initialized here. +// The order of the options MUST be alphabetic for ":set all" and findoption(). +// All option names MUST start with a lowercase letter (for findoption()). +// Exception: "t_" options are at the end. +// The options with a NULL variable are 'hidden': a set command for them is +// ignored and they are not printed. #ifdef INCLUDE_GENERATED_DECLARATIONS # include "options.generated.h" @@ -197,10 +191,8 @@ void set_init_1(bool clean_arg) langmap_init(); - /* - * Find default value for 'shell' option. - * Don't use it if it is empty. - */ + // Find default value for 'shell' option. + // Don't use it if it is empty. { const char *shell = os_getenv("SHELL"); if (shell != NULL) { @@ -215,10 +207,8 @@ void set_init_1(bool clean_arg) } } - /* - * Set the default for 'backupskip' to include environment variables for - * temp files. - */ + // Set the default for 'backupskip' to include environment variables for + // temp files. { #ifdef UNIX static char *(names[4]) = { "", "TMPDIR", "TEMP", "TMP" }; @@ -354,10 +344,8 @@ void set_init_1(bool clean_arg) rtp = NULL; // ownership taken } - /* - * Set all the options (except the terminal options) to their default - * value. Also set the global value for local options. - */ + // Set all the options (except the terminal options) to their default + // value. Also set the global value for local options. set_options_default(0); curbuf->b_p_initialized = true; @@ -380,15 +368,13 @@ void set_init_1(bool clean_arg) // didset_options() because it only depends on 'encoding'. init_spell_chartab(); - /* - * Expand environment variables and things like "~" for the defaults. - * If option_expand() returns non-NULL the variable is expanded. This can - * only happen for non-indirect options. - * Also set the default to the expanded value, so ":set" does not list - * them. - * Don't set the P_ALLOCED flag, because we don't want to free the - * default. - */ + // Expand environment variables and things like "~" for the defaults. + // If option_expand() returns non-NULL the variable is expanded. This can + // only happen for non-indirect options. + // Also set the default to the expanded value, so ":set" does not list + // them. + // Don't set the P_ALLOCED flag, because we don't want to free the + // default. for (opt_idx = 0; options[opt_idx].fullname; opt_idx++) { if (options[opt_idx].flags & P_NO_DEF_EXP) { continue; @@ -635,10 +621,8 @@ void set_init_2(bool headless) } comp_col(); - /* - * 'window' is only for backwards compatibility with Vi. - * Default is Rows - 1. - */ + // 'window' is only for backwards compatibility with Vi. + // Default is Rows - 1. if (!option_was_set("window")) { p_window = Rows - 1; } @@ -758,11 +742,9 @@ void set_title_defaults(void) { int idx1; - /* - * If GUI is (going to be) used, we can always set the window title and - * icon name. Saves a bit of time, because the X11 display server does - * not need to be contacted. - */ + // If GUI is (going to be) used, we can always set the window title and + // icon name. Saves a bit of time, because the X11 display server does + // not need to be contacted. idx1 = findoption("title"); if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) { options[idx1].def_val = (char_u *)(intptr_t)0; @@ -837,10 +819,8 @@ int do_set(char *arg, int opt_flags) if (STRNCMP(arg, "all", 3) == 0 && !isalpha(arg[3]) && !(opt_flags & OPT_MODELINE)) { - /* - * ":set all" show all options. - * ":set all&" set all options to their default value. - */ + // ":set all" show all options. + // ":set all&" set all options to their default value. arg += 3; if (*arg == '&') { arg++; @@ -1016,9 +996,7 @@ int do_set(char *arg, int opt_flags) || (prefix == 1 && vim_strchr("=:&<", nextchar) == NULL && !(flags & P_BOOL))) { - /* - * print value - */ + // print value if (did_show) { msg_putchar('\n'); // cursor below last one } else { @@ -1057,11 +1035,9 @@ int do_set(char *arg, int opt_flags) goto skip; } - /* - * ":set opt!": invert - * ":set opt&": reset to default value - * ":set opt<": reset to global value - */ + // ":set opt!": invert + // ":set opt&": reset to default value + // ":set opt<": reset to global value if (nextchar == '!') { value = *(int *)(varp) ^ 1; } else if (nextchar == '&') { @@ -1076,10 +1052,8 @@ int do_set(char *arg, int opt_flags) OPT_GLOBAL); } } else { - /* - * ":set invopt": invert - * ":set opt" or ":set noopt": set or reset - */ + // ":set invopt": invert + // ":set opt" or ":set noopt": set or reset if (nextchar != NUL && !ascii_iswhite(afterchar)) { errmsg = e_trailing; goto skip; @@ -1289,11 +1263,10 @@ int do_set(char *arg, int opt_flags) arg++; } - /* - * Copy the new string into allocated memory. - * Can't use set_string_option_direct(), because - * we need to remove the backslashes. - */ + // Copy the new string into allocated memory. + // Can't use set_string_option_direct(), because + // we need to remove the backslashes. + // get a bit too much newlen = (unsigned)STRLEN(arg) + 1; if (adding || prepending || removing) { @@ -1302,14 +1275,12 @@ int do_set(char *arg, int opt_flags) newval = xmalloc(newlen); s = newval; - /* - * Copy the string, skip over escaped chars. - * For WIN32 backslashes before normal - * file name characters are not removed, and keep - * backslash at start, for "\\machine\path", but - * do remove it for "\\\\machine\\path". - * The reverse is found in ExpandOldSetting(). - */ + // Copy the string, skip over escaped chars. + // For WIN32 backslashes before normal + // file name characters are not removed, and keep + // backslash at start, for "\\machine\path", but + // do remove it for "\\\\machine\\path". + // The reverse is found in ExpandOldSetting(). while (*arg && !ascii_iswhite(*arg)) { if (*arg == '\\' && arg[1] != NUL #ifdef BACKSLASH_IN_FILENAME @@ -1335,11 +1306,9 @@ int do_set(char *arg, int opt_flags) } *s = NUL; - /* - * Expand environment variables and ~. - * Don't do it when adding without inserting a - * comma. - */ + // Expand environment variables and ~. + // Don't do it when adding without inserting a + // comma. if (!(adding || prepending || removing) || (flags & P_COMMA)) { s = option_expand(opt_idx, newval); @@ -1521,12 +1490,10 @@ int do_set(char *arg, int opt_flags) } skip: - /* - * Advance to next argument. - * - skip until a blank found, taking care of backslashes - * - skip blanks - * - skip one "=val" argument (for hidden options ":set gfn =xx") - */ + // Advance to next argument. + // - skip until a blank found, taking care of backslashes + // - skip blanks + // - skip one "=val" argument (for hidden options ":set gfn =xx") for (i = 0; i < 2; i++) { while (*arg != NUL && !ascii_iswhite(*arg)) { if (*arg++ == '\\' && *arg != NUL) { @@ -1629,10 +1596,8 @@ void did_set_title(void) /// @param opt_flags OPT_LOCAL and/or OPT_GLOBAL void set_options_bin(int oldval, int newval, int opt_flags) { - /* - * The option values that are changed when 'bin' changes are - * copied when 'bin is set and restored when 'bin' is reset. - */ + // The option values that are changed when 'bin' changes are + // copied when 'bin is set and restored when 'bin' is reset. if (newval) { if (!oldval) { // switched on if (!(opt_flags & OPT_GLOBAL)) { @@ -1735,12 +1700,10 @@ static char_u *option_expand(int opt_idx, char_u *val) return NULL; } - /* - * Expanding this with NameBuff, expand_env() must not be passed IObuff. - * Escape spaces when expanding 'tags', they are used to separate file - * names. - * For 'spellsuggest' expand after "file:". - */ + // Expanding this with NameBuff, expand_env() must not be passed IObuff. + // Escape spaces when expanding 'tags', they are used to separate file + // names. + // For 'spellsuggest' expand after "file:". expand_env_esc(val, (char_u *)NameBuff, MAXPATHL, (char_u **)options[opt_idx].var == &p_tags, false, (char_u **)options[opt_idx].var == (char_u **)&p_sps ? (char_u *)"file:" : @@ -2153,9 +2116,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va if ((int *)varp == &curwin->w_p_arab) { if (curwin->w_p_arab) { - /* - * 'arabic' is set, handle various sub-settings. - */ + // 'arabic' is set, handle various sub-settings. if (!p_tbidi) { // set rightleft mode if (!curwin->w_p_rl) { @@ -2186,9 +2147,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va // Force-set the necessary keymap for arabic. errmsg = set_option_value("keymap", 0L, "arabic", OPT_LOCAL); } else { - /* - * 'arabic' is reset, handle various sub-settings. - */ + // 'arabic' is reset, handle various sub-settings. if (!p_tbidi) { // reset rightleft mode if (curwin->w_p_rl) { @@ -2209,9 +2168,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va } } - /* - * End of handling side effects for bool options. - */ + // End of handling side effects for bool options. // after handling side effects, call autocommand @@ -3328,9 +3285,7 @@ static void showoptions(int all, int opt_flags) } } - /* - * display the items - */ + // display the items if (run == 1) { assert(Columns <= INT_MAX - GAP && Columns + GAP >= INT_MIN + 3 @@ -3467,15 +3422,13 @@ int makeset(FILE *fd, int opt_flags, int local_only) int round; int pri; - /* - * Some options are never written: - * - Options that don't have a default (terminal name, columns, lines). - * - Terminal options. - * - Hidden options. - * - * Do the loop over "options[]" twice: once for options with the - * P_PRI_MKRC flag and once without. - */ + // Some options are never written: + // - Options that don't have a default (terminal name, columns, lines). + // - Terminal options. + // - Hidden options. + // + // Do the loop over "options[]" twice: once for options with the + // P_PRI_MKRC flag and once without. for (pri = 1; pri >= 0; pri--) { for (p = &options[0]; p->fullname; p++) { if (!(p->flags & P_NO_MKRC) @@ -4400,10 +4353,8 @@ void buf_copy_options(buf_T *buf, int flags) int dont_do_help; int did_isk = false; - /* - * Skip this when the option defaults have not been set yet. Happens when - * main() allocates the first buffer. - */ + // Skip this when the option defaults have not been set yet. Happens when + // main() allocates the first buffer. if (p_cpo != NULL) { // // Always copy when entering and 'cpo' contains 'S'. @@ -4617,12 +4568,10 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_p_lw = empty_option; buf->b_p_menc = empty_option; - /* - * Don't copy the options set by ex_help(), use the saved values, - * when going from a help buffer to a non-help buffer. - * Don't touch these at all when BCO_NOHELP is used and going from - * or to a help buffer. - */ + // Don't copy the options set by ex_help(), use the saved values, + // when going from a help buffer to a non-help buffer. + // Don't touch these at all when BCO_NOHELP is used and going from + // or to a help buffer. if (dont_do_help) { buf->b_p_isk = (char *)save_p_isk; if (p_vts && p_vts != empty_option && !buf->b_p_vts_array) { @@ -4652,10 +4601,8 @@ void buf_copy_options(buf_T *buf, int flags) } } - /* - * When the options should be copied (ignoring BCO_ALWAYS), set the - * flag that indicates that the options have been initialized. - */ + // When the options should be copied (ignoring BCO_ALWAYS), set the + // flag that indicates that the options have been initialized. if (should_copy) { buf->b_p_initialized = true; } @@ -4947,9 +4894,7 @@ void ExpandOldSetting(int *num_file, char ***file) *num_file = 0; *file = xmalloc(sizeof(char_u *)); - /* - * For a terminal key code expand_option_idx is < 0. - */ + // For a terminal key code expand_option_idx is < 0. if (expand_option_idx < 0) { expand_option_idx = findoption((const char *)expand_option_name); } @@ -5055,10 +5000,8 @@ static void paste_option_changed(void) static int save_hkmap = 0; if (p_paste) { - /* - * Paste switched from off to on. - * Save the current values, so they can be restored later. - */ + // Paste switched from off to on. + // Save the current values, so they can be restored later. if (!old_p_paste) { // save options for each buffer FOR_ALL_BUFFERS(buf) { diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index 6af6b16e86..bfac0cff87 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -379,9 +379,7 @@ enum { #define LISPWORD_VALUE \ "defun,define,defmacro,set!,lambda,if,case,let,flet,let*,letrec,do,do*,define-syntax,let-syntax,letrec-syntax,destructuring-bind,defpackage,defparameter,defstruct,deftype,defvar,do-all-symbols,do-external-symbols,do-symbols,dolist,dotimes,ecase,etypecase,eval-when,labels,macrolet,multiple-value-bind,multiple-value-call,multiple-value-prog1,multiple-value-setq,prog1,progv,typecase,unless,unwind-protect,when,with-input-from-string,with-open-file,with-open-stream,with-output-to-string,with-package-iterator,define-condition,handler-bind,handler-case,restart-bind,restart-case,with-simple-restart,store-value,use-value,muffle-warning,abort,continue,with-slots,with-slots*,with-accessors,with-accessors*,defclass,defmethod,print-unreadable-object" -/* - * The following are actual variables for the options - */ +// The following are actual variables for the options EXTERN long p_aleph; // 'aleph' EXTERN char *p_ambw; ///< 'ambiwidth' @@ -924,11 +922,9 @@ enum { BV_COUNT, // must be the last one }; -/* - * "indir" values for window-local options. - * These need to be defined globally, so that the WV_COUNT can be used in the - * window structure. - */ +// "indir" values for window-local options. +// These need to be defined globally, so that the WV_COUNT can be used in the +// window structure. enum { WV_LIST = 0, WV_ARAB, diff --git a/src/nvim/path.c b/src/nvim/path.c index e6de5388e0..607f1fc09a 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -248,9 +248,7 @@ int vim_ispathsep(int c) #endif } -/* - * Like vim_ispathsep(c), but exclude the colon for MS-Windows. - */ +// Like vim_ispathsep(c), but exclude the colon for MS-Windows. int vim_ispathsep_nocolon(int c) { return vim_ispathsep(c) @@ -532,9 +530,7 @@ bool path_has_wildcard(const char *p) return false; } -/* - * Unix style wildcard expansion code. - */ +// Unix style wildcard expansion code. static int pstrcmp(const void *a, const void *b) { return pathcmp(*(char **)a, *(char **)b, -1); @@ -779,10 +775,8 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, return matches; } -/* - * Moves "*psep" back to the previous path separator in "path". - * Returns FAIL is "*psep" ends up at the beginning of "path". - */ +// Moves "*psep" back to the previous path separator in "path". +// Returns FAIL is "*psep" ends up at the beginning of "path". static int find_previous_pathsep(char_u *path, char_u **psep) { // skip the current separator @@ -825,15 +819,13 @@ static bool is_unique(char_u *maybe_unique, garray_T *gap, int i) return true; // no match found } -/* - * Split the 'path' option into an array of strings in garray_T. Relative - * paths are expanded to their equivalent fullpath. This includes the "." - * (relative to current buffer directory) and empty path (relative to current - * directory) notations. - * - * TODO: handle upward search (;) and path limiter (**N) notations by - * expanding each into their equivalent path(s). - */ +// Split the 'path' option into an array of strings in garray_T. Relative +// paths are expanded to their equivalent fullpath. This includes the "." +// (relative to current buffer directory) and empty path (relative to current +// directory) notations. +// +// TODO(vim): handle upward search (;) and path limiter (**N) notations by +// expanding each into their equivalent path(s). static void expand_path_option(char_u *curdir, garray_T *gap) { char_u *path_option = *curbuf->b_p_path == NUL ? p_path : (char_u *)curbuf->b_p_path; @@ -883,14 +875,12 @@ static void expand_path_option(char_u *curdir, garray_T *gap) xfree(buf); } -/* - * Returns a pointer to the file or directory name in "fname" that matches the - * longest path in "ga"p, or NULL if there is no match. For example: - * - * path: /foo/bar/baz - * fname: /foo/bar/baz/quux.txt - * returns: ^this - */ +// Returns a pointer to the file or directory name in "fname" that matches the +// longest path in "ga"p, or NULL if there is no match. For example: +// +// path: /foo/bar/baz +// fname: /foo/bar/baz/quux.txt +// returns: ^this static char_u *get_path_cutoff(char_u *fname, garray_T *gap) { int maxlen = 0; @@ -924,11 +914,9 @@ static char_u *get_path_cutoff(char_u *fname, garray_T *gap) return cutoff; } -/* - * Sorts, removes duplicates and modifies all the fullpath names in "gap" so - * that they are unique with respect to each other while conserving the part - * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len". - */ +// Sorts, removes duplicates and modifies all the fullpath names in "gap" so +// that they are unique with respect to each other while conserving the part +// that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len". static void uniquefy_paths(garray_T *gap, char_u *pattern) { char_u **fnames = (char_u **)gap->ga_data; @@ -1212,26 +1200,23 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i int add_pat; bool did_expand_in_path = false; - /* - * expand_env() is called to expand things like "~user". If this fails, - * it calls ExpandOne(), which brings us back here. In this case, always - * call the machine specific expansion function, if possible. Otherwise, - * return FAIL. - */ - if (recursive) + // expand_env() is called to expand things like "~user". If this fails, + // it calls ExpandOne(), which brings us back here. In this case, always + // call the machine specific expansion function, if possible. Otherwise, + // return FAIL. + if (recursive) { #ifdef SPECIAL_WILDCHAR - { return os_expand_wildcards(num_pat, pat, num_file, file, flags); } + return os_expand_wildcards(num_pat, pat, num_file, file, flags); #else - { return FAIL; } + return FAIL; #endif + } #ifdef SPECIAL_WILDCHAR - /* - * If there are any special wildcard characters which we cannot handle - * here, call machine specific function for all the expansion. This - * avoids starting the shell for each argument separately. - * For `=expr` do use the internal function. - */ + // If there are any special wildcard characters which we cannot handle + // here, call machine specific function for all the expansion. This + // avoids starting the shell for each argument separately. + // For `=expr` do use the internal function. for (int i = 0; i < num_pat; i++) { if (has_special_wildchar((char_u *)pat[i]) && !(vim_backtick((char_u *)pat[i]) && pat[i][1] == '=')) { @@ -1242,9 +1227,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i recursive = true; - /* - * The matching file names are stored in a growarray. Init it empty. - */ + // The matching file names are stored in a growarray. Init it empty. ga_init(&ga, (int)sizeof(char_u *), 30); for (int i = 0; i < num_pat && !got_int; i++) { @@ -1266,31 +1249,28 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i p = expand_env_save_opt(p, true); if (p == NULL) { p = (char_u *)pat[i]; - } + } else { #ifdef UNIX - /* - * On Unix, if expand_env() can't expand an environment - * variable, use the shell to do that. Discard previously - * found file names and start all over again. - */ - else if (has_env_var(p) || *p == '~') { - xfree(p); - ga_clear_strings(&ga); - i = os_expand_wildcards(num_pat, pat, num_file, file, - flags | EW_KEEPDOLLAR); - recursive = false; - return i; - } + // On Unix, if expand_env() can't expand an environment + // variable, use the shell to do that. Discard previously + // found file names and start all over again. + if (has_env_var(p) || *p == '~') { + xfree(p); + ga_clear_strings(&ga); + i = os_expand_wildcards(num_pat, pat, num_file, file, + flags | EW_KEEPDOLLAR); + recursive = false; + return i; + } #endif + } } - /* - * If there are wildcards: Expand file names and add each match to - * the list. If there is no match, and EW_NOTFOUND is given, add - * the pattern. - * If there are no wildcards: Add the file name if it exists or - * when EW_NOTFOUND is given. - */ + // If there are wildcards: Expand file names and add each match to + // the list. If there is no match, and EW_NOTFOUND is given, add + // the pattern. + // If there are no wildcards: Add the file name if it exists or + // when EW_NOTFOUND is given. if (path_has_exp_wildcard(p)) { if ((flags & EW_PATH) && !path_is_absolute(p) @@ -1491,21 +1471,17 @@ void addfile(garray_T *gap, char_u *f, int flags) #ifdef BACKSLASH_IN_FILENAME slash_adjust(p); #endif - /* - * Append a slash or backslash after directory names if none is present. - */ + // Append a slash or backslash after directory names if none is present. if (isdir && (flags & EW_ADDSLASH)) { add_pathsep((char *)p); } GA_APPEND(char_u *, gap, p); } -/* - * Converts a file name into a canonical form. It simplifies a file name into - * its simplest form by stripping out unneeded components, if any. The - * resulting file name is simplified in place and will either be the same - * length as that supplied, or shorter. - */ +// Converts a file name into a canonical form. It simplifies a file name into +// its simplest form by stripping out unneeded components, if any. The +// resulting file name is simplified in place and will either be the same +// length as that supplied, or shorter. void simplify_filename(char_u *filename) { int components = 0; @@ -1704,10 +1680,8 @@ char *find_file_name_in_path(char *ptr, size_t len, int options, long count, cha file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS, true, (char_u *)rel_fname); - /* - * If the file could not be found in a normal way, try applying - * 'includeexpr' (unless done already). - */ + // If the file could not be found in a normal way, try applying + // 'includeexpr' (unless done already). if (file_name == NULL && !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL) { tofree = eval_includeexpr(ptr, len); @@ -1976,11 +1950,9 @@ bool same_directory(char_u *f1, char_u *f2) && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0; } -/* - * Compare path "p[]" to "q[]". - * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]" - * Return value like strcmp(p, q), but consider path separators. - */ +// Compare path "p[]" to "q[]". +// If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]" +// Return value like strcmp(p, q), but consider path separators. int pathcmp(const char *p, const char *q, int maxlen) { int i, j; @@ -2185,9 +2157,7 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int return retval; } - /* - * Remove names that match 'wildignore'. - */ + // Remove names that match 'wildignore'. if (*p_wig) { char_u *ffname; diff --git a/src/nvim/path.h b/src/nvim/path.h index 1006ef9ffb..37a0883c7f 100644 --- a/src/nvim/path.h +++ b/src/nvim/path.h @@ -18,8 +18,8 @@ #define EW_NOERROR 0x200 // no error for bad regexp #define EW_NOTWILD 0x400 // add match with literal name if exists #define EW_KEEPDOLLAR 0x800 // do not escape $, $var is expanded -/* Note: mostly EW_NOTFOUND and EW_SILENT are mutually exclusive: EW_NOTFOUND -* is used when executing commands and EW_SILENT for interactive expanding. */ +// Note: mostly EW_NOTFOUND and EW_SILENT are mutually exclusive: EW_NOTFOUND +// is used when executing commands and EW_SILENT for interactive expanding. #define EW_ALLLINKS 0x1000 // also links not pointing to existing file #define EW_SHELLCMD 0x2000 // called from expand_shellcmd(), don't check // if executable is in $PATH diff --git a/src/nvim/search.c b/src/nvim/search.c index 5c1fe3a657..490e79ebb0 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * search.c: code for normal mode searching commands - */ +// search.c: code for normal mode searching commands #include #include @@ -106,10 +104,8 @@ static bool saved_spats_no_hlsearch = false; static char_u *mr_pattern = NULL; // pattern used by search_regcomp() static bool mr_pattern_alloced = false; // mr_pattern was allocated -/* - * Type used by find_pattern_in_path() to remember which included files have - * been searched already. - */ +// Type used by find_pattern_in_path() to remember which included files have +// been searched already. typedef struct SearchedFile { FILE *fp; // File pointer char_u *name; // Full name of file @@ -139,9 +135,7 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc rc_did_emsg = false; magic = p_magic; - /* - * If no pattern given, use a previously defined pattern. - */ + // If no pattern given, use a previously defined pattern. if (pat == NULL || *pat == NUL) { if (pat_use == RE_LAST) { i = last_idx; @@ -176,10 +170,8 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc mr_pattern = pat; } - /* - * Save the currently used pattern in the appropriate place, - * unless the pattern should not be remembered. - */ + // Save the currently used pattern in the appropriate place, + // unless the pattern should not be remembered. if (!(options & SEARCH_KEEP) && (cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) { // search or global command if (pat_save == RE_SEARCH || pat_save == RE_BOTH) { @@ -200,9 +192,7 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc return OK; } -/* - * Get search pattern used by search_regcomp(). - */ +// Get search pattern used by search_regcomp(). char_u *get_search_pat(void) { return mr_pattern; @@ -226,10 +216,8 @@ void save_re_pat(int idx, char_u *pat, int magic) } } -/* - * Save the search patterns, so they can be restored later. - * Used before/after executing autocommands and user functions. - */ +// Save the search patterns, so they can be restored later. +// Used before/after executing autocommands and user functions. static int save_level = 0; void save_search_patterns(void) @@ -450,19 +438,15 @@ char_u *last_search_pat(void) return spats[last_idx].pat; } -/* - * Reset search direction to forward. For "gd" and "gD" commands. - */ +// Reset search direction to forward. For "gd" and "gD" commands. void reset_search_dir(void) { spats[0].off.dir = '/'; set_vv_searchforward(); } -/* - * Set the last search pattern. For ":let @/ =" and ShaDa file. - * Also set the saved search pattern, so that this works in an autocommand. - */ +// Set the last search pattern. For ":let @/ =" and ShaDa file. +// Also set the saved search pattern, so that this works in an autocommand. void set_last_search_pat(const char_u *s, int idx, int magic, int setlast) { free_spat(&spats[idx]); @@ -500,11 +484,9 @@ void set_last_search_pat(const char_u *s, int idx, int magic, int setlast) } } -/* - * Get a regexp program for the last used search pattern. - * This is used for highlighting all matches in a window. - * Values returned in regmatch->regprog and regmatch->rmm_ic. - */ +// Get a regexp program for the last used search pattern. +// This is used for highlighting all matches in a window. +// Values returned in regmatch->regprog and regmatch->rmm_ic. void last_pat_prog(regmmatch_T *regmatch) { if (spats[last_idx].pat == NULL) { @@ -578,9 +560,7 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, return FAIL; } - /* - * find the string - */ + // find the string do { // loop for count // When not accepting a match at the start position set "extra_col" to a // non-zero value. Don't do that when starting at MAXCOL, since MAXCOL + 1 @@ -615,13 +595,11 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, at_first_line = false; // not in first line now } - /* - * Start searching in current line, unless searching backwards and - * we're in column 0. - * If we are searching backwards, in column 0, and not including the - * current position, gain some efficiency by skipping back a line. - * Otherwise begin the search in the current line. - */ + // Start searching in current line, unless searching backwards and + // we're in column 0. + // If we are searching backwards, in column 0, and not including the + // current position, gain some efficiency by skipping back a line. + // Otherwise begin the search in the current line. if (dir == BACKWARD && start_pos.col == 0 && (options & SEARCH_START) == 0) { lnum = pos->lnum - 1; @@ -667,11 +645,9 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, ptr = ml_get_buf(buf, lnum + matchpos.lnum, false); } - /* - * Forward search in the first line: match should be after - * the start position. If not, continue at the end of the - * match (this is vi compatible) or on the next char. - */ + // Forward search in the first line: match should be after + // the start position. If not, continue at the end of the + // match (this is vi compatible) or on the next char. if (dir == FORWARD && at_first_line) { match_ok = true; // When the match starts in a next line it's certainly @@ -687,11 +663,9 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, : ((int)matchpos.col - (ptr[matchpos.col] == NUL) < (int)start_pos.col + extra_col))) { - /* - * If vi-compatible searching, continue at the end - * of the match, otherwise continue one position - * forward. - */ + // If vi-compatible searching, continue at the end + // of the match, otherwise continue one position + // forward. if (vim_strchr(p_cpo, CPO_SEARCH) != NULL) { if (nmatched > 1) { // end is in next line, thus no match in @@ -744,13 +718,11 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, } } if (dir == BACKWARD) { - /* - * Now, if there are multiple matches on this line, - * we have to get the last one. Or the last one before - * the cursor, if we're on that line. - * When putting the new cursor at the end, compare - * relative to the end of the match. - */ + // Now, if there are multiple matches on this line, + // we have to get the last one. Or the last one before + // the cursor, if we're on that line. + // When putting the new cursor at the end, compare + // relative to the end of the match. match_ok = false; for (;;) { // Remember a position that is before the start @@ -825,10 +797,8 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, ptr = ml_get_buf(buf, lnum + matchpos.lnum, false); } - /* - * If there is only a match after the cursor, skip - * this match. - */ + // If there is only a match after the cursor, skip + // this match. if (!match_ok) { continue; } @@ -1042,25 +1012,19 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, size_t len; bool has_offset = false; - /* - * A line offset is not remembered, this is vi compatible. - */ + // A line offset is not remembered, this is vi compatible. if (spats[0].off.line && vim_strchr(p_cpo, CPO_LINEOFF) != NULL) { spats[0].off.line = false; spats[0].off.off = 0; } - /* - * Save the values for when (options & SEARCH_KEEP) is used. - * (there is no "if ()" around this because gcc wants them initialized) - */ + // Save the values for when (options & SEARCH_KEEP) is used. + // (there is no "if ()" around this because gcc wants them initialized) old_off = spats[0].off; pos = curwin->w_cursor; // start searching at the cursor position - /* - * Find out the direction of the search. - */ + // Find out the direction of the search. if (dirc == 0) { dirc = (char_u)spats[0].off.dir; } else { @@ -1087,17 +1051,13 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, } } - /* - * Turn 'hlsearch' highlighting back on. - */ + // Turn 'hlsearch' highlighting back on. if (no_hlsearch && !(options & SEARCH_KEEP)) { redraw_all_later(UPD_SOME_VALID); set_no_hlsearch(false); } - /* - * Repeat the search when pattern followed by ';', e.g. "/foo/;?bar". - */ + // Repeat the search when pattern followed by ';', e.g. "/foo/;?bar". for (;;) { bool show_top_bot_msg = false; @@ -1119,10 +1079,8 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, } if (pat != NULL && *pat != NUL) { // look for (new) offset - /* - * Find end of regular expression. - * If there is a matching '/' or '?', toss it. - */ + // Find end of regular expression. + // If there is a matching '/' or '?', toss it. ps = (char_u *)strcopy; p = (char_u *)skip_regexp((char *)pat, search_delim, p_magic, &strcopy); if (strcopy != (char *)ps) { @@ -1287,13 +1245,11 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, } } - /* - * If there is a character offset, subtract it from the current - * position, so we don't get stuck at "?pat?e+2" or "/pat/s-2". - * Skip this if pos.col is near MAXCOL (closed fold). - * This is not done for a line offset, because then we would not be vi - * compatible. - */ + // If there is a character offset, subtract it from the current + // position, so we don't get stuck at "?pat?e+2" or "/pat/s-2". + // Skip this if pos.col is near MAXCOL (closed fold). + // This is not done for a line offset, because then we would not be vi + // compatible. if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2) { if (spats[0].off.off > 0) { for (c = spats[0].off.off; c; c--) { @@ -1350,9 +1306,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, apply_autocmds(EVENT_SEARCHWRAPPED, NULL, NULL, false, NULL); } - /* - * Add character and/or line offset - */ + // Add character and/or line offset if (!(options & SEARCH_NOOF) || (pat != NULL && *pat == ';')) { pos_T org_pos = pos; @@ -1444,15 +1398,13 @@ end_do_search: return retval; } -/* - * search_for_exact_line(buf, pos, dir, pat) - * - * Search for a line starting with the given pattern (ignoring leading - * white-space), starting from pos and going in direction "dir". "pos" will - * contain the position of the match found. Blank lines match only if - * ADDING is set. If p_ic is set then the pattern must be in lowercase. - * Return OK for success, or FAIL if no line found. - */ +// search_for_exact_line(buf, pos, dir, pat) +// +// Search for a line starting with the given pattern (ignoring leading +// white-space), starting from pos and going in direction "dir". "pos" will +// contain the position of the match found. Blank lines match only if +// ADDING is set. If p_ic is set then the pattern must be in lowercase. +// Return OK for success, or FAIL if no line found. int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) { linenr_T start = 0; @@ -1513,9 +1465,7 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) return FAIL; } -/* - * Character Searches - */ +// Character Searches /// Search for a character in a line. If "t_cmd" is false, move to the /// position of the character, otherwise move to just before the char. @@ -1618,15 +1568,11 @@ int searchc(cmdarg_T *cap, int t_cmd) return OK; } -/* - * "Other" Searches - */ +// "Other" Searches -/* - * findmatch - find the matching paren or brace - * - * Improvement over vi: Braces inside quotes are ignored. - */ +// findmatch - find the matching paren or brace +// +// Improvement over vi: Braces inside quotes are ignored. pos_T *findmatch(oparg_T *oap, int initc) { return findmatchlimit(oap, initc, 0, 0); @@ -1725,27 +1671,24 @@ static void find_mps_values(int *initc, int *findc, bool *backwards, bool switch } } -/* - * findmatchlimit -- find the matching paren or brace, if it exists within - * maxtravel lines of the cursor. A maxtravel of 0 means search until falling - * off the edge of the file. - * - * "initc" is the character to find a match for. NUL means to find the - * character at or after the cursor. Special values: - * '*' look for C-style comment / * - * '/' look for C-style comment / *, ignoring comment-end - * '#' look for preprocessor directives - * 'R' look for raw string start: R"delim(text)delim" (only backwards) - * - * flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#') - * FM_FORWARD search forwards (when initc is '/', '*' or '#') - * FM_BLOCKSTOP stop at start/end of block ({ or } in column 0) - * FM_SKIPCOMM skip comments (not implemented yet!) - * - * "oap" is only used to set oap->motion_type for a linewise motion, it can be - * NULL - */ - +// findmatchlimit -- find the matching paren or brace, if it exists within +// maxtravel lines of the cursor. A maxtravel of 0 means search until falling +// off the edge of the file. +// +// "initc" is the character to find a match for. NUL means to find the +// character at or after the cursor. Special values: +// '*' look for C-style comment / * +// '/' look for C-style comment / *, ignoring comment-end +// '#' look for preprocessor directives +// 'R' look for raw string start: R"delim(text)delim" (only backwards) +// +// flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#') +// FM_FORWARD search forwards (when initc is '/', '*' or '#') +// FM_BLOCKSTOP stop at start/end of block ({ or } in column 0) +// FM_SKIPCOMM skip comments (not implemented yet!) +// +// "oap" is only used to set oap->motion_type for a linewise motion, it can be +// NULL pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) { static pos_T pos; // current search position @@ -1783,12 +1726,10 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) dir = 0; } - /* - * if initc given, look in the table for the matching character - * '/' and '*' are special cases: look for start or end of comment. - * When '/' is used, we ignore running backwards into a star-slash, for - * "[*" command, we just want to find any comment. - */ + // if initc given, look in the table for the matching character + // '/' and '*' are special cases: look for start or end of comment. + // When '/' is used, we ignore running backwards into a star-slash, for + // "[*" command, we just want to find any comment. if (initc == '/' || initc == '*' || initc == 'R') { comment_dir = dir; if (initc == '/') { @@ -1806,18 +1747,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) return NULL; } } else { - /* - * Either initc is '#', or no initc was given and we need to look - * under the cursor. - */ + // Either initc is '#', or no initc was given and we need to look + // under the cursor. if (initc == '#') { hash_dir = dir; } else { - /* - * initc was not given, must look for something to match under - * or near the cursor. - * Only check for special things when 'cpo' doesn't have '%'. - */ + // initc was not given, must look for something to match under + // or near the cursor. + // Only check for special things when 'cpo' doesn't have '%'. if (!cpo_match) { // Are we before or at #if, #else etc.? ptr = (char_u *)skipwhite((char *)linep); @@ -1851,16 +1788,12 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } } - /* - * If we are not on a comment or the # at the start of a line, then - * look for brace anywhere on this line after the cursor. - */ + // If we are not on a comment or the # at the start of a line, then + // look for brace anywhere on this line after the cursor. if (!hash_dir && !comment_dir) { - /* - * Find the brace under or after the cursor. - * If beyond the end of the line, use the last character in - * the line. - */ + // Find the brace under or after the cursor. + // If beyond the end of the line, use the last character in + // the line. if (linep[pos.col] == NUL && pos.col) { pos.col--; } @@ -1896,9 +1829,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } } if (hash_dir) { - /* - * Look for matching #if, #else, #elif, or #endif - */ + // Look for matching #if, #else, #elif, or #endif if (oap != NULL) { oap->motion_type = kMTLineWise; // Linewise for this case only } @@ -1983,10 +1914,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } while (!got_int) { - /* - * Go to the next position, forward or backward. We could use - * inc() and dec() here, but that is much slower - */ + // Go to the next position, forward or backward. We could use + // inc() and dec() here, but that is much slower if (backwards) { // char to match is inside of comment, don't search outside if (lispcomm && pos.col < (colnr_T)comment_col) { @@ -2067,10 +1996,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) return &pos; } } else { // Searching backwards - /* - * A comment may contain / * or / /, it may also start or end - * with / * /. Ignore a / * after / / and after *. - */ + // A comment may contain / * or / /, it may also start or end + // with / * /. Ignore a / * after / / and after *. if (pos.col == 0) { continue; } else if (raw_string) { @@ -2113,18 +2040,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) continue; } - /* - * If smart matching ('cpoptions' does not contain '%'), braces inside - * of quotes are ignored, but only if there is an even number of - * quotes in the line. - */ + // If smart matching ('cpoptions' does not contain '%'), braces inside + // of quotes are ignored, but only if there is an even number of + // quotes in the line. if (cpo_match) { do_quotes = 0; } else if (do_quotes == -1) { - /* - * Count the number of quotes in the line, skipping \" and '"'. - * Watch out for "\\". - */ + // Count the number of quotes in the line, skipping \" and '"'. + // Watch out for "\\". at_start = do_quotes; for (ptr = linep; *ptr; ptr++) { if (ptr == linep + pos.col + backwards) { @@ -2140,10 +2063,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } do_quotes &= 1; // result is 1 with even number of quotes - /* - * If we find an uneven count, check current line and previous - * one for a '\' at the end. - */ + // If we find an uneven count, check current line and previous + // one for a '\' at the end. if (!do_quotes) { inquote = false; if (ptr[-1] == '\\') { @@ -2179,17 +2100,15 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) start_in_quotes = kFalse; } - /* - * If 'smartmatch' is set: - * Things inside quotes are ignored by setting 'inquote'. If we - * find a quote without a preceding '\' invert 'inquote'. At the - * end of a line not ending in '\' we reset 'inquote'. - * - * In lines with an uneven number of quotes (without preceding '\') - * we do not know which part to ignore. Therefore we only set - * inquote if the number of quotes in a line is even, unless this - * line or the previous one ends in a '\'. Complicated, isn't it? - */ + // If 'smartmatch' is set: + // Things inside quotes are ignored by setting 'inquote'. If we + // find a quote without a preceding '\' invert 'inquote'. At the + // end of a line not ending in '\' we reset 'inquote'. + // + // In lines with an uneven number of quotes (without preceding '\') + // we do not know which part to ignore. Therefore we only set + // inquote if the number of quotes in a line is even, unless this + // line or the previous one ends in a '\'. Complicated, isn't it? const int c = utf_ptr2char((char *)linep + pos.col); switch (c) { case NUL: @@ -2218,13 +2137,11 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } break; - /* - * If smart matching ('cpoptions' does not contain '%'): - * Skip things in single quotes: 'x' or '\x'. Be careful for single - * single quotes, eg jon's. Things like '\233' or '\x3f' are not - * skipped, there is never a brace in them. - * Ignore this when finding matches for `'. - */ + // If smart matching ('cpoptions' does not contain '%'): + // Skip things in single quotes: 'x' or '\x'. Be careful for single + // single quotes, eg jon's. Things like '\233' or '\x3f' are not + // skipped, there is never a brace in them. + // Ignore this when finding matches for `'. case '\'': if (!cpo_match && initc != '\'' && findc != '\'') { if (backwards) { @@ -2252,10 +2169,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) FALLTHROUGH; default: - /* - * For Lisp skip over backslashed (), {} and []. - * (actually, we skip #\( et al) - */ + // For Lisp skip over backslashed (), {} and []. + // (actually, we skip #\( et al) if (curbuf->b_p_lisp && vim_strchr("(){}[]", c) != NULL && pos.col > 1 @@ -2367,9 +2282,7 @@ void showmatch(int c) colnr_T save_dollar_vcol; char_u *p; - /* - * Only show match for chars in the 'matchpairs' option. - */ + // Only show match for chars in the 'matchpairs' option. // 'matchpairs' is "x:y,x:y" for (p = (char_u *)curbuf->b_p_mps; *p != NUL; p++) { if (utf_ptr2char((char *)p) == c && (curwin->w_p_rl ^ p_ri)) { @@ -2425,10 +2338,8 @@ void showmatch(int c) // and has a higher column number. dollar_vcol = save_dollar_vcol; - /* - * brief pause, unless 'm' is present in 'cpo' and a character is - * available. - */ + // brief pause, unless 'm' is present in 'cpo' and a character is + // available. if (vim_strchr(p_cpo, CPO_SHOWMATCH) != NULL) { os_delay((uint64_t)p_mat * 100L + 8, true); } else if (!char_avail()) { @@ -3667,10 +3578,8 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo // 'includeexpr' is set. msg_outtrans_attr((char *)new_fname, HL_ATTR(HLF_D)); } else { - /* - * Isolate the file name. - * Include the surrounding "" or <> if present. - */ + // Isolate the file name. + // Include the surrounding "" or <> if present. if (inc_opt != NULL && strstr(inc_opt, "\\zs") != NULL) { // pattern contains \zs, use the match @@ -3763,9 +3672,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo } } } else { - /* - * Check if the line is a define (type == FIND_DEFINE) - */ + // Check if the line is a define (type == FIND_DEFINE) p = line; search_line: define_matched = false; @@ -3781,10 +3688,8 @@ search_line: define_matched = true; } - /* - * Look for a match. Don't do this if we are looking for a - * define and this line didn't match define_prog above. - */ + // Look for a match. Don't do this if we are looking for a + // define and this line didn't match define_prog above. if (def_regmatch.regprog == NULL || define_matched) { if (define_matched || compl_status_sol()) { // compare the first "len" chars from "ptr" @@ -3812,12 +3717,10 @@ search_line: matched = false; } - /* - * Also check for a "/ *" or "/ /" before the match. - * Skips lines like "int backwards; / * normal index - * * /" when looking for "normal". - * Note: Doesn't skip "/ *" in comments. - */ + // Also check for a "/ *" or "/ /" before the match. + // Skips lines like "int backwards; / * normal index + // * /" when looking for "normal". + // Note: Doesn't skip "/ *" in comments. p = (char_u *)skipwhite((char *)line); if (matched || (p[0] == '/' && p[1] == '*') || p[0] == '*') { @@ -4033,11 +3936,9 @@ exit_matched: break; } - /* - * Read the next line. When reading an included file and encountering - * end-of-file, close the file and continue in the file that included - * it. - */ + // Read the next line. When reading an included file and encountering + // end-of-file, close the file and continue in the file that included + // it. while (depth >= 0 && !already && vim_fgets(line = file_line, LSIZE, files[depth].fp)) { fclose(files[depth].fp); diff --git a/src/nvim/strings.c b/src/nvim/strings.c index 423436eccc..12bfa35dd6 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -65,28 +65,22 @@ char *xstrnsave(const char *string, size_t len) return strncpy(xmallocz(len), string, len); // NOLINT(runtime/printf) } -/* - * Same as vim_strsave(), but any characters found in esc_chars are preceded - * by a backslash. - */ +// Same as vim_strsave(), but any characters found in esc_chars are preceded +// by a backslash. char_u *vim_strsave_escaped(const char_u *string, const char_u *esc_chars) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { return vim_strsave_escaped_ext(string, esc_chars, '\\', false); } -/* - * Same as vim_strsave_escaped(), but when "bsl" is true also escape - * characters where rem_backslash() would remove the backslash. - * Escape the characters with "cc". - */ +// Same as vim_strsave_escaped(), but when "bsl" is true also escape +// characters where rem_backslash() would remove the backslash. +// Escape the characters with "cc". char_u *vim_strsave_escaped_ext(const char_u *string, const char_u *esc_chars, char_u cc, bool bsl) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { - /* - * First count the number of backslashes required. - * Then allocate the memory and insert them. - */ + // First count the number of backslashes required. + // Then allocate the memory and insert them. size_t length = 1; // count the trailing NUL for (const char_u *p = string; *p; p++) { const size_t l = (size_t)(utfc_ptr2len((char *)p)); @@ -169,16 +163,14 @@ char *vim_strnsave_unquoted(const char *const string, const size_t length) return ret; } -/* - * Escape "string" for use as a shell argument with system(). - * This uses single quotes, except when we know we need to use double quotes - * (MS-Windows without 'shellslash' set). - * Escape a newline, depending on the 'shell' option. - * When "do_special" is true also replace "!", "%", "#" and things starting - * with "<" like "". - * When "do_newline" is false do not escape newline unless it is csh shell. - * Returns the result in allocated memory. - */ +// Escape "string" for use as a shell argument with system(). +// This uses single quotes, except when we know we need to use double quotes +// (MS-Windows without 'shellslash' set). +// Escape a newline, depending on the 'shell' option. +// When "do_special" is true also replace "!", "%", "#" and things starting +// with "<" like "". +// When "do_newline" is false do not escape newline unless it is csh shell. +// Returns the result in allocated memory. char_u *vim_strsave_shellescape(const char_u *string, bool do_special, bool do_newline) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { @@ -295,10 +287,8 @@ char_u *vim_strsave_shellescape(const char_u *string, bool do_special, bool do_n return escaped_string; } -/* - * Like vim_strsave(), but make all characters uppercase. - * This uses ASCII lower-to-upper case translation, language independent. - */ +// Like vim_strsave(), but make all characters uppercase. +// This uses ASCII lower-to-upper case translation, language independent. char_u *vim_strsave_up(const char_u *string) FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { @@ -319,9 +309,7 @@ char *vim_strnsave_up(const char *string, size_t len) return p1; } -/* - * ASCII lower-to-upper case translation, language independent. - */ +// ASCII lower-to-upper case translation, language independent. void vim_strup(char_u *p) FUNC_ATTR_NONNULL_ALL { @@ -375,9 +363,7 @@ char *strcase_save(const char *const orig, bool upper) return res; } -/* - * delete spaces at the end of a string - */ +// delete spaces at the end of a string void del_trailing_spaces(char_u *ptr) FUNC_ATTR_NONNULL_ALL { @@ -402,11 +388,9 @@ size_t xstrnlen(const char *s, size_t n) #endif #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) -/* - * Compare two strings, ignoring case, using current locale. - * Doesn't work for multi-byte characters. - * return 0 for match, < 0 for smaller, > 0 for bigger - */ +// Compare two strings, ignoring case, using current locale. +// Doesn't work for multi-byte characters. +// return 0 for match, < 0 for smaller, > 0 for bigger int vim_stricmp(const char *s1, const char *s2) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE { @@ -428,11 +412,9 @@ int vim_stricmp(const char *s1, const char *s2) #endif #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) -/* - * Compare two strings, for length "len", ignoring case, using current locale. - * Doesn't work for multi-byte characters. - * return 0 for match, < 0 for smaller, > 0 for bigger - */ +// Compare two strings, for length "len", ignoring case, using current locale. +// Doesn't work for multi-byte characters. +// return 0 for match, < 0 for smaller, > 0 for bigger int vim_strnicmp(const char *s1, const char *s2, size_t len) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE { @@ -477,9 +459,7 @@ char *vim_strchr(const char *const string, const int c) } } -/* - * Sort an array of strings. - */ +// Sort an array of strings. #ifdef INCLUDE_GENERATED_DECLARATIONS # include "strings.c.generated.h" @@ -495,10 +475,8 @@ void sort_strings(char **files, int count) qsort((void *)files, (size_t)count, sizeof(char *), sort_compare); } -/* - * Return true if string "s" contains a non-ASCII character (128 or higher). - * When "s" is NULL false is returned. - */ +// Return true if string "s" contains a non-ASCII character (128 or higher). +// When "s" is NULL false is returned. bool has_non_ascii(const char_u *s) FUNC_ATTR_PURE { diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index 9eb412b803..fedd053e88 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * syntax.c: code for syntax highlighting - */ +// syntax.c: code for syntax highlighting #include #include @@ -104,11 +102,9 @@ typedef struct syn_cluster_S { int16_t *scl_list; // IDs in this syntax cluster } syn_cluster_T; -/* - * For the current state we need to remember more than just the idx. - * When si_m_endpos.lnum is 0, the items other than si_idx are unknown. - * (The end positions have the column number of the next char) - */ +// For the current state we need to remember more than just the idx. +// When si_m_endpos.lnum is 0, the items other than si_idx are unknown. +// (The end positions have the column number of the next char) typedef struct state_item { int si_idx; // index of syntax pattern or // KEYWORD_IDX @@ -133,10 +129,8 @@ typedef struct state_item { // pattern } stateitem_T; -/* - * Struct to reduce the number of arguments to get_syn_options(), it's used - * very often. - */ +// Struct to reduce the number of arguments to get_syn_options(), it's used +// very often. typedef struct { int flags; // flags for contained and transparent bool keyword; // true for ":syn keyword" @@ -184,9 +178,7 @@ static char *(spo_name_tab[SPO_COUNT]) = #define NONE_IDX (-2) // value of sp_sync_idx for "NONE" -/* - * Flags for b_syn_sync_flags: - */ +// Flags for b_syn_sync_flags: #define SF_CCOMMENT 0x01 // sync on a C-style comment #define SF_MATCH 0x02 // sync by matching a pattern @@ -194,9 +186,7 @@ static char *(spo_name_tab[SPO_COUNT]) = #define MAXKEYWLEN 80 // maximum length of a keyword -/* - * The attributes of the syntax item that has been recognized. - */ +// The attributes of the syntax item that has been recognized. static int current_attr = 0; // attr of current syntax word static int current_id = 0; // ID of current char for syn_get_id() static int current_trans_id = 0; // idem, transparency removed @@ -204,23 +194,19 @@ static int current_flags = 0; static int current_seqnr = 0; static int current_sub_char = 0; -/* - * Methods of combining two clusters - */ +// Methods of combining two clusters #define CLUSTER_REPLACE 1 // replace first list with second #define CLUSTER_ADD 2 // add second list to first #define CLUSTER_SUBTRACT 3 // subtract second list from first #define SYN_CLSTR(buf) ((syn_cluster_T *)((buf)->b_syn_clusters.ga_data)) -/* - * Syntax group IDs have different types: - * 0 - 19999 normal syntax groups - * 20000 - 20999 ALLBUT indicator (current_syn_inc_tag added) - * 21000 - 21999 TOP indicator (current_syn_inc_tag added) - * 22000 - 22999 CONTAINED indicator (current_syn_inc_tag added) - * 23000 - 32767 cluster IDs (subtract SYNID_CLUSTER for the cluster ID) - */ +// Syntax group IDs have different types: +// 0 - 19999 normal syntax groups +// 20000 - 20999 ALLBUT indicator (current_syn_inc_tag added) +// 21000 - 21999 TOP indicator (current_syn_inc_tag added) +// 22000 - 22999 CONTAINED indicator (current_syn_inc_tag added) +// 23000 - 32767 cluster IDs (subtract SYNID_CLUSTER for the cluster ID) #define SYNID_ALLBUT MAX_HL_ID // syntax group ID for contains=ALLBUT #define SYNID_TOP 21000 // syntax group ID for contains=TOP #define SYNID_CONTAINED 22000 // syntax group ID for contains=CONTAINED @@ -234,21 +220,17 @@ static int current_sub_char = 0; // instead of passing it to them, we stow it here. static char **syn_cmdlinep; -/* - * Another Annoying Hack(TM): To prevent rules from other ":syn include"'d - * files from leaking into ALLBUT lists, we assign a unique ID to the - * rules in each ":syn include"'d file. - */ +// Another Annoying Hack(TM): To prevent rules from other ":syn include"'d +// files from leaking into ALLBUT lists, we assign a unique ID to the +// rules in each ":syn include"'d file. static int current_syn_inc_tag = 0; static int running_syn_inc_tag = 0; -/* - * In a hashtable item "hi_key" points to "keyword" in a keyentry. - * This avoids adding a pointer to the hashtable item. - * KE2HIKEY() converts a var pointer to a hashitem key pointer. - * HIKEY2KE() converts a hashitem key pointer to a var pointer. - * HI2KE() converts a hashitem pointer to a var pointer. - */ +// In a hashtable item "hi_key" points to "keyword" in a keyentry. +// This avoids adding a pointer to the hashtable item. +// KE2HIKEY() converts a var pointer to a hashitem key pointer. +// HIKEY2KE() converts a hashitem key pointer to a var pointer. +// HI2KE() converts a hashitem pointer to a var pointer. static keyentry_T dumkey; #define KE2HIKEY(kp) ((kp)->keyword) #define HIKEY2KE(p) ((keyentry_T *)((p) - (dumkey.keyword - (char_u *)&dumkey))) @@ -256,11 +238,9 @@ static keyentry_T dumkey; // -V:HI2KE:782 -/* - * To reduce the time spent in keepend(), remember at which level in the state - * stack the first item with "keepend" is present. When "-1", there is no - * "keepend" on the stack. - */ +// To reduce the time spent in keepend(), remember at which level in the state +// stack the first item with "keepend" is present. When "-1", there is no +// "keepend" on the stack. static int keepend_level = -1; static char msg_no_items[] = N_("No Syntax items defined for this buffer"); @@ -272,13 +252,11 @@ static char msg_no_items[] = N_("No Syntax items defined for this buffer"); static int next_seqnr = 1; // value to use for si_seqnr -/* - * The next possible match in the current line for any pattern is remembered, - * to avoid having to try for a match in each column. - * If next_match_idx == -1, not tried (in this line) yet. - * If next_match_col == MAXCOL, no match found in this line. - * (All end positions have the column of the char after the end) - */ +// The next possible match in the current line for any pattern is remembered, +// to avoid having to try for a match in each column. +// If next_match_idx == -1, not tried (in this line) yet. +// If next_match_col == MAXCOL, no match found in this line. +// (All end positions have the column of the char after the end) static int next_match_col; // column for start of next match static lpos_T next_match_m_endpos; // position for end of next match static lpos_T next_match_h_startpos; // pos. for highl. start of next match @@ -290,17 +268,13 @@ static lpos_T next_match_eoe_pos; // pos. for end of end pattern static int next_match_end_idx; // ID of group for end pattn or zero static reg_extmatch_T *next_match_extmatch = NULL; -/* - * A state stack is an array of integers or stateitem_T, stored in a - * garray_T. A state stack is invalid if its itemsize entry is zero. - */ +// A state stack is an array of integers or stateitem_T, stored in a +// garray_T. A state stack is invalid if its itemsize entry is zero. #define INVALID_STATE(ssp) ((ssp)->ga_itemsize == 0) #define VALID_STATE(ssp) ((ssp)->ga_itemsize != 0) -/* - * The current state (within the line) of the recognition engine. - * When current_state.ga_itemsize is 0 the current state is invalid. - */ +// The current state (within the line) of the recognition engine. +// When current_state.ga_itemsize is 0 the current state is invalid. static win_T *syn_win; // current window for highlighting static buf_T *syn_buf; // current buffer for highlighting static synblock_T *syn_block; // current buffer for highlighting @@ -328,13 +302,11 @@ void syn_set_timeout(proftime_T *tm) syn_tm = tm; } -/* - * Start the syntax recognition for a line. This function is normally called - * from the screen updating, once for each displayed line. - * The buffer is remembered in syn_buf, because get_syntax_attr() doesn't get - * it. Careful: curbuf and curwin are likely to point to another buffer and - * window. - */ +// Start the syntax recognition for a line. This function is normally called +// from the screen updating, once for each displayed line. +// The buffer is remembered in syn_buf, because get_syntax_attr() doesn't get +// it. Careful: curbuf and curwin are likely to point to another buffer and +// window. void syntax_start(win_T *wp, linenr_T lnum) { synstate_T *p; @@ -348,11 +320,9 @@ void syntax_start(win_T *wp, linenr_T lnum) current_sub_char = NUL; - /* - * After switching buffers, invalidate current_state. - * Also do this when a change was made, the current state may be invalid - * then. - */ + // After switching buffers, invalidate current_state. + // Also do this when a change was made, the current state may be invalid + // then. if (syn_block != wp->w_s || syn_buf != wp->w_buffer || changedtick != buf_get_changedtick(syn_buf)) { @@ -363,18 +333,14 @@ void syntax_start(win_T *wp, linenr_T lnum) changedtick = buf_get_changedtick(syn_buf); syn_win = wp; - /* - * Allocate syntax stack when needed. - */ + // Allocate syntax stack when needed. syn_stack_alloc(); if (syn_block->b_sst_array == NULL) { return; // out of memory } syn_block->b_sst_lasttick = display_tick; - /* - * If the state of the end of the previous line is useful, store it. - */ + // If the state of the end of the previous line is useful, store it. if (VALID_STATE(¤t_state) && current_lnum < lnum && current_lnum < syn_buf->b_ml.ml_line_count) { @@ -384,11 +350,9 @@ void syntax_start(win_T *wp, linenr_T lnum) (void)store_current_state(); } - /* - * If the current_lnum is now the same as "lnum", keep the current - * state (this happens very often!). Otherwise invalidate - * current_state and figure it out below. - */ + // If the current_lnum is now the same as "lnum", keep the current + // state (this happens very often!). Otherwise invalidate + // current_state and figure it out below. if (current_lnum != lnum) { invalidate_current_state(); } @@ -396,10 +360,8 @@ void syntax_start(win_T *wp, linenr_T lnum) invalidate_current_state(); } - /* - * Try to synchronize from a saved state in b_sst_array[]. - * Only do this if lnum is not before and not to far beyond a saved state. - */ + // Try to synchronize from a saved state in b_sst_array[]. + // Only do this if lnum is not before and not to far beyond a saved state. if (INVALID_STATE(¤t_state) && syn_block->b_sst_array != NULL) { // Find last valid saved state before start_lnum. for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) { @@ -418,10 +380,8 @@ void syntax_start(win_T *wp, linenr_T lnum) } } - /* - * If "lnum" is before or far beyond a line with a saved state, need to - * re-synchronize. - */ + // If "lnum" is before or far beyond a line with a saved state, need to + // re-synchronize. if (INVALID_STATE(¤t_state)) { syn_sync(wp, lnum, last_valid); if (current_lnum == 1) { @@ -436,10 +396,8 @@ void syntax_start(win_T *wp, linenr_T lnum) first_stored = current_lnum; } - /* - * Advance from the sync point or saved state until the current line. - * Save some entries for syncing with later on. - */ + // Advance from the sync point or saved state until the current line. + // Save some entries for syncing with later on. if (syn_block->b_sst_len <= Rows) { dist = 999999; } else { @@ -506,10 +464,8 @@ void syntax_start(win_T *wp, linenr_T lnum) syn_start_line(); } -/* - * We cannot simply discard growarrays full of state_items or buf_states; we - * have to manually release their extmatch pointers first. - */ +// We cannot simply discard growarrays full of state_items or buf_states; we +// have to manually release their extmatch pointers first. static void clear_syn_state(synstate_T *p) { if (p->sst_stacksize > SST_FIX_STATES) { @@ -522,24 +478,20 @@ static void clear_syn_state(synstate_T *p) } } -/* - * Cleanup the current_state stack. - */ +// Cleanup the current_state stack. static void clear_current_state(void) { #define UNREF_STATEITEM_EXTMATCH(si) unref_extmatch((si)->si_extmatch) GA_DEEP_CLEAR(¤t_state, stateitem_T, UNREF_STATEITEM_EXTMATCH); } -/* - * Try to find a synchronisation point for line "lnum". - * - * This sets current_lnum and the current state. One of three methods is - * used: - * 1. Search backwards for the end of a C-comment. - * 2. Search backwards for given sync patterns. - * 3. Simply start on a given number of lines above "lnum". - */ +// Try to find a synchronisation point for line "lnum". +// +// This sets current_lnum and the current state. One of three methods is +// used: +// 1. Search backwards for the end of a C-comment. +// 2. Search backwards for given sync patterns. +// 3. Simply start on a given number of lines above "lnum". static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) { buf_T *curbuf_save; @@ -560,19 +512,15 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) lpos_T found_m_endpos; colnr_T prev_current_col; - /* - * Clear any current state that might be hanging around. - */ + // Clear any current state that might be hanging around. invalidate_current_state(); - /* - * Start at least "minlines" back. Default starting point for parsing is - * there. - * Start further back, to avoid that scrolling backwards will result in - * resyncing for every line. Now it resyncs only one out of N lines, - * where N is minlines * 1.5, or minlines * 2 if minlines is small. - * Watch out for overflow when minlines is MAXLNUM. - */ + // Start at least "minlines" back. Default starting point for parsing is + // there. + // Start further back, to avoid that scrolling backwards will result in + // resyncing for every line. Now it resyncs only one out of N lines, + // where N is minlines * 1.5, or minlines * 2 if minlines is small. + // Watch out for overflow when minlines is MAXLNUM. if (syn_block->b_syn_sync_minlines > start_lnum) { start_lnum = 1; } else { @@ -595,9 +543,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) } current_lnum = start_lnum; - /* - * 1. Search backwards for the end of a C-style comment. - */ + // 1. Search backwards for the end of a C-style comment. if (syn_block->b_syn_sync_flags & SF_CCOMMENT) { // Need to make syn_buf the current buffer for a moment, to be able to // use find_start_comment(). @@ -606,9 +552,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) curbuf_save = curbuf; curbuf = syn_buf; - /* - * Skip lines that end in a backslash. - */ + // Skip lines that end in a backslash. for (; start_lnum > 1; start_lnum--) { line = (char_u *)ml_get(start_lnum - 1); if (*line == NUL || *(line + STRLEN(line) - 1) != '\\') { @@ -622,11 +566,9 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) wp->w_cursor.lnum = start_lnum; wp->w_cursor.col = 0; - /* - * If the line is inside a comment, need to find the syntax item that - * defines the comment. - * Restrict the search for the end of a comment to b_syn_sync_maxlines. - */ + // If the line is inside a comment, need to find the syntax item that + // defines the comment. + // Restrict the search for the end of a comment to b_syn_sync_maxlines. if (find_start_comment((int)syn_block->b_syn_sync_maxlines) != NULL) { for (idx = syn_block->b_syn_patterns.ga_len; --idx >= 0;) { if (SYN_ITEMS(syn_block)[idx].sp_syn.id @@ -644,11 +586,8 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) wp->w_cursor = cursor_save; curwin = curwin_save; curbuf = curbuf_save; - } - /* - * 2. Search backwards for given sync patterns. - */ - else if (syn_block->b_syn_sync_flags & SF_MATCH) { + } else if (syn_block->b_syn_sync_flags & SF_MATCH) { + // 2. Search backwards for given sync patterns. if (syn_block->b_syn_sync_maxlines != 0 && start_lnum > syn_block->b_syn_sync_maxlines) { break_lnum = start_lnum - syn_block->b_syn_sync_maxlines; @@ -675,16 +614,12 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) break; } - /* - * Check if the previous line has the line-continuation pattern. - */ + // Check if the previous line has the line-continuation pattern. if (lnum > 1 && syn_match_linecont(lnum - 1)) { continue; } - /* - * Start with nothing on the state stack - */ + // Start with nothing on the state stack validate_current_state(); for (current_lnum = lnum; current_lnum < end_lnum; current_lnum++) { @@ -712,10 +647,8 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) found_current_lnum = current_lnum; found_current_col = current_col; found_m_endpos = cur_si->si_m_endpos; - /* - * Continue after the match (be aware of a zero-length - * match). - */ + // Continue after the match (be aware of a zero-length + // match). if (found_m_endpos.lnum > current_lnum) { current_lnum = found_m_endpos.lnum; current_col = found_m_endpos.col; @@ -743,27 +676,21 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) } } - /* - * If a sync point was encountered, break here. - */ + // If a sync point was encountered, break here. if (found_flags) { - /* - * Put the item that was specified by the sync point on the - * state stack. If there was no item specified, make the - * state stack empty. - */ + // Put the item that was specified by the sync point on the + // state stack. If there was no item specified, make the + // state stack empty. clear_current_state(); if (found_match_idx >= 0) { push_current_state(found_match_idx); update_si_attr(current_state.ga_len - 1); } - /* - * When using "grouphere", continue from the sync point - * match, until the end of the line. Parsing starts at - * the next line. - * For "groupthere" the parsing starts at start_lnum. - */ + // When using "grouphere", continue from the sync point + // match, until the end of the line. Parsing starts at + // the next line. + // For "groupthere" the parsing starts at start_lnum. if (found_flags & HL_SYNC_HERE) { if (!GA_EMPTY(¤t_state)) { cur_si = &CUR_STATE(current_state.ga_len - 1); @@ -833,18 +760,14 @@ static int syn_match_linecont(linenr_T lnum) return false; } -/* - * Prepare the current state for the start of a line. - */ +// Prepare the current state for the start of a line. static void syn_start_line(void) { current_finished = false; current_col = 0; - /* - * Need to update the end of a start/skip/end that continues from the - * previous line and regions that have "keepend". - */ + // Need to update the end of a start/skip/end that continues from the + // previous line and regions that have "keepend". if (!GA_EMPTY(¤t_state)) { syn_update_ends(true); check_state_ends(); @@ -881,15 +804,13 @@ static void syn_update_ends(bool startofline) } } - /* - * Need to update the end of a start/skip/end that continues from the - * previous line. And regions that have "keepend", because they may - * influence contained items. If we've just removed "extend" - * (startofline == 0) then we should update ends of normal regions - * contained inside "keepend" because "extend" could have extended - * these "keepend" regions as well as contained normal regions. - * Then check for items ending in column 0. - */ + // Need to update the end of a start/skip/end that continues from the + // previous line. And regions that have "keepend", because they may + // influence contained items. If we've just removed "extend" + // (startofline == 0) then we should update ends of normal regions + // contained inside "keepend" because "extend" could have extended + // these "keepend" regions as well as contained normal regions. + // Then check for items ending in column 0. int i = current_state.ga_len - 1; if (keepend_level >= 0) { for (; i > keepend_level; i--) { @@ -923,37 +844,35 @@ static void syn_update_ends(bool startofline) ///////////////////////////////////////// // Handling of the state stack cache. -/* - * EXPLANATION OF THE SYNTAX STATE STACK CACHE - * - * To speed up syntax highlighting, the state stack for the start of some - * lines is cached. These entries can be used to start parsing at that point. - * - * The stack is kept in b_sst_array[] for each buffer. There is a list of - * valid entries. b_sst_first points to the first one, then follow sst_next. - * The entries are sorted on line number. The first entry is often for line 2 - * (line 1 always starts with an empty stack). - * There is also a list for free entries. This construction is used to avoid - * having to allocate and free memory blocks too often. - * - * When making changes to the buffer, this is logged in b_mod_*. When calling - * update_screen() to update the display, it will call - * syn_stack_apply_changes() for each displayed buffer to adjust the cached - * entries. The entries which are inside the changed area are removed, - * because they must be recomputed. Entries below the changed have their line - * number adjusted for deleted/inserted lines, and have their sst_change_lnum - * set to indicate that a check must be made if the changed lines would change - * the cached entry. - * - * When later displaying lines, an entry is stored for each line. Displayed - * lines are likely to be displayed again, in which case the state at the - * start of the line is needed. - * For not displayed lines, an entry is stored for every so many lines. These - * entries will be used e.g., when scrolling backwards. The distance between - * entries depends on the number of lines in the buffer. For small buffers - * the distance is fixed at SST_DIST, for large buffers there is a fixed - * number of entries SST_MAX_ENTRIES, and the distance is computed. - */ +// EXPLANATION OF THE SYNTAX STATE STACK CACHE +// +// To speed up syntax highlighting, the state stack for the start of some +// lines is cached. These entries can be used to start parsing at that point. +// +// The stack is kept in b_sst_array[] for each buffer. There is a list of +// valid entries. b_sst_first points to the first one, then follow sst_next. +// The entries are sorted on line number. The first entry is often for line 2 +// (line 1 always starts with an empty stack). +// There is also a list for free entries. This construction is used to avoid +// having to allocate and free memory blocks too often. +// +// When making changes to the buffer, this is logged in b_mod_*. When calling +// update_screen() to update the display, it will call +// syn_stack_apply_changes() for each displayed buffer to adjust the cached +// entries. The entries which are inside the changed area are removed, +// because they must be recomputed. Entries below the changed have their line +// number adjusted for deleted/inserted lines, and have their sst_change_lnum +// set to indicate that a check must be made if the changed lines would change +// the cached entry. +// +// When later displaying lines, an entry is stored for each line. Displayed +// lines are likely to be displayed again, in which case the state at the +// start of the line is needed. +// For not displayed lines, an entry is stored for every so many lines. These +// entries will be used e.g., when scrolling backwards. The distance between +// entries depends on the number of lines in the buffer. For small buffers +// the distance is fixed at SST_DIST, for large buffers there is a fixed +// number of entries SST_MAX_ENTRIES, and the distance is computed. static void syn_stack_free_block(synblock_T *block) { @@ -968,10 +887,8 @@ static void syn_stack_free_block(synblock_T *block) block->b_sst_len = 0; } } -/* - * Free b_sst_array[] for buffer "buf". - * Used when syntax items changed to force resyncing everywhere. - */ +// Free b_sst_array[] for buffer "buf". +// Used when syntax items changed to force resyncing everywhere. void syn_stack_free_all(synblock_T *block) { syn_stack_free_block(block); @@ -984,12 +901,10 @@ void syn_stack_free_all(synblock_T *block) } } -/* - * Allocate the syntax state stack for syn_buf when needed. - * If the number of entries in b_sst_array[] is much too big or a bit too - * small, reallocate it. - * Also used to allocate b_sst_array[] for the first time. - */ +// Allocate the syntax state stack for syn_buf when needed. +// If the number of entries in b_sst_array[] is much too big or a bit too +// small, reallocate it. +// Also used to allocate b_sst_array[] for the first time. static void syn_stack_alloc(void) { synstate_T *to, *from; @@ -1056,12 +971,10 @@ static void syn_stack_alloc(void) } } -/* - * Check for changes in a buffer to affect stored syntax states. Uses the - * b_mod_* fields. - * Called from update_screen(), before screen is being updated, once for each - * displayed buffer. - */ +// Check for changes in a buffer to affect stored syntax states. Uses the +// b_mod_* fields. +// Called from update_screen(), before screen is being updated, once for each +// displayed buffer. void syn_stack_apply_changes(buf_T *buf) { syn_stack_apply_changes_block(&buf->b_s, buf); @@ -1137,11 +1050,9 @@ static bool syn_stack_cleanup(void) dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1; } - /* - * Go through the list to find the "tick" for the oldest entry that can - * be removed. Set "above" when the "tick" for the oldest entry is above - * "b_sst_lasttick" (the display tick wraps around). - */ + // Go through the list to find the "tick" for the oldest entry that can + // be removed. Set "above" when the "tick" for the oldest entry is above + // "b_sst_lasttick" (the display tick wraps around). tick = syn_block->b_sst_lasttick; bool above = false; prev = syn_block->b_sst_first; @@ -1158,10 +1069,8 @@ static bool syn_stack_cleanup(void) } } - /* - * Go through the list to make the entries for the oldest tick at an - * interval of several lines. - */ + // Go through the list to make the entries for the oldest tick at an + // interval of several lines. prev = syn_block->b_sst_first; for (p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) { if (p->sst_tick == tick && prev->sst_lnum + dist > p->sst_lnum) { @@ -1175,10 +1084,8 @@ static bool syn_stack_cleanup(void) return retval; } -/* - * Free the allocated memory for a syn_state item. - * Move the entry into the free list. - */ +// Free the allocated memory for a syn_state item. +// Move the entry into the free list. static void syn_stack_free_entry(synblock_T *block, synstate_T *p) { clear_syn_state(p); @@ -1187,10 +1094,8 @@ static void syn_stack_free_entry(synblock_T *block, synstate_T *p) block->b_sst_freecount++; } -/* - * Find an entry in the list of state stacks at or before "lnum". - * Returns NULL when there is no entry or the first entry is after "lnum". - */ +// Find an entry in the list of state stacks at or before "lnum". +// Returns NULL when there is no entry or the first entry is after "lnum". static synstate_T *syn_stack_find_entry(linenr_T lnum) { synstate_T *p, *prev; @@ -1207,10 +1112,8 @@ static synstate_T *syn_stack_find_entry(linenr_T lnum) return prev; } -/* - * Try saving the current state in b_sst_array[]. - * The current state must be valid for the start of the current_lnum line! - */ +// Try saving the current state in b_sst_array[]. +// The current state must be valid for the start of the current_lnum line! static synstate_T *store_current_state(void) { int i; @@ -1219,10 +1122,8 @@ static synstate_T *store_current_state(void) stateitem_T *cur_si; synstate_T *sp = syn_stack_find_entry(current_lnum); - /* - * If the current state contains a start or end pattern that continues - * from the previous line, we can't use it. Don't store it then. - */ + // If the current state contains a start or end pattern that continues + // from the previous line, we can't use it. Don't store it then. for (i = current_state.ga_len - 1; i >= 0; i--) { cur_si = &CUR_STATE(i); if (cur_si->si_h_startpos.lnum >= current_lnum @@ -1254,9 +1155,7 @@ static synstate_T *store_current_state(void) sp = NULL; } } else if (sp == NULL || sp->sst_lnum != current_lnum) { - /* - * Add a new entry - */ + // Add a new entry // If no free items, cleanup the array first. if (syn_block->b_sst_freecount == 0) { (void)syn_stack_cleanup(); @@ -1316,9 +1215,7 @@ static synstate_T *store_current_state(void) return sp; } -/* - * Copy a state stack from "from" in b_sst_array[] to current_state; - */ +// Copy a state stack from "from" in b_sst_array[] to current_state; static void load_current_state(synstate_T *from) { int i; @@ -1422,16 +1319,14 @@ static bool syn_stack_equal(synstate_T *sp) return i < 0 ? true : false; } -/* - * We stop parsing syntax above line "lnum". If the stored state at or below - * this line depended on a change before it, it now depends on the line below - * the last parsed line. - * The window looks like this: - * line which changed - * displayed line - * displayed line - * lnum -> line below window - */ +// We stop parsing syntax above line "lnum". If the stored state at or below +// this line depended on a change before it, it now depends on the line below +// the last parsed line. +// The window looks like this: +// line which changed +// displayed line +// displayed line +// lnum -> line below window void syntax_end_parsing(linenr_T lnum) { synstate_T *sp; @@ -1446,9 +1341,8 @@ void syntax_end_parsing(linenr_T lnum) } } -/* - * End of handling of the state stack. - ****************************************/ +// End of handling of the state stack. +// ************************************** static void invalidate_current_state(void) { @@ -1473,33 +1367,25 @@ bool syntax_check_changed(linenr_T lnum) bool retval = true; synstate_T *sp; - /* - * Check the state stack when: - * - lnum is just below the previously syntaxed line. - * - lnum is not before the lines with saved states. - * - lnum is not past the lines with saved states. - * - lnum is at or before the last changed line. - */ + // Check the state stack when: + // - lnum is just below the previously syntaxed line. + // - lnum is not before the lines with saved states. + // - lnum is not past the lines with saved states. + // - lnum is at or before the last changed line. if (VALID_STATE(¤t_state) && lnum == current_lnum + 1) { sp = syn_stack_find_entry(lnum); if (sp != NULL && sp->sst_lnum == lnum) { - /* - * finish the previous line (needed when not all of the line was - * drawn) - */ + // finish the previous line (needed when not all of the line was + // drawn) (void)syn_finish_line(false); - /* - * Compare the current state with the previously saved state of - * the line. - */ + // Compare the current state with the previously saved state of + // the line. if (syn_stack_equal(sp)) { retval = false; } - /* - * Store the current state in b_sst_array[] for later use. - */ + // Store the current state in b_sst_array[] for later use. current_lnum++; (void)store_current_state(); } @@ -1587,9 +1473,7 @@ int get_syntax_attr(const colnr_T col, bool *const can_spell, const bool keep_st validate_current_state(); } - /* - * Skip from the current column to "col", get the attributes for "col". - */ + // Skip from the current column to "col", get the attributes for "col". while (current_col <= col) { attr = syn_current_attr(false, true, can_spell, current_col == col ? keep_state : false); @@ -1638,9 +1522,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con // Do try matching with an empty line (could be the start of a region). line = (char_u *)syn_getcurline(); if (line[current_col] == NUL && current_col != 0) { - /* - * If we found a match after the last column, use it. - */ + // If we found a match after the last column, use it. if (next_match_idx >= 0 && next_match_col >= (int)current_col && next_match_col != MAXCOL) { (void)push_next_match(); @@ -1657,11 +1539,9 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con current_state_stored = false; } - /* - * When in the previous column there was a match but it could not be used - * (empty match or already matched in this column) need to try again in - * the next column. - */ + // When in the previous column there was a match but it could not be used + // (empty match or already matched in this column) need to try again in + // the next column. if (try_next_column) { next_match_idx = -1; try_next_column = false; @@ -1679,23 +1559,19 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con // use syntax iskeyword option save_chartab((char *)buf_chartab); - /* - * Repeat matching keywords and patterns, to find contained items at the - * same column. This stops when there are no extra matches at the current - * column. - */ + // Repeat matching keywords and patterns, to find contained items at the + // same column. This stops when there are no extra matches at the current + // column. do { found_match = false; keep_next_list = false; int syn_id = 0; - /* - * 1. Check for a current state. - * Only when there is no current state, or if the current state may - * contain other things, we need to check for keywords and patterns. - * Always need to check for contained items if some item has the - * "containedin" argument (takes extra time!). - */ + // 1. Check for a current state. + // Only when there is no current state, or if the current state may + // contain other things, we need to check for keywords and patterns. + // Always need to check for contained items if some item has the + // "containedin" argument (takes extra time!). if (current_state.ga_len) { cur_si = &CUR_STATE(current_state.ga_len - 1); } else { @@ -1758,21 +1634,15 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } - /* - * 3. Check for patterns (only if no keyword found). - */ + // 3. Check for patterns (only if no keyword found). if (syn_id == 0 && syn_block->b_syn_patterns.ga_len) { - /* - * If we didn't check for a match yet, or we are past it, check - * for any match with a pattern. - */ + // If we didn't check for a match yet, or we are past it, check + // for any match with a pattern. if (next_match_idx < 0 || next_match_col < (int)current_col) { - /* - * Check all relevant patterns for a match at this - * position. This is complicated, because matching with a - * pattern takes quite a bit of time, thus we want to - * avoid doing it when it's not needed. - */ + // Check all relevant patterns for a match at this + // position. This is complicated, because matching with a + // pattern takes quite a bit of time, thus we want to + // avoid doing it when it's not needed. next_match_idx = 0; // no match in this line yet next_match_col = MAXCOL; for (int idx = syn_block->b_syn_patterns.ga_len; --idx >= 0;) { @@ -1814,9 +1684,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con continue; } - /* - * Compute the first column of the match. - */ + // Compute the first column of the match. syn_add_start_off(&pos, ®match, spp, SPO_MS_OFF, -1); if (pos.lnum > current_lnum) { @@ -1831,19 +1699,15 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con // matches in the current line spp->sp_startcol = startcol; - /* - * If a previously found match starts at a lower - * column number, don't use this one. - */ + // If a previously found match starts at a lower + // column number, don't use this one. if (startcol >= next_match_col) { continue; } - /* - * If we matched this pattern at this position - * before, skip it. Must retry in the next - * column, because it may match from there. - */ + // If we matched this pattern at this position + // before, skip it. Must retry in the next + // column, because it may match from there. if (did_match_already(idx, &zero_width_next_ga)) { try_next_column = true; continue; @@ -1861,10 +1725,8 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con syn_add_end_off(&eos_pos, ®match, spp, SPO_RS_OFF, 0); - /* - * Grab the external submatches before they get - * overwritten. Reference count doesn't change. - */ + // Grab the external submatches before they get + // overwritten. Reference count doesn't change. unref_extmatch(cur_extmatch); cur_extmatch = re_extmatch_out; re_extmatch_out = NULL; @@ -1875,12 +1737,10 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con end_idx = 0; hl_endpos.lnum = 0; - /* - * For a "oneline" the end must be found in the - * same line too. Search for it after the end of - * the match with the start pattern. Set the - * resulting end positions at the same time. - */ + // For a "oneline" the end must be found in the + // same line too. Search for it after the end of + // the match with the start pattern. Set the + // resulting end positions at the same time. if (spp->sp_type == SPTYPE_START && (spp->sp_flags & HL_ONELINE)) { lpos_T startpos; @@ -1891,23 +1751,18 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con if (endpos.lnum == 0) { continue; // not found } - } - /* - * For a "match" the size must be > 0 after the - * end offset needs has been added. Except when - * syncing. - */ - else if (spp->sp_type == SPTYPE_MATCH) { + } else if (spp->sp_type == SPTYPE_MATCH) { + // For a "match" the size must be > 0 after the + // end offset needs has been added. Except when + // syncing. syn_add_end_off(&hl_endpos, ®match, spp, SPO_HE_OFF, 0); syn_add_end_off(&endpos, ®match, spp, SPO_ME_OFF, 0); if (endpos.lnum == current_lnum && (int)endpos.col + syncing < startcol) { - /* - * If an empty string is matched, may need - * to try matching again at next column. - */ + // If an empty string is matched, may need + // to try matching again at next column. if (regmatch.startpos[0].col == regmatch.endpos[0].col) { try_next_column = true; } @@ -1915,9 +1770,8 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } - /* - * keep the best match so far in next_match_* - */ + // keep the best match so far in next_match_* + // Highlighting must start after startpos and end // before endpos. if (hl_startpos.lnum == current_lnum @@ -1942,9 +1796,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } - /* - * If we found a match at the current column, use it. - */ + // If we found a match at the current column, use it. if (next_match_idx >= 0 && next_match_col == (int)current_col) { synpat_T *lspp; @@ -1972,9 +1824,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } - /* - * Handle searching for nextgroup match. - */ + // Handle searching for nextgroup match. if (current_next_list != NULL && !keep_next_list) { // If a nextgroup was not found, continue looking for one if: // - this is an empty line and the "skipempty" option was given @@ -1989,14 +1839,12 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } - /* - * If a nextgroup was found: Use it, and continue looking for - * contained matches. - * If a nextgroup was not found: Continue looking for a normal - * match. - * When did set current_next_list for a zero-width item and no - * match was found don't loop (would get stuck). - */ + // If a nextgroup was found: Use it, and continue looking for + // contained matches. + // If a nextgroup was not found: Continue looking for a normal + // match. + // When did set current_next_list for a zero-width item and no + // match was found don't loop (would get stuck). current_next_list = NULL; next_match_idx = -1; if (!zero_width_next_list) { @@ -2007,10 +1855,8 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con restore_chartab((char *)buf_chartab); - /* - * Use attributes from the current state, if within its highlighting. - * If not, use attributes from the current-but-one state, etc. - */ + // Use attributes from the current state, if within its highlighting. + // If not, use attributes from the current-but-one state, etc. current_attr = 0; current_id = 0; current_trans_id = 0; @@ -2076,14 +1922,12 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con } } - /* - * Check for end of current state (and the states before it) at the - * next column. Don't do this for syncing, because we would miss a - * single character match. - * First check if the current state ends at the current column. It - * may be for an empty match and a containing item might end in the - * current column. - */ + // Check for end of current state (and the states before it) at the + // next column. Don't do this for syncing, because we would miss a + // single character match. + // First check if the current state ends at the current column. It + // may be for an empty match and a containing item might end in the + // current column. if (!syncing && !keep_state) { check_state_ends(); if (!GA_EMPTY(¤t_state) @@ -2143,9 +1987,7 @@ static bool did_match_already(int idx, garray_T *gap) return false; } -/* - * Push the next match onto the stack. - */ +// Push the next match onto the stack. static stateitem_T *push_next_match(void) { stateitem_T *cur_si; @@ -2154,15 +1996,11 @@ static stateitem_T *push_next_match(void) spp = &(SYN_ITEMS(syn_block)[next_match_idx]); - /* - * Push the item in current_state stack; - */ + // Push the item in current_state stack; push_current_state(next_match_idx); { - /* - * If it's a start-skip-end type that crosses lines, figure out how - * much it continues in this line. Otherwise just fill in the length. - */ + // If it's a start-skip-end type that crosses lines, figure out how + // much it continues in this line. Otherwise just fill in the length. cur_si = &CUR_STATE(current_state.ga_len - 1); cur_si->si_h_startpos = next_match_h_startpos; cur_si->si_m_startcol = current_col; @@ -2195,10 +2033,8 @@ static stateitem_T *push_next_match(void) update_si_attr(current_state.ga_len - 1); save_flags = cur_si->si_flags & (HL_CONCEAL | HL_CONCEALENDS); - /* - * If the start pattern has another highlight group, push another item - * on the stack for the start pattern. - */ + // If the start pattern has another highlight group, push another item + // on the stack for the start pattern. if (spp->sp_type == SPTYPE_START && spp->sp_syn_match_id != 0) { push_current_state(next_match_idx); cur_si = &CUR_STATE(current_state.ga_len - 1); @@ -2226,9 +2062,7 @@ static stateitem_T *push_next_match(void) return cur_si; } -/* - * Check for end of current state (and the states before it). - */ +// Check for end of current state (and the states before it). static void check_state_ends(void) { stateitem_T *cur_si; @@ -2240,12 +2074,10 @@ static void check_state_ends(void) && (cur_si->si_m_endpos.lnum < current_lnum || (cur_si->si_m_endpos.lnum == current_lnum && cur_si->si_m_endpos.col <= current_col))) { - /* - * If there is an end pattern group ID, highlight the end pattern - * now. No need to pop the current item from the stack. - * Only do this if the end pattern continues beyond the current - * position. - */ + // If there is an end pattern group ID, highlight the end pattern + // now. No need to pop the current item from the stack. + // Only do this if the end pattern continues beyond the current + // position. if (cur_si->si_end_idx && (cur_si->si_eoe_pos.lnum > current_lnum || (cur_si->si_eoe_pos.lnum == current_lnum @@ -2322,10 +2154,8 @@ static void check_state_ends(void) } } -/* - * Update an entry in the current_state stack for a match or region. This - * fills in si_attr, si_next_list and si_cont_list. - */ +// Update an entry in the current_state stack for a match or region. This +// fills in si_attr, si_next_list and si_cont_list. static void update_si_attr(int idx) { stateitem_T *sip = &CUR_STATE(idx); @@ -2350,11 +2180,9 @@ static void update_si_attr(int idx) sip->si_cont_list = spp->sp_cont_list; } - /* - * For transparent items, take attr from outer item. - * Also take cont_list, if there is none. - * Don't do this for the matchgroup of a start or end pattern. - */ + // For transparent items, take attr from outer item. + // Also take cont_list, if there is none. + // Don't do this for the matchgroup of a start or end pattern. if ((spp->sp_flags & HL_TRANSP) && !(sip->si_flags & HL_MATCH)) { if (idx == 0) { sip->si_attr = 0; @@ -2373,10 +2201,8 @@ static void update_si_attr(int idx) } } -/* - * Check the current stack for patterns with "keepend" flag. - * Propagate the match-end to contained items, until a "skipend" item is found. - */ +// Check the current stack for patterns with "keepend" flag. +// Propagate the match-end to contained items, until a "skipend" item is found. static void check_keepend(void) { int i; @@ -2384,19 +2210,15 @@ static void check_keepend(void) lpos_T maxpos_h; stateitem_T *sip; - /* - * This check can consume a lot of time; only do it from the level where - * there really is a keepend. - */ + // This check can consume a lot of time; only do it from the level where + // there really is a keepend. if (keepend_level < 0) { return; } - /* - * Find the last index of an "extend" item. "keepend" items before that - * won't do anything. If there is no "extend" item "i" will be - * "keepend_level" and all "keepend" items will work normally. - */ + // Find the last index of an "extend" item. "keepend" items before that + // won't do anything. If there is no "extend" item "i" will be + // "keepend_level" and all "keepend" items will work normally. for (i = current_state.ga_len - 1; i > keepend_level; i--) { if (CUR_STATE(i).si_flags & HL_EXTEND) { break; @@ -2456,10 +2278,8 @@ static void update_si_end(stateitem_T *sip, int startcol, bool force) return; } - /* - * We need to find the end of the region. It may continue in the next - * line. - */ + // We need to find the end of the region. It may continue in the next + // line. int end_idx = 0; lpos_T startpos = { .lnum = current_lnum, @@ -2492,10 +2312,8 @@ static void update_si_end(stateitem_T *sip, int startcol, bool force) } } -/* - * Add a new state to the current state stack. - * It is cleared and the index set to "idx". - */ +// Add a new state to the current state stack. +// It is cleared and the index set to "idx". static void push_current_state(int idx) { stateitem_T *p = GA_APPEND_VIA_PTR(stateitem_T, ¤t_state); @@ -2503,9 +2321,7 @@ static void push_current_state(int idx) p->si_idx = idx; } -/* - * Remove a state from the current_state stack. - */ +// Remove a state from the current_state stack. static void pop_current_state(void) { if (!GA_EMPTY(¤t_state)) { @@ -2556,20 +2372,16 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ return; } - /* - * Check for being called with a START pattern. - * Can happen with a match that continues to the next line, because it - * contained a region. - */ + // Check for being called with a START pattern. + // Can happen with a match that continues to the next line, because it + // contained a region. spp = &(SYN_ITEMS(syn_block)[idx]); if (spp->sp_type != SPTYPE_START) { *hl_endpos = *startpos; return; } - /* - * Find the SKIP or first END pattern after the last START pattern. - */ + // Find the SKIP or first END pattern after the last START pattern. for (;;) { spp = &(SYN_ITEMS(syn_block)[idx]); if (spp->sp_type != SPTYPE_START) { @@ -2578,9 +2390,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ idx++; } - /* - * Lookup the SKIP pattern (if present) - */ + // Lookup the SKIP pattern (if present) if (spp->sp_type == SPTYPE_SKIP) { spp_skip = spp; idx++; @@ -2600,9 +2410,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ save_chartab((char *)buf_chartab); for (;;) { - /* - * Find end pattern that matches first after "matchcol". - */ + // Find end pattern that matches first after "matchcol". best_idx = -1; for (idx = start_idx; idx < syn_block->b_syn_patterns.ga_len; idx++) { int lc_col = matchcol; @@ -2631,18 +2439,14 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ } } - /* - * If all end patterns have been tried, and there is no match, the - * item continues until end-of-line. - */ + // If all end patterns have been tried, and there is no match, the + // item continues until end-of-line. if (best_idx == -1) { break; } - /* - * If the skip pattern matches before the end pattern, - * continue searching after the skip pattern. - */ + // If the skip pattern matches before the end pattern, + // continue searching after the skip pattern. if (spp_skip != NULL) { int lc_col = matchcol - spp_skip->sp_offsets[SPO_LC_OFF]; @@ -2688,10 +2492,8 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ } } - /* - * Match from start pattern to end pattern. - * Correct for match and highlight offset of end pattern. - */ + // Match from start pattern to end pattern. + // Correct for match and highlight offset of end pattern. spp = &(SYN_ITEMS(syn_block)[best_idx]); syn_add_end_off(m_endpos, &best_regmatch, spp, SPO_ME_OFF, 1); // can't end before the start @@ -2708,9 +2510,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ // can't end after the match limit_pos(end_endpos, m_endpos); - /* - * If the end group is highlighted differently, adjust the pointers. - */ + // If the end group is highlighted differently, adjust the pointers. if (spp->sp_syn_match_id != spp->sp_syn.id && spp->sp_syn_match_id != 0) { *end_idx = best_idx; if (spp->sp_off_flags & (1 << (SPO_RE_OFF + SPO_COUNT))) { @@ -2755,9 +2555,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_ re_extmatch_in = NULL; } -/* - * Limit "pos" not to be after "limit". - */ +// Limit "pos" not to be after "limit". static void limit_pos(lpos_T *pos, lpos_T *limit) { if (pos->lnum > limit->lnum) { @@ -2767,9 +2565,7 @@ static void limit_pos(lpos_T *pos, lpos_T *limit) } } -/* - * Limit "pos" not to be after "limit", unless pos->lnum is zero. - */ +// Limit "pos" not to be after "limit", unless pos->lnum is zero. static void limit_pos_zero(lpos_T *pos, lpos_T *limit) { if (pos->lnum == 0) { @@ -2875,10 +2671,8 @@ static char *syn_getcurline(void) return (char *)ml_get_buf(syn_buf, current_lnum, false); } -/* - * Call vim_regexec() to find a match with "rmp" in "syn_buf". - * Returns true when there is a match. - */ +// Call vim_regexec() to find a match with "rmp" in "syn_buf". +// Returns true when there is a match. static int syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T *st) { int timed_out = 0; @@ -3001,9 +2795,7 @@ static keyentry_T *match_keyword(char *keyword, hashtab_T *ht, stateitem_T *cur_ return NULL; } -/* - * Handle ":syntax conceal" command. - */ +// Handle ":syntax conceal" command. static void syn_cmd_conceal(exarg_T *eap, int syncing) { char_u *arg = (char_u *)eap->arg; @@ -3171,9 +2963,7 @@ static void syn_cmd_iskeyword(exarg_T *eap, int syncing) redraw_later(curwin, UPD_NOT_VALID); } -/* - * Clear all syntax info for one buffer. - */ +// Clear all syntax info for one buffer. void syntax_clear(synblock_T *block) { block->b_syn_error = false; // clear previous error @@ -3221,9 +3011,7 @@ void syntax_clear(synblock_T *block) running_syn_inc_tag = 0; } -/* - * Get rid of ownsyntax for window "wp". - */ +// Get rid of ownsyntax for window "wp". void reset_synblock(win_T *wp) { if (wp->w_s != &wp->w_buffer->b_s) { @@ -3233,9 +3021,7 @@ void reset_synblock(win_T *wp) } } -/* - * Clear syncing info for one buffer. - */ +// Clear syncing info for one buffer. static void syntax_sync_clear(void) { // free the syntax patterns @@ -3258,9 +3044,7 @@ static void syntax_sync_clear(void) syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } -/* - * Remove one pattern from the buffer's pattern list. - */ +// Remove one pattern from the buffer's pattern list. static void syn_remove_pattern(synblock_T *block, int idx) { synpat_T *spp; @@ -3274,10 +3058,8 @@ static void syn_remove_pattern(synblock_T *block, int idx) block->b_syn_patterns.ga_len--; } -/* - * Clear and free one syntax pattern. When clearing all, must be called from - * last to first! - */ +// Clear and free one syntax pattern. When clearing all, must be called from +// last to first! static void syn_clear_pattern(synblock_T *block, int i) { xfree(SYN_ITEMS(block)[i].sp_pattern); @@ -3290,9 +3072,7 @@ static void syn_clear_pattern(synblock_T *block, int i) } } -/* - * Clear and free one syntax cluster. - */ +// Clear and free one syntax cluster. static void syn_clear_cluster(synblock_T *block, int i) { xfree(SYN_CLSTR(block)[i].scl_name); @@ -3312,20 +3092,16 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) return; } - /* - * We have to disable this within ":syn include @group filename", - * because otherwise @group would get deleted. - * Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn - * clear". - */ + // We have to disable this within ":syn include @group filename", + // because otherwise @group would get deleted. + // Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn + // clear". if (curwin->w_s->b_syn_topgrp != 0) { return; } if (ends_excmd(*arg)) { - /* - * No argument: Clear all syntax items. - */ + // No argument: Clear all syntax items. if (syncing) { syntax_sync_clear(); } else { @@ -3336,9 +3112,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) do_unlet(S_LEN("w:current_syntax"), true); } } else { - /* - * Clear the group IDs that are in the argument. - */ + // Clear the group IDs that are in the argument. while (!ends_excmd(*arg)) { arg_end = skiptowhite(arg); if (*arg == '@') { @@ -3370,9 +3144,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } -/* - * Clear one syntax group for the current buffer. - */ +// Clear one syntax group for the current buffer. static void syn_clear_one(const int id, const bool syncing) { synpat_T *spp; @@ -3393,18 +3165,14 @@ static void syn_clear_one(const int id, const bool syncing) } } -/* - * Handle ":syntax on" command. - */ +// Handle ":syntax on" command. static void syn_cmd_on(exarg_T *eap, int syncing) { syn_cmd_onoff(eap, "syntax"); } -/* - * Handle ":syntax reset" command. - * It actually resets highlighting, not syntax. - */ +// Handle ":syntax reset" command. +// It actually resets highlighting, not syntax. static void syn_cmd_reset(exarg_T *eap, int syncing) { eap->nextcmd = check_nextcmd(eap->arg); @@ -3413,17 +3181,13 @@ static void syn_cmd_reset(exarg_T *eap, int syncing) } } -/* - * Handle ":syntax manual" command. - */ +// Handle ":syntax manual" command. static void syn_cmd_manual(exarg_T *eap, int syncing) { syn_cmd_onoff(eap, "manual"); } -/* - * Handle ":syntax off" command. - */ +// Handle ":syntax off" command. static void syn_cmd_off(exarg_T *eap, int syncing) { syn_cmd_onoff(eap, "nosyntax"); @@ -3503,9 +3267,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing) msg_puts_title(_("\n--- Syntax items ---")); } if (ends_excmd(*arg)) { - /* - * No argument: List all group IDs and all syntax clusters. - */ + // No argument: List all group IDs and all syntax clusters. for (int id = 1; id <= highlight_num_groups() && !got_int; id++) { syn_list_one(id, syncing, false); } @@ -3513,9 +3275,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing) syn_list_cluster(id); } } else { - /* - * List the group IDs and syntax clusters that are in the argument. - */ + // List the group IDs and syntax clusters that are in the argument. while (!ends_excmd(*arg) && !got_int) { arg_end = (char_u *)skiptowhite((char *)arg); if (*arg == '@') { @@ -3693,9 +3453,7 @@ static void syn_list_flags(struct name_list *nlist, int flags, int attr) } } -/* - * List one syntax cluster, for ":syntax" or "syntax list syntax_name". - */ +// List one syntax cluster, for ":syntax" or "syntax list syntax_name". static void syn_list_cluster(int id) { int endcol = 15; @@ -3939,9 +3697,7 @@ static void syn_clear_keyword(int id, hashtab_T *ht) hash_unlock(ht); } -/* - * Clear a whole keyword table. - */ +// Clear a whole keyword table. static void clear_keywtab(hashtab_T *ht) { hashitem_T *hi; @@ -4088,11 +3844,9 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i } for (;;) { - /* - * This is used very often when a large number of keywords is defined. - * Need to skip quickly when no option name is found. - * Also avoid tolower(), it's slow. - */ + // This is used very often when a large number of keywords is defined. + // Need to skip quickly when no option name is found. + // Also avoid tolower(), it's slow. if (strchr(first_letters, *arg) == NULL) { break; } @@ -4196,11 +3950,9 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i return arg; } -/* - * Adjustments to syntax item when declared in a ":syn include"'d file. - * Set the contained flag, and if the item is not already contained, add it - * to the specified top-level group, if any. - */ +// Adjustments to syntax item when declared in a ":syn include"'d file. +// Set the contained flag, and if the item is not already contained, add it +// to the specified top-level group, if any. static void syn_incl_toplevel(int id, int *flagsp) { if ((*flagsp & HL_CONTAINED) || curwin->w_s->b_syn_topgrp == 0) { @@ -4219,9 +3971,7 @@ static void syn_incl_toplevel(int id, int *flagsp) } } -/* - * Handle ":syntax include [@{group-name}] filename" command. - */ +// Handle ":syntax include [@{group-name}] filename" command. static void syn_cmd_include(exarg_T *eap, int syncing) { char *arg = eap->arg; @@ -4253,10 +4003,8 @@ static void syn_cmd_include(exarg_T *eap, int syncing) eap->arg = rest; } - /* - * Everything that's left, up to the next command, should be the - * filename to include. - */ + // Everything that's left, up to the next command, should be the + // filename to include. eap->argt |= (EX_XFILE | EX_NOSPC); separate_nextcmd(eap); if (*eap->arg == '<' || *eap->arg == '$' || path_is_absolute((char_u *)eap->arg)) { @@ -4272,10 +4020,8 @@ static void syn_cmd_include(exarg_T *eap, int syncing) } } - /* - * Save and restore the existing top-level grouplist id and ":syn - * include" tag around the actual inclusion. - */ + // Save and restore the existing top-level grouplist id and ":syn + // include" tag around the actual inclusion. if (running_syn_inc_tag >= MAX_SYN_INC_TAG) { emsg(_("E847: Too many syntax includes")); return; @@ -4293,9 +4039,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing) current_syn_inc_tag = prev_syn_inc_tag; } -/* - * Handle ":syntax keyword {group-name} [{option}] keyword .." command. - */ +// Handle ":syntax keyword {group-name} [{option}] keyword .." command. static void syn_cmd_keyword(exarg_T *eap, int syncing) { char *arg = eap->arg; @@ -4444,18 +4188,14 @@ static void syn_cmd_match(exarg_T *eap, int syncing) rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); if (rest != NULL) { // all arguments are valid - /* - * Check for trailing command and illegal trailing arguments. - */ + // Check for trailing command and illegal trailing arguments. eap->nextcmd = check_nextcmd(rest); if (!ends_excmd(*rest) || eap->skip) { rest = NULL; } else { if ((syn_id = syn_check_group(arg, (size_t)(group_name_end - arg))) != 0) { syn_incl_toplevel(syn_id, &syn_opt_arg.flags); - /* - * Store the pattern in the syn_items list - */ + // Store the pattern in the syn_items list synpat_T *spp = GA_APPEND_VIA_PTR(synpat_T, &curwin->w_s->b_syn_patterns); *spp = item; @@ -4488,9 +4228,7 @@ static void syn_cmd_match(exarg_T *eap, int syncing) } } - /* - * Something failed, free the allocated memory. - */ + // Something failed, free the allocated memory. vim_regfree(item.sp_prog); xfree(item.sp_pattern); xfree(syn_opt_arg.cont_list); @@ -4608,11 +4346,9 @@ static void syn_cmd_region(exarg_T *eap, int syncing) } rest = skipwhite(p); } else { - /* - * Allocate room for a syn_pattern, and link it in the list of - * syn_patterns for this item, at the start (because the list is - * used from end to start). - */ + // Allocate room for a syn_pattern, and link it in the list of + // syn_patterns for this item, at the start (because the list is + // used from end to start). ppp = xmalloc(sizeof(struct pat_ptr)); ppp->pp_next = pat_ptrs[item]; pat_ptrs[item] = ppp; @@ -4650,10 +4386,8 @@ static void syn_cmd_region(exarg_T *eap, int syncing) } if (rest != NULL) { - /* - * Check for trailing garbage or command. - * If OK, add the item. - */ + // Check for trailing garbage or command. + // If OK, add the item. eap->nextcmd = check_nextcmd(rest); if (!ends_excmd(*rest) || eap->skip) { rest = NULL; @@ -4661,9 +4395,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) ga_grow(&(curwin->w_s->b_syn_patterns), pat_count); if ((syn_id = syn_check_group(arg, (size_t)(group_name_end - arg))) != 0) { syn_incl_toplevel(syn_id, &syn_opt_arg.flags); - /* - * Store the start/skip/end in the syn_items list - */ + // Store the start/skip/end in the syn_items list int idx = curwin->w_s->b_syn_patterns.ga_len; for (item = ITEM_START; item <= ITEM_END; item++) { for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp->pp_next) { @@ -4704,9 +4436,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing) } } - /* - * Free the allocated memory. - */ + // Free the allocated memory. for (item = ITEM_START; item <= ITEM_END; item++) { for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp_next) { if (!success && ppp->pp_synp != NULL) { @@ -4750,9 +4480,7 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con const int16_t *g2; int16_t *clstr = NULL; - /* - * Handle degenerate cases. - */ + // Handle degenerate cases. if (*clstr2 == NULL) { return; } @@ -4788,13 +4516,9 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con g2 = *clstr2; int count = 0; - /* - * First, loop through the lists until one of them is empty. - */ + // First, loop through the lists until one of them is empty. while (*g1 && *g2) { - /* - * We always want to add from the first list. - */ + // We always want to add from the first list. if (*g1 < *g2) { if (round == 2) { clstr[count] = *g1; @@ -4803,10 +4527,8 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con g1++; continue; } - /* - * We only want to add from the second list if we're adding the - * lists. - */ + // We only want to add from the second list if we're adding the + // lists. if (list_op == CLUSTER_ADD) { if (round == 2) { clstr[count] = *g2; @@ -4819,11 +4541,9 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con g2++; } - /* - * Now add the leftovers from whichever list didn't get finished - * first. As before, we only want to add from the second list if - * we're adding the lists. - */ + // Now add the leftovers from whichever list didn't get finished + // first. As before, we only want to add from the second list if + // we're adding the lists. for (; *g1; g1++, count++) { if (round == 2) { clstr[count] = *g1; @@ -4838,10 +4558,8 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con } if (round == 1) { - /* - * If the group ended up empty, we don't need to allocate any - * space for it. - */ + // If the group ended up empty, we don't need to allocate any + // space for it. if (count == 0) { clstr = NULL; break; @@ -4851,9 +4569,7 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con } } - /* - * Finally, put the new list in place. - */ + // Finally, put the new list in place. xfree(*clstr1); xfree(*clstr2); *clstr1 = clstr; @@ -4909,9 +4625,7 @@ static int syn_check_cluster(char *pp, int len) /// @return 0 for failure. static int syn_add_cluster(char *name) { - /* - * First call for this growarray: init growing array. - */ + // First call for this growarray: init growing array. if (curwin->w_s->b_syn_clusters.ga_data == NULL) { curwin->w_s->b_syn_clusters.ga_itemsize = sizeof(syn_cluster_T); ga_set_growsize(&curwin->w_s->b_syn_clusters, 10); @@ -4941,10 +4655,8 @@ static int syn_add_cluster(char *name) return len + SYNID_CLUSTER; } -/* - * Handle ":syntax cluster {cluster-name} [contains={groupname},..] - * [add={groupname},..] [remove={groupname},..]". - */ +// Handle ":syntax cluster {cluster-name} [contains={groupname},..] +// [add={groupname},..] [remove={groupname},..]". static void syn_cmd_cluster(exarg_T *eap, int syncing) { char *arg = eap->arg; @@ -5013,9 +4725,7 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) } } -/* - * On first call for current buffer: Init growing array. - */ +// On first call for current buffer: Init growing array. static void init_syn_patterns(void) { curwin->w_s->b_syn_patterns.ga_itemsize = sizeof(synpat_T); @@ -5058,9 +4768,7 @@ static char *get_syn_pattern(char *arg, synpat_T *ci) ci->sp_ic = curwin->w_s->b_syn_ic; syn_clear_time(&ci->sp_time); - /* - * Check for a match, highlight or region offset. - */ + // Check for a match, highlight or region offset. end++; do { for (idx = SPO_COUNT; --idx >= 0;) { @@ -5324,9 +5032,7 @@ static int get_id_list(char **const arg, const int keylen, int16_t **const list, id = syn_check_cluster(name + 2, (int)(end - p - 1)); } } else { - /* - * Handle full group name. - */ + // Handle full group name. if (strpbrk(name + 1, "\\.*^$~[") == NULL) { id = syn_check_group((name + 1), (size_t)(end - p)); } else { @@ -5411,9 +5117,7 @@ static int get_id_list(char **const arg, const int keylen, int16_t **const list, return OK; } -/* - * Make a copy of an ID list. - */ +// Make a copy of an ID list. static int16_t *copy_id_list(const int16_t *const list) { if (list == NULL) { @@ -5470,10 +5174,8 @@ static int in_id_list(stateitem_T *cur_si, int16_t *list, struct sp_syn *ssp, in return false; } - /* - * If list is ID_LIST_ALL, we are in a transparent item that isn't - * inside anything. Only allow not-contained groups. - */ + // If list is ID_LIST_ALL, we are in a transparent item that isn't + // inside anything. Only allow not-contained groups. if (list == ID_LIST_ALL) { return !contained; } @@ -5505,9 +5207,7 @@ static int in_id_list(stateitem_T *cur_si, int16_t *list, struct sp_syn *ssp, in retval = true; } - /* - * Return "retval" if id is in the contains list. - */ + // Return "retval" if id is in the contains list. while (item != 0) { if (item == id) { return retval; @@ -5651,19 +5351,15 @@ static enum { EXP_CLUSTER, // expand ":syn list @cluster" arguments } expand_what; -/* - * Reset include_link, include_default, include_none to 0. - * Called when we are done expanding. - */ +// Reset include_link, include_default, include_none to 0. +// Called when we are done expanding. void reset_expand_highlight(void) { include_link = include_default = include_none = 0; } -/* - * Handle command line completion for :match and :echohl command: Add "None" - * as highlight group. - */ +// Handle command line completion for :match and :echohl command: Add "None" +// as highlight group. void set_context_in_echohl_cmd(expand_T *xp, const char *arg) { xp->xp_context = EXPAND_HIGHLIGHT; @@ -5671,9 +5367,7 @@ void set_context_in_echohl_cmd(expand_T *xp, const char *arg) include_none = 1; } -/* - * Handle command line completion for :syntax command. - */ +// Handle command line completion for :syntax command. void set_context_in_syntax_cmd(expand_T *xp, const char *arg) { // Default: expand subcommands. @@ -5714,10 +5408,8 @@ void set_context_in_syntax_cmd(expand_T *xp, const char *arg) } } -/* - * Function given to ExpandGeneric() to obtain the list syntax names for - * expansion. - */ +// Function given to ExpandGeneric() to obtain the list syntax names for +// expansion. char *get_syntax_name(expand_T *xp, int idx) { switch (expand_what) { @@ -5773,12 +5465,10 @@ int syn_get_id(win_T *wp, linenr_T lnum, colnr_T col, int trans, bool *spellp, i return trans ? current_trans_id : current_id; } -/* - * Get extra information about the syntax item. Must be called right after - * get_syntax_attr(). - * Stores the current item sequence nr in "*seqnrp". - * Returns the current flags. - */ +// Get extra information about the syntax item. Must be called right after +// get_syntax_attr(). +// Stores the current item sequence nr in "*seqnrp". +// Returns the current flags. int get_syntax_info(int *seqnrp) { *seqnrp = current_seqnr; @@ -5802,19 +5492,15 @@ int syn_get_concealed_id(win_T *wp, linenr_T lnum, colnr_T col) return 0; } -/* - * Return conceal substitution character - */ +// Return conceal substitution character int syn_get_sub_char(void) { return current_sub_char; } -/* - * Return the syntax ID at position "i" in the current stack. - * The caller must have called syn_get_id() before to fill the stack. - * Returns -1 when "i" is out of range. - */ +// Return the syntax ID at position "i" in the current stack. +// The caller must have called syn_get_id() before to fill the stack. +// Returns -1 when "i" is out of range. int syn_get_stack_item(int i) { if (i >= current_state.ga_len) { @@ -5877,9 +5563,7 @@ int syn_get_foldlevel(win_T *wp, linenr_T lnum) return level; } -/* - * ":syntime". - */ +// ":syntime". void ex_syntime(exarg_T *eap) { if (STRCMP(eap->arg, "on") == 0) { @@ -5903,9 +5587,7 @@ static void syn_clear_time(syn_time_T *st) st->match = 0; } -/* - * Clear the syntax timing for the current buffer. - */ +// Clear the syntax timing for the current buffer. static void syntime_clear(void) { synpat_T *spp; @@ -5920,10 +5602,8 @@ static void syntime_clear(void) } } -/* - * Function given to ExpandGeneric() to obtain the possible arguments of the - * ":syntime {on,off,clear,report}" command. - */ +// Function given to ExpandGeneric() to obtain the possible arguments of the +// ":syntime {on,off,clear,report}" command. char *get_syntime_arg(expand_T *xp, int idx) { switch (idx) { @@ -5947,9 +5627,7 @@ static int syn_compare_syntime(const void *v1, const void *v2) return profile_cmp(s1->total, s2->total); } -/* - * Clear the syntax timing for the current buffer. - */ +// Clear the syntax timing for the current buffer. static void syntime_report(void) { if (!syntax_present(curwin)) { diff --git a/src/nvim/tag.c b/src/nvim/tag.c index d1d5514648..04154384af 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -1,9 +1,7 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com -/* - * Code to handle tags and the tag stack - */ +// Code to handle tags and the tag stack #include #include @@ -51,9 +49,7 @@ #include "nvim/vim.h" #include "nvim/window.h" -/* - * Structure to hold pointers to various items in a tag line. - */ +// Structure to hold pointers to various items in a tag line. typedef struct tag_pointers { // filled in by parse_tag_line(): char_u *tagname; // start of tag name (skip "file:") @@ -73,9 +69,7 @@ typedef struct tag_pointers { linenr_T tagline; // "line:" value } tagptrs_T; -/* - * Structure to hold info about the tag pattern being used. - */ +// Structure to hold info about the tag pattern being used. typedef struct { char_u *pat; // the pattern int len; // length of pat[] @@ -117,10 +111,8 @@ static char_u *tfu_inv_ret_msg static char_u *tagmatchname = NULL; // name of last used tag -/* - * Tag for preview window is remembered separately, to avoid messing up the - * normal tagstack. - */ +// Tag for preview window is remembered separately, to avoid messing up the +// normal tagstack. static taggy_T ptag_entry = { NULL, INIT_FMARK, 0, 0, NULL }; static int tfu_in_use = false; // disallow recursive call of tagfunc @@ -243,10 +235,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) ptag_entry.tagname = (char *)vim_strsave(tag); } } else { - /* - * If the last used entry is not at the top, delete all tag - * stack entries above it. - */ + // If the last used entry is not at the top, delete all tag + // stack entries above it. while (tagstackidx < tagstacklen) { tagstack_clear_entry(&tagstack[--tagstacklen]); } @@ -300,10 +290,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) // tagstack before it's used. saved_fmark = tagstack[tagstackidx].fmark; if (saved_fmark.fnum != curbuf->b_fnum) { - /* - * Jump to other file. If this fails (e.g. because the - * file was changed) keep original position in tag stack. - */ + // Jump to other file. If this fails (e.g. because the + // file was changed) keep original position in tag stack. if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum, GETF_SETMARK, forceit) == FAIL) { tagstackidx = oldtagstackidx; // back to old posn @@ -340,11 +328,9 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) // ":tag" (no argument): go to newer pattern save_pos = true; // save the cursor position below if ((tagstackidx += count - 1) >= tagstacklen) { - /* - * Beyond the last one, just give an error message and - * go to the last one. Don't store the cursor - * position. - */ + // Beyond the last one, just give an error message and + // go to the last one. Don't store the cursor + // position. tagstackidx = tagstacklen - 1; emsg(_(topmsg)); save_pos = false; @@ -401,9 +387,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) ptag_entry.cur_fnum = cur_fnum; } } else { - /* - * For ":tag [arg]" or ":tselect" remember position before the jump. - */ + // For ":tag [arg]" or ":tselect" remember position before the jump. saved_fmark = tagstack[tagstackidx].fmark; if (save_pos) { tagstack[tagstackidx].fmark.mark = curwin->w_cursor; @@ -432,9 +416,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) } } - /* - * Repeat searching for tags, when a file has not been found. - */ + // Repeat searching for tags, when a file has not been found. for (;;) { int other_name; char_u *name; @@ -598,10 +580,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) ptag_entry.cur_fnum = cur_fnum; } - /* - * Only when going to try the next match, report that the previous - * file didn't exist. Otherwise an emsg() is given below. - */ + // Only when going to try the next match, report that the previous + // file didn't exist. Otherwise an emsg() is given below. if (nofile_fname != NULL && error_cur_match != cur_match) { smsg(_("File \"%s\" does not exist"), nofile_fname); } @@ -640,9 +620,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose) vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name); set_vim_var_string(VV_SWAPCOMMAND, (char *)IObuff, -1); - /* - * Jump to the desired match. - */ + // Jump to the desired match. i = jumpto_tag((char_u *)matches[cur_match], forceit, type != DT_CSCOPE); set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); @@ -1005,9 +983,7 @@ static int add_llist_tags(char_u *tag, int num_matches, char **matches) return OK; } -/* - * Free cached tags. - */ +// Free cached tags. void tag_freematch(void) { XFREE_CLEAR(tagmatchname); @@ -1023,9 +999,7 @@ static void taglen_advance(int l) } } -/* - * Print the tag stack - */ +// Print the tag stack void do_tags(exarg_T *eap) { int i; @@ -1061,11 +1035,9 @@ void do_tags(exarg_T *eap) } } -/* - * Compare two strings, for length "len", ignoring case the ASCII way. - * return 0 for match, < 0 for smaller, > 0 for bigger - * Make sure case is folded to uppercase in comparison (like for 'sort -f') - */ +// Compare two strings, for length "len", ignoring case the ASCII way. +// return 0 for match, < 0 for smaller, > 0 for bigger +// Make sure case is folded to uppercase in comparison (like for 'sort -f') static int tag_strnicmp(char_u *s1, char_u *s2, size_t len) { int i; @@ -1085,9 +1057,7 @@ static int tag_strnicmp(char_u *s1, char_u *s2, size_t len) return 0; // strings match } -/* - * Extract info from the tag search pattern "pats->pat". - */ +// Extract info from the tag search pattern "pats->pat". static void prepare_pats(pat_T *pats, int has_re) { pats->head = pats->pat; @@ -1472,9 +1442,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc orgpat.regmatch.regprog = NULL; vimconv.vc_type = CONV_NONE; - /* - * Allocate memory for the buffers that are used - */ + // Allocate memory for the buffers that are used lbuf = xmalloc((size_t)lbuf_size); tag_fname = xmalloc(MAXPATHL + 1); for (mtt = 0; mtt < MT_COUNT; mtt++) { @@ -1484,9 +1452,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc STRCPY(tag_fname, "from cscope"); // for error messages - /* - * Initialize a few variables - */ + // Initialize a few variables if (help_only) { // want tags from help file curbuf->b_help = true; // will be restored later } else if (use_cscope) { @@ -1534,16 +1500,15 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc } } - /* - * When finding a specified number of matches, first try with matching - * case, so binary search can be used, and try ignore-case matches in a - * second loop. - * When finding all matches, 'tagbsearch' is off, or there is no fixed - * string to look for, ignore case right away to avoid going though the - * tags files twice. - * When the tag file is case-fold sorted, it is either one or the other. - * Only ignore case when TAG_NOIC not used or 'ignorecase' set. - */ + // When finding a specified number of matches, first try with matching + // case, so binary search can be used, and try ignore-case matches in a + // second loop. + // When finding all matches, 'tagbsearch' is off, or there is no fixed + // string to look for, ignore case right away to avoid going though the + // tags files twice. + // When the tag file is case-fold sorted, it is either one or the other. + // Only ignore case when TAG_NOIC not used or 'ignorecase' set. + // Set a flag if the file extension is .txt if ((flags & TAG_KEEP_LANG) && help_lang_find == NULL @@ -1634,9 +1599,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc state = TS_START; // we're at the start of the file - /* - * Read and parse the lines in the file one by one - */ + // Read and parse the lines in the file one by one for (;;) { // check for CTRL-C typed, more often when jumping around if (state == TS_BINARY || state == TS_SKIP_BACK) { @@ -1661,9 +1624,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc if (get_it_again) { goto line_read_in; } - /* - * For binary search: compute the next offset to use. - */ + // For binary search: compute the next offset to use. if (state == TS_BINARY) { offset = search_info.low_offset + ((search_info.high_offset - search_info.low_offset) / 2); @@ -1682,10 +1643,8 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc } } - /* - * When jumping around in the file, first read a line to find the - * start of the next line. - */ + // When jumping around in the file, first read a line to find the + // start of the next line. if (state == TS_BINARY || state == TS_SKIP_BACK) { // Adjust the search file offset to the correct position search_info.curr_offset_used = search_info.curr_offset; @@ -1714,11 +1673,9 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc search_info.curr_offset = search_info.curr_offset_used; continue; } - } - /* - * Not jumping around in the file: Read the next line. - */ - else { + } else { + // Not jumping around in the file: Read the next line. + // skip empty and blank lines do { eof = use_cscope @@ -1754,10 +1711,8 @@ line_read_in: } } - /* - * When still at the start of the file, check for Emacs tags file - * format, and for "not sorted" flag. - */ + // When still at the start of the file, check for Emacs tags file + // format, and for "not sorted" flag. if (state == TS_START) { // The header ends when the line sorts below "!_TAG_". When // case is folded lower case letters sort before "_". @@ -1768,9 +1723,7 @@ line_read_in: goto parse_line; } - /* - * Read header line. - */ + // Read header line. if (STRNCMP(lbuf, "!_TAG_FILE_SORTED\t", 18) == 0) { tag_file_sorted = lbuf[18]; } @@ -1788,15 +1741,13 @@ line_read_in: // Headers ends. - /* - * When there is no tag head, or ignoring case, need to do a - * linear search. - * When no "!_TAG_" is found, default to binary search. If - * the tag file isn't sorted, the second loop will find it. - * When "!_TAG_FILE_SORTED" found: start binary search if - * flag set. - * For cscope, it's always linear. - */ + // When there is no tag head, or ignoring case, need to do a + // linear search. + // When no "!_TAG_" is found, default to binary search. If + // the tag file isn't sorted, the second loop will find it. + // When "!_TAG_FILE_SORTED" found: start binary search if + // flag set. + // For cscope, it's always linear. if (linear || use_cscope) { state = TS_LINEAR; } else if (tag_file_sorted == NUL) { @@ -1871,10 +1822,8 @@ parse_line: break; } - /* - * Skip this line if the length of the tag is different and - * there is no regexp, or the tag is too short. - */ + // Skip this line if the length of the tag is different and + // there is no regexp, or the tag is too short. cmplen = (int)(tagp.tagname_end - tagp.tagname); if (p_tl != 0 && cmplen > p_tl) { // adjust for 'taglength' cmplen = (int)p_tl; @@ -1886,9 +1835,7 @@ parse_line: } if (state == TS_BINARY) { - /* - * Simplistic check for unsorted tags file. - */ + // Simplistic check for unsorted tags file. i = (int)tagp.tagname[0]; if (sortic) { i = TOUPPER_ASC(tagp.tagname[0]); @@ -1897,9 +1844,7 @@ parse_line: sort_error = true; } - /* - * Compare the current tag with the searched tag. - */ + // Compare the current tag with the searched tag. if (sortic) { tagcmp = tag_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen); @@ -1907,10 +1852,8 @@ parse_line: tagcmp = STRNCMP(tagp.tagname, orgpat.head, cmplen); } - /* - * A match with a shorter tag means to search forward. - * A match with a longer tag means to search backward. - */ + // A match with a shorter tag means to search forward. + // A match with a longer tag means to search backward. if (tagcmp == 0) { if (cmplen < orgpat.headlen) { tagcmp = -1; @@ -1998,10 +1941,8 @@ parse_line: break; } - /* - * First try matching with the pattern literally (also when it is - * a regexp). - */ + // First try matching with the pattern literally (also when it is + // a regexp). cmplen = (int)(tagp.tagname_end - tagp.tagname); if (p_tl != 0 && cmplen > p_tl) { // adjust for 'taglength' cmplen = (int)p_tl; @@ -2022,9 +1963,7 @@ parse_line: } } - /* - * Has a regexp: Also find tags matching regexp. - */ + // Has a regexp: Also find tags matching regexp. match_re = false; if (!match && orgpat.regmatch.regprog != NULL) { int cc; @@ -2211,9 +2150,7 @@ parse_line: sort_error = false; } - /* - * Stop searching if sufficient tags have been found. - */ + // Stop searching if sufficient tags have been found. if (match_count >= mincount) { retval = OK; stop_searching = true; @@ -2251,10 +2188,8 @@ findtag_end: vim_regfree(orgpat.regmatch.regprog); xfree(tag_fname); - /* - * Move the matches from the ga_match[] arrays into one list of - * matches. When retval == FAIL, free the matches. - */ + // Move the matches from the ga_match[] arrays into one list of + // matches. When retval == FAIL, free the matches. if (retval == FAIL) { match_count = 0; } @@ -2303,10 +2238,8 @@ findtag_end: static garray_T tag_fnames = GA_EMPTY_INIT_VALUE; -/* - * Callback function for finding all "tags" and "tags-??" files in - * 'runtimepath' doc directories. - */ +// Callback function for finding all "tags" and "tags-??" files in +// 'runtimepath' doc directories. static void found_tagfile_cb(char *fname, void *cookie) { char_u *const tag_fname = vim_strsave((char_u *)fname); @@ -2348,11 +2281,9 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) } if (curbuf->b_help) { - /* - * For help files it's done in a completely different way: - * Find "doc/tags" and "doc/tags-??" in all directories in - * 'runtimepath'. - */ + // For help files it's done in a completely different way: + // Find "doc/tags" and "doc/tags-??" in all directories in + // 'runtimepath'. if (first) { ga_clear_strings(&tag_fnames); ga_init(&tag_fnames, (int)sizeof(char *), 10); @@ -2392,12 +2323,10 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) tnp->tn_np = (char *)tnp->tn_tags; } - /* - * Loop until we have found a file name that can be used. - * There are two states: - * tnp->tn_did_filefind_init == false: setup for next part in 'tags'. - * tnp->tn_did_filefind_init == true: find next file in this part. - */ + // Loop until we have found a file name that can be used. + // There are two states: + // tnp->tn_did_filefind_init == false: setup for next part in 'tags'. + // tnp->tn_did_filefind_init == true: find next file in this part. for (;;) { if (tnp->tn_did_filefind_init) { fname = (char *)vim_findfile(tnp->tn_search_ctx); @@ -2416,9 +2345,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) return FAIL; } - /* - * Copy next file name into buf. - */ + // Copy next file name into buf. buf[0] = NUL; (void)copy_option_part(&tnp->tn_np, buf, MAXPATHL - 1, " ,"); @@ -2445,9 +2372,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf) return OK; } -/* - * Free the contents of a tagname_T that was filled by get_tagfname(). - */ +// Free the contents of a tagname_T that was filled by get_tagfname(). void tagname_free(tagname_T *tnp) { xfree(tnp->tn_tags); @@ -2499,20 +2424,18 @@ static int parse_tag_line(char_u *lbuf, tagptrs_T *tagp) return OK; } -/* - * Check if tagname is a static tag - * - * Static tags produced by the older ctags program have the format: - * 'file:tag file /pattern'. - * This is only recognized when both occurrence of 'file' are the same, to - * avoid recognizing "string::string" or ":exit". - * - * Static tags produced by the new ctags program have the format: - * 'tag file /pattern/;"file:' " - * - * Return true if it is a static tag and adjust *tagname to the real tag. - * Return false if it is not a static tag. - */ +// Check if tagname is a static tag +// +// Static tags produced by the older ctags program have the format: +// 'file:tag file /pattern'. +// This is only recognized when both occurrence of 'file' are the same, to +// avoid recognizing "string::string" or ":exit". +// +// Static tags produced by the new ctags program have the format: +// 'tag file /pattern/;"file:' " +// +// Return true if it is a static tag and adjust *tagname to the real tag. +// Return false if it is not a static tag. static bool test_for_static(tagptrs_T *tagp) { char_u *p; @@ -2620,11 +2543,9 @@ static int parse_match(char *lbuf, tagptrs_T *tagp) return retval; } -/* - * Find out the actual file name of a tag. Concatenate the tags file name - * with the matching tag file name. - * Returns an allocated string. - */ +// Find out the actual file name of a tag. Concatenate the tags file name +// with the matching tag file name. +// Returns an allocated string. static char_u *tag_full_fname(tagptrs_T *tagp) { int c = *tagp->fname_end; @@ -2688,9 +2609,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) *pbuf_end = NUL; { - /* - * Remove the "fieldname:value" stuff; we don't need it here. - */ + // Remove the "fieldname:value" stuff; we don't need it here. str = pbuf; if (find_extra(&str) == OK) { pbuf_end = str; @@ -2698,18 +2617,14 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) } } - /* - * Expand file name, when needed (for environment variables). - * If 'tagrelative' option set, may change file name. - */ + // Expand file name, when needed (for environment variables). + // If 'tagrelative' option set, may change file name. fname = expand_tag_fname(fname, tagp.tag_fname, true); tofree_fname = fname; // free() it later - /* - * Check if the file with the tag exists before abandoning the current - * file. Also accept a file name for which there is a matching BufReadCmd - * autocommand event (e.g., http://sys/file). - */ + // Check if the file with the tag exists before abandoning the current + // file. Also accept a file name for which there is a matching BufReadCmd + // autocommand event (e.g., http://sys/file). if (!os_path_exists((char *)fname) && !has_autocmd(EVENT_BUFREADCMD, (char *)fname, NULL)) { @@ -2725,19 +2640,15 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) postponed_split = 0; // don't split again below curwin_save = curwin; // Save current window - /* - * If we are reusing a window, we may change dir when - * entering it (autocommands) so turn the tag filename - * into a fullpath - */ + // If we are reusing a window, we may change dir when + // entering it (autocommands) so turn the tag filename + // into a fullpath if (!curwin->w_p_pvw) { full_fname = (char_u *)FullName_save((char *)fname, false); fname = full_fname; - /* - * Make the preview window the current window. - * Open a preview window when needed. - */ + // Make the preview window the current window. + // Open a preview window when needed. prepare_tagpreview(true); } } @@ -2803,25 +2714,21 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) // Save value of no_hlsearch, jumping to a tag is not a real search const bool save_no_hlsearch = no_hlsearch; - /* - * If 'cpoptions' contains 't', store the search pattern for the "n" - * command. If 'cpoptions' does not contain 't', the search pattern - * is not stored. - */ + // If 'cpoptions' contains 't', store the search pattern for the "n" + // command. If 'cpoptions' does not contain 't', the search pattern + // is not stored. if (vim_strchr(p_cpo, CPO_TAGPAT) != NULL) { search_options = 0; } else { search_options = SEARCH_KEEP; } - /* - * If the command is a search, try here. - * - * Reset 'smartcase' for the search, since the search pattern was not - * typed by the user. - * Only use do_search() when there is a full search command, without - * anything following. - */ + // If the command is a search, try here. + // + // Reset 'smartcase' for the search, since the search pattern was not + // typed by the user. + // Only use do_search() when there is a full search command, without + // anything following. str = pbuf; if (pbuf[0] == '/' || pbuf[0] == '?') { str = (char_u *)skip_regexp((char *)pbuf + 1, pbuf[0], false, NULL) + 1; @@ -2848,9 +2755,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) int found = 1; int cc; - /* - * try again, ignore case now - */ + // try again, ignore case now p_ic = true; if (!do_search(NULL, pbuf[0], pbuf[0], pbuf + 1, (long)1, search_options, NULL)) { @@ -2875,10 +2780,8 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) emsg(_("E434: Can't find tag pattern")); curwin->w_cursor.lnum = save_lnum; } else { - /* - * Only give a message when really guessed, not when 'ic' - * is set and match found while ignoring case. - */ + // Only give a message when really guessed, not when 'ic' + // is set and match found while ignoring case. if (found == 2 || !save_p_ic) { msg(_("E435: Couldn't find tag, just guessing!")); if (!msg_scrolled && msg_silent == 0) { @@ -2927,10 +2830,8 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help) } if (retval == OK) { - /* - * For a help buffer: Put the cursor line at the top of the window, - * the help subject will be below it. - */ + // For a help buffer: Put the cursor line at the top of the window, + // the help subject will be below it. if (curbuf->b_help) { set_topline(curwin, curwin->w_cursor.lnum); } @@ -2976,9 +2877,7 @@ static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bo char_u *expanded_fname = NULL; expand_T xpc; - /* - * Expand file name (for environment variables) when needed. - */ + // Expand file name (for environment variables) when needed. if (expand && path_has_wildcard((char *)fname)) { ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; @@ -2997,9 +2896,7 @@ static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bo STRCPY(retval, tag_fname); STRLCPY(retval + (p - tag_fname), fname, MAXPATHL - (p - tag_fname)); - /* - * Translate names like "src/a/../b/file.c" into "src/b/file.c". - */ + // Translate names like "src/a/../b/file.c" into "src/b/file.c". simplify_filename(retval); } else { retval = vim_strsave(fname); @@ -3034,10 +2931,8 @@ static int test_for_current(char *fname, char *fname_end, char *tag_fname, char return retval; } -/* - * Find the end of the tagaddress. - * Return OK if ";\"" is following, FAIL otherwise. - */ +// Find the end of the tagaddress. +// Return OK if ";\"" is following, FAIL otherwise. static int find_extra(char_u **pp) { char_u *str = *pp; diff --git a/src/nvim/window.c b/src/nvim/window.c index 6ee3820d95..530cbc0c7b 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -970,21 +970,19 @@ static int check_split_disallowed(void) return OK; } -/* - * split the current window, implements CTRL-W s and :split - * - * "size" is the height or width for the new window, 0 to use half of current - * height or width. - * - * "flags": - * WSP_ROOM: require enough room for new window - * WSP_VERT: vertical split. - * WSP_TOP: open window at the top-left of the screen (help window). - * WSP_BOT: open window at the bottom-right of the screen (quickfix window). - * WSP_HELP: creating the help window, keep layout snapshot - * - * return FAIL for failure, OK otherwise - */ +// split the current window, implements CTRL-W s and :split +// +// "size" is the height or width for the new window, 0 to use half of current +// height or width. +// +// "flags": +// WSP_ROOM: require enough room for new window +// WSP_VERT: vertical split. +// WSP_TOP: open window at the top-left of the screen (help window). +// WSP_BOT: open window at the bottom-right of the screen (quickfix window). +// WSP_HELP: creating the help window, keep layout snapshot +// +// return FAIL for failure, OK otherwise int win_split(int size, int flags) { if (check_split_disallowed() == FAIL) { @@ -1014,12 +1012,10 @@ int win_split(int size, int flags) return win_split_ins(size, flags, NULL, 0); } -/* - * When "new_wp" is NULL: split the current window in two. - * When "new_wp" is not NULL: insert this window at the far - * top/left/right/bottom. - * return FAIL for failure, OK otherwise - */ +// When "new_wp" is NULL: split the current window in two. +// When "new_wp" is not NULL: insert this window at the far +// top/left/right/bottom. +// return FAIL for failure, OK otherwise int win_split_ins(int size, int flags, win_T *new_wp, int dir) { win_T *wp = new_wp; @@ -1069,10 +1065,8 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) layout = FR_ROW; - /* - * Check if we are able to split the current window and compute its - * width. - */ + // Check if we are able to split the current window and compute its + // width. // Current window requires at least 1 space. wmw1 = (p_wmw == 0 ? 1 : (int)p_wmw); needed = wmw1 + 1; @@ -1243,9 +1237,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) } } - /* - * allocate new window structure and link it in the window list - */ + // allocate new window structure and link it in the window list if ((flags & WSP_TOP) == 0 && ((flags & WSP_BOT) || (flags & WSP_BELOW) @@ -1282,9 +1274,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) CLEAR_FIELD(wp->w_border_adj); } - /* - * Reorganise the tree of frames to insert the new window. - */ + // Reorganise the tree of frames to insert the new window. if (flags & (WSP_TOP | WSP_BOT)) { if ((topframe->fr_layout == FR_COL && (flags & WSP_VERT) == 0) || (topframe->fr_layout == FR_ROW && (flags & WSP_VERT) != 0)) { @@ -1489,9 +1479,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) msg_col = 0; // put position back at start of line } - /* - * equalize the window sizes. - */ + // equalize the window sizes. if (do_equal || dir != 0) { win_equal(wp, true, (flags & WSP_VERT) ? (dir == 'v' ? 'b' : 'h') : (dir == 'h' ? 'b' : 'v')); } @@ -1527,13 +1515,11 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) return OK; } -/* - * Initialize window "newp" from window "oldp". - * Used when splitting a window and when creating a new tab page. - * The windows will both edit the same buffer. - * WSP_NEWLOC may be specified in flags to prevent the location list from - * being copied. - */ +// Initialize window "newp" from window "oldp". +// Used when splitting a window and when creating a new tab page. +// The windows will both edit the same buffer. +// WSP_NEWLOC may be specified in flags to prevent the location list from +// being copied. static void win_init(win_T *newp, win_T *oldp, int flags) { int i; @@ -1591,10 +1577,8 @@ static void win_init(win_T *newp, win_T *oldp, int flags) newp->w_winbar_height = oldp->w_winbar_height; } -/* - * Initialize window "newp" from window "old". - * Only the essential things are copied. - */ +// Initialize window "newp" from window "old". +// Only the essential things are copied. static void win_init_some(win_T *newp, win_T *oldp) { // Use the same argument list. @@ -1671,9 +1655,7 @@ bool win_valid_any_tab(win_T *win) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT return false; } -/* - * Return the number of windows. - */ +// Return the number of windows. int win_count(void) { int count = 0; @@ -1746,9 +1728,7 @@ int make_windows(int count, bool vertical) return count - todo; } -/* - * Exchange current and next window - */ +// Exchange current and next window static void win_exchange(long Prenum) { frame_T *frp; @@ -1768,9 +1748,7 @@ static void win_exchange(long Prenum) return; } - /* - * find window to exchange with - */ + // find window to exchange with if (Prenum) { frp = curwin->w_frame->fr_parent->fr_child; while (frp != NULL && --Prenum > 0) { @@ -1789,14 +1767,12 @@ static void win_exchange(long Prenum) } wp = frp->fr_win; - /* - * 1. remove curwin from the list. Remember after which window it was in wp2 - * 2. insert curwin before wp in the list - * if wp != wp2 - * 3. remove wp from the list - * 4. insert wp after wp2 - * 5. exchange the status line height, winbar height, hsep height and vsep width. - */ + // 1. remove curwin from the list. Remember after which window it was in wp2 + // 2. insert curwin before wp in the list + // if wp != wp2 + // 3. remove wp from the list + // 4. insert wp after wp2 + // 5. exchange the status line height, winbar height, hsep height and vsep width. wp2 = curwin->w_prev; frp2 = curwin->w_frame->fr_prev; if (wp->w_prev != curwin) { @@ -1927,9 +1903,7 @@ static void win_rotate(bool upwards, int count) redraw_all_later(UPD_NOT_VALID); } -/* - * Move the current window to the very top/bottom/left/right of the screen. - */ +// Move the current window to the very top/bottom/left/right of the screen. static void win_totop(int size, int flags) { int dir = 0; @@ -1973,10 +1947,8 @@ static void win_totop(int size, int flags) } } -/* - * Move window "win1" to below/right of "win2" and make "win1" the current - * window. Only works within the same frame! - */ +// Move window "win1" to below/right of "win2" and make "win1" the current +// window. Only works within the same frame! void win_move_after(win_T *win1, win_T *win2) { int height; @@ -2146,11 +2118,9 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int totwincount = (n + extra_sep) / ((int)p_wmw + 1); has_next_curwin = frame_has_win(topfr, next_curwin); - /* - * Compute width for "next_curwin" window and room available for - * other windows. - * "m" is the minimal width when counting p_wiw for "next_curwin". - */ + // Compute width for "next_curwin" window and room available for + // other windows. + // "m" is the minimal width when counting p_wiw for "next_curwin". m = frame_minwidth(topfr, next_curwin); room = width - m; if (room < 0) { @@ -2274,11 +2244,9 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int totwincount = get_maximum_wincount(topfr, n + extra_sep); has_next_curwin = frame_has_win(topfr, next_curwin); - /* - * Compute height for "next_curwin" window and room available for - * other windows. - * "m" is the minimal height when counting p_wh for "next_curwin". - */ + // Compute height for "next_curwin" window and room available for + // other windows. + // "m" is the minimal height when counting p_wh for "next_curwin". m = frame_minheight(topfr, next_curwin); room = height - m; if (room < 0) { @@ -2594,14 +2562,12 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev free_buf = false; } - /* - * Closing the last window in a tab page. First go to another tab - * page and then close the window and the tab page. This avoids that - * curwin and curtab are invalid while we are freeing memory, they may - * be used in GUI events. - * Don't trigger autocommands yet, they may use wrong values, so do - * that below. - */ + // Closing the last window in a tab page. First go to another tab + // page and then close the window and the tab page. This avoids that + // curwin and curtab are invalid while we are freeing memory, they may + // be used in GUI events. + // Don't trigger autocommands yet, they may use wrong values, so do + // that below. goto_tabpage_tp(alt_tabpage(), false, true); redraw_tabline = true; @@ -2745,10 +2711,8 @@ int win_close(win_T *win, bool free_buf, bool force) } } - /* - * Be careful: If autocommands delete the window or cause this window - * to be the last one left, return now. - */ + // Be careful: If autocommands delete the window or cause this window + // to be the last one left, return now. if (wp->w_buffer != curbuf) { reset_VIsual_and_resel(); // stop Visual mode @@ -2860,10 +2824,8 @@ int win_close(win_T *win, bool free_buf, bool force) if (win == curwin) { curwin = wp; if (wp->w_p_pvw || bt_quickfix(wp->w_buffer)) { - /* - * If the cursor goes to the preview or the quickfix window, try - * finding another window to go to. - */ + // If the cursor goes to the preview or the quickfix window, try + // finding another window to go to. for (;;) { if (wp->w_next == NULL) { wp = firstwin; @@ -2908,10 +2870,8 @@ int win_close(win_T *win, bool free_buf, bool force) split_disallowed--; - /* - * If last window has a status line now and we don't want one, - * remove the status line. - */ + // If last window has a status line now and we don't want one, + // remove the status line. last_status(false); // After closing the help window, try restoring the window layout from @@ -2955,13 +2915,11 @@ static void do_autocmd_winclosed(win_T *win) recursive = false; } -/* - * Close window "win" in tab page "tp", which is not the current tab page. - * This may be the last window in that tab page and result in closing the tab, - * thus "tp" may become invalid! - * Caller must check if buffer is hidden and whether the tabline needs to be - * updated. - */ +// Close window "win" in tab page "tp", which is not the current tab page. +// This may be the last window in that tab page and result in closing the tab, +// thus "tp" may become invalid! +// Caller must check if buffer is hidden and whether the tabline needs to be +// updated. void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) { int dir; @@ -3138,16 +3096,12 @@ win_T *winframe_remove(win_T *win, int *dirp, tabpage_T *tp) frame_T *frp_close = win->w_frame; win_T *wp; - /* - * If there is only one window there is nothing to remove. - */ + // If there is only one window there is nothing to remove. if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin) { return NULL; } - /* - * Remove the window from its frame. - */ + // Remove the window from its frame. frp2 = win_altframe(win, tp); wp = frame2win(frp2); @@ -3334,9 +3288,7 @@ static frame_T *win_altframe(win_T *win, tabpage_T *tp) return target_fr; } -/* - * Return the tabpage that will be used if the current one is closed. - */ +// Return the tabpage that will be used if the current one is closed. static tabpage_T *alt_tabpage(void) { tabpage_T *tp; @@ -3351,9 +3303,7 @@ static tabpage_T *alt_tabpage(void) return tp; } -/* - * Find the left-upper window in frame "frp". - */ +// Find the left-upper window in frame "frp". win_T *frame2win(frame_T *frp) { while (frp->fr_win == NULL) { @@ -3557,10 +3507,8 @@ static bool frame_fixed_width(frame_T *frp) return true; } -/* - * Add a status line to windows at the bottom of "frp". - * Note: Does not check if there is room! - */ +// Add a status line to windows at the bottom of "frp". +// Note: Does not check if there is room! static void frame_add_statusline(frame_T *frp) { win_T *wp; @@ -3748,17 +3696,13 @@ static void frame_add_hsep(const frame_T *frp) } } -/* - * Set frame width from the window it contains. - */ +// Set frame width from the window it contains. static void frame_fix_width(win_T *wp) { wp->w_frame->fr_width = wp->w_width + wp->w_vsep_width; } -/* - * Set frame height from the window it contains. - */ +// Set frame height from the window it contains. static void frame_fix_height(win_T *wp) FUNC_ATTR_NONNULL_ALL { @@ -3913,12 +3857,10 @@ void close_others(int message, int forceit) } } -/* - * Allocate the first window and put an empty buffer in it. - * Called from main(). - * - * Return FAIL when something goes wrong. - */ +// Allocate the first window and put an empty buffer in it. +// Called from main(). +// +// Return FAIL when something goes wrong. int win_alloc_first(void) { if (win_alloc_firstwin(NULL) == FAIL) { @@ -3949,12 +3891,10 @@ void win_alloc_aucmd_win(void) RESET_BINDING(aucmd_win); } -/* - * Allocate the first window or the first window in a new tab page. - * When "oldwin" is NULL create an empty buffer for it. - * When "oldwin" is not NULL copy info from it to the new window. - * Return FAIL when something goes wrong (out of memory). - */ +// Allocate the first window or the first window in a new tab page. +// When "oldwin" is NULL create an empty buffer for it. +// When "oldwin" is not NULL copy info from it to the new window. +// Return FAIL when something goes wrong (out of memory). static int win_alloc_firstwin(win_T *oldwin) { curwin = win_alloc(NULL, false); @@ -3986,9 +3926,7 @@ static int win_alloc_firstwin(win_T *oldwin) return OK; } -/* - * Create a frame for window "wp". - */ +// Create a frame for window "wp". static void new_frame(win_T *wp) { frame_T *frp = xcalloc(1, sizeof(frame_T)); @@ -3998,9 +3936,7 @@ static void new_frame(win_T *wp) frp->fr_win = wp; } -/* - * Initialize the window and frame size to the maximum. - */ +// Initialize the window and frame size to the maximum. void win_init_size(void) { firstwin->w_height = (int)ROWS_AVAIL; @@ -4014,9 +3950,7 @@ void win_init_size(void) topframe->fr_width = Columns; } -/* - * Allocate a new tabpage_T and init the values. - */ +// Allocate a new tabpage_T and init the values. static tabpage_T *alloc_tabpage(void) { static int last_tp_handle = 0; @@ -4138,11 +4072,9 @@ int win_new_tabpage(int after, char_u *filename) return FAIL; } -/* - * Open a new tab page if ":tab cmd" was used. It will edit the same buffer, - * like with ":split". - * Returns OK if a new tab page was created, FAIL otherwise. - */ +// Open a new tab page if ":tab cmd" was used. It will edit the same buffer, +// like with ":split". +// Returns OK if a new tab page was created, FAIL otherwise. int may_open_tabpage(void) { int n = (cmdmod.cmod_tab == 0) ? postponed_split_tab : cmdmod.cmod_tab; @@ -4155,10 +4087,8 @@ int may_open_tabpage(void) return FAIL; } -/* - * Create up to "maxcount" tabpages with empty windows. - * Returns the number of resulting tab pages. - */ +// Create up to "maxcount" tabpages with empty windows. +// Returns the number of resulting tab pages. int make_tabpages(int maxcount) { int count = maxcount; @@ -4169,10 +4099,8 @@ int make_tabpages(int maxcount) count = (int)p_tpm; } - /* - * Don't execute autocommands while creating the tab pages. Must do that - * when putting the buffers in the windows. - */ + // Don't execute autocommands while creating the tab pages. Must do that + // when putting the buffers in the windows. block_autocmds(); for (todo = count - 1; todo > 0; todo--) { @@ -4239,9 +4167,7 @@ void close_tabpage(tabpage_T *tab) free_tabpage(tab); } -/* - * Find tab page "n" (first one is 1). Returns NULL when not found. - */ +// Find tab page "n" (first one is 1). Returns NULL when not found. tabpage_T *find_tabpage(int n) { tabpage_T *tp; @@ -4253,10 +4179,8 @@ tabpage_T *find_tabpage(int n) return tp; } -/* - * Get index of tab page "tp". First one has index 1. - * When not found returns number of tab pages plus one. - */ +// Get index of tab page "tp". First one has index 1. +// When not found returns number of tab pages plus one. int tabpage_index(tabpage_T *ftp) { int i = 1; @@ -4412,10 +4336,8 @@ static void tabpage_check_windows(tabpage_T *old_curtab) } } -/* - * Go to tab page "n". For ":tab N" and "Ngt". - * When "n" is 9999 go to the last tab page. - */ +// Go to tab page "n". For ":tab N" and "Ngt". +// When "n" is 9999 go to the last tab page. void goto_tabpage(int n) { tabpage_T *tp = NULL; // shut up compiler @@ -4504,10 +4426,8 @@ bool goto_tabpage_lastused(void) return false; } -/* - * Enter window "wp" in tab page "tp". - * Also updates the GUI tab. - */ +// Enter window "wp" in tab page "tp". +// Also updates the GUI tab. void goto_tabpage_win(tabpage_T *tp, win_T *wp) { goto_tabpage_tp(tp, true, true); @@ -4570,13 +4490,11 @@ void tabpage_move(int nr) redraw_tabline = true; } -/* - * Go to another window. - * When jumping to another buffer, stop Visual mode. Do this before - * changing windows so we can yank the selection into the '*' register. - * When jumping to another window on the same buffer, adjust its cursor - * position to keep the same Visual area. - */ +// Go to another window. +// When jumping to another buffer, stop Visual mode. Do this before +// changing windows so we can yank the selection into the '*' register. +// When jumping to another window on the same buffer, adjust its cursor +// position to keep the same Visual area. void win_goto(win_T *wp) { win_T *owp = curwin; @@ -4603,9 +4521,7 @@ void win_goto(win_T *wp) } } -/* - * Find the tabpage for window "win". - */ +// Find the tabpage for window "win". tabpage_T *win_find_tabpage(win_T *win) { FOR_ALL_TAB_WINDOWS(tp, wp) { @@ -4638,10 +4554,8 @@ win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count) } while (count--) { - /* - * First go upwards in the tree of frames until we find an upwards or - * downwards neighbor. - */ + // First go upwards in the tree of frames until we find an upwards or + // downwards neighbor. fr = foundfr; for (;;) { if (fr == tp->tp_topframe) { @@ -4658,9 +4572,7 @@ win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count) fr = fr->fr_parent; } - /* - * Now go downwards to find the bottom or top frame in it. - */ + // Now go downwards to find the bottom or top frame in it. for (;;) { if (nfr->fr_layout == FR_LEAF) { foundfr = nfr; @@ -4721,10 +4633,8 @@ win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count) } while (count--) { - /* - * First go upwards in the tree of frames until we find a left or - * right neighbor. - */ + // First go upwards in the tree of frames until we find a left or + // right neighbor. fr = foundfr; for (;;) { if (fr == tp->tp_topframe) { @@ -4741,9 +4651,7 @@ win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count) fr = fr->fr_parent; } - /* - * Now go downwards to find the leftmost or rightmost frame in it. - */ + // Now go downwards to find the leftmost or rightmost frame in it. for (;;) { if (nfr->fr_layout == FR_LEAF) { foundfr = nfr; @@ -5036,9 +4944,7 @@ static win_T *win_alloc(win_T *after, bool hidden) // initialized yet. gui_create_scrollbar() may trigger a FocusGained // event. block_autocmds(); - /* - * link the window in the window list - */ + // link the window in the window list if (!hidden) { win_append(after, new_wp); } @@ -5202,9 +5108,7 @@ void win_free_grid(win_T *wp, bool reinit) } } -/* - * Append window "wp" in the window list after window "after". - */ +// Append window "wp" in the window list after window "after". void win_append(win_T *after, win_T *wp) { win_T *before; @@ -5250,9 +5154,7 @@ void win_remove(win_T *wp, tabpage_T *tp) } } -/* - * Append frame "frp" in a frame list after frame "after". - */ +// Append frame "frp" in a frame list after frame "after". static void frame_append(frame_T *after, frame_T *frp) { frp->fr_next = after->fr_next; @@ -5263,9 +5165,7 @@ static void frame_append(frame_T *after, frame_T *frp) frp->fr_prev = after; } -/* - * Insert frame "frp" in a frame list before frame "before". - */ +// Insert frame "frp" in a frame list before frame "before". static void frame_insert(frame_T *before, frame_T *frp) { frp->fr_next = before; @@ -5278,9 +5178,7 @@ static void frame_insert(frame_T *before, frame_T *frp) } } -/* - * Remove a frame from a frame list. - */ +// Remove a frame from a frame list. static void frame_remove(frame_T *frp) { if (frp->fr_prev != NULL) { @@ -5390,9 +5288,7 @@ void may_trigger_winscrolled(void) } } -/* - * Save the size of all windows in "gap". - */ +// Save the size of all windows in "gap". void win_size_save(garray_T *gap) { ga_init(gap, (int)sizeof(int), 1); @@ -5459,12 +5355,10 @@ void win_reconfig_floats(void) } } -/* - * Update the position of the windows in frame "topfrp", using the width and - * height of the frames. - * "*row" and "*col" are the top-left position of the frame. They are updated - * to the bottom-right position plus one. - */ +// Update the position of the windows in frame "topfrp", using the width and +// height of the frames. +// "*row" and "*col" are the top-left position of the frame. They are updated +// to the bottom-right position plus one. static void frame_comp_pos(frame_T *topfrp, int *row, int *col) { win_T *wp; @@ -5500,19 +5394,15 @@ static void frame_comp_pos(frame_T *topfrp, int *row, int *col) } } -/* - * Set current window height and take care of repositioning other windows to - * fit around it. - */ +// Set current window height and take care of repositioning other windows to +// fit around it. void win_setheight(int height) { win_setheight_win(height, curwin); } -/* - * Set the window height of window "win" and take care of repositioning other - * windows to fit around it. - */ +// Set the window height of window "win" and take care of repositioning other +// windows to fit around it. void win_setheight_win(int height, win_T *win) { // Always keep current window at least one line high, even when 'winminheight' is zero. @@ -5547,19 +5437,17 @@ void win_setheight_win(int height, win_T *win) } } -/* - * Set the height of a frame to "height" and take care that all frames and - * windows inside it are resized. Also resize frames on the left and right if - * the are in the same FR_ROW frame. - * - * Strategy: - * If the frame is part of a FR_COL frame, try fitting the frame in that - * frame. If that doesn't work (the FR_COL frame is too small), recursively - * go to containing frames to resize them and make room. - * If the frame is part of a FR_ROW frame, all frames must be resized as well. - * Check for the minimal height of the FR_ROW frame. - * At the top level we can also use change the command line height. - */ +// Set the height of a frame to "height" and take care that all frames and +// windows inside it are resized. Also resize frames on the left and right if +// the are in the same FR_ROW frame. +// +// Strategy: +// If the frame is part of a FR_COL frame, try fitting the frame in that +// frame. If that doesn't work (the FR_COL frame is too small), recursively +// go to containing frames to resize them and make room. +// If the frame is part of a FR_ROW frame, all frames must be resized as well. +// Check for the minimal height of the FR_ROW frame. +// At the top level we can also use change the command line height. static void frame_setheight(frame_T *curfrp, int height) { int room; // total number of lines available @@ -5595,16 +5483,13 @@ static void frame_setheight(frame_T *curfrp, int height) } frame_setheight(curfrp->fr_parent, height); } else { - /* - * Column of frames: try to change only frames in this column. - */ - /* - * Do this twice: - * 1: compute room available, if it's not enough try resizing the - * containing frame. - * 2: compute the room available and adjust the height to it. - * Try not to reduce the height of a window with 'winfixheight' set. - */ + // Column of frames: try to change only frames in this column. + + // Do this twice: + // 1: compute room available, if it's not enough try resizing the + // containing frame. + // 2: compute the room available and adjust the height to it. + // Try not to reduce the height of a window with 'winfixheight' set. for (run = 1; run <= 2; run++) { room = 0; room_reserved = 0; @@ -5642,10 +5527,8 @@ static void frame_setheight(frame_T *curfrp, int height) //NOTREACHED } - /* - * Compute the number of lines we will take from others frames (can be - * negative!). - */ + // Compute the number of lines we will take from others frames (can be + // negative!). take = height - curfrp->fr_height; // If there is not enough room, also reduce the height of a window @@ -5668,16 +5551,12 @@ static void frame_setheight(frame_T *curfrp, int height) topframe->fr_height += room_cmdline; } - /* - * set the current frame to the new height - */ + // set the current frame to the new height frame_new_height(curfrp, height, false, false); - /* - * First take lines from the frames after the current frame. If - * that is not enough, takes lines from frames above the current - * frame. - */ + // First take lines from the frames after the current frame. If + // that is not enough, takes lines from frames above the current + // frame. for (run = 0; run < 2; run++) { if (run == 0) { frp = curfrp->fr_next; // 1st run: start with next window @@ -5718,10 +5597,8 @@ static void frame_setheight(frame_T *curfrp, int height) } } -/* - * Set current window width and take care of repositioning other windows to - * fit around it. - */ +// Set current window width and take care of repositioning other windows to +// fit around it. void win_setwidth(int width) { win_setwidth_win(width, curwin); @@ -5754,13 +5631,11 @@ void win_setwidth_win(int width, win_T *wp) } } -/* - * Set the width of a frame to "width" and take care that all frames and - * windows inside it are resized. Also resize frames above and below if the - * are in the same FR_ROW frame. - * - * Strategy is similar to frame_setheight(). - */ +// Set the width of a frame to "width" and take care that all frames and +// windows inside it are resized. Also resize frames above and below if the +// are in the same FR_ROW frame. +// +// Strategy is similar to frame_setheight(). static void frame_setwidth(frame_T *curfrp, int width) { int room; // total number of lines available @@ -5789,14 +5664,12 @@ static void frame_setwidth(frame_T *curfrp, int width) } frame_setwidth(curfrp->fr_parent, width); } else { - /* - * Row of frames: try to change only frames in this row. - * - * Do this twice: - * 1: compute room available, if it's not enough try resizing the - * containing frame. - * 2: compute the room available and adjust the width to it. - */ + // Row of frames: try to change only frames in this row. + // + // Do this twice: + // 1: compute room available, if it's not enough try resizing the + // containing frame. + // 2: compute the room available and adjust the width to it. for (run = 1; run <= 2; run++) { room = 0; room_reserved = 0; @@ -5823,10 +5696,8 @@ static void frame_setwidth(frame_T *curfrp, int width) + frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1); } - /* - * Compute the number of lines we will take from others frames (can be - * negative!). - */ + // Compute the number of lines we will take from others frames (can be + // negative!). take = width - curfrp->fr_width; // If there is not enough room, also reduce the width of a window @@ -5840,16 +5711,12 @@ static void frame_setwidth(frame_T *curfrp, int width) room_reserved = 0; } - /* - * set the current frame to the new width - */ + // set the current frame to the new width frame_new_width(curfrp, width, false, false); - /* - * First take lines from the frames right of the current frame. If - * that is not enough, takes lines from frames left of the current - * frame. - */ + // First take lines from the frames right of the current frame. If + // that is not enough, takes lines from frames left of the current + // frame. for (run = 0; run < 2; run++) { if (run == 0) { frp = curfrp->fr_next; // 1st run: start with next window @@ -6016,10 +5883,8 @@ void win_drag_status_line(win_T *dragwin, int offset) return; } - /* - * Grow frame fr by "offset" lines. - * Doesn't happen when dragging the last status line up. - */ + // Grow frame fr by "offset" lines. + // Doesn't happen when dragging the last status line up. if (fr != NULL) { frame_new_height(fr, fr->fr_height + offset, up, false); } @@ -6029,9 +5894,7 @@ void win_drag_status_line(win_T *dragwin, int offset) } else { fr = curfr->fr_next; // next frame gets smaller } - /* - * Now make the other frames smaller. - */ + // Now make the other frames smaller. while (fr != NULL && offset > 0) { n = frame_minheight(fr, NULL); if (fr->fr_height - offset <= n) { @@ -6059,9 +5922,7 @@ void win_drag_status_line(win_T *dragwin, int offset) showmode(); } -/* - * Separator line of dragwin is dragged "offset" lines right (negative is left). - */ +// Separator line of dragwin is dragged "offset" lines right (negative is left). void win_drag_vsep_line(win_T *dragwin, int offset) { frame_T *curfr; @@ -6214,10 +6075,8 @@ void scroll_to_fraction(win_T *wp, int prev_height) && (!wp->w_p_scb || wp == curwin) && (height < wp->w_buffer->b_ml.ml_line_count || wp->w_topline > 1)) { - /* - * Find a value for w_topline that shows the cursor at the same - * relative position in the window as before (more or less). - */ + // Find a value for w_topline that shows the cursor at the same + // relative position in the window as before (more or less). lnum = wp->w_cursor.lnum; if (lnum < 1) { // can happen when starting up lnum = 1; @@ -6237,11 +6096,9 @@ void scroll_to_fraction(win_T *wp, int prev_height) } if (sline < 0) { - /* - * Cursor line would go off top of screen if w_wrow was this high. - * Make cursor line the first line in the window. If not enough - * room use w_skipcol; - */ + // Cursor line would go off top of screen if w_wrow was this high. + // Make cursor line the first line in the window. If not enough + // room use w_skipcol; wp->w_wrow = line_size; if (wp->w_wrow >= wp->w_height_inner && (wp->w_width_inner - win_col_off(wp)) > 0) { @@ -6273,10 +6130,8 @@ void scroll_to_fraction(win_T *wp, int prev_height) } if (sline < 0) { - /* - * Line we want at top would go off top of screen. Use next - * line instead. - */ + // Line we want at top would go off top of screen. Use next + // line instead. (void)hasFoldingWin(wp, lnum, NULL, &lnum, true, NULL); lnum++; wp->w_wrow -= line_size + sline; @@ -6403,9 +6258,7 @@ void win_comp_scroll(win_T *wp) } } -/* - * command_height: called whenever p_ch has been changed - */ +// command_height: called whenever p_ch has been changed void command_height(void) { int h; @@ -6488,10 +6341,8 @@ void command_height(void) } } -/* - * Resize frame "frp" to be "n" lines higher (negative for less high). - * Also resize the frames it is contained in. - */ +// Resize frame "frp" to be "n" lines higher (negative for less high). +// Also resize the frames it is contained in. static void frame_add_height(frame_T *frp, int n) { frame_new_height(frp, frp->fr_height + n, false, false); @@ -6504,11 +6355,9 @@ static void frame_add_height(frame_T *frp, int n) } } -/* - * Get the file name at the cursor. - * If Visual mode is active, use the selected text if it's in one line. - * Returns the name in allocated memory, NULL for failure. - */ +// Get the file name at the cursor. +// If Visual mode is active, use the selected text if it's in one line. +// Returns the name in allocated memory, NULL for failure. char_u *grab_file_name(long count, linenr_T *file_lnum) { int options = FNAME_MESS | FNAME_EXP | FNAME_REL | FNAME_UNESC; @@ -6529,19 +6378,17 @@ char_u *grab_file_name(long count, linenr_T *file_lnum) return file_name_at_cursor(options | FNAME_HYP, count, file_lnum); } -/* - * Return the file name under or after the cursor. - * - * The 'path' option is searched if the file name is not absolute. - * The string returned has been alloc'ed and should be freed by the caller. - * NULL is returned if the file name or file is not found. - * - * options: - * FNAME_MESS give error messages - * FNAME_EXP expand to path - * FNAME_HYP check for hypertext link - * FNAME_INCL apply "includeexpr" - */ +// Return the file name under or after the cursor. +// +// The 'path' option is searched if the file name is not absolute. +// The string returned has been alloc'ed and should be freed by the caller. +// NULL is returned if the file name or file is not found. +// +// options: +// FNAME_MESS give error messages +// FNAME_EXP expand to path +// FNAME_HYP check for hypertext link +// FNAME_INCL apply "includeexpr" char_u *file_name_at_cursor(int options, long count, linenr_T *file_lnum) { return file_name_in_line((char_u *)get_cursor_line_ptr(), @@ -6561,9 +6408,7 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u bool in_type = true; bool is_url = false; - /* - * search forward for what could be the start of a file name - */ + // search forward for what could be the start of a file name ptr = (char *)line + col; while (*ptr != NUL && !vim_isfilec(*ptr)) { MB_PTR_ADV(ptr); @@ -6575,10 +6420,8 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u return NULL; } - /* - * Search backward for first char of the file name. - * Go one char back to ":" before "//" even when ':' is not in 'isfname'. - */ + // Search backward for first char of the file name. + // Go one char back to ":" before "//" even when ':' is not in 'isfname'. while ((char_u *)ptr > line) { if ((len = (size_t)(utf_head_off((char *)line, ptr - 1))) > 0) { ptr -= len + 1; @@ -6589,10 +6432,8 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u } } - /* - * Search forward for the last char of the file name. - * Also allow ":/" when ':' is not in 'isfname'. - */ + // Search forward for the last char of the file name. + // Also allow ":/" when ':' is not in 'isfname'. len = 0; while (vim_isfilec(ptr[len]) || (ptr[len] == '\\' && ptr[len + 1] == ' ') || ((options & FNAME_HYP) && path_is_url(ptr + len)) @@ -6615,10 +6456,8 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u len += (size_t)(utfc_ptr2len(ptr + len)); } - /* - * If there is trailing punctuation, remove it. - * But don't remove "..", could be a directory name. - */ + // If there is trailing punctuation, remove it. + // But don't remove "..", could be a directory name. if (len > 2 && vim_strchr(".,:;!", ptr[len - 1]) != NULL && ptr[len - 2] != '.') { len--; @@ -6972,21 +6811,17 @@ void reset_lnums(void) } } -/* - * A snapshot of the window sizes, to restore them after closing the help - * window. - * Only these fields are used: - * fr_layout - * fr_width - * fr_height - * fr_next - * fr_child - * fr_win (only valid for the old curwin, NULL otherwise) - */ +// A snapshot of the window sizes, to restore them after closing the help +// window. +// Only these fields are used: +// fr_layout +// fr_width +// fr_height +// fr_next +// fr_child +// fr_win (only valid for the old curwin, NULL otherwise) -/* - * Create a snapshot of the current frame sizes. - */ +// Create a snapshot of the current frame sizes. void make_snapshot(int idx) { clear_snapshot(curtab, idx); @@ -7010,9 +6845,7 @@ static void make_snapshot_rec(frame_T *fr, frame_T **frp) } } -/* - * Remove any existing snapshot. - */ +// Remove any existing snapshot. static void clear_snapshot(tabpage_T *tp, int idx) { clear_snapshot_rec(tp->tp_snapshot[idx]); @@ -7097,11 +6930,9 @@ static int check_snapshot_rec(frame_T *sn, frame_T *fr) return OK; } -/* - * Copy the size of snapshot frame "sn" to frame "fr". Do the same for all - * following frames and children. - * Returns a pointer to the old current window, or NULL. - */ +// Copy the size of snapshot frame "sn" to frame "fr". Do the same for all +// following frames and children. +// Returns a pointer to the old current window, or NULL. static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr) { win_T *wp = NULL; -- cgit From 05b49ef975664ccdfea4e7b5a0fc09c8ed2cf11a Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 3 Sep 2022 06:50:11 +0800 Subject: vim-patch:8.2.1505: not all file read and writecode is tested MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problem: Not all file read and writecode is tested. Solution: Add a few tests. (Dominique Pellé, closes vim/vim#6764) https://github.com/vim/vim/commit/1b04ce2d400fda97410a961288c496bd8f445a9c Cherry-pick Test_glob() from patch 8.2.0634. --- src/nvim/testdir/test_eval_stuff.vim | 25 +++++++++++++++++++------ src/nvim/testdir/test_fnamemodify.vim | 6 ++++++ src/nvim/testdir/test_functions.vim | 19 +++++++++++++++++++ 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/nvim/testdir/test_eval_stuff.vim b/src/nvim/testdir/test_eval_stuff.vim index eff1376d3c..351120bf11 100644 --- a/src/nvim/testdir/test_eval_stuff.vim +++ b/src/nvim/testdir/test_eval_stuff.vim @@ -91,18 +91,31 @@ func Test_readfile_binary() new call setline(1, ['one', 'two', 'three']) setlocal ff=dos - silent write XReadfile - let lines = readfile('XReadfile') + silent write XReadfile_bin + let lines = 'XReadfile_bin'->readfile() call assert_equal(['one', 'two', 'three'], lines) - let lines = readfile('XReadfile', '', 2) + let lines = readfile('XReadfile_bin', '', 2) call assert_equal(['one', 'two'], lines) - let lines = readfile('XReadfile', 'b') + let lines = readfile('XReadfile_bin', 'b') call assert_equal(["one\r", "two\r", "three\r", ""], lines) - let lines = readfile('XReadfile', 'b', 2) + let lines = readfile('XReadfile_bin', 'b', 2) call assert_equal(["one\r", "two\r"], lines) bwipe! - call delete('XReadfile') + call delete('XReadfile_bin') +endfunc + +func Test_readfile_bom() + call writefile(["\ufeffFOO", "FOO\ufeffBAR"], 'XReadfile_bom') + call assert_equal(['FOO', 'FOOBAR'], readfile('XReadfile_bom')) + call delete('XReadfile_bom') +endfunc + +func Test_readfile_max() + call writefile(range(1, 4), 'XReadfile_max') + call assert_equal(['1', '2'], readfile('XReadfile_max', '', 2)) + call assert_equal(['3', '4'], readfile('XReadfile_max', '', -2)) + call delete('XReadfile_max') endfunc func Test_let_errmsg() diff --git a/src/nvim/testdir/test_fnamemodify.vim b/src/nvim/testdir/test_fnamemodify.vim index 5ae2a5ee17..258a2093bd 100644 --- a/src/nvim/testdir/test_fnamemodify.vim +++ b/src/nvim/testdir/test_fnamemodify.vim @@ -11,6 +11,7 @@ func Test_fnamemodify() call assert_equal('/', fnamemodify('.', ':p')[-1:]) call assert_equal('r', fnamemodify('.', ':p:h')[-1:]) call assert_equal('t', fnamemodify('test.out', ':p')[-1:]) + call assert_equal($HOME .. "/foo" , fnamemodify('~/foo', ':p')) call assert_equal('test.out', fnamemodify('test.out', ':.')) call assert_equal('a', fnamemodify('../testdir/a', ':.')) call assert_equal('~/testdir/test.out', fnamemodify('test.out', ':~')) @@ -95,4 +96,9 @@ func Test_fnamemodify_er() call assert_equal('', fnamemodify(v:_null_string, v:_null_string)) endfunc +func Test_fnamemodify_fail() + call assert_fails('call fnamemodify({}, ":p")', 'E731:') + call assert_fails('call fnamemodify("x", {})', 'E731:') +endfunc + " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim index 147eda5b0a..99ac6ae32c 100644 --- a/src/nvim/testdir/test_functions.vim +++ b/src/nvim/testdir/test_functions.vim @@ -2015,6 +2015,25 @@ func Test_getmousepos() bwipe! endfunc +" Test for glob() +func Test_glob() + call assert_equal('', glob(v:_null_string)) + call assert_equal('', globpath(v:_null_string, v:_null_string)) + + call writefile([], 'Xglob1') + call writefile([], 'XGLOB2') + set wildignorecase + " Sort output of glob() otherwise we end up with different + " ordering depending on whether file system is case-sensitive. + call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1))) + set wildignorecase& + + call delete('Xglob1') + call delete('XGLOB2') + + call assert_fails("call glob('*', 0, {})", 'E728:') +endfunc + func HasDefault(msg = 'msg') return a:msg endfunc -- cgit From 7243b1cbde8a08deab6bf29b452b3383fa4f6d8d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 3 Sep 2022 06:46:30 +0800 Subject: vim-patch:9.0.0360: crash when invalid line number on :for is ignored Problem: Crash when invalid line number on :for is ignored. Solution: Do not check breakpoint for non-existing line. https://github.com/vim/vim/commit/35d21c6830fc2d68aca838424a0e786821c5891c Test does not fail without the fix in Nvim as Nvim uses 0 when line number overflows. If it is changed to MAXLNUM then the test does fail without the fix, but using 0 seems better as E481 is still given. --- src/nvim/ex_docmd.c | 2 +- src/nvim/testdir/test_eval_stuff.vim | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index c2c5bb90ce..6517ebd081 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -642,7 +642,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags) // Check for the next breakpoint at or after the ":while" // or ":for". - if (breakpoint != NULL) { + if (breakpoint != NULL && lines_ga.ga_len > current_line) { *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), fname, ((wcmd_T *)lines_ga.ga_data)[current_line].lnum - 1); *dbg_tick = debug_tick; diff --git a/src/nvim/testdir/test_eval_stuff.vim b/src/nvim/testdir/test_eval_stuff.vim index 351120bf11..dc110af356 100644 --- a/src/nvim/testdir/test_eval_stuff.vim +++ b/src/nvim/testdir/test_eval_stuff.vim @@ -1,5 +1,8 @@ " Tests for various eval things. +source view_util.vim +source shared.vim + function s:foo() abort try return [] == 0 @@ -87,6 +90,18 @@ func Test_for_over_null_string() let &enc = save_enc endfunc +func Test_for_invalid_line_count() + let lines =<< trim END + 111111111111111111111111 for line in ['one'] + endfor + END + call writefile(lines, 'XinvalidFor') + " only test that this doesn't crash + call RunVim([], [], '-u NONE -e -s -S XinvalidFor -c qa') + + call delete('XinvalidFor') +endfunc + func Test_readfile_binary() new call setline(1, ['one', 'two', 'three']) -- cgit From c62e5b50795d38db68f198a3d1230c047fc0ccfa Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 3 Sep 2022 07:51:51 +0800 Subject: vim-patch:9.0.0362: expanding ":e %" does not work for remote files Problem: Expanding ":e %" does not work for remote files. Solution: If the "%" or "#" file does not exist add the expansion anyway. https://github.com/vim/vim/commit/f5724376ab7362b5a98eaa8a331d663ef722c2a2 --- src/nvim/path.c | 15 ++++++++++++++- src/nvim/testdir/test_cmdline.vim | 12 ++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/nvim/path.c b/src/nvim/path.c index 607f1fc09a..1e5fa49ad6 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -2106,13 +2106,16 @@ int expand_wildcards_eval(char_u **pat, int *num_file, char ***file, int flags) char *exp_pat = (char *)(*pat); char *ignored_msg; size_t usedlen; + const bool is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#'; + bool star_follows = false; - if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<') { + if (is_cur_alt_file || *exp_pat == '<') { emsg_off++; eval_pat = eval_vars((char_u *)exp_pat, (char_u *)exp_pat, &usedlen, NULL, &ignored_msg, NULL, true); emsg_off--; if (eval_pat != NULL) { + star_follows = strcmp(exp_pat + usedlen, "*") == 0; exp_pat = concat_str((char *)eval_pat, exp_pat + usedlen); } } @@ -2122,6 +2125,16 @@ int expand_wildcards_eval(char_u **pat, int *num_file, char ***file, int flags) } if (eval_pat != NULL) { + if (*num_file == 0 && is_cur_alt_file && star_follows) { + // Expanding "%" or "#" and the file does not exist: Add the + // pattern anyway (without the star) so that this works for remote + // files and non-file buffer names. + *file = xmalloc(sizeof(char *)); + **file = (char *)eval_pat; + eval_pat = NULL; + *num_file = 1; + ret = OK; + } xfree(exp_pat); xfree(eval_pat); } diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index bc06e70ff4..e40ff65051 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -1055,6 +1055,18 @@ func Test_cmdline_write_alternatefile() bw! endfunc +func Test_cmdline_expand_cur_alt_file() + enew + file http://some.com/file.txt + call feedkeys(":e %\\\"\", 'xt') + call assert_equal('"e http://some.com/file.txt', @:) + edit another + call feedkeys(":e #\\\"\", 'xt') + call assert_equal('"e http://some.com/file.txt', @:) + bwipe + bwipe http://some.com/file.txt +endfunc + " using a leading backslash here set cpo+=C -- cgit From 1e3073bc35cc954b3ed0144688ac596f231ae74c Mon Sep 17 00:00:00 2001 From: Lewis Russell Date: Sat, 3 Sep 2022 10:18:05 +0100 Subject: docs: update .git-blame-ignore-revs (#20066) --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 23c7862b99..b9830dd2fd 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -50,6 +50,9 @@ ee031eb5256bb83e0d6add2bae6fd943a4186ffe aefdc6783cb77f09786542c90901a9e7120bea42 aa4f9c5341f5280f16cce0630ea54b84eef717b3 0adc66171a355a12494d87ebb767d509540c7ef9 +93f24403f8cc760ff47979c596976b53a8b16358 +1ffd527c837fb2465c9659273bbe5447a1352db2 +2498e9feb025361576603a0101c86393d211e31e # typos d238b8f6003d34cae7f65ff7585b48a2cd9449fb -- cgit From 5296e9407db5b7ace29e2822e20d70d8e621fc8b Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sat, 3 Sep 2022 11:30:24 +0200 Subject: build(deps): bump tree-sitter to v0.20.7 (#20067) --- cmake.deps/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index 27659b2a56..e9ca2b233d 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -208,8 +208,8 @@ set(LIBICONV_SHA256 ccf536620a45458d26ba83887a983b96827001e92a13847b45e4925cc891 set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.1.tar.gz) set(TREESITTER_C_SHA256 ffcc2ef0eded59ad1acec9aec4f9b0c7dd209fc1a85d85f8b0e81298e3dddcc2) -set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/1f1b1eb4501ed0a2d195d37f7de15f72aa10acd0.tar.gz) -set(TREESITTER_SHA256 a324bdb7ff507cd5157a36b908224d60ba638f8e3363070dd51aa383c7cbd790) +set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) +set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) if(USE_BUNDLED_UNIBILIUM) include(BuildUnibilium) -- cgit From ea611c7122470af0e03f4b0a5ae99c0878da2712 Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Sat, 3 Sep 2022 12:00:00 +0200 Subject: ci(clint): remove "Inner expression indentation should be 4" rule (#20047) It completely breaks down in shada.c and is generally useless. --- src/clint.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/clint.py b/src/clint.py index 28f6031a57..0556f53372 100755 --- a/src/clint.py +++ b/src/clint.py @@ -1941,13 +1941,6 @@ def CheckExpressionAlignment(filename, clean_lines, linenum, error, startpos=0): error(filename, linenum, 'whitespace/indent', 2, 'End of the inner expression should have ' 'the same indent as start') - else: - if (pos != depth_line_starts[depth][0] + 4 - and not (depth_line_starts[depth][1] == '{' - and pos == depth_line_starts[depth][0] + 2)): - if depth not in ignore_error_levels: - error(filename, linenum, 'whitespace/indent', 2, - 'Inner expression indentation should be 4') else: if (pos != level_starts[depth][0] + 1 + (level_starts[depth][2] == '{')): -- cgit From c50460cf3b02f8e684d038a1ea37e6fdc2d13a09 Mon Sep 17 00:00:00 2001 From: Stephan Seitz Date: Sat, 3 Sep 2022 07:02:58 -0700 Subject: feat(treesitter): include language in invalid query error (#14053) --- src/nvim/lua/treesitter.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/nvim/lua/treesitter.c b/src/nvim/lua/treesitter.c index 7ff4fbbff4..65e024b707 100644 --- a/src/nvim/lua/treesitter.c +++ b/src/nvim/lua/treesitter.c @@ -1276,8 +1276,8 @@ int tslua_parse_query(lua_State *L) TSQuery *query = ts_query_new(lang, src, (uint32_t)len, &error_offset, &error_type); if (!query) { - return luaL_error(L, "query: %s at position %d", - query_err_string(error_type), (int)error_offset); + return luaL_error(L, "query: %s at position %d for language %s", + query_err_string(error_type), (int)error_offset, lang_name); } TSQuery **ud = lua_newuserdata(L, sizeof(TSQuery *)); // [udata] -- cgit From 927d4d2a15b8474cd6c605df65ef53873cf73131 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sat, 3 Sep 2022 19:27:57 +0200 Subject: fix(filetype): run filetype.match on StdinReadPost (#20070) Problem: filetype detection does not run on piped input Solution: add `StdinReadPost` to main filetype.lua autocommand Rationale: legacy filetype detection checked contents by sourcing `scripts.vim` in separate autocommands, including on `StdinReadPost`. For Lua filetype detection, this was moved into the main autocommand, with bundled `scripts.vim` gated behind `g:do_legacy_filetype` (i.e., only user `scripts.vim` are sourced for compatibility by default). Adding `StdinReadPost` to the main autocommand again runs content checks on piped input without requiring code duplication and low-payoff refactoring. --- runtime/filetype.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/filetype.lua b/runtime/filetype.lua index 9f5b5fd0dc..c50ba6453d 100644 --- a/runtime/filetype.lua +++ b/runtime/filetype.lua @@ -6,7 +6,7 @@ vim.g.did_load_filetypes = 1 vim.api.nvim_create_augroup('filetypedetect', { clear = false }) -vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, { +vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile', 'StdinReadPost' }, { group = 'filetypedetect', callback = function(args) local ft, on_detect = vim.filetype.match({ filename = args.match, buf = args.buf }) -- cgit From ea10e0c104897528a20bb1d9618e2b941eed1b3a Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Sat, 3 Sep 2022 21:49:45 -0600 Subject: ci: remove gpanders from api reviewers (#20074) --- .github/scripts/reviews.js | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/scripts/reviews.js b/.github/scripts/reviews.js index 6e9a829353..0f14707179 100644 --- a/.github/scripts/reviews.js +++ b/.github/scripts/reviews.js @@ -9,7 +9,6 @@ module.exports = async ({github, context}) => { const reviewers = new Set() if (labels.includes('api')) { reviewers.add("bfredl") - reviewers.add("gpanders") reviewers.add("muniter") } -- cgit From 24fbda04b9e9537577220e1f5bf7d2934d94191d Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sun, 4 Sep 2022 12:09:04 +0200 Subject: build(deps): bump tree-sitter-c to v0.20.2 (#20079) --- cmake.deps/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index e9ca2b233d..d2047c5b3d 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -205,8 +205,8 @@ set(GETTEXT_SHA256 66415634c6e8c3fa8b71362879ec7575e27da43da562c798a8a2f223e6e47 set(LIBICONV_URL https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.15.tar.gz) set(LIBICONV_SHA256 ccf536620a45458d26ba83887a983b96827001e92a13847b45e4925cc8913178) -set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.1.tar.gz) -set(TREESITTER_C_SHA256 ffcc2ef0eded59ad1acec9aec4f9b0c7dd209fc1a85d85f8b0e81298e3dddcc2) +set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.2.tar.gz) +set(TREESITTER_C_SHA256 af66fde03feb0df4faf03750102a0d265b007e5d957057b6b293c13116a70af2 ) set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) -- cgit From 6f7d55d3d987560d65220522e3705704abca5325 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 4 Sep 2022 06:40:19 +0800 Subject: vim-patch:7.4.{1578,1624} https://github.com/vim/vim/commit/975b5271eed4fa0500c24a8f37be0b1797cb9db7 https://github.com/vim/vim/commit/03602ec28ed25739e88b2c835adb0662d3720bb2 --- runtime/doc/builtin.txt | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index a2e15142e7..50087db4ea 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -2510,7 +2510,8 @@ funcref({name} [, {arglist}] [, {dict}]) *function()* *E700* *E922* *E923* function({name} [, {arglist}] [, {dict}]) Return a |Funcref| variable that refers to function {name}. - {name} can be a user defined function or an internal function. + {name} can be the name of a user defined function or an + internal function. {name} can also be a Funcref or a partial. When it is a partial the dict stored in it will be used and the {dict} @@ -2536,6 +2537,18 @@ function({name} [, {arglist}] [, {dict}]) < Invokes the function as with: > call Callback('one', 'two', 'name') +< The function() call can be nested to add more arguments to the + Funcref. The extra arguments are appended to the list of + arguments. Example: > + func Callback(arg1, arg2, name) + ... + let Func = function('Callback', ['one']) + let Func2 = function(Func, ['two']) + ... + call Func2('name') +< Invokes the function as with: > + call Callback('one', 'two', 'name') + < The Dictionary is only useful when calling a "dict" function. In that case the {dict} is passed in as "self". Example: > function Callback() dict @@ -2546,6 +2559,10 @@ function({name} [, {arglist}] [, {dict}]) let Func = function('Callback', context) ... call Func() " will echo: called for example +< The use of function() is not needed when there are no extra + arguments, these two are equivalent: > + let Func = function('Callback', context) + let Func = context.Callback < The argument list and the Dictionary can be combined: > function Callback(arg1, count) dict -- cgit From 21dad0dcf34330cfd7c765485b19d0ac46ce8565 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 4 Sep 2022 06:20:23 +0800 Subject: vim-patch:088e8e344352 Update runtime files. https://github.com/vim/vim/commit/088e8e3443520dec91a384081e66445a104810bb Also cherry-pick "partial" tag from a later runtime update. --- runtime/doc/builtin.txt | 11 ++++++++++- runtime/doc/eval.txt | 5 +++++ runtime/doc/quickref.txt | 1 + 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 50087db4ea..3ca6f04389 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -2507,7 +2507,7 @@ funcref({name} [, {arglist}] [, {dict}]) Can also be used as a |method|: > GetFuncname()->funcref([arg]) < - *function()* *E700* *E922* *E923* + *function()* *partial* *E700* *E922* *E923* function({name} [, {arglist}] [, {dict}]) Return a |Funcref| variable that refers to function {name}. {name} can be the name of a user defined function or an @@ -2537,6 +2537,15 @@ function({name} [, {arglist}] [, {dict}]) < Invokes the function as with: > call Callback('one', 'two', 'name') +< With a |method|: > + func Callback(one, two, three) + ... + let Partial = function('Callback', ['two']) + ... + eval 'one'->Partial('three') +< Invokes the function as with: > + call Callback('one', 'two', 'three') + < The function() call can be nested to add more arguments to the Funcref. The extra arguments are appended to the list of arguments. Example: > diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index 3fbf1ee136..bce0189cfb 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -2622,6 +2622,11 @@ It is also possible to use `:eval`. It does not support a range, but does allow for method chaining, e.g.: > eval GetList()->Filter()->append('$') +A function can also be called as part of evaluating an expression or when it +is used as a method: > + let x = GetList() + let y = GetList()->Filter() + AUTOMATICALLY LOADING FUNCTIONS ~ *autoload-functions* diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt index 6f16db5cc2..9f3993506a 100644 --- a/runtime/doc/quickref.txt +++ b/runtime/doc/quickref.txt @@ -649,6 +649,7 @@ Short explanation of each option: *option-list* 'complete' 'cpt' specify how Insert mode completion works 'completefunc' 'cfu' function to be used for Insert mode completion 'completeopt' 'cot' options for Insert mode completion +'completeslash' 'csl' like 'shellslash' for completion 'concealcursor' 'cocu' whether concealable text is hidden in cursor line 'conceallevel' 'cole' whether concealable text is shown or hidden 'confirm' 'cf' ask what to do about unsaved/read-only files -- cgit From 00b49dd8dd638c5fe1b664273aea5c843d69f36d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 24 Jul 2022 11:20:23 +0800 Subject: vim-patch:8.2.4674: cannot force getting MouseMove events Problem: Cannot force getting MouseMove events. Solution: Add the 'mousemoveevent' option with implementaiton for the GUI. (Ernie Rael, closes vim/vim#10044) https://github.com/vim/vim/commit/c4cb544cd5beaa864b3893e4b8d0085393c7dbce This only ports the docs and the option variable. The following commits will actually implement it as a UI option. --- runtime/doc/options.txt | 12 ++++++++++++ src/nvim/option_defs.h | 1 + src/nvim/options.lua | 7 +++++++ 3 files changed, 20 insertions(+) diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 9e396dd3e8..208633f93f 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -4231,6 +4231,18 @@ A jump table for the options with a short description can be found at |Q_op|. The 'mousemodel' option is set by the |:behave| command. + *'mousemoveevent'* *'mousemev'* +'mousemoveevent' 'mousemev' boolean (default off) + global + {only works in the GUI} + When on, mouse move events are delivered to the input queue and are + available for mapping. The default, off, avoids the mouse movement + overhead except when needed. + Warning: Setting this option can make pending mappings to be aborted + when the mouse is moved. + Currently only works in the GUI, may be made to work in a terminal + later. + *'mousescroll'* 'mousescroll' string (default "ver:3,hor:6") global diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index bfac0cff87..64b3f69df4 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -616,6 +616,7 @@ EXTERN int p_ma; ///< 'modifiable' EXTERN int p_mod; ///< 'modified' EXTERN char *p_mouse; // 'mouse' EXTERN char *p_mousem; // 'mousemodel' +EXTERN int p_mousemev; ///< 'mousemoveevent' EXTERN int p_mousef; // 'mousefocus' EXTERN char *p_mousescroll; // 'mousescroll' EXTERN long p_mousescroll_vert INIT(= MOUSESCROLL_VERT_DFLT); diff --git a/src/nvim/options.lua b/src/nvim/options.lua index 2f941f5d0c..9f540e6005 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -1621,6 +1621,13 @@ return { varname='p_mousem', defaults={if_true="popup_setpos"} }, + { + full_name='mousemoveevent', abbreviation='mousemev', + short_desc=N_("deliver mouse move events to input queue"), + type='bool', scope={'global'}, + varname='p_mousemev', + defaults={if_true=false} + }, { full_name='mousescroll', short_desc=N_("amount to scroll by when scrolling with a mouse"), -- cgit From a5fe7940c8b9436b78ae408eae8345266423f2c8 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 24 Jul 2022 11:32:56 +0800 Subject: feat(ui-ext): make 'mousemoveevent' a ui_option --- runtime/doc/ui.txt | 1 + src/nvim/options.lua | 1 + test/functional/ui/options_spec.lua | 7 +++++++ 3 files changed, 9 insertions(+) diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt index 3fb9ed1125..955af84679 100644 --- a/runtime/doc/ui.txt +++ b/runtime/doc/ui.txt @@ -207,6 +207,7 @@ the editor. 'guifontwide' 'linespace' 'mousefocus' + 'mousemoveevent' 'pumblend' 'showtabline' 'termguicolors' diff --git a/src/nvim/options.lua b/src/nvim/options.lua index 9f540e6005..717ca6747b 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -1625,6 +1625,7 @@ return { full_name='mousemoveevent', abbreviation='mousemev', short_desc=N_("deliver mouse move events to input queue"), type='bool', scope={'global'}, + redraw={'ui_option'}, varname='p_mousemev', defaults={if_true=false} }, diff --git a/test/functional/ui/options_spec.lua b/test/functional/ui/options_spec.lua index 8d7c404637..bd0d2104db 100644 --- a/test/functional/ui/options_spec.lua +++ b/test/functional/ui/options_spec.lua @@ -19,6 +19,7 @@ describe('UI receives option updates', function() linespace=0, pumblend=0, mousefocus=false, + mousemoveevent=false, showtabline=1, termguicolors=false, ttimeout=true, @@ -131,6 +132,12 @@ describe('UI receives option updates', function() eq(expected, screen.options) end) + command("set mousemoveevent") + expected.mousemoveevent = true + screen:expect(function() + eq(expected, screen.options) + end) + command("set nottimeout") expected.ttimeout = false screen:expect(function() -- cgit From 04bd700ac3bc2bdea0e0d8747de95dab2034aa11 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 24 Jul 2022 11:26:54 +0800 Subject: feat(tui): support 'mousemoveevent' --- runtime/doc/options.txt | 3 --- src/nvim/os/input.c | 6 ++++-- src/nvim/tui/input.c | 7 +++--- src/nvim/tui/tui.c | 27 +++++++++++++++++++++-- test/functional/ui/popupmenu_spec.lua | 40 +++++++++++++++++++++++++++++------ 5 files changed, 67 insertions(+), 16 deletions(-) diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 208633f93f..316b7ae3f1 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -4234,14 +4234,11 @@ A jump table for the options with a short description can be found at |Q_op|. *'mousemoveevent'* *'mousemev'* 'mousemoveevent' 'mousemev' boolean (default off) global - {only works in the GUI} When on, mouse move events are delivered to the input queue and are available for mapping. The default, off, avoids the mouse movement overhead except when needed. Warning: Setting this option can make pending mappings to be aborted when the mouse is moved. - Currently only works in the GUI, may be made to work in a terminal - later. *'mousescroll'* 'mousescroll' string (default "ver:3,hor:6") diff --git a/src/nvim/os/input.c b/src/nvim/os/input.c index bfe6d59dc6..ea9f31d776 100644 --- a/src/nvim/os/input.c +++ b/src/nvim/os/input.c @@ -293,7 +293,8 @@ static uint8_t check_multiclick(int code, int grid, int row, int col) || code == KE_MOUSEDOWN || code == KE_MOUSEUP || code == KE_MOUSELEFT - || code == KE_MOUSERIGHT) { + || code == KE_MOUSERIGHT + || code == KE_MOUSEMOVE) { return 0; } uint64_t mouse_time = os_hrtime(); // time of current mouse click (ns) @@ -347,7 +348,8 @@ static unsigned int handle_mouse_event(char **ptr, uint8_t *buf, unsigned int bu if (type != KS_EXTRA || !((mouse_code >= KE_LEFTMOUSE && mouse_code <= KE_RIGHTRELEASE) - || (mouse_code >= KE_MOUSEDOWN && mouse_code <= KE_MOUSERIGHT))) { + || (mouse_code >= KE_MOUSEDOWN && mouse_code <= KE_MOUSERIGHT) + || mouse_code == KE_MOUSEMOVE)) { return bufsize; } diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index d269878f46..728520c20c 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -406,8 +406,8 @@ static void forward_mouse_event(TermInput *input, TermKeyKey *key) } } - if (button == 0 || (ev != TERMKEY_MOUSE_PRESS && ev != TERMKEY_MOUSE_DRAG - && ev != TERMKEY_MOUSE_RELEASE)) { + if ((button == 0 && ev != TERMKEY_MOUSE_RELEASE) + || (ev != TERMKEY_MOUSE_PRESS && ev != TERMKEY_MOUSE_DRAG && ev != TERMKEY_MOUSE_RELEASE)) { return; } @@ -453,7 +453,8 @@ static void forward_mouse_event(TermInput *input, TermKeyKey *key) len += (size_t)snprintf(buf + len, sizeof(buf) - len, "Drag"); break; case TERMKEY_MOUSE_RELEASE: - len += (size_t)snprintf(buf + len, sizeof(buf) - len, "Release"); + len += (size_t)snprintf(buf + len, sizeof(buf) - len, button ? "Release" : "MouseMove"); + last_pressed_button = 0; break; case TERMKEY_MOUSE_UNKNOWN: abort(); diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 38e8c15762..471a3fb859 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -103,6 +103,7 @@ struct TUIData { bool immediate_wrap_after_last_column; bool bce; bool mouse_enabled; + bool mouse_move_enabled; bool busy, is_invisible, want_invisible; bool cork, overflow; bool cursor_color_changed; @@ -117,6 +118,7 @@ struct TUIData { ModeShape showing_mode; struct { int enable_mouse, disable_mouse; + int enable_mouse_move, disable_mouse_move; int enable_bracketed_paste, disable_bracketed_paste; int enable_lr_margin, disable_lr_margin; int enter_strikethrough_mode; @@ -236,6 +238,8 @@ static void terminfo_start(UI *ui) data->showing_mode = SHAPE_IDX_N; data->unibi_ext.enable_mouse = -1; data->unibi_ext.disable_mouse = -1; + data->unibi_ext.enable_mouse_move = -1; + data->unibi_ext.disable_mouse_move = -1; data->unibi_ext.set_cursor_color = -1; data->unibi_ext.reset_cursor_color = -1; data->unibi_ext.enable_bracketed_paste = -1; @@ -1138,6 +1142,9 @@ static void tui_mouse_on(UI *ui) TUIData *data = ui->data; if (!data->mouse_enabled) { unibi_out_ext(ui, data->unibi_ext.enable_mouse); + if (data->mouse_move_enabled) { + unibi_out_ext(ui, data->unibi_ext.enable_mouse_move); + } data->mouse_enabled = true; } } @@ -1146,6 +1153,9 @@ static void tui_mouse_off(UI *ui) { TUIData *data = ui->data; if (data->mouse_enabled) { + if (data->mouse_move_enabled) { + unibi_out_ext(ui, data->unibi_ext.disable_mouse_move); + } unibi_out_ext(ui, data->unibi_ext.disable_mouse); data->mouse_enabled = false; } @@ -1457,9 +1467,18 @@ static void tui_screenshot(UI *ui, String path) static void tui_option_set(UI *ui, String name, Object value) { TUIData *data = ui->data; - if (strequal(name.data, "termguicolors")) { + if (strequal(name.data, "mousemoveevent")) { + if (data->mouse_move_enabled != value.data.boolean) { + if (data->mouse_enabled) { + tui_mouse_off(ui); + data->mouse_move_enabled = value.data.boolean; + tui_mouse_on(ui); + } else { + data->mouse_move_enabled = value.data.boolean; + } + } + } else if (strequal(name.data, "termguicolors")) { ui->rgb = value.data.boolean; - data->print_attr_id = -1; invalidate(ui, 0, data->grid.height, 0, data->grid.width); } else if (strequal(name.data, "ttimeout")) { @@ -2135,6 +2154,10 @@ static void augment_terminfo(TUIData *data, const char *term, long vte_version, "\x1b[?1002h\x1b[?1006h"); data->unibi_ext.disable_mouse = (int)unibi_add_ext_str(ut, "ext.disable_mouse", "\x1b[?1002l\x1b[?1006l"); + data->unibi_ext.enable_mouse_move = (int)unibi_add_ext_str(ut, "ext.enable_mouse_move", + "\x1b[?1003h"); + data->unibi_ext.disable_mouse_move = (int)unibi_add_ext_str(ut, "ext.disable_mouse_move", + "\x1b[?1003l"); // Extended underline. // terminfo will have Smulx for this (but no support for colors yet). diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index dcd4ad3d9a..bcd146e40d 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -2755,7 +2755,7 @@ describe('builtin popupmenu', function() menu PopUp.bar :let g:menustr = 'bar' menu PopUp.baz :let g:menustr = 'baz' ]]) - meths.input_mouse('right', 'press', '', 0, 0, 4) + feed('<4,0>') screen:expect([[ ^popup menu test | {1:~ }{n: foo }{1: }| @@ -2792,7 +2792,7 @@ describe('builtin popupmenu', function() :let g:menustr = 'bar' | ]]) eq('bar', meths.get_var('menustr')) - meths.input_mouse('right', 'press', '', 0, 1, 20) + feed('<20,1>') screen:expect([[ ^popup menu test | {1:~ }| @@ -2801,7 +2801,7 @@ describe('builtin popupmenu', function() {1:~ }{n: baz }{1: }| :let g:menustr = 'bar' | ]]) - meths.input_mouse('left', 'press', '', 0, 4, 22) + feed('<22,4>') screen:expect([[ ^popup menu test | {1:~ }| @@ -2811,7 +2811,7 @@ describe('builtin popupmenu', function() :let g:menustr = 'baz' | ]]) eq('baz', meths.get_var('menustr')) - meths.input_mouse('right', 'press', '', 0, 0, 4) + feed('<4,0>') screen:expect([[ ^popup menu test | {1:~ }{n: foo }{1: }| @@ -2820,7 +2820,7 @@ describe('builtin popupmenu', function() {1:~ }| :let g:menustr = 'baz' | ]]) - meths.input_mouse('right', 'drag', '', 0, 3, 6) + feed('<6,3>') screen:expect([[ ^popup menu test | {1:~ }{n: foo }{1: }| @@ -2829,7 +2829,7 @@ describe('builtin popupmenu', function() {1:~ }| :let g:menustr = 'baz' | ]]) - meths.input_mouse('right', 'release', '', 0, 1, 6) + feed('<6,1>') screen:expect([[ ^popup menu test | {1:~ }| @@ -2839,6 +2839,34 @@ describe('builtin popupmenu', function() :let g:menustr = 'foo' | ]]) eq('foo', meths.get_var('menustr')) + feed('<4,0>') + screen:expect([[ + ^popup menu test | + {1:~ }{n: foo }{1: }| + {1:~ }{n: bar }{1: }| + {1:~ }{n: baz }{1: }| + {1:~ }| + :let g:menustr = 'foo' | + ]]) + feed('<6,3>') + screen:expect([[ + ^popup menu test | + {1:~ }{n: foo }{1: }| + {1:~ }{n: bar }{1: }| + {1:~ }{s: baz }{1: }| + {1:~ }| + :let g:menustr = 'foo' | + ]]) + feed('<6,2>') + screen:expect([[ + ^popup menu test | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :let g:menustr = 'bar' | + ]]) + eq('bar', meths.get_var('menustr')) end) end) -- cgit From ceb09701f29dcabcf219f458fffbb64f5adced9b Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 24 Jul 2022 13:58:29 +0800 Subject: feat(api): add "move" to nvim_input_mouse --- runtime/doc/api.txt | 4 ++- src/nvim/api/vim.c | 8 +++-- test/functional/ui/mouse_spec.lua | 15 ++++++++- test/functional/ui/popupmenu_spec.lua | 63 +++++++++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 5 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 82978d0b3c..063e17ded9 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1067,9 +1067,11 @@ nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col}) |api-fast| Parameters: ~ - {button} Mouse button: one of "left", "right", "middle", "wheel". + {button} Mouse button: one of "left", "right", "middle", "wheel", + "move". {action} For ordinary buttons, one of "press", "drag", "release". For the wheel, one of "up", "down", "left", "right". + Ignored for "move". {modifier} String of modifiers each represented by a single char. The same specifiers are used as for a key press, except that the "-" separator is optional, so "C-A-", "c-a" and "CA" diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index 83d6ba8dc7..95c9919522 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -336,9 +336,9 @@ Integer nvim_input(String keys) /// mouse input in a GUI. The deprecated pseudokey form /// ("") of |nvim_input()| has the same limitation. /// -/// @param button Mouse button: one of "left", "right", "middle", "wheel". +/// @param button Mouse button: one of "left", "right", "middle", "wheel", "move". /// @param action For ordinary buttons, one of "press", "drag", "release". -/// For the wheel, one of "up", "down", "left", "right". +/// For the wheel, one of "up", "down", "left", "right". Ignored for "move". /// @param modifier String of modifiers each represented by a single char. /// The same specifiers are used as for a key press, except /// that the "-" separator is optional, so "C-A-", "c-a" @@ -365,6 +365,8 @@ void nvim_input_mouse(String button, String action, String modifier, Integer gri code = KE_RIGHTMOUSE; } else if (strequal(button.data, "wheel")) { code = KE_MOUSEDOWN; + } else if (strequal(button.data, "move")) { + code = KE_MOUSEMOVE; } else { goto error; } @@ -381,7 +383,7 @@ void nvim_input_mouse(String button, String action, String modifier, Integer gri } else { goto error; } - } else { + } else if (code != KE_MOUSEMOVE) { if (strequal(action.data, "press")) { // pass } else if (strequal(action.data, "drag")) { diff --git a/test/functional/ui/mouse_spec.lua b/test/functional/ui/mouse_spec.lua index 9896b11218..8c5475ecce 100644 --- a/test/functional/ui/mouse_spec.lua +++ b/test/functional/ui/mouse_spec.lua @@ -1585,7 +1585,20 @@ describe('ui/mouse/input', function() eq(0, meths.get_var('mouse_up2')) end) - it('feeding does not use uninitialized memory #19480', function() + it(' is not translated into multiclicks and can be mapped', function() + meths.set_var('mouse_move', 0) + meths.set_var('mouse_move2', 0) + command('nnoremap let g:mouse_move += 1') + command('nnoremap <2-MouseMove> let g:mouse_move2 += 1') + feed('<0,0>') + feed('<0,0>') + meths.input_mouse('move', '', '', 0, 0, 0) + meths.input_mouse('move', '', '', 0, 0, 0) + eq(4, meths.get_var('mouse_move')) + eq(0, meths.get_var('mouse_move2')) + end) + + it('feeding in Normal mode does not use uninitialized memory #19480', function() feed('') helpers.poke_eventloop() helpers.assert_alive() diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index bcd146e40d..b16e404ea8 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -3075,5 +3075,68 @@ describe('builtin popupmenu with ui/ext_multigrid', function() :let g:menustr = 'foo' | ]]}) eq('foo', meths.get_var('menustr')) + meths.input_mouse('right', 'press', '', 2, 0, 4) + screen:expect({grid=[[ + ## grid 1 + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [3:--------------------------------]| + ## grid 2 + ^popup menu test | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + ## grid 3 + :let g:menustr = 'foo' | + ## grid 4 + {n: foo }| + {n: bar }| + {n: baz }| + ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 3, false, 100}}}) + meths.input_mouse('move', '', '', 2, 3, 6) + screen:expect({grid=[[ + ## grid 1 + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [3:--------------------------------]| + ## grid 2 + ^popup menu test | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + ## grid 3 + :let g:menustr = 'foo' | + ## grid 4 + {n: foo }| + {n: bar }| + {s: baz }| + ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 3, false, 100}}}) + meths.input_mouse('left', 'press', '', 2, 2, 6) + screen:expect({grid=[[ + ## grid 1 + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [2:--------------------------------]| + [3:--------------------------------]| + ## grid 2 + ^popup menu test | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + ## grid 3 + :let g:menustr = 'bar' | + ]]}) + eq('bar', meths.get_var('menustr')) end) end) -- cgit From 82d128405aaeb619a0c04353449f5717da126249 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 24 Jul 2022 15:24:15 +0800 Subject: feat(pum): pretend 'mousemoveevent' is set when showing right-click menu --- src/nvim/popupmenu.c | 7 +++++ test/functional/terminal/tui_spec.lua | 52 +++++++++++++++++++++++++++++++++++ test/functional/ui/popupmenu_spec.lua | 8 ++++++ 3 files changed, 67 insertions(+) diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c index 0d9080ceb7..2265334a45 100644 --- a/src/nvim/popupmenu.c +++ b/src/nvim/popupmenu.c @@ -1042,6 +1042,10 @@ void pum_show_popupmenu(vimmenu_T *menu) pum_scrollbar = 0; pum_height = pum_size; pum_position_at_mouse(20); + if (!p_mousemev) { + // Pretend 'mousemoveevent' is set. + ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(true)); + } pum_selected = -1; pum_first = 0; @@ -1102,6 +1106,9 @@ void pum_show_popupmenu(vimmenu_T *menu) xfree(array); pum_undisplay(true); + if (!p_mousemev) { + ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(false)); + } } void pum_make_popup(const char *path_name, int use_mouse_pos) diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua index 4f444316c3..3c56ad5f79 100644 --- a/test/functional/terminal/tui_spec.lua +++ b/test/functional/terminal/tui_spec.lua @@ -21,6 +21,7 @@ local nvim_set = helpers.nvim_set local ok = helpers.ok local read_file = helpers.read_file local funcs = helpers.funcs +local meths = helpers.meths if helpers.pending_win32(pending) then return end @@ -666,6 +667,57 @@ describe('TUI', function() ]], attrs) end) + it('mouse events work with right-click menu', function() + child_session:request('nvim_command', [[ + call setline(1, 'popup menu test') + set mouse=a mousemodel=popup + + aunmenu PopUp + menu PopUp.foo :let g:menustr = 'foo' + menu PopUp.bar :let g:menustr = 'bar' + menu PopUp.baz :let g:menustr = 'baz' + highlight Pmenu ctermbg=NONE ctermfg=NONE cterm=underline,reverse + highlight PmenuSel ctermbg=NONE ctermfg=NONE cterm=underline,reverse,bold + ]]) + local attrs = screen:get_default_attr_ids() + attrs[11] = {underline = true, reverse = true} + attrs[12] = {underline = true, reverse = true, bold = true} + meths.input_mouse('right', 'press', '', 0, 0, 4) + screen:expect([[ + {1:p}opup menu test | + {4:~ }{11: foo }{4: }| + {4:~ }{11: bar }{4: }| + {4:~ }{11: baz }{4: }| + {5:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]], attrs) + meths.input_mouse('right', 'release', '', 0, 0, 4) + screen:expect_unchanged() + meths.input_mouse('move', '', '', 0, 3, 6) + screen:expect([[ + {1:p}opup menu test | + {4:~ }{11: foo }{4: }| + {4:~ }{11: bar }{4: }| + {4:~ }{12: baz }{4: }| + {5:[No Name] [+] }| + | + {3:-- TERMINAL --} | + ]], attrs) + meths.input_mouse('left', 'press', '', 0, 2, 6) + screen:expect([[ + {1:p}opup menu test | + {4:~ }| + {4:~ }| + {4:~ }| + {5:[No Name] [+] }| + :let g:menustr = 'bar' | + {3:-- TERMINAL --} | + ]], attrs) + meths.input_mouse('left', 'release', '', 0, 2, 6) + screen:expect_unchanged() + end) + it('paste: Insert mode', function() -- "bracketed paste" feed_data('i""\027i\027[200~') diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index b16e404ea8..3c752875f0 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -2839,6 +2839,7 @@ describe('builtin popupmenu', function() :let g:menustr = 'foo' | ]]) eq('foo', meths.get_var('menustr')) + eq(false, screen.options.mousemoveevent) feed('<4,0>') screen:expect([[ ^popup menu test | @@ -2848,6 +2849,7 @@ describe('builtin popupmenu', function() {1:~ }| :let g:menustr = 'foo' | ]]) + eq(true, screen.options.mousemoveevent) feed('<6,3>') screen:expect([[ ^popup menu test | @@ -2857,6 +2859,7 @@ describe('builtin popupmenu', function() {1:~ }| :let g:menustr = 'foo' | ]]) + eq(true, screen.options.mousemoveevent) feed('<6,2>') screen:expect([[ ^popup menu test | @@ -2866,6 +2869,7 @@ describe('builtin popupmenu', function() {1:~ }| :let g:menustr = 'bar' | ]]) + eq(false, screen.options.mousemoveevent) eq('bar', meths.get_var('menustr')) end) end) @@ -3075,6 +3079,7 @@ describe('builtin popupmenu with ui/ext_multigrid', function() :let g:menustr = 'foo' | ]]}) eq('foo', meths.get_var('menustr')) + eq(false, screen.options.mousemoveevent) meths.input_mouse('right', 'press', '', 2, 0, 4) screen:expect({grid=[[ ## grid 1 @@ -3097,6 +3102,7 @@ describe('builtin popupmenu with ui/ext_multigrid', function() {n: bar }| {n: baz }| ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 3, false, 100}}}) + eq(true, screen.options.mousemoveevent) meths.input_mouse('move', '', '', 2, 3, 6) screen:expect({grid=[[ ## grid 1 @@ -3119,6 +3125,7 @@ describe('builtin popupmenu with ui/ext_multigrid', function() {n: bar }| {s: baz }| ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 3, false, 100}}}) + eq(true, screen.options.mousemoveevent) meths.input_mouse('left', 'press', '', 2, 2, 6) screen:expect({grid=[[ ## grid 1 @@ -3137,6 +3144,7 @@ describe('builtin popupmenu with ui/ext_multigrid', function() ## grid 3 :let g:menustr = 'bar' | ]]}) + eq(false, screen.options.mousemoveevent) eq('bar', meths.get_var('menustr')) end) end) -- cgit From a220650fd6ef6490a787eb7efcab24b4bf13dab8 Mon Sep 17 00:00:00 2001 From: UnkwUsr Date: Mon, 5 Sep 2022 09:44:52 +0300 Subject: docs(contributing): fix broken link (#20044) --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 582d5fbdd4..558d0986db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ low-risk/isolated tasks: - Try a [complexity:low] issue. - Fix bugs found by [Clang](#clang-scan-build), [PVS](#pvs-studio) or [Coverity](#coverity). -- [Improve documentation][wiki-contribute-help] +- [Improve documentation](#documenting) - [Merge a Vim patch] (familiarity with Vim is *strongly* recommended) Reporting problems -- cgit From 29cd072351cfb600c1e04d1b3eb8d52c983bff16 Mon Sep 17 00:00:00 2001 From: Matthieu Coudron Date: Sat, 3 Sep 2022 00:13:39 +0200 Subject: build(flake): add sumneko lsp in PATH and reformatted the file --- contrib/flake.nix | 117 +++++++++++++++++++++++++++++------------------------- 1 file changed, 62 insertions(+), 55 deletions(-) diff --git a/contrib/flake.nix b/contrib/flake.nix index a1072674ba..8d94afa5bb 100644 --- a/contrib/flake.nix +++ b/contrib/flake.nix @@ -23,24 +23,25 @@ }); # a development binary to help debug issues - neovim-debug = let - stdenv = if pkgs.stdenv.isLinux then pkgs.llvmPackages_latest.stdenv else pkgs.stdenv; - in + neovim-debug = + let + stdenv = if pkgs.stdenv.isLinux then pkgs.llvmPackages_latest.stdenv else pkgs.stdenv; + in ((neovim.override { - lua = pkgs.luajit; - inherit stdenv; - }).overrideAttrs (oa: { + lua = pkgs.luajit; + inherit stdenv; + }).overrideAttrs (oa: { - dontStrip = true; - NIX_CFLAGS_COMPILE = " -ggdb -Og"; + dontStrip = true; + NIX_CFLAGS_COMPILE = " -ggdb -Og"; - cmakeBuildType = "Debug"; - cmakeFlags = oa.cmakeFlags ++ [ - "-DMIN_LOG_LEVEL=0" - ]; + cmakeBuildType = "Debug"; + cmakeFlags = oa.cmakeFlags ++ [ + "-DMIN_LOG_LEVEL=0" + ]; - disallowedReferences = []; - })); + disallowedReferences = [ ]; + })); # for neovim developers, beware of the slow binary neovim-developer = @@ -68,9 +69,11 @@ inherit system; }; - pythonEnv = pkgs.python3.withPackages(ps: [ + lua = pkgs.lua5_1; + + pythonEnv = pkgs.python3.withPackages (ps: [ ps.msgpack - ps.flake8 # for 'make pylint' + ps.flake8 # for 'make pylint' ]); in rec { @@ -80,14 +83,16 @@ }; checks = { - pylint = pkgs.runCommandNoCC "pylint" { - nativeBuildInputs = [ pythonEnv ]; - preferLocalBuild = true; + pylint = pkgs.runCommandNoCC "pylint" + { + nativeBuildInputs = [ pythonEnv ]; + preferLocalBuild = true; } "make -C ${./..} pylint > $out"; - shlint = pkgs.runCommandNoCC "shlint" { - nativeBuildInputs = [ pkgs.shellcheck ]; - preferLocalBuild = true; + shlint = pkgs.runCommandNoCC "shlint" + { + nativeBuildInputs = [ pkgs.shellcheck ]; + preferLocalBuild = true; } "make -C ${./..} shlint > $out"; }; @@ -100,38 +105,40 @@ defaultApp = apps.nvim; - devShell = let - in - pkgs.neovim-developer.overrideAttrs(oa: { - - buildInputs = with pkgs; oa.buildInputs ++ [ - cmake - pythonEnv - include-what-you-use # for scripts/check-includes.py - jq # jq for scripts/vim-patch.sh -r - shellcheck # for `make shlint` - doxygen # for script/gen_vimdoc.py - clang-tools # for clangd to find the correct headers - ]; + devShells = { + default = pkgs.neovim-developer.overrideAttrs (oa: { + + buildInputs = with pkgs; oa.buildInputs ++ [ + cmake + lua.pkgs.luacheck + sumneko-lua-language-server + pythonEnv + include-what-you-use # for scripts/check-includes.py + jq # jq for scripts/vim-patch.sh -r + shellcheck # for `make shlint` + doxygen # for script/gen_vimdoc.py + clang-tools # for clangd to find the correct headers + ]; - shellHook = oa.shellHook + '' - export NVIM_PYTHON_LOG_LEVEL=DEBUG - export NVIM_LOG_FILE=/tmp/nvim.log - export ASAN_SYMBOLIZER_PATH=${pkgs.llvm_11}/bin/llvm-symbolizer - - # ASAN_OPTIONS=detect_leaks=1 - export ASAN_OPTIONS="log_path=./test.log:abort_on_error=1" - export UBSAN_OPTIONS=print_stacktrace=1 - mkdir -p build/runtime/parser - # nvim looks into CMAKE_INSTALL_DIR. Hack to avoid errors - # when running the functionaltests - mkdir -p outputs/out/share/nvim/syntax - touch outputs/out/share/nvim/syntax/syntax.vim - - # for treesitter functionaltests - mkdir -p runtime/parser - cp -f ${pkgs.tree-sitter.builtGrammars.tree-sitter-c}/parser runtime/parser/c.so - ''; - }); - }); + shellHook = oa.shellHook + '' + export NVIM_PYTHON_LOG_LEVEL=DEBUG + export NVIM_LOG_FILE=/tmp/nvim.log + export ASAN_SYMBOLIZER_PATH=${pkgs.llvm_11}/bin/llvm-symbolizer + + # ASAN_OPTIONS=detect_leaks=1 + export ASAN_OPTIONS="log_path=./test.log:abort_on_error=1" + export UBSAN_OPTIONS=print_stacktrace=1 + mkdir -p build/runtime/parser + # nvim looks into CMAKE_INSTALL_DIR. Hack to avoid errors + # when running the functionaltests + mkdir -p outputs/out/share/nvim/syntax + touch outputs/out/share/nvim/syntax/syntax.vim + + # for treesitter functionaltests + mkdir -p runtime/parser + cp -f ${pkgs.tree-sitter.builtGrammars.tree-sitter-c}/parser runtime/parser/c.so + ''; + }); + }; + }); } -- cgit From 8570a700cce5c8c4148652693dba9bb0b14e3aa4 Mon Sep 17 00:00:00 2001 From: Matthieu Coudron Date: Fri, 2 Sep 2022 01:45:29 +0200 Subject: build(nix): bumped flake --- contrib/flake.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/flake.lock b/contrib/flake.lock index b72e1f8d5f..48f5f0115a 100644 --- a/contrib/flake.lock +++ b/contrib/flake.lock @@ -2,11 +2,11 @@ "nodes": { "flake-utils": { "locked": { - "lastModified": 1644229661, - "narHash": "sha256-1YdnJAsNy69bpcjuoKdOYQX0YxZBiCYZo4Twxerqv7k=", + "lastModified": 1659877975, + "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", "owner": "numtide", "repo": "flake-utils", - "rev": "3cecb5b042f7f209c56ffd8371b2711a290ec797", + "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", "type": "github" }, "original": { @@ -17,11 +17,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1646254136, - "narHash": "sha256-8nQx02tTzgYO21BP/dy5BCRopE8OwE8Drsw98j+Qoaw=", + "lastModified": 1662019588, + "narHash": "sha256-oPEjHKGGVbBXqwwL+UjsveJzghWiWV0n9ogo1X6l4cw=", "owner": "nixos", "repo": "nixpkgs", - "rev": "3e072546ea98db00c2364b81491b893673267827", + "rev": "2da64a81275b68fdad38af669afeda43d401e94b", "type": "github" }, "original": { -- cgit From fc7a64291a5ed074eafff47b21b411bfe9d4a19e Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 5 Sep 2022 21:54:23 +0800 Subject: vim-patch:9.0.0386: some code blocks are nested too deep Problem: Some code blocks are nested too deep. Solution: Bail out earlier. (Yegappan Lakshmanan, closes vim/vim#11058) https://github.com/vim/vim/commit/b1f471ee20b0fa783ecd6e29aa69067e6c821376 --- src/nvim/arglist.c | 167 ++++++++++++++++++++++++++++------------------------- src/nvim/memory.c | 18 +++--- 2 files changed, 99 insertions(+), 86 deletions(-) diff --git a/src/nvim/arglist.c b/src/nvim/arglist.c index 70b2e71949..e6ac1f6247 100644 --- a/src/nvim/arglist.c +++ b/src/nvim/arglist.c @@ -79,11 +79,12 @@ void alist_expand(int *fnum_list, int fnum_len) { char *save_p_su = p_su; + char **old_arg_files = xmalloc(sizeof(*old_arg_files) * GARGCOUNT); + // Don't use 'suffixes' here. This should work like the shell did the // expansion. Also, the vimrc file isn't read yet, thus the user // can't set the options. p_su = empty_option; - char **old_arg_files = xmalloc(sizeof(*old_arg_files) * GARGCOUNT); for (int i = 0; i < GARGCOUNT; i++) { old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname); } @@ -308,6 +309,50 @@ static void alist_add_list(int count, char **files, int after, bool will_edit) } } +/// Delete the file names in "alist_ga" from the argument list. +static void arglist_del_files(garray_T *alist_ga) +{ + regmatch_T regmatch; + + // Delete the items: use each item as a regexp and find a match in the + // argument list. + regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set + for (int i = 0; i < alist_ga->ga_len && !got_int; i++) { + char *p = ((char **)alist_ga->ga_data)[i]; + p = file_pat_to_reg_pat(p, NULL, NULL, false); + if (p == NULL) { + break; + } + regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0); + if (regmatch.regprog == NULL) { + xfree(p); + break; + } + + bool didone = false; + for (int match = 0; match < ARGCOUNT; match++) { + if (vim_regexec(®match, alist_name(&ARGLIST[match]), (colnr_T)0)) { + didone = true; + xfree(ARGLIST[match].ae_fname); + memmove(ARGLIST + match, ARGLIST + match + 1, + (size_t)(ARGCOUNT - match - 1) * sizeof(aentry_T)); + ALIST(curwin)->al_ga.ga_len--; + if (curwin->w_arg_idx > match) { + curwin->w_arg_idx--; + } + match--; + } + } + + vim_regfree(regmatch.regprog); + xfree(p); + if (!didone) { + semsg(_(e_nomatch2), ((char **)alist_ga->ga_data)[i]); + } + } + ga_clear(alist_ga); +} + /// @param str /// @param what /// AL_SET: Redefine the argument list to 'str'. @@ -324,8 +369,6 @@ static int do_arglist(char *str, int what, int after, bool will_edit) garray_T new_ga; int exp_count; char **exp_files; - char *p; - int match; int arg_escaped = true; // Set default argument for ":argadd" command. @@ -341,46 +384,7 @@ static int do_arglist(char *str, int what, int after, bool will_edit) get_arglist(&new_ga, str, arg_escaped); if (what == AL_DEL) { - regmatch_T regmatch; - bool didone; - - // Delete the items: use each item as a regexp and find a match in the - // argument list. - regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set - for (int i = 0; i < new_ga.ga_len && !got_int; i++) { - p = ((char **)new_ga.ga_data)[i]; - p = file_pat_to_reg_pat(p, NULL, NULL, false); - if (p == NULL) { - break; - } - regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0); - if (regmatch.regprog == NULL) { - xfree(p); - break; - } - - didone = false; - for (match = 0; match < ARGCOUNT; match++) { - if (vim_regexec(®match, alist_name(&ARGLIST[match]), (colnr_T)0)) { - didone = true; - xfree(ARGLIST[match].ae_fname); - memmove(ARGLIST + match, ARGLIST + match + 1, - (size_t)(ARGCOUNT - match - 1) * sizeof(aentry_T)); - ALIST(curwin)->al_ga.ga_len--; - if (curwin->w_arg_idx > match) { - curwin->w_arg_idx--; - } - match--; - } - } - - vim_regfree(regmatch.regprog); - xfree(p); - if (!didone) { - semsg(_(e_nomatch2), ((char **)new_ga.ga_data)[i]); - } - } - ga_clear(&new_ga); + arglist_del_files(&new_ga); } else { int i = expand_wildcards(new_ga.ga_len, new_ga.ga_data, &exp_count, &exp_files, @@ -471,22 +475,27 @@ void ex_args(exarg_T *eap) ex_next(eap); } else if (eap->cmdidx == CMD_args) { // ":args": list arguments. - if (ARGCOUNT > 0) { - char **items = xmalloc(sizeof(char *) * (size_t)ARGCOUNT); - // Overwrite the command, for a short list there is no scrolling - // required and no wait_return(). - gotocmdline(true); - for (int i = 0; i < ARGCOUNT; i++) { - items[i] = alist_name(&ARGLIST[i]); - } - list_in_columns(items, ARGCOUNT, curwin->w_arg_idx); - xfree(items); + if (ARGCOUNT <= 0) { + return; } + + char **items = xmalloc(sizeof(char *) * (size_t)ARGCOUNT); + + // Overwrite the command, for a short list there is no scrolling + // required and no wait_return(). + gotocmdline(true); + + for (int i = 0; i < ARGCOUNT; i++) { + items[i] = alist_name(&ARGLIST[i]); + } + list_in_columns(items, ARGCOUNT, curwin->w_arg_idx); + xfree(items); } else if (eap->cmdidx == CMD_arglocal) { garray_T *gap = &curwin->w_alist->al_ga; // ":argslocal": make a local copy of the global argument list. ga_grow(gap, GARGCOUNT); + for (int i = 0; i < GARGCOUNT; i++) { if (GARGLIST[i].ae_fname != NULL) { AARGLIST(curwin->w_alist)[gap->ga_len].ae_fname = xstrdup(GARGLIST[i].ae_fname); @@ -1126,31 +1135,33 @@ void f_argv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) aentry_T *arglist = NULL; int argcount = -1; - if (argvars[0].v_type != VAR_UNKNOWN) { - if (argvars[1].v_type == VAR_UNKNOWN) { - arglist = ARGLIST; - argcount = ARGCOUNT; - } else if (argvars[1].v_type == VAR_NUMBER - && tv_get_number(&argvars[1]) == -1) { - arglist = GARGLIST; - argcount = GARGCOUNT; - } else { - win_T *wp = find_win_by_nr_or_id(&argvars[1]); - if (wp != NULL) { - // Use the argument list of the specified window - arglist = WARGLIST(wp); - argcount = WARGCOUNT(wp); - } - } - rettv->v_type = VAR_STRING; - rettv->vval.v_string = NULL; - int idx = (int)tv_get_number_chk(&argvars[0], NULL); - if (arglist != NULL && idx >= 0 && idx < argcount) { - rettv->vval.v_string = xstrdup((const char *)alist_name(&arglist[idx])); - } else if (idx == -1) { - get_arglist_as_rettv(arglist, argcount, rettv); - } - } else { + if (argvars[0].v_type == VAR_UNKNOWN) { get_arglist_as_rettv(ARGLIST, ARGCOUNT, rettv); + return; + } + + if (argvars[1].v_type == VAR_UNKNOWN) { + arglist = ARGLIST; + argcount = ARGCOUNT; + } else if (argvars[1].v_type == VAR_NUMBER + && tv_get_number(&argvars[1]) == -1) { + arglist = GARGLIST; + argcount = GARGCOUNT; + } else { + win_T *wp = find_win_by_nr_or_id(&argvars[1]); + if (wp != NULL) { + // Use the argument list of the specified window + arglist = WARGLIST(wp); + argcount = WARGCOUNT(wp); + } + } + + rettv->v_type = VAR_STRING; + rettv->vval.v_string = NULL; + int idx = (int)tv_get_number_chk(&argvars[0], NULL); + if (arglist != NULL && idx >= 0 && idx < argcount) { + rettv->vval.v_string = xstrdup((const char *)alist_name(&arglist[idx])); + } else if (idx == -1) { + get_arglist_as_rettv(arglist, argcount, rettv); } } diff --git a/src/nvim/memory.c b/src/nvim/memory.c index e5fea027cb..03cfde6160 100644 --- a/src/nvim/memory.c +++ b/src/nvim/memory.c @@ -506,16 +506,18 @@ bool striequal(const char *a, const char *b) // Did_outofmem_msg is reset when a character is read. void do_outofmem_msg(size_t size) { - if (!did_outofmem_msg) { - // Don't hide this message - emsg_silent = 0; + if (did_outofmem_msg) { + return; + } - /* Must come first to avoid coming back here when printing the error - * message fails, e.g. when setting v:errmsg. */ - did_outofmem_msg = true; + // Don't hide this message + emsg_silent = 0; - semsg(_("E342: Out of memory! (allocating %" PRIu64 " bytes)"), (uint64_t)size); - } + // Must come first to avoid coming back here when printing the error + // message fails, e.g. when setting v:errmsg. + did_outofmem_msg = true; + + semsg(_("E342: Out of memory! (allocating %" PRIu64 " bytes)"), (uint64_t)size); } /// Writes time_t to "buf[8]". -- cgit From f6a8d395a72da61c9305cd242f38bd8137c4f5b0 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 5 Sep 2022 22:10:14 +0800 Subject: refactor(ex_cd): add an early return to fix clint warning The popupmenu.c change is unrelated. --- src/nvim/ex_docmd.c | 39 +++++++++++++++++++-------------------- src/nvim/popupmenu.c | 6 +++--- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 6517ebd081..8fb166d2c9 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -5544,27 +5544,26 @@ void ex_cd(exarg_T *eap) // for non-UNIX ":cd" means: print current directory unless 'cdhome' is set if (*new_dir == NUL && !p_cdh) { ex_pwd(NULL); - } else + return; + } #endif - { - CdScope scope = kCdScopeGlobal; - switch (eap->cmdidx) { - case CMD_tcd: - case CMD_tchdir: - scope = kCdScopeTabpage; - break; - case CMD_lcd: - case CMD_lchdir: - scope = kCdScopeWindow; - break; - default: - break; - } - if (changedir_func(new_dir, scope)) { - // Echo the new current directory if the command was typed. - if (KeyTyped || p_verbose >= 5) { - ex_pwd(eap); - } + CdScope scope = kCdScopeGlobal; + switch (eap->cmdidx) { + case CMD_tcd: + case CMD_tchdir: + scope = kCdScopeTabpage; + break; + case CMD_lcd: + case CMD_lchdir: + scope = kCdScopeWindow; + break; + default: + break; + } + if (changedir_func(new_dir, scope)) { + // Echo the new current directory if the command was typed. + if (KeyTyped || p_verbose >= 5) { + ex_pwd(eap); } } } diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c index 2265334a45..4de3713f4f 100644 --- a/src/nvim/popupmenu.c +++ b/src/nvim/popupmenu.c @@ -1042,14 +1042,14 @@ void pum_show_popupmenu(vimmenu_T *menu) pum_scrollbar = 0; pum_height = pum_size; pum_position_at_mouse(20); + + pum_selected = -1; + pum_first = 0; if (!p_mousemev) { // Pretend 'mousemoveevent' is set. ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(true)); } - pum_selected = -1; - pum_first = 0; - for (;;) { pum_is_visible = true; pum_is_drawn = true; -- cgit From 93f32bb0aaa86ecb04ca4c15e0d9e1ebd2ba4716 Mon Sep 17 00:00:00 2001 From: Matthieu Coudron Date: Mon, 5 Sep 2022 11:41:42 +0200 Subject: build(nix): removed the useless 'app' the format changed depending on the nix version and it is useless anyway. --- contrib/flake.nix | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/contrib/flake.nix b/contrib/flake.nix index 8d94afa5bb..ef3174dda1 100644 --- a/contrib/flake.nix +++ b/contrib/flake.nix @@ -79,6 +79,7 @@ rec { packages = with pkgs; { + default = neovim; inherit neovim neovim-debug neovim-developer; }; @@ -96,15 +97,9 @@ } "make -C ${./..} shlint > $out"; }; + # kept for backwards-compatibility defaultPackage = pkgs.neovim; - apps = { - nvim = flake-utils.lib.mkApp { drv = pkgs.neovim; name = "nvim"; }; - nvim-debug = flake-utils.lib.mkApp { drv = pkgs.neovim-debug; name = "nvim"; }; - }; - - defaultApp = apps.nvim; - devShells = { default = pkgs.neovim-developer.overrideAttrs (oa: { -- cgit From da34833fdfde14287843e9354b63d9cebc052eef Mon Sep 17 00:00:00 2001 From: Dundar Goc Date: Sun, 22 May 2022 21:44:50 +0200 Subject: fix: assertion failure when requiring missing module in autocmd Closes https://github.com/neovim/neovim/issues/15348 --- src/nvim/ex_getln.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index da99a03c38..aee06d7045 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -870,7 +870,8 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init if (!tl_ret && ERROR_SET(&err)) { msg_putchar('\n'); - msg_printf_attr(HL_ATTR(HLF_E)|MSG_HIST, (char *)e_autocmd_err, err.msg); + semsg(e_autocmd_err, err.msg); + did_emsg = false; api_clear_error(&err); } -- cgit From 905dd49fece0903dba4e5a618f503d0237415b14 Mon Sep 17 00:00:00 2001 From: Thomas Vigouroux Date: Mon, 16 Aug 2021 15:37:01 +0200 Subject: feat(treesitter): bundle Lua parser and queries parser from https://github.com/MunifTanjim/tree-sitter-lua queries from nvim-treesitter --- cmake.deps/CMakeLists.txt | 3 + cmake.deps/cmake/BuildTreesitterParsers.cmake | 56 +++---- cmake.deps/cmake/TreesitterParserCMakeLists.txt | 7 +- runtime/CMakeLists.txt | 2 +- runtime/queries/lua/highlights.scm | 192 ++++++++++++++++++++++++ 5 files changed, 228 insertions(+), 32 deletions(-) create mode 100644 runtime/queries/lua/highlights.scm diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index d2047c5b3d..d7abb500c2 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -208,6 +208,9 @@ set(LIBICONV_SHA256 ccf536620a45458d26ba83887a983b96827001e92a13847b45e4925cc891 set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.2.tar.gz) set(TREESITTER_C_SHA256 af66fde03feb0df4faf03750102a0d265b007e5d957057b6b293c13116a70af2 ) +set(TREESITTER_LUA_URL https://github.com/MunifTanjim/tree-sitter-lua/archive/v0.0.12.tar.gz) +set(TREESITTER_LUA_SHA256 b6d7c6d04e9101a2e589d25f1d61668301e776c0b8defa6eae8dd86272e9e7c3) + set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) diff --git a/cmake.deps/cmake/BuildTreesitterParsers.cmake b/cmake.deps/cmake/BuildTreesitterParsers.cmake index 1ff86e89b9..c8f5815cd2 100644 --- a/cmake.deps/cmake/BuildTreesitterParsers.cmake +++ b/cmake.deps/cmake/BuildTreesitterParsers.cmake @@ -1,29 +1,29 @@ -ExternalProject_Add(treesitter-c -PREFIX ${DEPS_BUILD_DIR} -URL ${TREESITTER_C_URL} -DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/treesitter-c -DOWNLOAD_COMMAND ${CMAKE_COMMAND} - -DPREFIX=${DEPS_BUILD_DIR} - -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/treesitter-c - -DURL=${TREESITTER_C_URL} - -DEXPECTED_SHA256=${TREESITTER_C_SHA256} - -DTARGET=treesitter-c - -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR} - -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake -PATCH_COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_CURRENT_SOURCE_DIR}/cmake/TreesitterParserCMakeLists.txt - ${DEPS_BUILD_DIR}/src/treesitter-c/CMakeLists.txt -CMAKE_ARGS - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_GENERATOR=${CMAKE_GENERATOR} - -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM} - ${BUILD_TYPE_STRING} - -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR} - -DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES_ALT_SEP} - # Pass toolchain - -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} - -DPARSERLANG=c +function(BuildTSParser LANG TS_URL TS_SHA256 TS_CMAKE_FILE) + set(NAME treesitter-${LANG}) + ExternalProject_Add(${NAME} + PREFIX ${DEPS_BUILD_DIR} + URL ${TREESITTER_C_URL} + DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/${NAME} + DOWNLOAD_COMMAND ${CMAKE_COMMAND} + -DPREFIX=${DEPS_BUILD_DIR} + -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/${NAME} + -DURL=${TS_URL} + -DEXPECTED_SHA256=${TS_SHA256} + -DTARGET=${NAME} + -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR} + -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake + PATCH_COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${TS_CMAKE_FILE} + ${DEPS_BUILD_DIR}/src/${NAME}/CMakeLists.txt + CMAKE_ARGS + -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} + -DCMAKE_GENERATOR=${CMAKE_GENERATOR} + ${BUILD_TYPE_STRING} + -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR} + # Pass toolchain + -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} + -DPARSERLANG=${LANG}) +endfunction() -BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE} -INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE} -LIST_SEPARATOR |) +BuildTSParser(c ${TREESITTER_C_URL} ${TREESITTER_C_SHA256} TreesitterParserCMakeLists.txt) +BuildTSParser(lua ${TREESITTER_LUA_URL} ${TREESITTER_LUA_SHA256} TreesitterParserCMakeLists.txt) diff --git a/cmake.deps/cmake/TreesitterParserCMakeLists.txt b/cmake.deps/cmake/TreesitterParserCMakeLists.txt index 54bc35fb8a..9ec7a23864 100644 --- a/cmake.deps/cmake/TreesitterParserCMakeLists.txt +++ b/cmake.deps/cmake/TreesitterParserCMakeLists.txt @@ -1,10 +1,11 @@ cmake_minimum_required(VERSION 3.10) -# some parsers have c++ scanner, problem? -project(parser C) # CXX +project(parser C) + +file(GLOB source_files src/*.c) add_library(parser MODULE - src/parser.c + ${source_files} ) set_target_properties( parser diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e0a0b34d28..b42b1de54b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -123,7 +123,7 @@ foreach(PROG ${RUNTIME_PROGRAMS}) endforeach() globrecurse_wrapper(RUNTIME_FILES ${CMAKE_CURRENT_SOURCE_DIR} - *.vim *.lua *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json) + *.vim *.lua *.scm *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json) foreach(F ${RUNTIME_FILES}) get_filename_component(BASEDIR ${F} DIRECTORY) diff --git a/runtime/queries/lua/highlights.scm b/runtime/queries/lua/highlights.scm new file mode 100644 index 0000000000..92baba0f39 --- /dev/null +++ b/runtime/queries/lua/highlights.scm @@ -0,0 +1,192 @@ +;; Keywords + +"return" @keyword.return + +[ + "goto" + "in" + "local" +] @keyword + +(label_statement) @label + +(break_statement) @keyword + +(do_statement +[ + "do" + "end" +] @keyword) + +(while_statement +[ + "while" + "do" + "end" +] @repeat) + +(repeat_statement +[ + "repeat" + "until" +] @repeat) + +(if_statement +[ + "if" + "elseif" + "else" + "then" + "end" +] @conditional) + +(elseif_statement +[ + "elseif" + "then" + "end" +] @conditional) + +(else_statement +[ + "else" + "end" +] @conditional) + +(for_statement +[ + "for" + "do" + "end" +] @repeat) + +(function_declaration +[ + "function" + "end" +] @keyword.function) + +(function_definition +[ + "function" + "end" +] @keyword.function) + +;; Operators + +[ + "and" + "not" + "or" +] @keyword.operator + +[ + "+" + "-" + "*" + "/" + "%" + "^" + "#" + "==" + "~=" + "<=" + ">=" + "<" + ">" + "=" + "&" + "~" + "|" + "<<" + ">>" + "//" + ".." +] @operator + +;; Punctuations + +[ + ";" + ":" + "," + "." +] @punctuation.delimiter + +;; Brackets + +[ + "(" + ")" + "[" + "]" + "{" + "}" +] @punctuation.bracket + +;; Variables + +(identifier) @variable + +((identifier) @variable.builtin + (#eq? @variable.builtin "self")) + +;; Constants + +((identifier) @constant + (#lua-match? @constant "^[A-Z][A-Z_0-9]*$")) + +(vararg_expression) @constant + +(nil) @constant.builtin + +[ + (false) + (true) +] @boolean + +;; Tables + +(field name: (identifier) @field) + +(dot_index_expression field: (identifier) @field) + +(table_constructor +[ + "{" + "}" +] @constructor) + +;; Functions + +(parameters (identifier) @parameter) + +(function_call name: (identifier) @function.call) +(function_declaration name: (identifier) @function) + +(function_call name: (dot_index_expression field: (identifier) @function.call)) +(function_declaration name: (dot_index_expression field: (identifier) @function)) + +(method_index_expression method: (identifier) @method) + +(function_call + (identifier) @function.builtin + (#any-of? @function.builtin + ;; built-in functions in Lua 5.1 + "assert" "collectgarbage" "dofile" "error" "getfenv" "getmetatable" "ipairs" + "load" "loadfile" "loadstring" "module" "next" "pairs" "pcall" "print" + "rawequal" "rawget" "rawset" "require" "select" "setfenv" "setmetatable" + "tonumber" "tostring" "type" "unpack" "xpcall")) + +;; Others + +(comment) @comment + +(hash_bang_line) @comment + +(number) @number + +(string) @string + +;; Error +(ERROR) @error -- cgit From 6254b0fd3bc725705020192dc9e35635136b9929 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sun, 4 Sep 2022 16:13:37 +0200 Subject: ci(tests): don't skip parsers on functionaltest Treesitter parsers are now a mandatory part of the installation and should be tested on all platforms. Remove `pending_c_parser` helper. --- .github/workflows/env.sh | 2 +- test/functional/helpers.lua | 10 ---------- test/functional/treesitter/highlight_spec.lua | 18 ------------------ test/functional/treesitter/language_spec.lua | 12 ++---------- test/functional/treesitter/node_spec.lua | 5 ----- test/functional/treesitter/parser_spec.lua | 3 --- test/functional/treesitter/utils_spec.lua | 2 -- 7 files changed, 3 insertions(+), 49 deletions(-) diff --git a/.github/workflows/env.sh b/.github/workflows/env.sh index 061588da1a..da70d358a9 100755 --- a/.github/workflows/env.sh +++ b/.github/workflows/env.sh @@ -57,7 +57,7 @@ EOF functionaltest-lua) BUILD_FLAGS="$BUILD_FLAGS -DPREFER_LUA=ON" FUNCTIONALTEST=functionaltest-lua - DEPS_CMAKE_FLAGS="$DEPS_CMAKE_FLAGS -DUSE_BUNDLED_LUAJIT=OFF -DUSE_BUNDLED_TS_PARSERS=OFF" + DEPS_CMAKE_FLAGS="$DEPS_CMAKE_FLAGS -DUSE_BUNDLED_LUAJIT=OFF" ;; *) ;; diff --git a/test/functional/helpers.lua b/test/functional/helpers.lua index 93fb0f245e..d672037a1e 100644 --- a/test/functional/helpers.lua +++ b/test/functional/helpers.lua @@ -755,16 +755,6 @@ function module.pending_win32(pending_fn) end end -function module.pending_c_parser(pending_fn) - local status, _ = unpack(module.exec_lua([[ return {pcall(vim.treesitter.require_language, 'c')} ]])) - if not status then - pending_fn 'no C parser, skipping' - return true - end - module.exec_lua [[vim._ts_remove_language 'c']] - return false -end - -- Calls pending() and returns `true` if the system is too slow to -- run fragile or expensive tests. Else returns `false`. function module.skip_fragile(pending_fn, cond) diff --git a/test/functional/treesitter/highlight_spec.lua b/test/functional/treesitter/highlight_spec.lua index 4b0bd1eb50..5a1081592e 100644 --- a/test/functional/treesitter/highlight_spec.lua +++ b/test/functional/treesitter/highlight_spec.lua @@ -5,7 +5,6 @@ local clear = helpers.clear local insert = helpers.insert local exec_lua = helpers.exec_lua local feed = helpers.feed -local pending_c_parser = helpers.pending_c_parser local command = helpers.command local meths = helpers.meths local eq = helpers.eq @@ -111,8 +110,6 @@ describe('treesitter highlighting', function() end) it('is updated with edits', function() - if pending_c_parser(pending) then return end - insert(hl_text) screen:expect{grid=[[ /// Schedule Lua callback on main loop's event queue | @@ -276,8 +273,6 @@ describe('treesitter highlighting', function() end) it('is updated with :sort', function() - if pending_c_parser(pending) then return end - insert(test_text) exec_lua [[ local parser = vim.treesitter.get_parser(0, "c") @@ -351,8 +346,6 @@ describe('treesitter highlighting', function() end) it("supports with custom parser", function() - if pending_c_parser(pending) then return end - screen:set_default_attr_ids { [1] = {bold = true, foreground = Screen.colors.SeaGreen4}; } @@ -417,8 +410,6 @@ describe('treesitter highlighting', function() end) it("supports injected languages", function() - if pending_c_parser(pending) then return end - insert([[ int x = INT_MAX; #define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y)) @@ -479,8 +470,6 @@ describe('treesitter highlighting', function() end) it("supports overriding queries, like ", function() - if pending_c_parser(pending) then return end - insert([[ int x = INT_MAX; #define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y)) @@ -520,8 +509,6 @@ describe('treesitter highlighting', function() end) it("supports highlighting with custom highlight groups", function() - if pending_c_parser(pending) then return end - insert(hl_text) exec_lua [[ @@ -577,8 +564,6 @@ describe('treesitter highlighting', function() end) it("supports highlighting with priority", function() - if pending_c_parser(pending) then return end - insert([[ int x = INT_MAX; #define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y)) @@ -625,8 +610,6 @@ describe('treesitter highlighting', function() end) it("allows to use captures with dots (don't use fallback when specialization of foo exists)", function() - if pending_c_parser(pending) then return end - insert([[ char* x = "Will somebody ever read this?"; ]]) @@ -708,7 +691,6 @@ describe('treesitter highlighting', function() end) it("supports conceal attribute", function() - if pending_c_parser(pending) then return end insert(hl_text) -- conceal can be empty or a single cchar. diff --git a/test/functional/treesitter/language_spec.lua b/test/functional/treesitter/language_spec.lua index 8e9941d797..ed84dedb5a 100644 --- a/test/functional/treesitter/language_spec.lua +++ b/test/functional/treesitter/language_spec.lua @@ -6,7 +6,6 @@ local command = helpers.command local exec_lua = helpers.exec_lua local pcall_err = helpers.pcall_err local matches = helpers.matches -local pending_c_parser = helpers.pending_c_parser local insert = helpers.insert before_each(clear) @@ -28,15 +27,11 @@ describe('treesitter language API', function() eq("Error executing lua: .../language.lua:0: no parser for 'borklang' language, see :help treesitter-parsers", pcall_err(exec_lua, "parser = vim.treesitter.inspect_language('borklang')")) - if not pending_c_parser(pending) then - matches("Error executing lua: Failed to load parser: uv_dlsym: .+", - pcall_err(exec_lua, 'vim.treesitter.require_language("c", nil, false, "borklang")')) - end + matches("Error executing lua: Failed to load parser: uv_dlsym: .+", + pcall_err(exec_lua, 'vim.treesitter.require_language("c", nil, false, "borklang")')) end) it('inspects language', function() - if pending_c_parser(pending) then return end - local keys, fields, symbols = unpack(exec_lua([[ local lang = vim.treesitter.inspect_language('c') local keys, symbols = {}, {} @@ -76,7 +71,6 @@ describe('treesitter language API', function() end) it('checks if vim.treesitter.get_parser tries to create a new parser on filetype change', function () - if pending_c_parser(pending) then return end command("set filetype=c") -- Should not throw an error when filetype is c eq('c', exec_lua("return vim.treesitter.get_parser(0):lang()")) @@ -87,7 +81,6 @@ describe('treesitter language API', function() end) it('retrieve the tree given a range', function () - if pending_c_parser(pending) then return end insert([[ int main() { int x = 3; @@ -102,7 +95,6 @@ describe('treesitter language API', function() end) it('retrieve the node given a range', function () - if pending_c_parser(pending) then return end insert([[ int main() { int x = 3; diff --git a/test/functional/treesitter/node_spec.lua b/test/functional/treesitter/node_spec.lua index 87ce1b973c..a82dce47b7 100644 --- a/test/functional/treesitter/node_spec.lua +++ b/test/functional/treesitter/node_spec.lua @@ -4,7 +4,6 @@ local clear = helpers.clear local eq = helpers.eq local exec_lua = helpers.exec_lua local insert = helpers.insert -local pending_c_parser = helpers.pending_c_parser before_each(clear) @@ -15,10 +14,6 @@ end describe('treesitter node API', function() clear() - if pending_c_parser(pending) then - return - end - it('can move between siblings', function() insert([[ int main(int x, int y, int z) { diff --git a/test/functional/treesitter/parser_spec.lua b/test/functional/treesitter/parser_spec.lua index 7f3b0e770a..ccbd55df0e 100644 --- a/test/functional/treesitter/parser_spec.lua +++ b/test/functional/treesitter/parser_spec.lua @@ -5,13 +5,11 @@ local eq = helpers.eq local insert = helpers.insert local exec_lua = helpers.exec_lua local feed = helpers.feed -local pending_c_parser = helpers.pending_c_parser before_each(clear) describe('treesitter parser API', function() clear() - if pending_c_parser(pending) then return end it('parses buffer', function() if helpers.pending_win32(pending) then return end @@ -249,7 +247,6 @@ void ui_refresh(void) end) it('supports getting text of multiline node', function() - if pending_c_parser(pending) then return end insert(test_text) local res = exec_lua([[ local parser = vim.treesitter.get_parser(0, "c") diff --git a/test/functional/treesitter/utils_spec.lua b/test/functional/treesitter/utils_spec.lua index 4f4c18a748..7f5a864c3d 100644 --- a/test/functional/treesitter/utils_spec.lua +++ b/test/functional/treesitter/utils_spec.lua @@ -4,7 +4,6 @@ local clear = helpers.clear local insert = helpers.insert local eq = helpers.eq local exec_lua = helpers.exec_lua -local pending_c_parser = helpers.pending_c_parser before_each(clear) @@ -12,7 +11,6 @@ describe('treesitter utils', function() before_each(clear) it('can find an ancestor', function() - if pending_c_parser(pending) then return end insert([[ int main() { -- cgit From e85b8aa7681a1870244795cccfbb74b589996eff Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sun, 4 Sep 2022 16:27:57 +0200 Subject: feat(treesitter): add viml parser and queries --- cmake.deps/CMakeLists.txt | 3 + cmake.deps/cmake/BuildTreesitterParsers.cmake | 1 + runtime/queries/vim/highlights.scm | 245 ++++++++++++++++++++++++++ 3 files changed, 249 insertions(+) create mode 100644 runtime/queries/vim/highlights.scm diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index d7abb500c2..2c19aa6e6b 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -211,6 +211,9 @@ set(TREESITTER_C_SHA256 af66fde03feb0df4faf03750102a0d265b007e5d957057b6b293c131 set(TREESITTER_LUA_URL https://github.com/MunifTanjim/tree-sitter-lua/archive/v0.0.12.tar.gz) set(TREESITTER_LUA_SHA256 b6d7c6d04e9101a2e589d25f1d61668301e776c0b8defa6eae8dd86272e9e7c3) +set(TREESITTER_VIM_URL https://github.com/vigoux/tree-sitter-viml/archive/v0.1.0.tar.gz) +set(TREESITTER_VIM_SHA256 ea64fa211ccc7197669017b55911fdb56e8d4b6de96ba25c32b9586ec1c4f4c5) + set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) diff --git a/cmake.deps/cmake/BuildTreesitterParsers.cmake b/cmake.deps/cmake/BuildTreesitterParsers.cmake index c8f5815cd2..6267a1387c 100644 --- a/cmake.deps/cmake/BuildTreesitterParsers.cmake +++ b/cmake.deps/cmake/BuildTreesitterParsers.cmake @@ -27,3 +27,4 @@ endfunction() BuildTSParser(c ${TREESITTER_C_URL} ${TREESITTER_C_SHA256} TreesitterParserCMakeLists.txt) BuildTSParser(lua ${TREESITTER_LUA_URL} ${TREESITTER_LUA_SHA256} TreesitterParserCMakeLists.txt) +BuildTSParser(vim ${TREESITTER_VIM_URL} ${TREESITTER_VIM_SHA256} TreesitterParserCMakeLists.txt) diff --git a/runtime/queries/vim/highlights.scm b/runtime/queries/vim/highlights.scm new file mode 100644 index 0000000000..c02e226b66 --- /dev/null +++ b/runtime/queries/vim/highlights.scm @@ -0,0 +1,245 @@ +(identifier) @variable +((identifier) @constant + (#lua-match? @constant "^[A-Z][A-Z_0-9]*$")) + +;; Keywords + +[ + "if" + "else" + "elseif" + "endif" +] @conditional + +[ + "try" + "catch" + "finally" + "endtry" + "throw" +] @exception + +[ + "for" + "endfor" + "in" + "while" + "endwhile" + "break" + "continue" +] @repeat + +[ + "function" + "endfunction" +] @keyword.function + +;; Function related +(function_declaration name: (_) @function) +(call_expression function: (identifier) @function) +(parameters (identifier) @parameter) +(default_parameter (identifier) @parameter) + +[ (bang) (spread) (at) ] @punctuation.special + +[ (no_option) (inv_option) (default_option) (option_name) ] @variable.builtin +[ + (scope) + "a:" + "$" +] @namespace + +;; Commands and user defined commands + +[ + "let" + "unlet" + "const" + "call" + "execute" + "normal" + "set" + "setlocal" + "silent" + "echo" + "echomsg" + "autocmd" + "augroup" + "return" + "syntax" + "lua" + "ruby" + "perl" + "python" + "highlight" + "command" + "delcommand" + "comclear" + "colorscheme" + "startinsert" + "stopinsert" + "global" + "runtime" + "wincmd" + "cnext" + "cprevious" + "cNext" + "vertical" + "leftabove" + "aboveleft" + "rightbelow" + "belowright" + "topleft" + "botright" + (unknown_command_name) +] @keyword +(map_statement cmd: _ @keyword) +(command_name) @function.macro + +;; Syntax command + +(syntax_statement (keyword) @string) +(syntax_statement [ + "enable" + "on" + "off" + "reset" + "case" + "spell" + "foldlevel" + "iskeyword" + "keyword" + "match" + "cluster" + "region" +] @keyword) + +(syntax_argument name: _ @keyword) + +[ + "" + "" + "" + " - -$treeview -$search -$mathjax - -$extrastylesheet - - - -
- - - - - diff --git a/contrib/doxygen/logo-devdoc.png b/contrib/doxygen/logo-devdoc.png deleted file mode 100644 index a25ef2b9d7..0000000000 Binary files a/contrib/doxygen/logo-devdoc.png and /dev/null differ -- cgit From ede66a0b85fcff44890cb34d71e22995eb621006 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Fri, 23 Sep 2022 12:02:16 -0400 Subject: fix: cleanup contrib/ #20304 - YouCompleteMe is unnecessary since Nvim LSP works well. - vim-addon-local-vimrc is not needed since we added `.editorconfig`. - Inline flake8 arguments. Eventually we will remove all python code, don't need a top-level `.flake8` file meanwhile. --- .flake8 | 2 - CMakeLists.txt | 1 + contrib/YouCompleteMe/README.md | 31 ---------------- contrib/YouCompleteMe/ycm_extra_conf.py | 65 --------------------------------- contrib/vim-addon-local-vimrc/README.md | 18 --------- contrib/vim-addon-local-vimrc/vimrc | 11 ------ 6 files changed, 1 insertion(+), 127 deletions(-) delete mode 100644 .flake8 delete mode 100644 contrib/YouCompleteMe/README.md delete mode 100644 contrib/YouCompleteMe/ycm_extra_conf.py delete mode 100644 contrib/vim-addon-local-vimrc/README.md delete mode 100644 contrib/vim-addon-local-vimrc/vimrc diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 2bcd70e390..0000000000 --- a/.flake8 +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length = 88 diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a1b0c6391..81a0a2f667 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -639,6 +639,7 @@ include(InstallHelpers) add_glob_targets( TARGET lintpy COMMAND ${FLAKE8_PRG} + FLAGS --max-line-length 88 GLOB_DIRS contrib scripts src test GLOB_PAT *.py TOUCH_STRATEGY SINGLE diff --git a/contrib/YouCompleteMe/README.md b/contrib/YouCompleteMe/README.md deleted file mode 100644 index 345a9d8d12..0000000000 --- a/contrib/YouCompleteMe/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# YouCompleteMe Integration - -## What is this? - -This provides the code necessary to configure vim's YCM plugin to provide C -semantic support (completion, go-to-definition, etc) for developers working on -the Neovim project. - -## Installation - -### Step 1 - -Install [YouCompleteMe](https://github.com/Valloric/YouCompleteMe). - -### Step 2 - -```bash -cp contrib/YouCompleteMe/ycm_extra_conf.py .ycm_extra_conf.py -echo .ycm_extra_conf.py >> .git/info/exclude -make -``` - -Tip: to improve source code navigation, add something like this to your nvim -configuration: - -```vim -au FileType c,cpp nnoremap :YcmCompleter GoTo -``` - -And use `ctrl+]` when the cursor is positioned in a symbol to quickly jump to a -definition or declaration. diff --git a/contrib/YouCompleteMe/ycm_extra_conf.py b/contrib/YouCompleteMe/ycm_extra_conf.py deleted file mode 100644 index e436609ce2..0000000000 --- a/contrib/YouCompleteMe/ycm_extra_conf.py +++ /dev/null @@ -1,65 +0,0 @@ -# .ycm_extra_conf.py for nvim source code. -import os -import ycm_core - - -def DirectoryOfThisScript(): - return os.path.dirname(os.path.abspath(__file__)) - - -def GetDatabase(): - compilation_database_folder = os.path.join(DirectoryOfThisScript(), - 'build') - if os.path.exists(compilation_database_folder): - return ycm_core.CompilationDatabase(compilation_database_folder) - return None - - -def GetCompilationInfoForFile(filename): - database = GetDatabase() - if not database: - return None - return database.GetCompilationInfoForFile(filename) - - -# It seems YCM does not resolve directories correctly. This function will -# adjust paths in the compiler flags to be absolute -def FixDirectories(args, compiler_working_dir): - def adjust_path(path): - return os.path.abspath(os.path.join(compiler_working_dir, path)) - - adjust_next_arg = False - new_args = [] - for arg in args: - if adjust_next_arg: - arg = adjust_path(arg) - adjust_next_arg = False - else: - for dir_flag in ['-I', '-isystem', '-o', '-c']: - if arg.startswith(dir_flag): - if arg != dir_flag: - # flag and path are concatenated in same arg - path = arg[len(dir_flag):] - new_path = adjust_path(path) - arg = '{0}{1}'.format(dir_flag, new_path) - else: - # path is specified in next argument - adjust_next_arg = True - new_args.append(arg) - return new_args - - -def FlagsForFile(filename): - compilation_info = GetCompilationInfoForFile(filename) - if not compilation_info: - return None - # Add flags not needed for clang-the-binary, - # but needed for libclang-the-library (YCM uses this last one). - flags = FixDirectories((list(compilation_info.compiler_flags_) - if compilation_info.compiler_flags_ - else []), compilation_info.compiler_working_dir_) - extra_flags = ['-Wno-newline-eof'] - return { - 'flags': flags + extra_flags, - 'do_cache': True - } diff --git a/contrib/vim-addon-local-vimrc/README.md b/contrib/vim-addon-local-vimrc/README.md deleted file mode 100644 index 2ff9f0d627..0000000000 --- a/contrib/vim-addon-local-vimrc/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# vim-addon-local-vimrc - -## Installation - -### Step 1 - -Install [vim-addon-local-vimrc](https://github.com/MarcWeber/vim-addon-local-vimrc). -For example with [Vundle](https://github.com/MarcWeber/vim-addon-local-vimrc): -```vim -Bundle 'MarcWeber/vim-addon-local-vimrc' -``` - -### Step 2 - -```bash -cp vimrc ../../.vimrc -echo .vimrc >> ../../.git/info/exclude -``` diff --git a/contrib/vim-addon-local-vimrc/vimrc b/contrib/vim-addon-local-vimrc/vimrc deleted file mode 100644 index cd8a2896ed..0000000000 --- a/contrib/vim-addon-local-vimrc/vimrc +++ /dev/null @@ -1,11 +0,0 @@ -set modelines=0 - -augroup LOCAL_SETUP - autocmd! - autocmd BufRead,BufNewFile *.h set filetype=c - autocmd FileType c setlocal expandtab - autocmd FileType c setlocal shiftwidth=2 - autocmd FileType c setlocal softtabstop=2 - autocmd FileType c setlocal textwidth=80 - autocmd FileType c setlocal comments=:///,:// -augroup end -- cgit From f3c842058ebc0ac475910726581a738d834955f6 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 24 Sep 2022 08:10:49 +0800 Subject: vim-patch:9.0.0559: timer test may get stuck at hit-enter prompt (#20312) Problem: Timer test may get stuck at hit-enter prompt. Solution: Feed some more characters. https://github.com/vim/vim/commit/4ecf16bbf951f10fd32c918c9d8bc004b7f8f7c9 --- src/nvim/testdir/test_timers.vim | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/nvim/testdir/test_timers.vim b/src/nvim/testdir/test_timers.vim index 6adf503f14..b3a22614b0 100644 --- a/src/nvim/testdir/test_timers.vim +++ b/src/nvim/testdir/test_timers.vim @@ -349,11 +349,13 @@ func Test_nocatch_timer_garbage_collect() let a = {'foo', 'bar'} endfunc func FeedChar(id) - call feedkeys('x', 't') + call feedkeys(":\", 't') endfunc call timer_start(300, 'FeedChar') call timer_start(100, 'CauseAnError') - let x = getchar() + let x = getchar() " wait for error in timer + let x = getchar(0) " read any remaining chars + let x = getchar(0) set ut& call test_override('no_wait_return', 1) -- cgit From 14610332b2e851f9464a2d32a0ef3869dcff9834 Mon Sep 17 00:00:00 2001 From: Mike Date: Fri, 23 Sep 2022 20:20:56 -0500 Subject: fix(lsp): use correct function name in deprecated message (#20308) fix: use correct function name in deprecated message --- runtime/lua/vim/lsp/buf.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 2ce565e1d9..8567619228 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -404,7 +404,7 @@ end ---@param end_pos ({number, number}, optional) mark-indexed position. ---Defaults to the end of the last visual selection. function M.range_formatting(options, start_pos, end_pos) - vim.deprecate('vim.lsp.buf.range_formatting', 'vim.lsp.formatexpr or vim.lsp.format', '0.9.0') + vim.deprecate('vim.lsp.buf.range_formatting', 'vim.lsp.formatexpr or vim.lsp.buf.format', '0.9.0') local params = util.make_given_range_params(start_pos, end_pos) params.options = util.make_formatting_params(options).options select_client('textDocument/rangeFormatting', function(client) -- cgit From 24b5449b3d9b39a436bb8fe935116afa15a9473e Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sat, 24 Sep 2022 10:16:30 +0200 Subject: vim-patch:9.0.0562: HSL playlist files are not recognized (#20307) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problem: HSL playlist files are not recognized. Solution: Add a pattern to recognize HSL palylist files. (Benoît Ryder, closes vim/vim#11204) https://github.com/vim/vim/commit/35fdd9a67d73d4750152c419d4193ebb6b6d6eee --- runtime/filetype.vim | 3 +++ runtime/lua/vim/filetype.lua | 1 + src/nvim/testdir/test_filetype.vim | 1 + 3 files changed, 5 insertions(+) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 4de1720c75..e2efaaa0ce 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -845,6 +845,9 @@ au BufNewFile,BufRead *.hex,*.h32 setf hex " Hjson au BufNewFile,BufRead *.hjson setf hjson +" HLS Playlist +au BufNewFile,BufRead *.m3u8 setf hlsplaylist + " Hollywood au BufRead,BufNewFile *.hws setf hollywood diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 5f58da7a34..c96ead323b 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -473,6 +473,7 @@ local extension = { hex = 'hex', ['h32'] = 'hex', hjson = 'hjson', + m3u8 = 'hlsplaylist', hog = 'hog', hws = 'hollywood', hoon = 'hoon', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index e3e698aa60..2d71d9b1a6 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -255,6 +255,7 @@ let s:filename_checks = { \ 'hex': ['file.hex', 'file.h32'], \ 'hgcommit': ['hg-editor-file.txt'], \ 'hjson': ['file.hjson'], + \ 'hlsplaylist': ['file.m3u8'], \ 'hog': ['file.hog', 'snort.conf', 'vision.conf'], \ 'hollywood': ['file.hws'], \ 'hoon': ['file.hoon'], -- cgit From caf5738fa9cc12fd448a9c0787a3ebf0c8e696e9 Mon Sep 17 00:00:00 2001 From: shaunsingh Date: Sat, 24 Sep 2022 06:46:21 -0400 Subject: fix(lsp): create missing directory before creating file (#19835) Co-authored-by: Mathias Fussenegger --- runtime/lua/vim/lsp/util.lua | 5 ++++- test/functional/plugin/lsp_spec.lua | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 1909dbd4d1..64512a9739 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -772,8 +772,11 @@ local function create_file(change) -- from spec: Overwrite wins over `ignoreIfExists` local fname = vim.uri_to_fname(change.uri) if not opts.ignoreIfExists or opts.overwrite then + vim.fn.mkdir(vim.fs.dirname(fname), 'p') local file = io.open(fname, 'w') - file:close() + if file then + file:close() + end end vim.fn.bufadd(fname) end diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index e032f3bc2b..bcae9b4084 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -1977,6 +1977,22 @@ describe('LSP', function() exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16') eq(true, exec_lua('return vim.loop.fs_stat(...) ~= nil', tmpfile)) end) + it('Supports file creation in folder that needs to be created with CreateFile payload', function() + local tmpfile = helpers.tmpname() + os.remove(tmpfile) -- Should not exist, only interested in a tmpname + tmpfile = tmpfile .. '/dummy/x/' + local uri = exec_lua('return vim.uri_from_fname(...)', tmpfile) + local edit = { + documentChanges = { + { + kind = 'create', + uri = uri, + }, + } + } + exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16') + eq(true, exec_lua('return vim.loop.fs_stat(...) ~= nil', tmpfile)) + end) it('createFile does not touch file if it exists and ignoreIfExists is set', function() local tmpfile = helpers.tmpname() write_file(tmpfile, 'Dummy content') -- cgit From f8b656c582c6f0d9cb35523ac2d2f3d0edbcd52b Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sat, 24 Sep 2022 12:59:37 +0200 Subject: vim-patch:9.0.0566: Nim files are not recognized (#20317) Problem: Nim files are not recognized. Solution: Add patterns for Nim files. (Nbiba Bedis, closes vim/vim#11205) https://github.com/vim/vim/commit/9fd1583c839c5e43b0d48ec815a79005a2364776 --- runtime/filetype.vim | 3 +++ runtime/lua/vim/filetype.lua | 3 +++ src/nvim/testdir/test_filetype.vim | 1 + 3 files changed, 7 insertions(+) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index e2efaaa0ce..a78478ec9e 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1279,6 +1279,9 @@ au BufNewFile,BufRead .netrc setf netrc " Nginx au BufNewFile,BufRead *.nginx,nginx*.conf,*nginx.conf,*/etc/nginx/*,*/usr/local/nginx/conf/*,*/nginx/*.conf setf nginx +" Nim file +au BufNewFile,BufRead *.nim,*.nims,*.nimble setf nim + " Ninja file au BufNewFile,BufRead *.ninja setf ninja diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index c96ead323b..d8ede33dfa 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -704,6 +704,9 @@ local extension = { nanorc = 'nanorc', ncf = 'ncf', nginx = 'nginx', + nim = 'nim', + nims = 'nim', + nimble = 'nim', ninja = 'ninja', nix = 'nix', nqc = 'nqc', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 2d71d9b1a6..3067fa439c 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -386,6 +386,7 @@ let s:filename_checks = { \ 'neomuttrc': ['Neomuttrc', '.neomuttrc', '.neomuttrc-file', '/.neomutt/neomuttrc', '/.neomutt/neomuttrc-file', 'Neomuttrc', 'Neomuttrc-file', 'any/.neomutt/neomuttrc', 'any/.neomutt/neomuttrc-file', 'neomuttrc', 'neomuttrc-file'], \ 'netrc': ['.netrc'], \ 'nginx': ['file.nginx', 'nginxfile.conf', 'filenginx.conf', 'any/etc/nginx/file', 'any/usr/local/nginx/conf/file', 'any/nginx/file.conf'], + \ 'nim': ['file.nim', 'file.nims', 'file.nimble'], \ 'ninja': ['file.ninja'], \ 'nix': ['file.nix'], \ 'nqc': ['file.nqc'], -- cgit From db056de29ad2d57ee8e1ba841d969560f9bc6714 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 24 Sep 2022 19:20:03 +0800 Subject: vim-patch:9.0.0568: autocmd code is indented more than needed (#20318) Problem: Autocmd code is indented more than needed. Solution: Break out sooner. (Yegappan Lakshmanan, closes vim/vim#11208) Also in user function code. https://github.com/vim/vim/commit/e9dcf13a3007d4f603e007e0526b0005fd026bc5 --- src/nvim/autocmd.c | 61 ++++++++++++++++++++++++++---------------------- src/nvim/eval/userfunc.c | 47 ++++++++++++++++++------------------- 2 files changed, 56 insertions(+), 52 deletions(-) diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 644f892f3c..1f23e7ab79 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -478,34 +478,37 @@ void augroup_del(char *name, bool stupid_legacy_mode) int i = augroup_find(name); if (i == AUGROUP_ERROR) { // the group doesn't exist semsg(_("E367: No such group: \"%s\""), name); - } else if (i == current_augroup) { + return; + } + if (i == current_augroup) { emsg(_("E936: Cannot delete the current group")); - } else { - if (stupid_legacy_mode) { - FOR_ALL_AUEVENTS(event) { - FOR_ALL_AUPATS_IN_EVENT(event, ap) { - if (ap->group == i && ap->pat != NULL) { - give_warning(_("W19: Deleting augroup that is still in use"), true); - map_put(String, int)(&map_augroup_name_to_id, cstr_as_string(name), AUGROUP_DELETED); - augroup_map_del(ap->group, NULL); - return; - } + return; + } + + if (stupid_legacy_mode) { + FOR_ALL_AUEVENTS(event) { + FOR_ALL_AUPATS_IN_EVENT(event, ap) { + if (ap->group == i && ap->pat != NULL) { + give_warning(_("W19: Deleting augroup that is still in use"), true); + map_put(String, int)(&map_augroup_name_to_id, cstr_as_string(name), AUGROUP_DELETED); + augroup_map_del(ap->group, NULL); + return; } } - } else { - FOR_ALL_AUEVENTS(event) { - FOR_ALL_AUPATS_IN_EVENT(event, ap) { - if (ap->group == i) { - aupat_del(ap); - } + } + } else { + FOR_ALL_AUEVENTS(event) { + FOR_ALL_AUPATS_IN_EVENT(event, ap) { + if (ap->group == i) { + aupat_del(ap); } } } - - // Remove the group because it's not currently in use. - augroup_map_del(i, name); - au_cleanup(); } + + // Remove the group because it's not currently in use. + augroup_map_del(i, name); + au_cleanup(); } /// Find the ID of an autocmd group name. @@ -733,7 +736,6 @@ char *au_event_disable(char *what) } set_string_option_direct("ei", -1, new_ei, OPT_FREE, SID_NONE); xfree(new_ei); - return save_ei; } @@ -837,13 +839,15 @@ void do_autocmd(char *arg_in, int forceit) bool invalid_flags = false; for (size_t i = 0; i < 2; i++) { - if (*cmd != NUL) { - invalid_flags |= arg_autocmd_flag_get(&once, &cmd, "++once", 6); - invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "++nested", 8); - - // Check the deprecated "nested" flag. - invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "nested", 6); + if (*cmd == NUL) { + continue; } + + invalid_flags |= arg_autocmd_flag_get(&once, &cmd, "++once", 6); + invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "++nested", 8); + + // Check the deprecated "nested" flag. + invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "nested", 6); } if (invalid_flags) { @@ -1275,6 +1279,7 @@ void ex_doautoall(exarg_T *eap) if (buf->b_ml.ml_mfp == NULL || buf == curbuf) { continue; } + // Find a window for this buffer and save some values. aucmd_prepbuf(&aco, buf); set_bufref(&bufref, buf); diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c index f28af5a6cc..72d6a1394e 100644 --- a/src/nvim/eval/userfunc.c +++ b/src/nvim/eval/userfunc.c @@ -515,35 +515,34 @@ static char *fname_trans_sid(const char *const name, char *const fname_buf, char int *const error) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { - char *fname; const int llen = eval_fname_script(name); - if (llen > 0) { - fname_buf[0] = (char)K_SPECIAL; - fname_buf[1] = (char)KS_EXTRA; - fname_buf[2] = KE_SNR; - int i = 3; - if (eval_fname_sid(name)) { // "" or "s:" - if (current_sctx.sc_sid <= 0) { - *error = FCERR_SCRIPT; - } else { - snprintf(fname_buf + i, (size_t)(FLEN_FIXED + 1 - i), "%" PRId64 "_", - (int64_t)current_sctx.sc_sid); - i = (int)strlen(fname_buf); - } - } - if ((size_t)i + strlen(name + llen) < FLEN_FIXED) { - STRCPY(fname_buf + i, name + llen); - fname = fname_buf; + if (llen == 0) { + return (char *)name; // no prefix + } + + fname_buf[0] = (char)K_SPECIAL; + fname_buf[1] = (char)KS_EXTRA; + fname_buf[2] = KE_SNR; + int i = 3; + if (eval_fname_sid(name)) { // "" or "s:" + if (current_sctx.sc_sid <= 0) { + *error = FCERR_SCRIPT; } else { - fname = xmalloc((size_t)i + strlen(name + llen) + 1); - *tofree = fname; - memmove(fname, fname_buf, (size_t)i); - STRCPY(fname + i, name + llen); + snprintf(fname_buf + i, (size_t)(FLEN_FIXED + 1 - i), "%" PRId64 "_", + (int64_t)current_sctx.sc_sid); + i = (int)strlen(fname_buf); } + } + char *fname; + if ((size_t)i + strlen(name + llen) < FLEN_FIXED) { + STRCPY(fname_buf + i, name + llen); + fname = fname_buf; } else { - fname = (char *)name; + fname = xmalloc((size_t)i + strlen(name + llen) + 1); + *tofree = fname; + memmove(fname, fname_buf, (size_t)i); + STRCPY(fname + i, name + llen); } - return fname; } -- cgit From 291a6496327e90056ea68085ad52ab74ca1df752 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 24 Sep 2022 21:07:18 +0800 Subject: fix(mapset): remove existing abbreviation of same lhs (#20320) --- src/nvim/mapping.c | 2 +- test/functional/vimscript/map_functions_spec.lua | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index a10146c110..6267e1c875 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -2199,7 +2199,7 @@ void f_mapset(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) MapArguments unmap_args = MAP_ARGUMENTS_INIT; set_maparg_lhs_rhs(lhs, strlen(lhs), "", 0, LUA_NOREF, 0, &unmap_args); unmap_args.buffer = buffer; - buf_do_map(MAPTYPE_UNMAP, &unmap_args, mode, false, curbuf); + buf_do_map(MAPTYPE_UNMAP, &unmap_args, mode, is_abbr, curbuf); xfree(unmap_args.rhs); xfree(unmap_args.orig_rhs); diff --git a/test/functional/vimscript/map_functions_spec.lua b/test/functional/vimscript/map_functions_spec.lua index 96b86d053e..ed1863754a 100644 --- a/test/functional/vimscript/map_functions_spec.lua +++ b/test/functional/vimscript/map_functions_spec.lua @@ -12,6 +12,7 @@ local meths = helpers.meths local nvim = helpers.nvim local source = helpers.source local command = helpers.command +local exec_capture = helpers.exec_capture local pcall_err = helpers.pcall_err describe('maparg()', function() @@ -178,8 +179,9 @@ describe('mapset()', function() eq('\nn lhs rhs\n map description', helpers.exec_capture("nmap lhs")) local mapargs = funcs.maparg('lhs', 'n', false, true) - meths.del_keymap('n', 'lhs') - eq('\nNo mapping found', helpers.exec_capture("nmap lhs")) + meths.set_keymap('n', 'lhs', 'rhs', {desc = 'MAP DESCRIPTION'}) + eq('\nn lhs rhs\n MAP DESCRIPTION', + helpers.exec_capture("nmap lhs")) funcs.mapset('n', false, mapargs) eq('\nn lhs rhs\n map description', helpers.exec_capture("nmap lhs")) @@ -198,6 +200,22 @@ describe('mapset()', function() expect('<<') end) + it('replaces an abbreviation of the same lhs #20320', function() + command('inoreabbr foo bar') + eq('\ni foo * bar', exec_capture('iabbr foo')) + feed('ifoo ') + expect('bar ') + local mapargs = funcs.maparg('foo', 'i', true, true) + command('inoreabbr foo BAR') + eq('\ni foo * BAR', exec_capture('iabbr foo')) + feed('foo ') + expect('bar BAR ') + funcs.mapset('i', true, mapargs) + eq('\ni foo * bar', exec_capture('iabbr foo')) + feed('foo') + expect('bar BAR bar') + end) + it('can restore Lua callback from the dict returned by maparg()', function() eq(0, exec_lua([[ GlobalCount = 0 -- cgit From 57b731818d3d54dacdace081f6db4a8ce813173d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 24 Sep 2022 21:13:32 +0800 Subject: vim-patch:9.0.0567: 'completeopt' "longest" is not used for complete() Problem: 'completeopt' "longest" is not used for complete(). Solution: Also use "longest" for complete(). (Bjorn Linse, closes vim/vim#11206) https://github.com/vim/vim/commit/87af60c91503e37c9144f8e48022b12994ce2c85 --- src/nvim/insexpand.c | 14 +++++++++++--- src/nvim/testdir/test_ins_complete.vim | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index a4b0d68ffe..1426f28453 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -199,6 +199,8 @@ static bool compl_no_insert = false; ///< false: select & insert ///< true: noinsert static bool compl_no_select = false; ///< false: select & insert ///< true: noselect +static bool compl_longest = false; ///< false: insert full match + ///< true: insert longest prefix /// Selected one of the matches. When false the match was edited or using the /// longest common string. @@ -1006,12 +1008,16 @@ void completeopt_was_set(void) { compl_no_insert = false; compl_no_select = false; + compl_longest = false; if (strstr(p_cot, "noselect") != NULL) { compl_no_select = true; } if (strstr(p_cot, "noinsert") != NULL) { compl_no_insert = true; } + if (strstr(p_cot, "longest") != NULL) { + compl_longest = true; + } } /// "compl_match_array" points the currently displayed list of entries in the @@ -2103,7 +2109,7 @@ bool ins_compl_prep(int c) // Set "compl_get_longest" when finding the first matches. if (ctrl_x_mode_not_defined_yet() || (ctrl_x_mode_normal() && !compl_started)) { - compl_get_longest = (strstr(p_cot, "longest") != NULL); + compl_get_longest = compl_longest; compl_used_match = true; } @@ -2420,6 +2426,7 @@ static void set_completion(colnr_T startcol, list_T *list) } ins_compl_clear(); ins_compl_free(); + compl_get_longest = compl_longest; compl_direction = FORWARD; if (startcol > curwin->w_cursor.col) { @@ -2449,9 +2456,10 @@ static void set_completion(colnr_T startcol, list_T *list) int save_w_leftcol = curwin->w_leftcol; compl_curr_match = compl_first_match; - if (compl_no_insert || compl_no_select) { + bool no_select = compl_no_select || compl_longest; + if (compl_no_insert || no_select) { ins_complete(K_DOWN, false); - if (compl_no_select) { + if (no_select) { ins_complete(K_UP, false); } } else { diff --git a/src/nvim/testdir/test_ins_complete.vim b/src/nvim/testdir/test_ins_complete.vim index 3e563f29f9..0810bd4adc 100644 --- a/src/nvim/testdir/test_ins_complete.vim +++ b/src/nvim/testdir/test_ins_complete.vim @@ -702,6 +702,26 @@ func Test_recursive_complete_func() bw! endfunc +" Test for using complete() with completeopt+=longest +func Test_complete_with_longest() + inoremap call complete(1, ["iaax", "iaay", "iaaz"]) + new + + " default: insert first match + set completeopt& + call setline(1, ['i']) + exe "normal Aa\\" + call assert_equal('iaax', getline(1)) + + " with longest: insert longest prefix + set completeopt+=longest + call setline(1, ['i']) + exe "normal Aa\\" + call assert_equal('iaa', getline(1)) + set completeopt& +endfunc + + " Test for completing words following a completed word in a line func Test_complete_wrapscan() " complete words from another buffer -- cgit From 0c77dba9a46765c7a769090ae21433efea5bda00 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 24 Sep 2022 21:16:50 +0800 Subject: vim-patch:9.0.0572: insert complete tests leave a mapping behind Problem: Insert complete tests leave a mapping behind. Solution: Use a buffer-local mapping. (closes vim/vim#11211) https://github.com/vim/vim/commit/75f4bafabdcc6bce5cf3e09fee29c634bf102c17 --- src/nvim/testdir/test_ins_complete.vim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/nvim/testdir/test_ins_complete.vim b/src/nvim/testdir/test_ins_complete.vim index 0810bd4adc..f706322a85 100644 --- a/src/nvim/testdir/test_ins_complete.vim +++ b/src/nvim/testdir/test_ins_complete.vim @@ -704,8 +704,8 @@ endfunc " Test for using complete() with completeopt+=longest func Test_complete_with_longest() - inoremap call complete(1, ["iaax", "iaay", "iaaz"]) new + inoremap call complete(1, ["iaax", "iaay", "iaaz"]) " default: insert first match set completeopt& @@ -719,6 +719,7 @@ func Test_complete_with_longest() exe "normal Aa\\" call assert_equal('iaa', getline(1)) set completeopt& + bwipe! endfunc @@ -1276,7 +1277,7 @@ endfunc " A mapping is not used for the key after CTRL-X. func Test_no_mapping_for_ctrl_x_key() new - inoremap let was_mapped = 'yes' + inoremap let was_mapped = 'yes' setlocal dictionary=README.txt call feedkeys("aexam\\ ", 'xt') call assert_equal('example ', getline(1)) -- cgit From 8317b9199edc6936fec829f4908f9c74dc874ce4 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 24 Sep 2022 22:28:41 +0800 Subject: fix(input): use click number of last click for mouse drag (#20300) --- src/nvim/os/input.c | 48 ++++++++++---------- test/functional/ui/mouse_spec.lua | 96 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 113 insertions(+), 31 deletions(-) diff --git a/src/nvim/os/input.c b/src/nvim/os/input.c index fc7390a303..cb0dba8cac 100644 --- a/src/nvim/os/input.c +++ b/src/nvim/os/input.c @@ -306,37 +306,35 @@ static uint8_t check_multiclick(int code, int grid, int row, int col) static int orig_mouse_row = 0; static uint64_t orig_mouse_time = 0; // time of previous mouse click - if (code == KE_LEFTRELEASE - || code == KE_RIGHTRELEASE - || code == KE_MIDDLERELEASE - || code == KE_MOUSEDOWN - || code == KE_MOUSEUP - || code == KE_MOUSELEFT - || code == KE_MOUSERIGHT - || code == KE_MOUSEMOVE) { + if ((code >= KE_MOUSEDOWN && code <= KE_MOUSERIGHT) || code == KE_MOUSEMOVE) { return 0; } - uint64_t mouse_time = os_hrtime(); // time of current mouse click (ns) - - // compute the time elapsed since the previous mouse click and - // convert p_mouse from ms to ns - uint64_t timediff = mouse_time - orig_mouse_time; - uint64_t mouset = (uint64_t)p_mouset * 1000000; - if (code == orig_mouse_code - && timediff < mouset - && orig_num_clicks != 4 - && orig_mouse_grid == grid - && orig_mouse_col == col - && orig_mouse_row == row) { - orig_num_clicks++; - } else { - orig_num_clicks = 1; + + // For click events the number of clicks is updated. + if (code == KE_LEFTMOUSE || code == KE_RIGHTMOUSE || code == KE_MIDDLEMOUSE) { + uint64_t mouse_time = os_hrtime(); // time of current mouse click (ns) + // compute the time elapsed since the previous mouse click and + // convert p_mouse from ms to ns + uint64_t timediff = mouse_time - orig_mouse_time; + uint64_t mouset = (uint64_t)p_mouset * 1000000; + if (code == orig_mouse_code + && timediff < mouset + && orig_num_clicks != 4 + && orig_mouse_grid == grid + && orig_mouse_col == col + && orig_mouse_row == row) { + orig_num_clicks++; + } else { + orig_num_clicks = 1; + } + orig_mouse_code = code; + orig_mouse_time = mouse_time; } - orig_mouse_code = code; + // For drag and release events the number of clicks is kept. + orig_mouse_grid = grid; orig_mouse_col = col; orig_mouse_row = row; - orig_mouse_time = mouse_time; uint8_t modifiers = 0; if (orig_num_clicks == 2) { diff --git a/test/functional/ui/mouse_spec.lua b/test/functional/ui/mouse_spec.lua index 8c5475ecce..cb8dfdb8e1 100644 --- a/test/functional/ui/mouse_spec.lua +++ b/test/functional/ui/mouse_spec.lua @@ -648,8 +648,10 @@ describe('ui/mouse/input', function() ]]} end) - it('two clicks will select the word and enter VISUAL', function() - feed('<2,2><2,2>') + it('two clicks will enter VISUAL and dragging selects words', function() + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') screen:expect([[ testing | mouse | @@ -657,10 +659,38 @@ describe('ui/mouse/input', function() {0:~ }| {2:-- VISUAL --} | ]]) + feed('<0,1>') + screen:expect([[ + testing | + ^m{1:ouse} | + {1:support} and selection | + {0:~ }| + {2:-- VISUAL --} | + ]]) + feed('<4,0>') + screen:expect([[ + ^t{1:esting} | + {1:mouse} | + {1:support} and selection | + {0:~ }| + {2:-- VISUAL --} | + ]]) + feed('<14,2>') + screen:expect([[ + testing | + mouse | + {1:support and selectio}^n | + {0:~ }| + {2:-- VISUAL --} | + ]]) end) - it('three clicks will select the line and enter VISUAL LINE', function() - feed('<2,2><2,2><2,2>') + it('three clicks will enter VISUAL LINE and dragging selects lines', function() + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') screen:expect([[ testing | mouse | @@ -668,10 +698,40 @@ describe('ui/mouse/input', function() {0:~ }| {2:-- VISUAL LINE --} | ]]) + feed('<0,1>') + screen:expect([[ + testing | + ^m{1:ouse} | + {1:support and selection} | + {0:~ }| + {2:-- VISUAL LINE --} | + ]]) + feed('<4,0>') + screen:expect([[ + {1:test}^i{1:ng} | + {1:mouse} | + {1:support and selection} | + {0:~ }| + {2:-- VISUAL LINE --} | + ]]) + feed('<14,2>') + screen:expect([[ + testing | + mouse | + {1:support and se}^l{1:ection} | + {0:~ }| + {2:-- VISUAL LINE --} | + ]]) end) - it('four clicks will enter VISUAL BLOCK', function() - feed('<2,2><2,2><2,2><2,2>') + it('four clicks will enter VISUAL BLOCK and dragging selects blockwise', function() + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') + feed('<2,2>') screen:expect([[ testing | mouse | @@ -679,6 +739,30 @@ describe('ui/mouse/input', function() {0:~ }| {2:-- VISUAL BLOCK --} | ]]) + feed('<0,1>') + screen:expect([[ + testing | + ^m{1:ou}se | + {1:sup}port and selection | + {0:~ }| + {2:-- VISUAL BLOCK --} | + ]]) + feed('<4,0>') + screen:expect([[ + te{1:st}^ing | + mo{1:use} | + su{1:ppo}rt and selection | + {0:~ }| + {2:-- VISUAL BLOCK --} | + ]]) + feed('<14,2>') + screen:expect([[ + testing | + mouse | + su{1:pport and se}^lection | + {0:~ }| + {2:-- VISUAL BLOCK --} | + ]]) end) it('right click extends visual selection to the clicked location', function() -- cgit From b0fcdf9f099b17198630025a700e87f05b4e3a84 Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Sun, 25 Sep 2022 00:07:59 +0200 Subject: vim-patch:9.0.0576: unused loop variables (#20326) Problem: Unused loop variables. Solution: Use a while loop instead. (closes vim/vim#11214) https://github.com/vim/vim/commit/b2209f213e2931cf3313b24868a9165bbb717cc4 --- src/nvim/digraph.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c index c0e7a6250e..1267d49ad1 100644 --- a/src/nvim/digraph.c +++ b/src/nvim/digraph.c @@ -1578,7 +1578,7 @@ static int getexactdigraph(int char1, int char2, bool meta_char) if (retval == 0) { dp = digraphdefault; - for (int i = 0; dp->char1 != 0; i++) { + while (dp->char1 != 0) { if (((int)dp->char1 == char1) && ((int)dp->char2 == char2)) { retval = dp->result; break; @@ -1707,7 +1707,7 @@ void listdigraphs(bool use_headers) const digr_T *dp = digraphdefault; - for (int i = 0; dp->char1 != NUL && !got_int; i++) { + while (dp->char1 != NUL && !got_int) { digr_T tmp; // May need to convert the result to 'encoding'. @@ -1759,7 +1759,7 @@ void digraph_getlist_common(bool list_all, typval_T *rettv) if (list_all) { dp = digraphdefault; - for (int i = 0; dp->char1 != NUL && !got_int; i++) { + while (dp->char1 != NUL && !got_int) { digr_T tmp; tmp.char1 = dp->char1; tmp.char2 = dp->char2; -- cgit From c7cf1232a71b0db700b818e2ae8e8ebaf40133f2 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 25 Sep 2022 09:49:21 +0800 Subject: vim-patch:8.2.4467: running filetype test leaves file behind (#20335) Problem: Running filetype test leaves file behind. Solution: Delete the file. https://github.com/vim/vim/commit/0e71b7d4ce3e1210150ce772e1af6956057a71ed vim-patch:8.2.4466: MS-Windows: illegal memory access in installer Problem: MS-Windows: illegal memory access in installer when using "create-directories" as the final argument. Solution: Check the argument count. (Cam Sinclair, closes vim/vim#9844) https://github.com/vim/vim/commit/5c6edf41f9beffea21ce45d658822cc4c0745fdb --- src/nvim/testdir/test_filetype.vim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 3067fa439c..516a764f45 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -932,7 +932,9 @@ func Test_d_file() call assert_equal('d', &filetype) bwipe! + " clean up filetype off + call delete('Xfile.d') endfunc func Test_dat_file() -- cgit From 2a3cb0893b03aeff4d8c0b2116cbddda53bba5a2 Mon Sep 17 00:00:00 2001 From: Louis Sven Goulet <31444858+lorlouis@users.noreply.github.com> Date: Sat, 24 Sep 2022 21:57:10 -0400 Subject: feat: ":write!" skips "file changed" warning #18665 Problem: Cannot opt-out of "WARNING: The file has been changed since reading it!!!", even with ":write!". Solution: Change ":write!" to skip the warning. closes #7270 --- runtime/doc/editing.txt | 6 ++-- runtime/doc/vim_diff.txt | 1 + src/nvim/fileio.c | 4 +-- test/functional/core/fileio_spec.lua | 58 ++++++++++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+), 5 deletions(-) diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt index dcb0bf8a2e..21a30ca429 100644 --- a/runtime/doc/editing.txt +++ b/runtime/doc/editing.txt @@ -941,7 +941,7 @@ WRITING WITH MULTIPLE BUFFERS *buffer-write* Vim will warn you if you try to overwrite a file that has been changed -elsewhere. See |timestamp|. +elsewhere (unless "!" was used). See |timestamp|. *backup* *E207* *E506* *E507* *E508* *E509* *E510* If you write to an existing file (but do not append) while the 'backup', @@ -1481,8 +1481,8 @@ doing something there and closing it should be OK (if there are no side effects from other autocommands). Closing unrelated windows and buffers will get you into trouble. -Before writing a file the timestamp is checked. If it has changed, Vim will -ask if you really want to overwrite the file: +Before writing a file, the timestamp is checked (unless "!" was used). +If it has changed, Vim will ask if you really want to overwrite the file: WARNING: The file has been changed since reading it!!! Do you really want to write to it (y/n)? diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index b013e00fe8..e254e5edd0 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -372,6 +372,7 @@ Lua interface (|lua.txt|): Commands: |:doautocmd| does not warn about "No matching autocommands". |:wincmd| accepts a count. + `:write!` does not show a prompt if the file was updated externally. Command line completion: The meanings of arrow keys do not change depending on 'wildoptions'. diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index d391e19964..76317298dc 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -2536,8 +2536,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en goto fail; } - // Check if the timestamp hasn't changed since reading the file. - if (overwriting) { + // If 'forceit' is false, check if the timestamp hasn't changed since reading the file. + if (overwriting && !forceit) { retval = check_mtime(buf, &file_info_old); if (retval == FAIL) { goto fail; diff --git a/test/functional/core/fileio_spec.lua b/test/functional/core/fileio_spec.lua index e71131dcf8..a589d088a4 100644 --- a/test/functional/core/fileio_spec.lua +++ b/test/functional/core/fileio_spec.lua @@ -23,6 +23,8 @@ local iswin = helpers.iswin local assert_alive = helpers.assert_alive local expect_exit = helpers.expect_exit local write_file = helpers.write_file +local Screen = require('test.functional.ui.screen') +local feed_command = helpers.feed_command local uname = helpers.uname describe('fileio', function() @@ -36,6 +38,7 @@ describe('fileio', function() os.remove('Xtest_startup_file2') os.remove('Xtest_тест.md') os.remove('Xtest-u8-int-max') + os.remove('Xtest-overwrite-forced') rmdir('Xtest_startup_swapdir') rmdir('Xtest_backupdir') end) @@ -151,6 +154,61 @@ describe('fileio', function() command('edit ++enc=utf32 Xtest-u8-int-max') assert_alive() end) + + it(':w! does not show "file has been changed" warning', function() + clear() + write_file("Xtest-overwrite-forced", 'foobar') + command('set nofixendofline') + local screen = Screen.new(40,4) + screen:set_default_attr_ids({ + [1] = {bold = true, foreground = Screen.colors.Blue1}, + [2] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red}, + [3] = {bold = true, foreground = Screen.colors.SeaGreen4} + }) + screen:attach() + command("set display-=msgsep shortmess-=F") + + command("e Xtest-overwrite-forced") + screen:expect([[ + ^foobar | + {1:~ }| + {1:~ }| + "Xtest-overwrite-forced" [noeol] 1L, 6B | + ]]) + + -- Get current unix time. + local cur_unix_time = os.time(os.date("!*t")) + local future_time = cur_unix_time + 999999 + -- Set the file's access/update time to be + -- greater than the time at which it was created. + local uv = require("luv") + uv.fs_utime('Xtest-overwrite-forced', future_time, future_time) + -- use async feed_command because nvim basically hangs on the prompt + feed_command("w") + screen:expect([[ + {2:WARNING: The file has been changed since}| + {2: reading it!!!} | + {3:Do you really want to write to it (y/n)^?}| + | + ]]) + + feed("n") + feed("") + screen:expect([[ + ^foobar | + {1:~ }| + {1:~ }| + | + ]]) + -- Use a screen test because the warning does not set v:errmsg. + command("w!") + screen:expect([[ + ^foobar | + {1:~ }| + {1:~ }| + Date: Sun, 25 Sep 2022 00:45:15 +0200 Subject: refactor(treesitter): rename x_position => x_pos "pos" has a long precedent as "position" in vim, and there is no reason to use a verbose name here. --- runtime/doc/develop.txt | 6 ++++++ runtime/doc/treesitter.txt | 6 ++---- runtime/lua/vim/treesitter.lua | 9 ++++----- test/functional/treesitter/highlight_spec.lua | 2 +- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt index b31ac47bda..4f17e7d34a 100644 --- a/runtime/doc/develop.txt +++ b/runtime/doc/develop.txt @@ -251,6 +251,12 @@ Use existing common {action} names if possible: list Get all things set Set a thing (or group of things) +Use existing common {thing} names if possible: + buf Buffer + pos Position + tab Tabpage + win Window + Use consistent names for {thing} in all API functions. E.g. a buffer is called "buf" everywhere, not "buffer" in some places and "buf" in others. diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index eda1a5e496..3102c6da9a 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -434,8 +434,7 @@ get_captures_at_cursor({winnr}) *get_captures_at_cursor()* Return: ~ string[] List of capture names - *get_captures_at_position()* -get_captures_at_position({bufnr}, {row}, {col}) +get_captures_at_pos({bufnr}, {row}, {col}) *get_captures_at_pos()* Returns a list of highlight captures at the given position Each capture is represented by a table containing the capture name as a @@ -460,8 +459,7 @@ get_node_at_cursor({winnr}) *get_node_at_cursor()* Return: ~ (string) Name of node under the cursor - *get_node_at_position()* -get_node_at_position({bufnr}, {row}, {col}, {opts}) +get_node_at_pos({bufnr}, {row}, {col}, {opts}) *get_node_at_pos()* Returns the smallest named node at the given position Parameters: ~ diff --git a/runtime/lua/vim/treesitter.lua b/runtime/lua/vim/treesitter.lua index 04e12cbe0b..6cd00516bf 100644 --- a/runtime/lua/vim/treesitter.lua +++ b/runtime/lua/vim/treesitter.lua @@ -202,7 +202,7 @@ end ---@param col number Position column --- ---@return table[] List of captures `{ capture = "capture name", metadata = { ... } }` -function M.get_captures_at_position(bufnr, row, col) +function M.get_captures_at_pos(bufnr, row, col) if bufnr == 0 then bufnr = a.nvim_get_current_buf() end @@ -258,7 +258,7 @@ function M.get_captures_at_cursor(winnr) local bufnr = a.nvim_win_get_buf(winnr) local cursor = a.nvim_win_get_cursor(winnr) - local data = M.get_captures_at_position(bufnr, cursor[1] - 1, cursor[2]) + local data = M.get_captures_at_pos(bufnr, cursor[1] - 1, cursor[2]) local captures = {} @@ -278,7 +278,7 @@ end --- - ignore_injections boolean Ignore injected languages (default true) --- ---@return userdata |tsnode| under the cursor -function M.get_node_at_position(bufnr, row, col, opts) +function M.get_node_at_pos(bufnr, row, col, opts) if bufnr == 0 then bufnr = a.nvim_get_current_buf() end @@ -302,8 +302,7 @@ function M.get_node_at_cursor(winnr) local bufnr = a.nvim_win_get_buf(winnr) local cursor = a.nvim_win_get_cursor(winnr) - return M.get_node_at_position(bufnr, cursor[1] - 1, cursor[2], { ignore_injections = false }) - :type() + return M.get_node_at_pos(bufnr, cursor[1] - 1, cursor[2], { ignore_injections = false }):type() end --- Starts treesitter highlighting for a buffer diff --git a/test/functional/treesitter/highlight_spec.lua b/test/functional/treesitter/highlight_spec.lua index 1684337c3c..ae3f42ff0a 100644 --- a/test/functional/treesitter/highlight_spec.lua +++ b/test/functional/treesitter/highlight_spec.lua @@ -607,7 +607,7 @@ describe('treesitter highlighting', function() eq({ {capture='Error', metadata = { priority='101' }}; {capture='type', metadata = { } }; - }, exec_lua [[ return vim.treesitter.get_captures_at_position(0, 0, 2) ]]) + }, exec_lua [[ return vim.treesitter.get_captures_at_pos(0, 0, 2) ]]) end) it("allows to use captures with dots (don't use fallback when specialization of foo exists)", function() -- cgit From 2a5692c64628ee0af3ef4931a774a2eb0a7e046f Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Sun, 25 Sep 2022 13:59:11 +0200 Subject: vim-patch:9.0.0583: only recognizing .m3u8 files is inconsistent (#20342) Problem: Only recognizing .m3u8 files is inconsistent. Solution: Also matc .m3u files. (issue vim/vim#11204) https://github.com/vim/vim/commit/b9725bc7f6427654eb4e35874034b0ec1b6b96b3 --- runtime/filetype.vim | 4 ++-- runtime/lua/vim/filetype.lua | 1 + src/nvim/testdir/test_filetype.vim | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index a78478ec9e..11536adf69 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -845,8 +845,8 @@ au BufNewFile,BufRead *.hex,*.h32 setf hex " Hjson au BufNewFile,BufRead *.hjson setf hjson -" HLS Playlist -au BufNewFile,BufRead *.m3u8 setf hlsplaylist +" HLS Playlist (or another form of playlist) +au BufNewFile,BufRead *.m3u,*.m3u8 setf hlsplaylist " Hollywood au BufRead,BufNewFile *.hws setf hollywood diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index d8ede33dfa..bd317baae9 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -473,6 +473,7 @@ local extension = { hex = 'hex', ['h32'] = 'hex', hjson = 'hjson', + m3u = 'hlsplaylist', m3u8 = 'hlsplaylist', hog = 'hog', hws = 'hollywood', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 516a764f45..4755d39cd3 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -255,7 +255,7 @@ let s:filename_checks = { \ 'hex': ['file.hex', 'file.h32'], \ 'hgcommit': ['hg-editor-file.txt'], \ 'hjson': ['file.hjson'], - \ 'hlsplaylist': ['file.m3u8'], + \ 'hlsplaylist': ['file.m3u', 'file.m3u8'], \ 'hog': ['file.hog', 'snort.conf', 'vision.conf'], \ 'hollywood': ['file.hws'], \ 'hoon': ['file.hoon'], -- cgit From 1b60b5ec94001f18b70dbebf6c232c33209f11b5 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 25 Sep 2022 13:45:41 +0200 Subject: fix(gen_vimdoc.py): handle missing luajit --- scripts/gen_vimdoc.py | 14 ++++++++++---- scripts/lua2dox_filter | 7 ++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/scripts/gen_vimdoc.py b/scripts/gen_vimdoc.py index 766c420c7d..306857ca6c 100755 --- a/scripts/gen_vimdoc.py +++ b/scripts/gen_vimdoc.py @@ -295,14 +295,16 @@ annotation_map = { # or if `cond()` is callable and returns True. def debug_this(o, cond=True): name = '' + if cond is False: + return if not isinstance(o, str): try: name = o.nodeName o = o.toprettyxml(indent=' ', newl='\n') except Exception: pass - if ((callable(cond) and cond()) - or (not callable(cond) and cond) + if (cond is True + or (callable(cond) and cond()) or (not callable(cond) and cond in o)): raise RuntimeError('xxx: {}\n{}'.format(name, o)) @@ -887,7 +889,7 @@ def extract_from_xml(filename, target, width, fmt_vimhelp): def fmt_doxygen_xml_as_vimhelp(filename, target): """Entrypoint for generating Vim :help from from Doxygen XML. - Returns 3 items: + Returns 2 items: 1. Vim help text for functions found in `filename`. 2. Vim help text for deprecated functions. """ @@ -1094,7 +1096,11 @@ def main(config, args): fn_map_full.update(fn_map) if len(sections) == 0: - fail(f'no sections for target: {target}') + if target == 'lua': + fail(f'no sections for target: {target} (this usually means' + + ' "luajit" was not found by scripts/lua2dox_filter)') + else: + fail(f'no sections for target: {target}') if len(sections) > len(CONFIG[target]['section_order']): raise RuntimeError( 'found new modules "{}"; update the "section_order" map'.format( diff --git a/scripts/lua2dox_filter b/scripts/lua2dox_filter index 22484a807f..0b9f59b6ac 100755 --- a/scripts/lua2dox_filter +++ b/scripts/lua2dox_filter @@ -36,6 +36,10 @@ test_executable(){ ##! \brief sets the lua interpreter set_lua(){ + if test -z "${EXE}"; then + test_executable '.deps/usr/bin/luajit' + fi + if test -z "${EXE}"; then test_executable 'luajit' fi @@ -73,7 +77,8 @@ do_readlink(){ set_lua if test -z "${EXE}" then - echo "no lua interpreter available" + echo "no lua interpreter found" + exit 1 else BASENAME=`basename "$0"` do_readlink "$0" -- cgit From 91e912f8d40284c74d4a997c8c95961eebb35d91 Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Sun, 25 Sep 2022 15:26:37 +0200 Subject: refactor: move klib out of src/nvim/ #20341 It's confusing to mix vendored dependencies with neovim source code. A clean separation is simpler to keep track of and simpler to document. --- src/klib/kbtree.h | 477 ++++++++++++++++++++++++ src/klib/khash.h | 730 +++++++++++++++++++++++++++++++++++++ src/klib/klist.h | 144 ++++++++ src/klib/kvec.h | 236 ++++++++++++ src/nvim/CMakeLists.txt | 4 +- src/nvim/api/private/defs.h | 2 +- src/nvim/api/private/helpers.c | 2 +- src/nvim/api/private/helpers.h | 2 +- src/nvim/buffer_defs.h | 2 +- src/nvim/context.h | 2 +- src/nvim/decoration_provider.c | 2 +- src/nvim/eval/decode.c | 2 +- src/nvim/eval/encode.c | 2 +- src/nvim/eval/typval_encode.c.h | 2 +- src/nvim/eval/typval_encode.h | 2 +- src/nvim/event/loop.h | 2 +- src/nvim/ex_getln.c | 2 +- src/nvim/extmark.c | 2 +- src/nvim/extmark_defs.h | 2 +- src/nvim/lib/kbtree.h | 477 ------------------------ src/nvim/lib/khash.h | 730 ------------------------------------- src/nvim/lib/klist.h | 144 -------- src/nvim/lib/kvec.h | 236 ------------ src/nvim/lua/converter.c | 2 +- src/nvim/lua/treesitter.c | 2 +- src/nvim/map.c | 2 +- src/nvim/map_defs.h | 2 +- src/nvim/marktree.c | 2 +- src/nvim/message.h | 2 +- src/nvim/msgpack_rpc/channel.c | 2 +- src/nvim/msgpack_rpc/helpers.c | 2 +- src/nvim/ops.c | 2 +- src/nvim/os/pty_conpty_win.h | 2 +- src/nvim/os/pty_process_unix.c | 2 +- src/nvim/os/shell.c | 2 +- src/nvim/shada.c | 4 +- src/nvim/state.c | 2 +- src/nvim/strings.h | 2 +- src/nvim/tui/tui.c | 2 +- src/nvim/ui_compositor.c | 2 +- src/nvim/undo.c | 2 +- src/nvim/viml/parser/expressions.c | 2 +- src/nvim/viml/parser/parser.h | 2 +- 43 files changed, 1624 insertions(+), 1624 deletions(-) create mode 100644 src/klib/kbtree.h create mode 100644 src/klib/khash.h create mode 100644 src/klib/klist.h create mode 100644 src/klib/kvec.h delete mode 100644 src/nvim/lib/kbtree.h delete mode 100644 src/nvim/lib/khash.h delete mode 100644 src/nvim/lib/klist.h delete mode 100644 src/nvim/lib/kvec.h diff --git a/src/klib/kbtree.h b/src/klib/kbtree.h new file mode 100644 index 0000000000..99f79952d7 --- /dev/null +++ b/src/klib/kbtree.h @@ -0,0 +1,477 @@ +/*- + * Copyright 1997-1999, 2001, John-Mark Gurney. + * 2008-2009, Attractive Chaos + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +// Gotchas +// ------- +// +// if you delete from a kbtree while iterating over it you must use +// kb_del_itr and not kb_del otherwise the iterator might point to freed memory. + +#ifndef NVIM_LIB_KBTREE_H +#define NVIM_LIB_KBTREE_H + +#include +#include +#include +#include + +#include "nvim/memory.h" + +#define KB_MAX_DEPTH 64 + +#define __KB_KEY(type, x) (x->key) +#define __KB_PTR(btr, x) (x->ptr) + +#define __KB_TREE_T(name, key_t, T) \ + typedef struct kbnode_##name##_s kbnode_##name##_t; \ + struct kbnode_##name##_s { \ + int32_t n; \ + bool is_internal; \ + key_t key[2*T - 1]; \ + kbnode_##name##_t *ptr[]; \ + }; \ + typedef struct { \ + kbnode_##name##_t *root; \ + int n_keys, n_nodes; \ + } kbtree_##name##_t; \ + typedef struct { \ + kbnode_##name##_t *x; \ + int i; \ + } kbpos_##name##_t; \ + typedef struct { \ + kbpos_##name##_t stack[KB_MAX_DEPTH], *p; \ + } kbitr_##name##_t; \ + + +#define __kb_destroy(kbnode_t, b) do { \ + int i; \ + unsigned int max = 8; \ + kbnode_t *x, **top, **stack = 0; \ + if (b->root) { \ + top = stack = (kbnode_t **)xcalloc(max, sizeof(kbnode_t *)); \ + *top++ = (b)->root; \ + while (top != stack) { \ + x = *--top; \ + if (x->is_internal == 0) { XFREE_CLEAR(x); continue; } \ + for (i = 0; i <= x->n; ++i) \ + if (__KB_PTR(b, x)[i]) { \ + if (top - stack == (int)max) { \ + max <<= 1; \ + stack = (kbnode_t **)xrealloc(stack, max * sizeof(kbnode_t *)); \ + top = stack + (max>>1); \ + } \ + *top++ = __KB_PTR(b, x)[i]; \ + } \ + XFREE_CLEAR(x); \ + } \ + } \ + XFREE_CLEAR(stack); \ +} while (0) + +#define __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ + static inline int __kb_getp_aux_##name(const kbnode_t * __restrict x, key_t * __restrict k, \ + int *r) \ + { \ + int tr, *rr, begin = 0, end = x->n; \ + if (x->n == 0) return -1; \ + rr = r? r : &tr; \ + while (begin < end) { \ + int mid = (begin + end) >> 1; \ + if (__cmp(__KB_KEY(key_t, x)[mid], *k) < 0) begin = mid + 1; \ + else end = mid; \ + } \ + if (begin == x->n) { *rr = 1; return x->n - 1; } \ + if ((*rr = __cmp(*k, __KB_KEY(key_t, x)[begin])) < 0) --begin; \ + return begin; \ + } + +#define __KB_GET(name, key_t, kbnode_t) \ + static key_t *kb_getp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ + { \ + if (!b->root) { \ + return 0; \ + } \ + int i, r = 0; \ + kbnode_t *x = b->root; \ + while (x) { \ + i = __kb_getp_aux_##name(x, k, &r); \ + if (i >= 0 && r == 0) return &__KB_KEY(key_t, x)[i]; \ + if (x->is_internal == 0) return 0; \ + x = __KB_PTR(b, x)[i + 1]; \ + } \ + return 0; \ + } \ + static inline key_t *kb_get_##name(kbtree_##name##_t *b, key_t k) \ + { \ + return kb_getp_##name(b, &k); \ + } + +#define __KB_INTERVAL(name, key_t, kbnode_t) \ + static inline void kb_intervalp_##name(kbtree_##name##_t *b, key_t * __restrict k, key_t **lower, \ + key_t **upper) \ + { \ + if (!b->root) { \ + return; \ + } \ + int i, r = 0; \ + kbnode_t *x = b->root; \ + *lower = *upper = 0; \ + while (x) { \ + i = __kb_getp_aux_##name(x, k, &r); \ + if (i >= 0 && r == 0) { \ + *lower = *upper = &__KB_KEY(key_t, x)[i]; \ + return; \ + } \ + if (i >= 0) *lower = &__KB_KEY(key_t, x)[i]; \ + if (i < x->n - 1) *upper = &__KB_KEY(key_t, x)[i + 1]; \ + if (x->is_internal == 0) return; \ + x = __KB_PTR(b, x)[i + 1]; \ + } \ + } \ + static inline void kb_interval_##name(kbtree_##name##_t *b, key_t k, key_t **lower, key_t **upper) \ + { \ + kb_intervalp_##name(b, &k, lower, upper); \ + } + +#define __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ + /* x must be an internal node */ \ + static inline void __kb_split_##name(kbtree_##name##_t *b, kbnode_t *x, int i, kbnode_t *y) \ + { \ + kbnode_t *z; \ + z = (kbnode_t *)xcalloc(1, y->is_internal? ILEN : sizeof(kbnode_##name##_t)); \ + ++b->n_nodes; \ + z->is_internal = y->is_internal; \ + z->n = T - 1; \ + memcpy(__KB_KEY(key_t, z), &__KB_KEY(key_t, y)[T], sizeof(key_t) * (T - 1)); \ + if (y->is_internal) memcpy(__KB_PTR(b, z), &__KB_PTR(b, y)[T], sizeof(void *) * T); \ + y->n = T - 1; \ + memmove(&__KB_PTR(b, x)[i + 2], &__KB_PTR(b, \ + x)[i + 1], sizeof(void *) * (unsigned int)(x->n - i)); \ + __KB_PTR(b, x)[i + 1] = z; \ + memmove(&__KB_KEY(key_t, x)[i + 1], &__KB_KEY(key_t, x)[i], \ + sizeof(key_t) * (unsigned int)(x->n - i)); \ + __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[T - 1]; \ + ++x->n; \ + } \ + static inline key_t *__kb_putp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k) \ + { \ + int i = x->n - 1; \ + key_t *ret; \ + if (x->is_internal == 0) { \ + i = __kb_getp_aux_##name(x, k, 0); \ + if (i != x->n - 1) \ + memmove(&__KB_KEY(key_t, x)[i + 2], &__KB_KEY(key_t, \ + x)[i + 1], \ + (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ + ret = &__KB_KEY(key_t, x)[i + 1]; \ + *ret = *k; \ + ++x->n; \ + } else { \ + i = __kb_getp_aux_##name(x, k, 0) + 1; \ + if (__KB_PTR(b, x)[i]->n == 2 * T - 1) { \ + __kb_split_##name(b, x, i, __KB_PTR(b, x)[i]); \ + if (__cmp(*k, __KB_KEY(key_t, x)[i]) > 0) ++i; \ + } \ + ret = __kb_putp_aux_##name(b, __KB_PTR(b, x)[i], k); \ + } \ + return ret; \ + } \ + static inline key_t *kb_putp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ + { \ + if (!b->root) { \ + b->root = (kbnode_t *)xcalloc(1, ILEN); \ + ++b->n_nodes; \ + } \ + kbnode_t *r, *s; \ + ++b->n_keys; \ + r = b->root; \ + if (r->n == 2 * T - 1) { \ + ++b->n_nodes; \ + s = (kbnode_t *)xcalloc(1, ILEN); \ + b->root = s; s->is_internal = 1; s->n = 0; \ + __KB_PTR(b, s)[0] = r; \ + __kb_split_##name(b, s, 0, r); \ + r = s; \ + } \ + return __kb_putp_aux_##name(b, r, k); \ + } \ + static inline void kb_put_##name(kbtree_##name##_t *b, key_t k) \ + { \ + kb_putp_##name(b, &k); \ + } + +#define __KB_DEL(name, key_t, kbnode_t, T) \ + static inline key_t __kb_delp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k, \ + int s) \ + { \ + int yn, zn, i, r = 0; \ + kbnode_t *xp, *y, *z; \ + key_t kp; \ + if (x == 0) return *k; \ + if (s) { /* s can only be 0, 1 or 2 */ \ + r = x->is_internal == 0? 0 : s == 1? 1 : -1; \ + i = s == 1? x->n - 1 : -1; \ + } else i = __kb_getp_aux_##name(x, k, &r); \ + if (x->is_internal == 0) { \ + if (s == 2) ++i; \ + kp = __KB_KEY(key_t, x)[i]; \ + memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ + x)[i + 1], \ + (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ + --x->n; \ + return kp; \ + } \ + if (r == 0) { \ + if ((yn = __KB_PTR(b, x)[i]->n) >= T) { \ + xp = __KB_PTR(b, x)[i]; \ + kp = __KB_KEY(key_t, x)[i]; \ + __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 1); \ + return kp; \ + } else if ((zn = __KB_PTR(b, x)[i + 1]->n) >= T) { \ + xp = __KB_PTR(b, x)[i + 1]; \ + kp = __KB_KEY(key_t, x)[i]; \ + __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 2); \ + return kp; \ + } else if (yn == T - 1 && zn == T - 1) { \ + y = __KB_PTR(b, x)[i]; z = __KB_PTR(b, x)[i + 1]; \ + __KB_KEY(key_t, y)[y->n++] = *k; \ + memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, z), (unsigned int)z->n * sizeof(key_t)); \ + if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, \ + z), \ + (unsigned int)(z->n + 1) * sizeof(void *)); \ + y->n += z->n; \ + memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ + x)[i + 1], \ + (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ + memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, \ + x)[i + 2], \ + (unsigned int)(x->n - i - 1) * sizeof(void *)); \ + --x->n; \ + XFREE_CLEAR(z); \ + return __kb_delp_aux_##name(b, y, k, s); \ + } \ + } \ + ++i; \ + if ((xp = __KB_PTR(b, x)[i])->n == T - 1) { \ + if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n >= T) { \ + memmove(&__KB_KEY(key_t, xp)[1], __KB_KEY(key_t, xp), (unsigned int)xp->n * sizeof(key_t)); \ + if (xp->is_internal) memmove(&__KB_PTR(b, xp)[1], __KB_PTR(b, \ + xp), \ + (unsigned int)(xp->n + 1) * sizeof(void *)); \ + __KB_KEY(key_t, xp)[0] = __KB_KEY(key_t, x)[i - 1]; \ + __KB_KEY(key_t, x)[i - 1] = __KB_KEY(key_t, y)[y->n - 1]; \ + if (xp->is_internal) __KB_PTR(b, xp)[0] = __KB_PTR(b, y)[y->n]; \ + --y->n; ++xp->n; \ + } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n >= T) { \ + __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ + __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[0]; \ + if (xp->is_internal) __KB_PTR(b, xp)[xp->n] = __KB_PTR(b, y)[0]; \ + --y->n; \ + memmove(__KB_KEY(key_t, y), &__KB_KEY(key_t, y)[1], (unsigned int)y->n * sizeof(key_t)); \ + if (y->is_internal) memmove(__KB_PTR(b, y), &__KB_PTR(b, \ + y)[1], \ + (unsigned int)(y->n + 1) * sizeof(void *)); \ + } else if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n == T - 1) { \ + __KB_KEY(key_t, y)[y->n++] = __KB_KEY(key_t, x)[i - 1]; \ + memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, xp), \ + (unsigned int)xp->n * sizeof(key_t)); \ + if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, \ + xp), \ + (unsigned int)(xp->n + 1) * sizeof(void *)); \ + y->n += xp->n; \ + memmove(&__KB_KEY(key_t, x)[i - 1], &__KB_KEY(key_t, \ + x)[i], \ + (unsigned int)(x->n - i) * sizeof(key_t)); \ + memmove(&__KB_PTR(b, x)[i], &__KB_PTR(b, \ + x)[i + 1], (unsigned int)(x->n - i) * sizeof(void *)); \ + --x->n; \ + XFREE_CLEAR(xp); \ + xp = y; \ + } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n == T - 1) { \ + __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ + memmove(&__KB_KEY(key_t, xp)[xp->n], __KB_KEY(key_t, y), \ + (unsigned int)y->n * sizeof(key_t)); \ + if (xp->is_internal) memmove(&__KB_PTR(b, xp)[xp->n], __KB_PTR(b, y), \ + (unsigned int)(y->n + 1) * sizeof(void *)); \ + xp->n += y->n; \ + memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ + x)[i + 1], \ + (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ + memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, \ + x)[i + 2], \ + (unsigned int)(x->n - i - 1) * sizeof(void *)); \ + --x->n; \ + XFREE_CLEAR(y); \ + } \ + } \ + return __kb_delp_aux_##name(b, xp, k, s); \ + } \ + static inline key_t kb_delp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ + { \ + kbnode_t *x; \ + key_t ret; \ + ret = __kb_delp_aux_##name(b, b->root, k, 0); \ + --b->n_keys; \ + if (b->root->n == 0 && b->root->is_internal) { \ + --b->n_nodes; \ + x = b->root; \ + b->root = __KB_PTR(b, x)[0]; \ + XFREE_CLEAR(x); \ + } \ + return ret; \ + } \ + static inline key_t kb_del_##name(kbtree_##name##_t *b, key_t k) \ + { \ + return kb_delp_##name(b, &k); \ + } + +#define __KB_ITR(name, key_t, kbnode_t) \ + static inline void kb_itr_first_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ + { \ + itr->p = NULL; \ + if (b->n_keys == 0) return; \ + itr->p = itr->stack; \ + itr->p->x = b->root; itr->p->i = 0; \ + while (itr->p->x->is_internal && __KB_PTR(b, itr->p->x)[0] != 0) { \ + kbnode_t *x = itr->p->x; \ + ++itr->p; \ + itr->p->x = __KB_PTR(b, x)[0]; itr->p->i = 0; \ + } \ + } \ + static inline int kb_itr_next_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ + { \ + if (itr->p == NULL) return 0; \ + for (;;) { \ + ++itr->p->i; \ + assert(itr->p->i <= 21); \ + while (itr->p->x && itr->p->i <= itr->p->x->n) { \ + itr->p[1].i = 0; \ + itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[itr->p->i] : 0; \ + ++itr->p; \ + } \ + if (itr->p == itr->stack) { \ + itr->p = NULL; \ + return 0; \ + } \ + --itr->p; \ + if (itr->p->x && itr->p->i < itr->p->x->n) return 1; \ + } \ + } \ + static inline int kb_itr_prev_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ + { \ + if (itr->p == NULL) return 0; \ + for (;;) { \ + while (itr->p->x && itr->p->i >= 0) { \ + itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[itr->p->i] : 0; \ + itr->p[1].i = itr->p[1].x ? itr->p[1].x->n : -1; \ + ++itr->p; \ + } \ + if (itr->p == itr->stack) { \ + itr->p = NULL; \ + return 0; \ + } \ + --itr->p; \ + --itr->p->i; \ + if (itr->p->x && itr->p->i >= 0) return 1; \ + } \ + } \ + static inline int kb_itr_getp_##name(kbtree_##name##_t *b, key_t * __restrict k, \ + kbitr_##name##_t *itr) \ + { \ + if (b->n_keys == 0) { \ + itr->p = NULL; \ + return 0; \ + } \ + int i, r = 0; \ + itr->p = itr->stack; \ + itr->p->x = b->root; \ + while (itr->p->x) { \ + i = __kb_getp_aux_##name(itr->p->x, k, &r); \ + itr->p->i = i; \ + if (i >= 0 && r == 0) return 1; \ + ++itr->p->i; \ + assert(itr->p->i <= 21); \ + itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[i + 1] : 0; \ + ++itr->p; \ + } \ + itr->p->i = 0; \ + return 0; \ + } \ + static inline int kb_itr_get_##name(kbtree_##name##_t *b, key_t k, kbitr_##name##_t *itr) \ + { \ + return kb_itr_getp_##name(b, &k, itr); \ + } \ + static inline void kb_del_itr_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ + { \ + key_t k = kb_itr_key(itr); \ + kb_delp_##name(b, &k); \ + kb_itr_getp_##name(b, &k, itr); \ + } + +#define KBTREE_INIT(name, key_t, __cmp, T) \ + KBTREE_INIT_IMPL(name, key_t, kbnode_##name##_t, __cmp, T, \ + (sizeof(kbnode_##name##_t) + (2*T)*sizeof(void *))) + +#define KBTREE_INIT_IMPL(name, key_t, kbnode_t, __cmp, T, ILEN) \ + __KB_TREE_T(name, key_t, T) \ + __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ + __KB_GET(name, key_t, kbnode_t) \ + __KB_INTERVAL(name, key_t, kbnode_t) \ + __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ + __KB_DEL(name, key_t, kbnode_t, T) \ + __KB_ITR(name, key_t, kbnode_t) + +#define KB_DEFAULT_SIZE 512 + +#define kbtree_t(name) kbtree_##name##_t +#define kbitr_t(name) kbitr_##name##_t +#define kb_init(b) ((b)->n_keys = (b)->n_nodes = 0, (b)->root = 0) +#define kb_destroy(name, b) __kb_destroy(kbnode_##name##_t, b) +#define kb_get(name, b, k) kb_get_##name(b, k) +#define kb_put(name, b, k) kb_put_##name(b, k) +#define kb_del(name, b, k) kb_del_##name(b, k) +#define kb_interval(name, b, k, l, u) kb_interval_##name(b, k, l, u) +#define kb_getp(name, b, k) kb_getp_##name(b, k) +#define kb_putp(name, b, k) kb_putp_##name(b, k) +#define kb_delp(name, b, k) kb_delp_##name(b, k) +#define kb_intervalp(name, b, k, l, u) kb_intervalp_##name(b, k, l, u) + +#define kb_itr_first(name, b, i) kb_itr_first_##name(b, i) +#define kb_itr_get(name, b, k, i) kb_itr_get_##name(b, k, i) +#define kb_itr_getp(name, b, k, i) kb_itr_getp_##name(b, k, i) +#define kb_itr_next(name, b, i) kb_itr_next_##name(b, i) +#define kb_itr_prev(name, b, i) kb_itr_prev_##name(b, i) +#define kb_del_itr(name, b, i) kb_del_itr_##name(b, i) +#define kb_itr_key(itr) __KB_KEY(dummy, (itr)->p->x)[(itr)->p->i] +#define kb_itr_valid(itr) ((itr)->p >= (itr)->stack) + +#define kb_size(b) ((b)->n_keys) + +#define kb_generic_cmp(a, b) (((b) < (a)) - ((a) < (b))) +#define kb_str_cmp(a, b) strcmp(a, b) + +#endif // NVIM_LIB_KBTREE_H diff --git a/src/klib/khash.h b/src/klib/khash.h new file mode 100644 index 0000000000..57a41f9c13 --- /dev/null +++ b/src/klib/khash.h @@ -0,0 +1,730 @@ +/* The MIT License + + Copyright (c) 2008, 2009, 2011 by Attractive Chaos + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ + +/* + Example: + + #include "nvim/khash.h" + KHASH_MAP_INIT_INT(32, char) + int main() { + int ret, is_missing; + khiter_t k; + khash_t(32) *h = kh_init(32); + k = kh_put(32, h, 5, &ret); + kh_value(h, k) = 10; + k = kh_get(32, h, 10); + is_missing = (k == kh_end(h)); + k = kh_get(32, h, 5); + kh_del(32, h, k); + for (k = kh_begin(h); k != kh_end(h); ++k) + if (kh_exist(h, k)) kh_value(h, k) = 1; + kh_destroy(32, h); + return 0; + } + */ + +/* + 2013-05-02 (0.2.8): + + * Use quadratic probing. When the capacity is power of 2, stepping function + i*(i+1)/2 guarantees to traverse each bucket. It is better than double + hashing on cache performance and is more robust than linear probing. + + In theory, double hashing should be more robust than quadratic probing. + However, my implementation is probably not for large hash tables, because + the second hash function is closely tied to the first hash function, + which reduce the effectiveness of double hashing. + + Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php + + 2011-12-29 (0.2.7): + + * Minor code clean up; no actual effect. + + 2011-09-16 (0.2.6): + + * The capacity is a power of 2. This seems to dramatically improve the + speed for simple keys. Thank Zilong Tan for the suggestion. Reference: + + - http://code.google.com/p/ulib/ + - http://nothings.org/computer/judy/ + + * Allow to optionally use linear probing which usually has better + performance for random input. Double hashing is still the default as it + is more robust to certain non-random input. + + * Added Wang's integer hash function (not used by default). This hash + function is more robust to certain non-random input. + + 2011-02-14 (0.2.5): + + * Allow to declare global functions. + + 2009-09-26 (0.2.4): + + * Improve portability + + 2008-09-19 (0.2.3): + + * Corrected the example + * Improved interfaces + + 2008-09-11 (0.2.2): + + * Improved speed a little in kh_put() + + 2008-09-10 (0.2.1): + + * Added kh_clear() + * Fixed a compiling error + + 2008-09-02 (0.2.0): + + * Changed to token concatenation which increases flexibility. + + 2008-08-31 (0.1.2): + + * Fixed a bug in kh_get(), which has not been tested previously. + + 2008-08-31 (0.1.1): + + * Added destructor + */ + +#ifndef NVIM_LIB_KHASH_H +#define NVIM_LIB_KHASH_H + +/*! + @header + + Generic hash table library. + */ + +#define AC_VERSION_KHASH_H "0.2.8" + +#include +#include +#include +#include + +#include "nvim/func_attr.h" +#include "nvim/memory.h" + +// compiler specific configuration + +#if UINT_MAX == 0xffffffffu +typedef unsigned int khint32_t; +#elif ULONG_MAX == 0xffffffffu +typedef unsigned long khint32_t; +#endif + +#if ULONG_MAX == ULLONG_MAX +typedef unsigned long khint64_t; +#else +typedef unsigned long long khint64_t; +#endif + +#ifdef _MSC_VER +# define kh_inline __inline +#else +# define kh_inline inline +#endif + +typedef khint32_t khint_t; +typedef khint_t khiter_t; + +#define __ac_isempty(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&2) +#define __ac_isdel(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&1) +#define __ac_iseither(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&3) +#define __ac_set_isdel_false(flag, i) (flag[i>>4]&=~(khint_t)(1ul<<((i&0xfU)<<1))) +#define __ac_set_isempty_false(flag, i) (flag[i>>4]&=~(khint_t)(2ul<<((i&0xfU)<<1))) +#define __ac_set_isboth_false(flag, i) (flag[i>>4]&=~(khint_t)(3ul<<((i&0xfU)<<1))) +#define __ac_set_isdel_true(flag, i) (flag[i>>4]|=(khint_t)1ul<<((i&0xfU)<<1)) + +#define __ac_fsize(m) ((m) < 16? 1 : (m)>>4) + +#ifndef kroundup32 +# define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, \ + ++(x)) +#endif + +#ifndef kcalloc +# define kcalloc(N, Z) xcalloc(N, Z) +#endif +#ifndef kmalloc +# define kmalloc(Z) xmalloc(Z) +#endif +#ifndef krealloc +# define krealloc(P, Z) xrealloc(P, Z) +#endif +#ifndef kfree +# define kfree(P) XFREE_CLEAR(P) +#endif + +#define __ac_HASH_UPPER 0.77 + +#define __KHASH_TYPE(name, khkey_t, khval_t) \ + typedef struct { \ + khint_t n_buckets, size, n_occupied, upper_bound; \ + khint32_t *flags; \ + khkey_t *keys; \ + khval_t *vals; \ + } kh_##name##_t; + +#define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \ + extern kh_##name##_t *kh_init_##name(void); \ + extern void kh_dealloc_##name(kh_##name##_t *h); \ + extern void kh_destroy_##name(kh_##name##_t *h); \ + extern void kh_clear_##name(kh_##name##_t *h); \ + extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \ + extern void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \ + extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \ + extern void kh_del_##name(kh_##name##_t *h, khint_t x); + +#define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, \ + __hash_equal) \ + SCOPE kh_##name##_t *kh_init_##name(void) \ + REAL_FATTR_UNUSED; \ + SCOPE kh_##name##_t *kh_init_##name(void) { \ + return (kh_##name##_t *)kcalloc(1, sizeof(kh_##name##_t)); \ + } \ + SCOPE void kh_dealloc_##name(kh_##name##_t *h) \ + REAL_FATTR_UNUSED; \ + SCOPE void kh_dealloc_##name(kh_##name##_t *h) \ + { \ + kfree(h->keys); \ + kfree(h->flags); \ + kfree(h->vals); \ + } \ + SCOPE void kh_destroy_##name(kh_##name##_t *h) \ + REAL_FATTR_UNUSED; \ + SCOPE void kh_destroy_##name(kh_##name##_t *h) \ + { \ + if (h) { \ + kh_dealloc_##name(h); \ + kfree(h); \ + } \ + } \ + SCOPE void kh_clear_##name(kh_##name##_t *h) \ + REAL_FATTR_UNUSED; \ + SCOPE void kh_clear_##name(kh_##name##_t *h) \ + { \ + if (h && h->flags) { \ + memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khint32_t)); \ + h->size = h->n_occupied = 0; \ + } \ + } \ + SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ + REAL_FATTR_UNUSED; \ + SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ + { \ + if (h->n_buckets) { \ + khint_t k, i, last, mask, step = 0; \ + mask = h->n_buckets - 1; \ + k = __hash_func(key); i = k & mask; \ + last = i; \ + while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || \ + !__hash_equal(h->keys[i], key))) { \ + i = (i + (++step)) & mask; \ + if (i == last) { \ + return h->n_buckets; \ + } \ + } \ + return __ac_iseither(h->flags, i) ? h->n_buckets : i; \ + } else { \ + return 0; \ + } \ + } \ + SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ + REAL_FATTR_UNUSED; \ + SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ + { /* This function uses 0.25*n_buckets bytes of working space instead of */ \ + /* [sizeof(key_t+val_t)+.25]*n_buckets. */ \ + khint32_t *new_flags = 0; \ + khint_t j = 1; \ + { \ + kroundup32(new_n_buckets); \ + if (new_n_buckets < 4) { \ + new_n_buckets = 4; \ + } \ + /* requested size is too small */ \ + if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) { \ + j = 0; \ + } else { /* hash table size to be changed (shrink or expand); rehash */ \ + new_flags = (khint32_t *)kmalloc(__ac_fsize(new_n_buckets) \ + * sizeof(khint32_t)); \ + memset(new_flags, 0xaa, \ + __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \ + if (h->n_buckets < new_n_buckets) { /* expand */ \ + khkey_t *new_keys = (khkey_t *)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \ + h->keys = new_keys; \ + if (kh_is_map) { \ + khval_t *new_vals = \ + (khval_t *)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \ + h->vals = new_vals; \ + } \ + } /* otherwise shrink */ \ + } \ + } \ + if (j) { /* rehashing is needed */ \ + for (j = 0; j != h->n_buckets; ++j) { \ + if (__ac_iseither(h->flags, j) == 0) { \ + khkey_t key = h->keys[j]; \ + khval_t val; \ + khint_t new_mask; \ + new_mask = new_n_buckets - 1; \ + if (kh_is_map) { \ + val = h->vals[j]; \ + } \ + __ac_set_isdel_true(h->flags, j); \ + /* kick-out process; sort of like in Cuckoo hashing */ \ + while (1) { \ + khint_t k, i, step = 0; \ + k = __hash_func(key); \ + i = k & new_mask; \ + while (!__ac_isempty(new_flags, i)) { \ + i = (i + (++step)) & new_mask; \ + } \ + __ac_set_isempty_false(new_flags, i); \ + /* kick out the existing element */ \ + if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { \ + { \ + khkey_t tmp = h->keys[i]; \ + h->keys[i] = key; \ + key = tmp; \ + } \ + if (kh_is_map) { \ + khval_t tmp = h->vals[i]; \ + h->vals[i] = val; \ + val = tmp; \ + } \ + /* mark it as deleted in the old hash table */ \ + __ac_set_isdel_true(h->flags, i); \ + } else { /* write the element and jump out of the loop */ \ + h->keys[i] = key; \ + if (kh_is_map) { \ + h->vals[i] = val; \ + } \ + break; \ + } \ + } \ + } \ + } \ + if (h->n_buckets > new_n_buckets) { /* shrink the hash table */ \ + h->keys = (khkey_t *)krealloc((void *)h->keys, \ + new_n_buckets * sizeof(khkey_t)); \ + if (kh_is_map) { \ + h->vals = (khval_t *)krealloc((void *)h->vals, \ + new_n_buckets * sizeof(khval_t)); \ + } \ + } \ + kfree(h->flags); /* free the working space */ \ + h->flags = new_flags; \ + h->n_buckets = new_n_buckets; \ + h->n_occupied = h->size; \ + h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \ + } \ + } \ + SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ + REAL_FATTR_UNUSED; \ + SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ + { \ + khint_t x; \ + if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \ + if (h->n_buckets > (h->size << 1)) { \ + kh_resize_##name(h, h->n_buckets - 1); /* clear "deleted" elements */ \ + } else { \ + kh_resize_##name(h, h->n_buckets + 1); /* expand the hash table */ \ + } \ + } /* TODO: implement automatically shrinking; */ \ + /* resize() already support shrinking */ \ + { \ + khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \ + x = site = h->n_buckets; \ + k = __hash_func(key); \ + i = k & mask; \ + if (__ac_isempty(h->flags, i)) { \ + x = i; /* for speed up */ \ + } else { \ + last = i; \ + while (!__ac_isempty(h->flags, i) \ + && (__ac_isdel(h->flags, i) \ + || !__hash_equal(h->keys[i], key))) { \ + if (__ac_isdel(h->flags, i)) { \ + site = i; \ + } \ + i = (i + (++step)) & mask; \ + if (i == last) { \ + x = site; \ + break; \ + } \ + } \ + if (x == h->n_buckets) { \ + if (__ac_isempty(h->flags, i) && site != h->n_buckets) { \ + x = site; \ + } else { \ + x = i; \ + } \ + } \ + } \ + } \ + if (__ac_isempty(h->flags, x)) { /* not present at all */ \ + h->keys[x] = key; \ + __ac_set_isboth_false(h->flags, x); \ + h->size++; \ + h->n_occupied++; \ + *ret = 1; \ + } else if (__ac_isdel(h->flags, x)) { /* deleted */ \ + h->keys[x] = key; \ + __ac_set_isboth_false(h->flags, x); \ + h->size++; \ + *ret = 2; \ + } else { \ + *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \ + } \ + return x; \ + } \ + SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ + REAL_FATTR_UNUSED; \ + SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ + { \ + if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \ + __ac_set_isdel_true(h->flags, x); \ + --h->size; \ + } \ + } + +#define KHASH_DECLARE(name, khkey_t, khval_t) \ + __KHASH_TYPE(name, khkey_t, khval_t) \ + __KHASH_PROTOTYPES(name, khkey_t, khval_t) + +#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ + __KHASH_TYPE(name, khkey_t, khval_t) \ + __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) + +#define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ + KHASH_INIT2(name, static kh_inline, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) + +// --- BEGIN OF HASH FUNCTIONS --- + +/*! @function + @abstract Integer hash function + @param key The integer [khint32_t] + @return The hash value [khint_t] + */ +#define kh_int_hash_func(key) (khint32_t)(key) +/*! @function + @abstract Integer comparison function + */ +#define kh_int_hash_equal(a, b) ((a) == (b)) +/*! @function + @abstract 64-bit integer hash function + @param key The integer [khint64_t] + @return The hash value [khint_t] + */ +#define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11) +/*! @function + @abstract 64-bit integer comparison function + */ +#define kh_int64_hash_equal(a, b) ((a) == (b)) +/*! @function + @abstract const char* hash function + @param s Pointer to a null terminated string + @return The hash value + */ +static kh_inline khint_t __ac_X31_hash_string(const char *s) +{ + khint_t h = (khint_t)*s; + if (h) { + for (++s; *s; ++s) { h = (h << 5) - h + (uint8_t)*s; } + } + return h; +} +/*! @function + @abstract Another interface to const char* hash function + @param key Pointer to a null terminated string [const char*] + @return The hash value [khint_t] + */ +#define kh_str_hash_func(key) __ac_X31_hash_string(key) +/*! @function + @abstract Const char* comparison function + */ +#define kh_str_hash_equal(a, b) (strcmp(a, b) == 0) + +static kh_inline khint_t __ac_Wang_hash(khint_t key) +{ + key += ~(key << 15); + key ^= (key >> 10); + key += (key << 3); + key ^= (key >> 6); + key += ~(key << 11); + key ^= (key >> 16); + return key; +} +#define kh_int_hash_func2(k) __ac_Wang_hash((khint_t)key) + +// --- END OF HASH FUNCTIONS --- + +// Other convenient macros... + +/*! + @abstract Type of the hash table. + @param name Name of the hash table [symbol] + */ +#define khash_t(name) kh_##name##_t + +/*! @function + @abstract Initiate a hash table. + @param name Name of the hash table [symbol] + @return Pointer to the hash table [khash_t(name)*] + */ +#define kh_init(name) kh_init_##name() + +/*! @function + @abstract Destroy a hash table. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + */ +#define kh_destroy(name, h) kh_destroy_##name(h) + +/*! @function + @abstract Free memory referenced directly inside a hash table. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + */ +#define kh_dealloc(name, h) kh_dealloc_##name(h) + +/*! @function + @abstract Reset a hash table without deallocating memory. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + */ +#define kh_clear(name, h) kh_clear_##name(h) + +/*! @function + @abstract Resize a hash table. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + @param s New size [khint_t] + */ +#define kh_resize(name, h, s) kh_resize_##name(h, s) + +/*! @function + @abstract Insert a key to the hash table. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + @param k Key [type of keys] + @param r Extra return code: -1 if the operation failed; + 0 if the key is present in the hash table; + 1 if the bucket is empty (never used); 2 if the element in + the bucket has been deleted [int*] + @return Iterator to the inserted element [khint_t] + */ +#define kh_put(name, h, k, r) kh_put_##name(h, k, r) + +/*! @function + @abstract Retrieve a key from the hash table. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + @param k Key [type of keys] + @return Iterator to the found element, or kh_end(h) if the element is absent [khint_t] + */ +#define kh_get(name, h, k) kh_get_##name(h, k) + +/*! @function + @abstract Remove a key from the hash table. + @param name Name of the hash table [symbol] + @param h Pointer to the hash table [khash_t(name)*] + @param k Iterator to the element to be deleted [khint_t] + */ +#define kh_del(name, h, k) kh_del_##name(h, k) + +/*! @function + @abstract Test whether a bucket contains data. + @param h Pointer to the hash table [khash_t(name)*] + @param x Iterator to the bucket [khint_t] + @return 1 if containing data; 0 otherwise [int] + */ +#define kh_exist(h, x) (!__ac_iseither((h)->flags, (x))) + +/*! @function + @abstract Get key given an iterator + @param h Pointer to the hash table [khash_t(name)*] + @param x Iterator to the bucket [khint_t] + @return Key [type of keys] + */ +#define kh_key(h, x) ((h)->keys[x]) + +/*! @function + @abstract Get value given an iterator + @param h Pointer to the hash table [khash_t(name)*] + @param x Iterator to the bucket [khint_t] + @return Value [type of values] + @discussion For hash sets, calling this results in segfault. + */ +#define kh_val(h, x) ((h)->vals[x]) + +/*! @function + @abstract Alias of kh_val() + */ +#define kh_value(h, x) ((h)->vals[x]) + +/*! @function + @abstract Get the start iterator + @param h Pointer to the hash table [khash_t(name)*] + @return The start iterator [khint_t] + */ +#define kh_begin(h) (khint_t)(0) + +/*! @function + @abstract Get the end iterator + @param h Pointer to the hash table [khash_t(name)*] + @return The end iterator [khint_t] + */ +#define kh_end(h) ((h)->n_buckets) + +/*! @function + @abstract Get the number of elements in the hash table + @param h Pointer to the hash table [khash_t(name)*] + @return Number of elements in the hash table [khint_t] + */ +#define kh_size(h) ((h)->size) + +/*! @function + @abstract Get the number of buckets in the hash table + @param h Pointer to the hash table [khash_t(name)*] + @return Number of buckets in the hash table [khint_t] + */ +#define kh_n_buckets(h) ((h)->n_buckets) + +/*! @function + @abstract Iterate over the entries in the hash table + @param h Pointer to the hash table [khash_t(name)*] + @param kvar Variable to which key will be assigned + @param vvar Variable to which value will be assigned + @param code Block of code to execute + */ +#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \ + for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ + if (!kh_exist(h, __i)) continue; \ + (kvar) = kh_key(h, __i); \ + (vvar) = kh_val(h, __i); \ + code; \ + } } + +/*! @function + @abstract Iterate over the values in the hash table + @param h Pointer to the hash table [khash_t(name)*] + @param vvar Variable to which value will be assigned + @param code Block of code to execute + */ +#define kh_foreach_value(h, vvar, code) { khint_t __i; \ + for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ + if (!kh_exist(h, __i)) continue; \ + (vvar) = kh_val(h, __i); \ + code; \ + } } + +/*! @function + @abstract Iterate over the keys in the hash table + @param h Pointer to the hash table [khash_t(name)*] + @param kvar Variable to which value will be assigned + @param code Block of code to execute + */ +#define kh_foreach_key(h, kvar, code) \ + { \ + khint_t __i; \ + for (__i = kh_begin(h); __i != kh_end(h); __i++) { \ + if (!kh_exist(h, __i)) { \ + continue; \ + } \ + (kvar) = kh_key(h, __i); \ + code; \ + } \ + } + +// More convenient interfaces + +/*! @function + @abstract Instantiate a hash set containing integer keys + @param name Name of the hash table [symbol] + */ +#define KHASH_SET_INIT_INT(name) \ + KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal) + +/*! @function + @abstract Instantiate a hash map containing integer keys + @param name Name of the hash table [symbol] + @param khval_t Type of values [type] + */ +#define KHASH_MAP_INIT_INT(name, khval_t) \ + KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) + +/*! @function + @abstract Instantiate a hash map containing 64-bit integer keys + @param name Name of the hash table [symbol] + */ +#define KHASH_SET_INIT_INT64(name) \ + KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) + +/*! @function + @abstract Instantiate a hash map containing 64-bit integer keys + @param name Name of the hash table [symbol] + @param khval_t Type of values [type] + */ +#define KHASH_MAP_INIT_INT64(name, khval_t) \ + KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) + +typedef const char *kh_cstr_t; +/*! @function + @abstract Instantiate a hash map containing const char* keys + @param name Name of the hash table [symbol] + */ +#define KHASH_SET_INIT_STR(name) \ + KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal) + +/*! @function + @abstract Instantiate a hash map containing const char* keys + @param name Name of the hash table [symbol] + @param khval_t Type of values [type] + */ +#define KHASH_MAP_INIT_STR(name, khval_t) \ + KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal) + +/*! @function + @abstract Return a literal for an empty hash table. + @param name Name of the hash table [symbol] + */ +#define KHASH_EMPTY_TABLE(name) \ + ((kh_##name##_t) { \ + .n_buckets = 0, \ + .size = 0, \ + .n_occupied = 0, \ + .upper_bound = 0, \ + .flags = NULL, \ + .keys = NULL, \ + .vals = NULL, \ + }) +#endif // NVIM_LIB_KHASH_H diff --git a/src/klib/klist.h b/src/klib/klist.h new file mode 100644 index 0000000000..a9abbc6dc2 --- /dev/null +++ b/src/klib/klist.h @@ -0,0 +1,144 @@ +/* The MIT License + + Copyright (c) 2008-2009, by Attractive Chaos + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + */ + +#ifndef _AC_KLIST_H +#define _AC_KLIST_H + +#include +#include + +#include "nvim/func_attr.h" +#include "nvim/memory.h" + +#define KMEMPOOL_INIT(name, kmptype_t, kmpfree_f) \ + typedef struct { \ + size_t cnt, n, max; \ + kmptype_t **buf; \ + } kmp_##name##_t; \ + static inline kmp_##name##_t *kmp_init_##name(void) { \ + return xcalloc(1, sizeof(kmp_##name##_t)); \ + } \ + static inline void kmp_destroy_##name(kmp_##name##_t *mp) \ + REAL_FATTR_UNUSED; \ + static inline void kmp_destroy_##name(kmp_##name##_t *mp) { \ + size_t k; \ + for (k = 0; k < mp->n; k++) { \ + kmpfree_f(mp->buf[k]); XFREE_CLEAR(mp->buf[k]); \ + } \ + XFREE_CLEAR(mp->buf); XFREE_CLEAR(mp); \ + } \ + static inline kmptype_t *kmp_alloc_##name(kmp_##name##_t *mp) { \ + mp->cnt++; \ + if (mp->n == 0) { \ + return xcalloc(1, sizeof(kmptype_t)); \ + } \ + return mp->buf[--mp->n]; \ + } \ + static inline void kmp_free_##name(kmp_##name##_t *mp, kmptype_t *p) { \ + mp->cnt--; \ + if (mp->n == mp->max) { \ + mp->max = mp->max ? (mp->max << 1) : 16; \ + mp->buf = xrealloc(mp->buf, sizeof(kmptype_t *) * mp->max); \ + } \ + mp->buf[mp->n++] = p; \ + } + +#define kmempool_t(name) kmp_##name##_t +#define kmp_init(name) kmp_init_##name() +#define kmp_destroy(name, mp) kmp_destroy_##name(mp) +#define kmp_alloc(name, mp) kmp_alloc_##name(mp) +#define kmp_free(name, mp, p) kmp_free_##name(mp, p) + +#define KLIST_INIT(name, kltype_t, kmpfree_t) \ + struct __kl1_##name { \ + kltype_t data; \ + struct __kl1_##name *next; \ + }; \ + typedef struct __kl1_##name kl1_##name; \ + KMEMPOOL_INIT(name, kl1_##name, kmpfree_t) \ + typedef struct { \ + kl1_##name *head, *tail; \ + kmp_##name##_t *mp; \ + size_t size; \ + } kl_##name##_t; \ + static inline kl_##name##_t *kl_init_##name(void) { \ + kl_##name##_t *kl = xcalloc(1, sizeof(kl_##name##_t)); \ + kl->mp = kmp_init(name); \ + kl->head = kl->tail = kmp_alloc(name, kl->mp); \ + kl->head->next = 0; \ + return kl; \ + } \ + static inline void kl_destroy_##name(kl_##name##_t *kl) \ + REAL_FATTR_UNUSED; \ + static inline void kl_destroy_##name(kl_##name##_t *kl) { \ + kl1_##name *p; \ + for (p = kl->head; p != kl->tail; p = p->next) { \ + kmp_free(name, kl->mp, p); \ + } \ + kmp_free(name, kl->mp, p); \ + kmp_destroy(name, kl->mp); \ + XFREE_CLEAR(kl); \ + } \ + static inline void kl_push_##name(kl_##name##_t *kl, kltype_t d) { \ + kl1_##name *q, *p = kmp_alloc(name, kl->mp); \ + q = kl->tail; p->next = 0; kl->tail->next = p; kl->tail = p; \ + kl->size++; \ + q->data = d; \ + } \ + static inline kltype_t kl_shift_at_##name(kl_##name##_t *kl, \ + kl1_##name **n) { \ + assert((*n)->next); \ + kl1_##name *p; \ + kl->size--; \ + p = *n; \ + *n = (*n)->next; \ + if (p == kl->head) { \ + kl->head = *n; \ + } \ + kltype_t d = p->data; \ + kmp_free(name, kl->mp, p); \ + return d; \ + } + +#define kliter_t(name) kl1_##name +#define klist_t(name) kl_##name##_t +#define kl_val(iter) ((iter)->data) +#define kl_next(iter) ((iter)->next) +#define kl_begin(kl) ((kl)->head) +#define kl_end(kl) ((kl)->tail) + +#define kl_init(name) kl_init_##name() +#define kl_destroy(name, kl) kl_destroy_##name(kl) +#define kl_push(name, kl, d) kl_push_##name(kl, d) +#define kl_shift_at(name, kl, node) kl_shift_at_##name(kl, node) +#define kl_shift(name, kl) kl_shift_at(name, kl, &kl->head) +#define kl_empty(kl) ((kl)->size == 0) +// Iteration macros. It's ok to modify the list while iterating as long as a +// `break` statement is executed before the next iteration. +#define kl_iter(name, kl, p) kl_iter_at(name, kl, p, NULL) +#define kl_iter_at(name, kl, p, h) \ + for (kl1_##name **p = h ? h : &kl->head; *p != kl->tail; p = &(*p)->next) + +#endif diff --git a/src/klib/kvec.h b/src/klib/kvec.h new file mode 100644 index 0000000000..b5b3adf7d2 --- /dev/null +++ b/src/klib/kvec.h @@ -0,0 +1,236 @@ +// The MIT License +// +// Copyright (c) 2008, by Attractive Chaos +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +// An example: +// +// #include "kvec.h" +// int main() { +// kvec_t(int) array = KV_INITIAL_VALUE; +// kv_push(array, 10); // append +// kv_a(array, 20) = 5; // dynamic +// kv_A(array, 20) = 4; // static +// kv_destroy(array); +// return 0; +// } + +#ifndef NVIM_LIB_KVEC_H +#define NVIM_LIB_KVEC_H + +#include +#include + +#include "nvim/memory.h" +#include "nvim/os/os_defs.h" + +#define kv_roundup32(x) \ + ((--(x)), \ + ((x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16), \ + (++(x))) + +#define KV_INITIAL_VALUE { .size = 0, .capacity = 0, .items = NULL } + +#define kvec_t(type) \ + struct { \ + size_t size; \ + size_t capacity; \ + type *items; \ + } + +#define kv_init(v) ((v).size = (v).capacity = 0, (v).items = 0) +#define kv_destroy(v) \ + do { \ + xfree((v).items); \ + kv_init(v); \ + } while (0) +#define kv_A(v, i) ((v).items[(i)]) +#define kv_pop(v) ((v).items[--(v).size]) +#define kv_size(v) ((v).size) +#define kv_max(v) ((v).capacity) +#define kv_Z(v, i) kv_A(v, kv_size(v) - (i) - 1) +#define kv_last(v) kv_Z(v, 0) + +/// Drop last n items from kvec without resizing +/// +/// Previously spelled as `(void)kv_pop(v)`, repeated n times. +/// +/// @param[out] v Kvec to drop items from. +/// @param[in] n Number of elements to drop. +#define kv_drop(v, n) ((v).size -= (n)) + +#define kv_resize(v, s) \ + ((v).capacity = (s), \ + (v).items = xrealloc((v).items, sizeof((v).items[0]) * (v).capacity)) + +#define kv_resize_full(v) \ + kv_resize(v, (v).capacity ? (v).capacity << 1 : 8) + +#define kv_copy(v1, v0) \ + do { \ + if ((v1).capacity < (v0).size) { \ + kv_resize(v1, (v0).size); \ + } \ + (v1).size = (v0).size; \ + memcpy((v1).items, (v0).items, sizeof((v1).items[0]) * (v0).size); \ + } while (0) + +/// fit at least "len" more items +#define kv_ensure_space(v, len) \ + do { \ + if ((v).capacity < (v).size + len) { \ + (v).capacity = (v).size + len; \ + kv_roundup32((v).capacity); \ + kv_resize((v), (v).capacity); \ + } \ + } while (0) + +#define kv_concat_len(v, data, len) \ + do { \ + kv_ensure_space(v, len); \ + memcpy((v).items + (v).size, data, sizeof((v).items[0]) * len); \ + (v).size = (v).size + len; \ + } while (0) + +#define kv_concat(v, str) kv_concat_len(v, str, STRLEN(str)) +#define kv_splice(v1, v0) kv_concat_len(v1, (v0).items, (v0).size) + +#define kv_pushp(v) \ + ((((v).size == (v).capacity) ? (kv_resize_full(v), 0) : 0), \ + ((v).items + ((v).size++))) + +#define kv_push(v, x) \ + (*kv_pushp(v) = (x)) + +#define kv_pushp_c(v) ((v).items + ((v).size++)) +#define kv_push_c(v, x) (*kv_pushp_c(v) = (x)) + +#define kv_a(v, i) \ + (*(((v).capacity <= (size_t)(i) \ + ? ((v).capacity = (v).size = (i) + 1, \ + kv_roundup32((v).capacity), \ + kv_resize((v), (v).capacity), 0UL) \ + : ((v).size <= (size_t)(i) \ + ? (v).size = (i) + 1 \ + : 0UL)), \ + &(v).items[(i)])) + +#define kv_printf(v, ...) kv_do_printf(&(v), __VA_ARGS__) + +/// Type of a vector with a few first members allocated on stack +/// +/// Is compatible with #kv_A, #kv_pop, #kv_size, #kv_max, #kv_last. +/// Is not compatible with #kv_resize, #kv_resize_full, #kv_copy, #kv_push, +/// #kv_pushp, #kv_a, #kv_destroy. +/// +/// @param[in] type Type of vector elements. +/// @param[in] init_size Number of the elements in the initial array. +#define kvec_withinit_t(type, INIT_SIZE) \ + struct { \ + size_t size; \ + size_t capacity; \ + type *items; \ + type init_array[INIT_SIZE]; \ + } + +/// Initialize vector with preallocated array +/// +/// @param[out] v Vector to initialize. +#define kvi_init(v) \ + ((v).capacity = ARRAY_SIZE((v).init_array), \ + (v).size = 0, \ + (v).items = (v).init_array) + +/// Move data to a new destination and free source +static inline void *_memcpy_free(void *const restrict dest, void *const restrict src, + const size_t size) + FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_ALWAYS_INLINE +{ + memcpy(dest, src, size); + XFREE_CLEAR(src); + return dest; +} + +// -V:kvi_push:512 + +/// Resize vector with preallocated array +/// +/// @note May not resize to an array smaller then init_array: if requested, +/// init_array will be used. +/// +/// @param[out] v Vector to resize. +/// @param[in] s New size. +#define kvi_resize(v, s) \ + ((v).capacity = ((s) > ARRAY_SIZE((v).init_array) \ + ? (s) \ + : ARRAY_SIZE((v).init_array)), \ + (v).items = ((v).capacity == ARRAY_SIZE((v).init_array) \ + ? ((v).items == (v).init_array \ + ? (v).items \ + : _memcpy_free((v).init_array, (v).items, \ + (v).size * sizeof((v).items[0]))) \ + : ((v).items == (v).init_array \ + ? memcpy(xmalloc((v).capacity * sizeof((v).items[0])), \ + (v).items, \ + (v).size * sizeof((v).items[0])) \ + : xrealloc((v).items, \ + (v).capacity * sizeof((v).items[0]))))) + +/// Resize vector with preallocated array when it is full +/// +/// @param[out] v Vector to resize. +#define kvi_resize_full(v) \ + /* ARRAY_SIZE((v).init_array) is the minimal capacity of this vector. */ \ + /* Thus when vector is full capacity may not be zero and it is safe */ \ + /* not to bother with checking whether (v).capacity is 0. But now */ \ + /* capacity is not guaranteed to have size that is a power of 2, it is */ \ + /* hard to fix this here and is not very necessary if users will use */ \ + /* 2^x initial array size. */ \ + kvi_resize(v, (v).capacity << 1) + +/// Get location where to store new element to a vector with preallocated array +/// +/// @param[in,out] v Vector to push to. +/// +/// @return Pointer to the place where new value should be stored. +#define kvi_pushp(v) \ + ((((v).size == (v).capacity) ? (kvi_resize_full(v), 0) : 0), \ + ((v).items + ((v).size++))) + +/// Push value to a vector with preallocated array +/// +/// @param[out] v Vector to push to. +/// @param[in] x Value to push. +#define kvi_push(v, x) \ + (*kvi_pushp(v) = (x)) + +/// Free array of elements of a vector with preallocated array if needed +/// +/// @param[out] v Vector to free. +#define kvi_destroy(v) \ + do { \ + if ((v).items != (v).init_array) { \ + XFREE_CLEAR((v).items); \ + } \ + } while (0) + +#endif // NVIM_LIB_KVEC_H diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt index a1b57f927e..f28b7a7e28 100755 --- a/src/nvim/CMakeLists.txt +++ b/src/nvim/CMakeLists.txt @@ -96,8 +96,8 @@ file(MAKE_DIRECTORY ${LINT_SUPPRESSES_ROOT}/src) glob_wrapper(NVIM_SOURCES *.c) glob_wrapper(NVIM_HEADERS *.h) -glob_wrapper(EXTERNAL_SOURCES ../xdiff/*.c ../mpack/*.c ../cjson/*.c) -glob_wrapper(EXTERNAL_HEADERS ../xdiff/*.h ../mpack/*.h ../cjson/*.h) +glob_wrapper(EXTERNAL_SOURCES ../xdiff/*.c ../mpack/*.c ../cjson/*.c ../klib/*.c) +glob_wrapper(EXTERNAL_HEADERS ../xdiff/*.h ../mpack/*.h ../cjson/*.h ../klib/*.h) foreach(subdir os diff --git a/src/nvim/api/private/defs.h b/src/nvim/api/private/defs.h index 9c7e59e4b3..2ae3ee6c7c 100644 --- a/src/nvim/api/private/defs.h +++ b/src/nvim/api/private/defs.h @@ -5,8 +5,8 @@ #include #include +#include "klib/kvec.h" #include "nvim/func_attr.h" -#include "nvim/lib/kvec.h" #include "nvim/types.h" #define ARRAY_DICT_INIT KV_INITIAL_VALUE diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c index 22d2ffbaf1..b888d09343 100644 --- a/src/nvim/api/private/helpers.c +++ b/src/nvim/api/private/helpers.c @@ -8,6 +8,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/private/converter.h" #include "nvim/api/private/defs.h" #include "nvim/api/private/helpers.h" @@ -22,7 +23,6 @@ #include "nvim/ex_eval.h" #include "nvim/extmark.h" #include "nvim/highlight_group.h" -#include "nvim/lib/kvec.h" #include "nvim/lua/executor.h" #include "nvim/map.h" #include "nvim/map_defs.h" diff --git a/src/nvim/api/private/helpers.h b/src/nvim/api/private/helpers.h index 2157ad0ec2..65215fa8c8 100644 --- a/src/nvim/api/private/helpers.h +++ b/src/nvim/api/private/helpers.h @@ -1,11 +1,11 @@ #ifndef NVIM_API_PRIVATE_HELPERS_H #define NVIM_API_PRIVATE_HELPERS_H +#include "klib/kvec.h" #include "nvim/api/private/defs.h" #include "nvim/decoration.h" #include "nvim/ex_eval_defs.h" #include "nvim/getchar.h" -#include "nvim/lib/kvec.h" #include "nvim/memory.h" #include "nvim/vim.h" diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index 3019a1323c..c18a8209cf 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -41,7 +41,7 @@ typedef struct { // for Map(K, V) #include "nvim/map.h" // for kvec -#include "nvim/lib/kvec.h" +#include "klib/kvec.h" // for marktree #include "nvim/marktree.h" diff --git a/src/nvim/context.h b/src/nvim/context.h index c2deca12c9..ae77e66516 100644 --- a/src/nvim/context.h +++ b/src/nvim/context.h @@ -3,8 +3,8 @@ #include +#include "klib/kvec.h" #include "nvim/api/private/defs.h" -#include "nvim/lib/kvec.h" typedef struct { msgpack_sbuffer regs; ///< Registers. diff --git a/src/nvim/decoration_provider.c b/src/nvim/decoration_provider.c index a11a4d2b04..48664421a3 100644 --- a/src/nvim/decoration_provider.c +++ b/src/nvim/decoration_provider.c @@ -1,13 +1,13 @@ // This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +#include "klib/kvec.h" #include "nvim/api/extmark.h" #include "nvim/api/private/helpers.h" #include "nvim/buffer.h" #include "nvim/decoration.h" #include "nvim/decoration_provider.h" #include "nvim/highlight.h" -#include "nvim/lib/kvec.h" #include "nvim/lua/executor.h" static kvec_t(DecorProvider) decor_providers = KV_INITIAL_VALUE; diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c index d585509df4..94ef419bed 100644 --- a/src/nvim/eval/decode.c +++ b/src/nvim/eval/decode.c @@ -4,6 +4,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/charset.h" // vim_str2nr #include "nvim/eval.h" @@ -11,7 +12,6 @@ #include "nvim/eval/encode.h" #include "nvim/eval/typval.h" #include "nvim/globals.h" -#include "nvim/lib/kvec.h" #include "nvim/macros.h" #include "nvim/message.h" #include "nvim/vim.h" // OK, FAIL diff --git a/src/nvim/eval/encode.c b/src/nvim/eval/encode.c index 599bbae0f5..27d35ea24f 100644 --- a/src/nvim/eval/encode.c +++ b/src/nvim/eval/encode.c @@ -13,6 +13,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/buffer_defs.h" #include "nvim/charset.h" // vim_isprintc() @@ -21,7 +22,6 @@ #include "nvim/eval/typval.h" #include "nvim/eval/typval_encode.h" #include "nvim/garray.h" -#include "nvim/lib/kvec.h" #include "nvim/macros.h" #include "nvim/math.h" #include "nvim/mbyte.h" diff --git a/src/nvim/eval/typval_encode.c.h b/src/nvim/eval/typval_encode.c.h index 73b36b8611..ff4f92e40b 100644 --- a/src/nvim/eval/typval_encode.c.h +++ b/src/nvim/eval/typval_encode.c.h @@ -250,7 +250,7 @@ #include "nvim/eval/typval.h" #include "nvim/eval/typval_encode.h" #include "nvim/func_attr.h" -#include "nvim/lib/kvec.h" +#include "klib/kvec.h" // -V::1063 diff --git a/src/nvim/eval/typval_encode.h b/src/nvim/eval/typval_encode.h index ed70ba87ec..33e19c531c 100644 --- a/src/nvim/eval/typval_encode.h +++ b/src/nvim/eval/typval_encode.h @@ -10,9 +10,9 @@ #include #include +#include "klib/kvec.h" #include "nvim/eval/typval.h" #include "nvim/func_attr.h" -#include "nvim/lib/kvec.h" /// Type of the stack entry typedef enum { diff --git a/src/nvim/event/loop.h b/src/nvim/event/loop.h index 65980c6c05..c0bcda40ce 100644 --- a/src/nvim/event/loop.h +++ b/src/nvim/event/loop.h @@ -4,8 +4,8 @@ #include #include +#include "klib/klist.h" #include "nvim/event/multiqueue.h" -#include "nvim/lib/klist.h" #include "nvim/os/time.h" typedef void *WatcherPtr; diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 2a91e9c672..2d39ced582 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -9,6 +9,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/extmark.h" #include "nvim/api/vim.h" #include "nvim/arabic.h" @@ -40,7 +41,6 @@ #include "nvim/highlight_group.h" #include "nvim/indent.h" #include "nvim/keycodes.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/main.h" #include "nvim/mapping.h" diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index 290d20b749..176ad0d5c8 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -30,6 +30,7 @@ #include +#include "klib/kbtree.h" #include "nvim/api/extmark.h" #include "nvim/buffer.h" #include "nvim/buffer_updates.h" @@ -37,7 +38,6 @@ #include "nvim/decoration.h" #include "nvim/extmark.h" #include "nvim/globals.h" -#include "nvim/lib/kbtree.h" #include "nvim/map.h" #include "nvim/memline.h" #include "nvim/pos.h" diff --git a/src/nvim/extmark_defs.h b/src/nvim/extmark_defs.h index 5570b5c71e..9ef4ec23e5 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/lib/kvec.h" +#include "klib/kvec.h" #include "nvim/types.h" typedef struct { diff --git a/src/nvim/lib/kbtree.h b/src/nvim/lib/kbtree.h deleted file mode 100644 index 99f79952d7..0000000000 --- a/src/nvim/lib/kbtree.h +++ /dev/null @@ -1,477 +0,0 @@ -/*- - * Copyright 1997-1999, 2001, John-Mark Gurney. - * 2008-2009, Attractive Chaos - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -// Gotchas -// ------- -// -// if you delete from a kbtree while iterating over it you must use -// kb_del_itr and not kb_del otherwise the iterator might point to freed memory. - -#ifndef NVIM_LIB_KBTREE_H -#define NVIM_LIB_KBTREE_H - -#include -#include -#include -#include - -#include "nvim/memory.h" - -#define KB_MAX_DEPTH 64 - -#define __KB_KEY(type, x) (x->key) -#define __KB_PTR(btr, x) (x->ptr) - -#define __KB_TREE_T(name, key_t, T) \ - typedef struct kbnode_##name##_s kbnode_##name##_t; \ - struct kbnode_##name##_s { \ - int32_t n; \ - bool is_internal; \ - key_t key[2*T - 1]; \ - kbnode_##name##_t *ptr[]; \ - }; \ - typedef struct { \ - kbnode_##name##_t *root; \ - int n_keys, n_nodes; \ - } kbtree_##name##_t; \ - typedef struct { \ - kbnode_##name##_t *x; \ - int i; \ - } kbpos_##name##_t; \ - typedef struct { \ - kbpos_##name##_t stack[KB_MAX_DEPTH], *p; \ - } kbitr_##name##_t; \ - - -#define __kb_destroy(kbnode_t, b) do { \ - int i; \ - unsigned int max = 8; \ - kbnode_t *x, **top, **stack = 0; \ - if (b->root) { \ - top = stack = (kbnode_t **)xcalloc(max, sizeof(kbnode_t *)); \ - *top++ = (b)->root; \ - while (top != stack) { \ - x = *--top; \ - if (x->is_internal == 0) { XFREE_CLEAR(x); continue; } \ - for (i = 0; i <= x->n; ++i) \ - if (__KB_PTR(b, x)[i]) { \ - if (top - stack == (int)max) { \ - max <<= 1; \ - stack = (kbnode_t **)xrealloc(stack, max * sizeof(kbnode_t *)); \ - top = stack + (max>>1); \ - } \ - *top++ = __KB_PTR(b, x)[i]; \ - } \ - XFREE_CLEAR(x); \ - } \ - } \ - XFREE_CLEAR(stack); \ -} while (0) - -#define __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ - static inline int __kb_getp_aux_##name(const kbnode_t * __restrict x, key_t * __restrict k, \ - int *r) \ - { \ - int tr, *rr, begin = 0, end = x->n; \ - if (x->n == 0) return -1; \ - rr = r? r : &tr; \ - while (begin < end) { \ - int mid = (begin + end) >> 1; \ - if (__cmp(__KB_KEY(key_t, x)[mid], *k) < 0) begin = mid + 1; \ - else end = mid; \ - } \ - if (begin == x->n) { *rr = 1; return x->n - 1; } \ - if ((*rr = __cmp(*k, __KB_KEY(key_t, x)[begin])) < 0) --begin; \ - return begin; \ - } - -#define __KB_GET(name, key_t, kbnode_t) \ - static key_t *kb_getp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ - { \ - if (!b->root) { \ - return 0; \ - } \ - int i, r = 0; \ - kbnode_t *x = b->root; \ - while (x) { \ - i = __kb_getp_aux_##name(x, k, &r); \ - if (i >= 0 && r == 0) return &__KB_KEY(key_t, x)[i]; \ - if (x->is_internal == 0) return 0; \ - x = __KB_PTR(b, x)[i + 1]; \ - } \ - return 0; \ - } \ - static inline key_t *kb_get_##name(kbtree_##name##_t *b, key_t k) \ - { \ - return kb_getp_##name(b, &k); \ - } - -#define __KB_INTERVAL(name, key_t, kbnode_t) \ - static inline void kb_intervalp_##name(kbtree_##name##_t *b, key_t * __restrict k, key_t **lower, \ - key_t **upper) \ - { \ - if (!b->root) { \ - return; \ - } \ - int i, r = 0; \ - kbnode_t *x = b->root; \ - *lower = *upper = 0; \ - while (x) { \ - i = __kb_getp_aux_##name(x, k, &r); \ - if (i >= 0 && r == 0) { \ - *lower = *upper = &__KB_KEY(key_t, x)[i]; \ - return; \ - } \ - if (i >= 0) *lower = &__KB_KEY(key_t, x)[i]; \ - if (i < x->n - 1) *upper = &__KB_KEY(key_t, x)[i + 1]; \ - if (x->is_internal == 0) return; \ - x = __KB_PTR(b, x)[i + 1]; \ - } \ - } \ - static inline void kb_interval_##name(kbtree_##name##_t *b, key_t k, key_t **lower, key_t **upper) \ - { \ - kb_intervalp_##name(b, &k, lower, upper); \ - } - -#define __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ - /* x must be an internal node */ \ - static inline void __kb_split_##name(kbtree_##name##_t *b, kbnode_t *x, int i, kbnode_t *y) \ - { \ - kbnode_t *z; \ - z = (kbnode_t *)xcalloc(1, y->is_internal? ILEN : sizeof(kbnode_##name##_t)); \ - ++b->n_nodes; \ - z->is_internal = y->is_internal; \ - z->n = T - 1; \ - memcpy(__KB_KEY(key_t, z), &__KB_KEY(key_t, y)[T], sizeof(key_t) * (T - 1)); \ - if (y->is_internal) memcpy(__KB_PTR(b, z), &__KB_PTR(b, y)[T], sizeof(void *) * T); \ - y->n = T - 1; \ - memmove(&__KB_PTR(b, x)[i + 2], &__KB_PTR(b, \ - x)[i + 1], sizeof(void *) * (unsigned int)(x->n - i)); \ - __KB_PTR(b, x)[i + 1] = z; \ - memmove(&__KB_KEY(key_t, x)[i + 1], &__KB_KEY(key_t, x)[i], \ - sizeof(key_t) * (unsigned int)(x->n - i)); \ - __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[T - 1]; \ - ++x->n; \ - } \ - static inline key_t *__kb_putp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k) \ - { \ - int i = x->n - 1; \ - key_t *ret; \ - if (x->is_internal == 0) { \ - i = __kb_getp_aux_##name(x, k, 0); \ - if (i != x->n - 1) \ - memmove(&__KB_KEY(key_t, x)[i + 2], &__KB_KEY(key_t, \ - x)[i + 1], \ - (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ - ret = &__KB_KEY(key_t, x)[i + 1]; \ - *ret = *k; \ - ++x->n; \ - } else { \ - i = __kb_getp_aux_##name(x, k, 0) + 1; \ - if (__KB_PTR(b, x)[i]->n == 2 * T - 1) { \ - __kb_split_##name(b, x, i, __KB_PTR(b, x)[i]); \ - if (__cmp(*k, __KB_KEY(key_t, x)[i]) > 0) ++i; \ - } \ - ret = __kb_putp_aux_##name(b, __KB_PTR(b, x)[i], k); \ - } \ - return ret; \ - } \ - static inline key_t *kb_putp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ - { \ - if (!b->root) { \ - b->root = (kbnode_t *)xcalloc(1, ILEN); \ - ++b->n_nodes; \ - } \ - kbnode_t *r, *s; \ - ++b->n_keys; \ - r = b->root; \ - if (r->n == 2 * T - 1) { \ - ++b->n_nodes; \ - s = (kbnode_t *)xcalloc(1, ILEN); \ - b->root = s; s->is_internal = 1; s->n = 0; \ - __KB_PTR(b, s)[0] = r; \ - __kb_split_##name(b, s, 0, r); \ - r = s; \ - } \ - return __kb_putp_aux_##name(b, r, k); \ - } \ - static inline void kb_put_##name(kbtree_##name##_t *b, key_t k) \ - { \ - kb_putp_##name(b, &k); \ - } - -#define __KB_DEL(name, key_t, kbnode_t, T) \ - static inline key_t __kb_delp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k, \ - int s) \ - { \ - int yn, zn, i, r = 0; \ - kbnode_t *xp, *y, *z; \ - key_t kp; \ - if (x == 0) return *k; \ - if (s) { /* s can only be 0, 1 or 2 */ \ - r = x->is_internal == 0? 0 : s == 1? 1 : -1; \ - i = s == 1? x->n - 1 : -1; \ - } else i = __kb_getp_aux_##name(x, k, &r); \ - if (x->is_internal == 0) { \ - if (s == 2) ++i; \ - kp = __KB_KEY(key_t, x)[i]; \ - memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ - x)[i + 1], \ - (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ - --x->n; \ - return kp; \ - } \ - if (r == 0) { \ - if ((yn = __KB_PTR(b, x)[i]->n) >= T) { \ - xp = __KB_PTR(b, x)[i]; \ - kp = __KB_KEY(key_t, x)[i]; \ - __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 1); \ - return kp; \ - } else if ((zn = __KB_PTR(b, x)[i + 1]->n) >= T) { \ - xp = __KB_PTR(b, x)[i + 1]; \ - kp = __KB_KEY(key_t, x)[i]; \ - __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 2); \ - return kp; \ - } else if (yn == T - 1 && zn == T - 1) { \ - y = __KB_PTR(b, x)[i]; z = __KB_PTR(b, x)[i + 1]; \ - __KB_KEY(key_t, y)[y->n++] = *k; \ - memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, z), (unsigned int)z->n * sizeof(key_t)); \ - if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, \ - z), \ - (unsigned int)(z->n + 1) * sizeof(void *)); \ - y->n += z->n; \ - memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ - x)[i + 1], \ - (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ - memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, \ - x)[i + 2], \ - (unsigned int)(x->n - i - 1) * sizeof(void *)); \ - --x->n; \ - XFREE_CLEAR(z); \ - return __kb_delp_aux_##name(b, y, k, s); \ - } \ - } \ - ++i; \ - if ((xp = __KB_PTR(b, x)[i])->n == T - 1) { \ - if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n >= T) { \ - memmove(&__KB_KEY(key_t, xp)[1], __KB_KEY(key_t, xp), (unsigned int)xp->n * sizeof(key_t)); \ - if (xp->is_internal) memmove(&__KB_PTR(b, xp)[1], __KB_PTR(b, \ - xp), \ - (unsigned int)(xp->n + 1) * sizeof(void *)); \ - __KB_KEY(key_t, xp)[0] = __KB_KEY(key_t, x)[i - 1]; \ - __KB_KEY(key_t, x)[i - 1] = __KB_KEY(key_t, y)[y->n - 1]; \ - if (xp->is_internal) __KB_PTR(b, xp)[0] = __KB_PTR(b, y)[y->n]; \ - --y->n; ++xp->n; \ - } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n >= T) { \ - __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ - __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[0]; \ - if (xp->is_internal) __KB_PTR(b, xp)[xp->n] = __KB_PTR(b, y)[0]; \ - --y->n; \ - memmove(__KB_KEY(key_t, y), &__KB_KEY(key_t, y)[1], (unsigned int)y->n * sizeof(key_t)); \ - if (y->is_internal) memmove(__KB_PTR(b, y), &__KB_PTR(b, \ - y)[1], \ - (unsigned int)(y->n + 1) * sizeof(void *)); \ - } else if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n == T - 1) { \ - __KB_KEY(key_t, y)[y->n++] = __KB_KEY(key_t, x)[i - 1]; \ - memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, xp), \ - (unsigned int)xp->n * sizeof(key_t)); \ - if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, \ - xp), \ - (unsigned int)(xp->n + 1) * sizeof(void *)); \ - y->n += xp->n; \ - memmove(&__KB_KEY(key_t, x)[i - 1], &__KB_KEY(key_t, \ - x)[i], \ - (unsigned int)(x->n - i) * sizeof(key_t)); \ - memmove(&__KB_PTR(b, x)[i], &__KB_PTR(b, \ - x)[i + 1], (unsigned int)(x->n - i) * sizeof(void *)); \ - --x->n; \ - XFREE_CLEAR(xp); \ - xp = y; \ - } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n == T - 1) { \ - __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \ - memmove(&__KB_KEY(key_t, xp)[xp->n], __KB_KEY(key_t, y), \ - (unsigned int)y->n * sizeof(key_t)); \ - if (xp->is_internal) memmove(&__KB_PTR(b, xp)[xp->n], __KB_PTR(b, y), \ - (unsigned int)(y->n + 1) * sizeof(void *)); \ - xp->n += y->n; \ - memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, \ - x)[i + 1], \ - (unsigned int)(x->n - i - 1) * sizeof(key_t)); \ - memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, \ - x)[i + 2], \ - (unsigned int)(x->n - i - 1) * sizeof(void *)); \ - --x->n; \ - XFREE_CLEAR(y); \ - } \ - } \ - return __kb_delp_aux_##name(b, xp, k, s); \ - } \ - static inline key_t kb_delp_##name(kbtree_##name##_t *b, key_t * __restrict k) \ - { \ - kbnode_t *x; \ - key_t ret; \ - ret = __kb_delp_aux_##name(b, b->root, k, 0); \ - --b->n_keys; \ - if (b->root->n == 0 && b->root->is_internal) { \ - --b->n_nodes; \ - x = b->root; \ - b->root = __KB_PTR(b, x)[0]; \ - XFREE_CLEAR(x); \ - } \ - return ret; \ - } \ - static inline key_t kb_del_##name(kbtree_##name##_t *b, key_t k) \ - { \ - return kb_delp_##name(b, &k); \ - } - -#define __KB_ITR(name, key_t, kbnode_t) \ - static inline void kb_itr_first_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ - { \ - itr->p = NULL; \ - if (b->n_keys == 0) return; \ - itr->p = itr->stack; \ - itr->p->x = b->root; itr->p->i = 0; \ - while (itr->p->x->is_internal && __KB_PTR(b, itr->p->x)[0] != 0) { \ - kbnode_t *x = itr->p->x; \ - ++itr->p; \ - itr->p->x = __KB_PTR(b, x)[0]; itr->p->i = 0; \ - } \ - } \ - static inline int kb_itr_next_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ - { \ - if (itr->p == NULL) return 0; \ - for (;;) { \ - ++itr->p->i; \ - assert(itr->p->i <= 21); \ - while (itr->p->x && itr->p->i <= itr->p->x->n) { \ - itr->p[1].i = 0; \ - itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[itr->p->i] : 0; \ - ++itr->p; \ - } \ - if (itr->p == itr->stack) { \ - itr->p = NULL; \ - return 0; \ - } \ - --itr->p; \ - if (itr->p->x && itr->p->i < itr->p->x->n) return 1; \ - } \ - } \ - static inline int kb_itr_prev_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ - { \ - if (itr->p == NULL) return 0; \ - for (;;) { \ - while (itr->p->x && itr->p->i >= 0) { \ - itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[itr->p->i] : 0; \ - itr->p[1].i = itr->p[1].x ? itr->p[1].x->n : -1; \ - ++itr->p; \ - } \ - if (itr->p == itr->stack) { \ - itr->p = NULL; \ - return 0; \ - } \ - --itr->p; \ - --itr->p->i; \ - if (itr->p->x && itr->p->i >= 0) return 1; \ - } \ - } \ - static inline int kb_itr_getp_##name(kbtree_##name##_t *b, key_t * __restrict k, \ - kbitr_##name##_t *itr) \ - { \ - if (b->n_keys == 0) { \ - itr->p = NULL; \ - return 0; \ - } \ - int i, r = 0; \ - itr->p = itr->stack; \ - itr->p->x = b->root; \ - while (itr->p->x) { \ - i = __kb_getp_aux_##name(itr->p->x, k, &r); \ - itr->p->i = i; \ - if (i >= 0 && r == 0) return 1; \ - ++itr->p->i; \ - assert(itr->p->i <= 21); \ - itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[i + 1] : 0; \ - ++itr->p; \ - } \ - itr->p->i = 0; \ - return 0; \ - } \ - static inline int kb_itr_get_##name(kbtree_##name##_t *b, key_t k, kbitr_##name##_t *itr) \ - { \ - return kb_itr_getp_##name(b, &k, itr); \ - } \ - static inline void kb_del_itr_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \ - { \ - key_t k = kb_itr_key(itr); \ - kb_delp_##name(b, &k); \ - kb_itr_getp_##name(b, &k, itr); \ - } - -#define KBTREE_INIT(name, key_t, __cmp, T) \ - KBTREE_INIT_IMPL(name, key_t, kbnode_##name##_t, __cmp, T, \ - (sizeof(kbnode_##name##_t) + (2*T)*sizeof(void *))) - -#define KBTREE_INIT_IMPL(name, key_t, kbnode_t, __cmp, T, ILEN) \ - __KB_TREE_T(name, key_t, T) \ - __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \ - __KB_GET(name, key_t, kbnode_t) \ - __KB_INTERVAL(name, key_t, kbnode_t) \ - __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \ - __KB_DEL(name, key_t, kbnode_t, T) \ - __KB_ITR(name, key_t, kbnode_t) - -#define KB_DEFAULT_SIZE 512 - -#define kbtree_t(name) kbtree_##name##_t -#define kbitr_t(name) kbitr_##name##_t -#define kb_init(b) ((b)->n_keys = (b)->n_nodes = 0, (b)->root = 0) -#define kb_destroy(name, b) __kb_destroy(kbnode_##name##_t, b) -#define kb_get(name, b, k) kb_get_##name(b, k) -#define kb_put(name, b, k) kb_put_##name(b, k) -#define kb_del(name, b, k) kb_del_##name(b, k) -#define kb_interval(name, b, k, l, u) kb_interval_##name(b, k, l, u) -#define kb_getp(name, b, k) kb_getp_##name(b, k) -#define kb_putp(name, b, k) kb_putp_##name(b, k) -#define kb_delp(name, b, k) kb_delp_##name(b, k) -#define kb_intervalp(name, b, k, l, u) kb_intervalp_##name(b, k, l, u) - -#define kb_itr_first(name, b, i) kb_itr_first_##name(b, i) -#define kb_itr_get(name, b, k, i) kb_itr_get_##name(b, k, i) -#define kb_itr_getp(name, b, k, i) kb_itr_getp_##name(b, k, i) -#define kb_itr_next(name, b, i) kb_itr_next_##name(b, i) -#define kb_itr_prev(name, b, i) kb_itr_prev_##name(b, i) -#define kb_del_itr(name, b, i) kb_del_itr_##name(b, i) -#define kb_itr_key(itr) __KB_KEY(dummy, (itr)->p->x)[(itr)->p->i] -#define kb_itr_valid(itr) ((itr)->p >= (itr)->stack) - -#define kb_size(b) ((b)->n_keys) - -#define kb_generic_cmp(a, b) (((b) < (a)) - ((a) < (b))) -#define kb_str_cmp(a, b) strcmp(a, b) - -#endif // NVIM_LIB_KBTREE_H diff --git a/src/nvim/lib/khash.h b/src/nvim/lib/khash.h deleted file mode 100644 index 57a41f9c13..0000000000 --- a/src/nvim/lib/khash.h +++ /dev/null @@ -1,730 +0,0 @@ -/* The MIT License - - Copyright (c) 2008, 2009, 2011 by Attractive Chaos - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - */ - -/* - Example: - - #include "nvim/khash.h" - KHASH_MAP_INIT_INT(32, char) - int main() { - int ret, is_missing; - khiter_t k; - khash_t(32) *h = kh_init(32); - k = kh_put(32, h, 5, &ret); - kh_value(h, k) = 10; - k = kh_get(32, h, 10); - is_missing = (k == kh_end(h)); - k = kh_get(32, h, 5); - kh_del(32, h, k); - for (k = kh_begin(h); k != kh_end(h); ++k) - if (kh_exist(h, k)) kh_value(h, k) = 1; - kh_destroy(32, h); - return 0; - } - */ - -/* - 2013-05-02 (0.2.8): - - * Use quadratic probing. When the capacity is power of 2, stepping function - i*(i+1)/2 guarantees to traverse each bucket. It is better than double - hashing on cache performance and is more robust than linear probing. - - In theory, double hashing should be more robust than quadratic probing. - However, my implementation is probably not for large hash tables, because - the second hash function is closely tied to the first hash function, - which reduce the effectiveness of double hashing. - - Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php - - 2011-12-29 (0.2.7): - - * Minor code clean up; no actual effect. - - 2011-09-16 (0.2.6): - - * The capacity is a power of 2. This seems to dramatically improve the - speed for simple keys. Thank Zilong Tan for the suggestion. Reference: - - - http://code.google.com/p/ulib/ - - http://nothings.org/computer/judy/ - - * Allow to optionally use linear probing which usually has better - performance for random input. Double hashing is still the default as it - is more robust to certain non-random input. - - * Added Wang's integer hash function (not used by default). This hash - function is more robust to certain non-random input. - - 2011-02-14 (0.2.5): - - * Allow to declare global functions. - - 2009-09-26 (0.2.4): - - * Improve portability - - 2008-09-19 (0.2.3): - - * Corrected the example - * Improved interfaces - - 2008-09-11 (0.2.2): - - * Improved speed a little in kh_put() - - 2008-09-10 (0.2.1): - - * Added kh_clear() - * Fixed a compiling error - - 2008-09-02 (0.2.0): - - * Changed to token concatenation which increases flexibility. - - 2008-08-31 (0.1.2): - - * Fixed a bug in kh_get(), which has not been tested previously. - - 2008-08-31 (0.1.1): - - * Added destructor - */ - -#ifndef NVIM_LIB_KHASH_H -#define NVIM_LIB_KHASH_H - -/*! - @header - - Generic hash table library. - */ - -#define AC_VERSION_KHASH_H "0.2.8" - -#include -#include -#include -#include - -#include "nvim/func_attr.h" -#include "nvim/memory.h" - -// compiler specific configuration - -#if UINT_MAX == 0xffffffffu -typedef unsigned int khint32_t; -#elif ULONG_MAX == 0xffffffffu -typedef unsigned long khint32_t; -#endif - -#if ULONG_MAX == ULLONG_MAX -typedef unsigned long khint64_t; -#else -typedef unsigned long long khint64_t; -#endif - -#ifdef _MSC_VER -# define kh_inline __inline -#else -# define kh_inline inline -#endif - -typedef khint32_t khint_t; -typedef khint_t khiter_t; - -#define __ac_isempty(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&2) -#define __ac_isdel(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&1) -#define __ac_iseither(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&3) -#define __ac_set_isdel_false(flag, i) (flag[i>>4]&=~(khint_t)(1ul<<((i&0xfU)<<1))) -#define __ac_set_isempty_false(flag, i) (flag[i>>4]&=~(khint_t)(2ul<<((i&0xfU)<<1))) -#define __ac_set_isboth_false(flag, i) (flag[i>>4]&=~(khint_t)(3ul<<((i&0xfU)<<1))) -#define __ac_set_isdel_true(flag, i) (flag[i>>4]|=(khint_t)1ul<<((i&0xfU)<<1)) - -#define __ac_fsize(m) ((m) < 16? 1 : (m)>>4) - -#ifndef kroundup32 -# define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, \ - ++(x)) -#endif - -#ifndef kcalloc -# define kcalloc(N, Z) xcalloc(N, Z) -#endif -#ifndef kmalloc -# define kmalloc(Z) xmalloc(Z) -#endif -#ifndef krealloc -# define krealloc(P, Z) xrealloc(P, Z) -#endif -#ifndef kfree -# define kfree(P) XFREE_CLEAR(P) -#endif - -#define __ac_HASH_UPPER 0.77 - -#define __KHASH_TYPE(name, khkey_t, khval_t) \ - typedef struct { \ - khint_t n_buckets, size, n_occupied, upper_bound; \ - khint32_t *flags; \ - khkey_t *keys; \ - khval_t *vals; \ - } kh_##name##_t; - -#define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \ - extern kh_##name##_t *kh_init_##name(void); \ - extern void kh_dealloc_##name(kh_##name##_t *h); \ - extern void kh_destroy_##name(kh_##name##_t *h); \ - extern void kh_clear_##name(kh_##name##_t *h); \ - extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \ - extern void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \ - extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \ - extern void kh_del_##name(kh_##name##_t *h, khint_t x); - -#define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, \ - __hash_equal) \ - SCOPE kh_##name##_t *kh_init_##name(void) \ - REAL_FATTR_UNUSED; \ - SCOPE kh_##name##_t *kh_init_##name(void) { \ - return (kh_##name##_t *)kcalloc(1, sizeof(kh_##name##_t)); \ - } \ - SCOPE void kh_dealloc_##name(kh_##name##_t *h) \ - REAL_FATTR_UNUSED; \ - SCOPE void kh_dealloc_##name(kh_##name##_t *h) \ - { \ - kfree(h->keys); \ - kfree(h->flags); \ - kfree(h->vals); \ - } \ - SCOPE void kh_destroy_##name(kh_##name##_t *h) \ - REAL_FATTR_UNUSED; \ - SCOPE void kh_destroy_##name(kh_##name##_t *h) \ - { \ - if (h) { \ - kh_dealloc_##name(h); \ - kfree(h); \ - } \ - } \ - SCOPE void kh_clear_##name(kh_##name##_t *h) \ - REAL_FATTR_UNUSED; \ - SCOPE void kh_clear_##name(kh_##name##_t *h) \ - { \ - if (h && h->flags) { \ - memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khint32_t)); \ - h->size = h->n_occupied = 0; \ - } \ - } \ - SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ - REAL_FATTR_UNUSED; \ - SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ - { \ - if (h->n_buckets) { \ - khint_t k, i, last, mask, step = 0; \ - mask = h->n_buckets - 1; \ - k = __hash_func(key); i = k & mask; \ - last = i; \ - while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || \ - !__hash_equal(h->keys[i], key))) { \ - i = (i + (++step)) & mask; \ - if (i == last) { \ - return h->n_buckets; \ - } \ - } \ - return __ac_iseither(h->flags, i) ? h->n_buckets : i; \ - } else { \ - return 0; \ - } \ - } \ - SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ - REAL_FATTR_UNUSED; \ - SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ - { /* This function uses 0.25*n_buckets bytes of working space instead of */ \ - /* [sizeof(key_t+val_t)+.25]*n_buckets. */ \ - khint32_t *new_flags = 0; \ - khint_t j = 1; \ - { \ - kroundup32(new_n_buckets); \ - if (new_n_buckets < 4) { \ - new_n_buckets = 4; \ - } \ - /* requested size is too small */ \ - if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) { \ - j = 0; \ - } else { /* hash table size to be changed (shrink or expand); rehash */ \ - new_flags = (khint32_t *)kmalloc(__ac_fsize(new_n_buckets) \ - * sizeof(khint32_t)); \ - memset(new_flags, 0xaa, \ - __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \ - if (h->n_buckets < new_n_buckets) { /* expand */ \ - khkey_t *new_keys = (khkey_t *)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \ - h->keys = new_keys; \ - if (kh_is_map) { \ - khval_t *new_vals = \ - (khval_t *)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \ - h->vals = new_vals; \ - } \ - } /* otherwise shrink */ \ - } \ - } \ - if (j) { /* rehashing is needed */ \ - for (j = 0; j != h->n_buckets; ++j) { \ - if (__ac_iseither(h->flags, j) == 0) { \ - khkey_t key = h->keys[j]; \ - khval_t val; \ - khint_t new_mask; \ - new_mask = new_n_buckets - 1; \ - if (kh_is_map) { \ - val = h->vals[j]; \ - } \ - __ac_set_isdel_true(h->flags, j); \ - /* kick-out process; sort of like in Cuckoo hashing */ \ - while (1) { \ - khint_t k, i, step = 0; \ - k = __hash_func(key); \ - i = k & new_mask; \ - while (!__ac_isempty(new_flags, i)) { \ - i = (i + (++step)) & new_mask; \ - } \ - __ac_set_isempty_false(new_flags, i); \ - /* kick out the existing element */ \ - if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { \ - { \ - khkey_t tmp = h->keys[i]; \ - h->keys[i] = key; \ - key = tmp; \ - } \ - if (kh_is_map) { \ - khval_t tmp = h->vals[i]; \ - h->vals[i] = val; \ - val = tmp; \ - } \ - /* mark it as deleted in the old hash table */ \ - __ac_set_isdel_true(h->flags, i); \ - } else { /* write the element and jump out of the loop */ \ - h->keys[i] = key; \ - if (kh_is_map) { \ - h->vals[i] = val; \ - } \ - break; \ - } \ - } \ - } \ - } \ - if (h->n_buckets > new_n_buckets) { /* shrink the hash table */ \ - h->keys = (khkey_t *)krealloc((void *)h->keys, \ - new_n_buckets * sizeof(khkey_t)); \ - if (kh_is_map) { \ - h->vals = (khval_t *)krealloc((void *)h->vals, \ - new_n_buckets * sizeof(khval_t)); \ - } \ - } \ - kfree(h->flags); /* free the working space */ \ - h->flags = new_flags; \ - h->n_buckets = new_n_buckets; \ - h->n_occupied = h->size; \ - h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \ - } \ - } \ - SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ - REAL_FATTR_UNUSED; \ - SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ - { \ - khint_t x; \ - if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \ - if (h->n_buckets > (h->size << 1)) { \ - kh_resize_##name(h, h->n_buckets - 1); /* clear "deleted" elements */ \ - } else { \ - kh_resize_##name(h, h->n_buckets + 1); /* expand the hash table */ \ - } \ - } /* TODO: implement automatically shrinking; */ \ - /* resize() already support shrinking */ \ - { \ - khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \ - x = site = h->n_buckets; \ - k = __hash_func(key); \ - i = k & mask; \ - if (__ac_isempty(h->flags, i)) { \ - x = i; /* for speed up */ \ - } else { \ - last = i; \ - while (!__ac_isempty(h->flags, i) \ - && (__ac_isdel(h->flags, i) \ - || !__hash_equal(h->keys[i], key))) { \ - if (__ac_isdel(h->flags, i)) { \ - site = i; \ - } \ - i = (i + (++step)) & mask; \ - if (i == last) { \ - x = site; \ - break; \ - } \ - } \ - if (x == h->n_buckets) { \ - if (__ac_isempty(h->flags, i) && site != h->n_buckets) { \ - x = site; \ - } else { \ - x = i; \ - } \ - } \ - } \ - } \ - if (__ac_isempty(h->flags, x)) { /* not present at all */ \ - h->keys[x] = key; \ - __ac_set_isboth_false(h->flags, x); \ - h->size++; \ - h->n_occupied++; \ - *ret = 1; \ - } else if (__ac_isdel(h->flags, x)) { /* deleted */ \ - h->keys[x] = key; \ - __ac_set_isboth_false(h->flags, x); \ - h->size++; \ - *ret = 2; \ - } else { \ - *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \ - } \ - return x; \ - } \ - SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ - REAL_FATTR_UNUSED; \ - SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ - { \ - if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \ - __ac_set_isdel_true(h->flags, x); \ - --h->size; \ - } \ - } - -#define KHASH_DECLARE(name, khkey_t, khval_t) \ - __KHASH_TYPE(name, khkey_t, khval_t) \ - __KHASH_PROTOTYPES(name, khkey_t, khval_t) - -#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ - __KHASH_TYPE(name, khkey_t, khval_t) \ - __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) - -#define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ - KHASH_INIT2(name, static kh_inline, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) - -// --- BEGIN OF HASH FUNCTIONS --- - -/*! @function - @abstract Integer hash function - @param key The integer [khint32_t] - @return The hash value [khint_t] - */ -#define kh_int_hash_func(key) (khint32_t)(key) -/*! @function - @abstract Integer comparison function - */ -#define kh_int_hash_equal(a, b) ((a) == (b)) -/*! @function - @abstract 64-bit integer hash function - @param key The integer [khint64_t] - @return The hash value [khint_t] - */ -#define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11) -/*! @function - @abstract 64-bit integer comparison function - */ -#define kh_int64_hash_equal(a, b) ((a) == (b)) -/*! @function - @abstract const char* hash function - @param s Pointer to a null terminated string - @return The hash value - */ -static kh_inline khint_t __ac_X31_hash_string(const char *s) -{ - khint_t h = (khint_t)*s; - if (h) { - for (++s; *s; ++s) { h = (h << 5) - h + (uint8_t)*s; } - } - return h; -} -/*! @function - @abstract Another interface to const char* hash function - @param key Pointer to a null terminated string [const char*] - @return The hash value [khint_t] - */ -#define kh_str_hash_func(key) __ac_X31_hash_string(key) -/*! @function - @abstract Const char* comparison function - */ -#define kh_str_hash_equal(a, b) (strcmp(a, b) == 0) - -static kh_inline khint_t __ac_Wang_hash(khint_t key) -{ - key += ~(key << 15); - key ^= (key >> 10); - key += (key << 3); - key ^= (key >> 6); - key += ~(key << 11); - key ^= (key >> 16); - return key; -} -#define kh_int_hash_func2(k) __ac_Wang_hash((khint_t)key) - -// --- END OF HASH FUNCTIONS --- - -// Other convenient macros... - -/*! - @abstract Type of the hash table. - @param name Name of the hash table [symbol] - */ -#define khash_t(name) kh_##name##_t - -/*! @function - @abstract Initiate a hash table. - @param name Name of the hash table [symbol] - @return Pointer to the hash table [khash_t(name)*] - */ -#define kh_init(name) kh_init_##name() - -/*! @function - @abstract Destroy a hash table. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - */ -#define kh_destroy(name, h) kh_destroy_##name(h) - -/*! @function - @abstract Free memory referenced directly inside a hash table. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - */ -#define kh_dealloc(name, h) kh_dealloc_##name(h) - -/*! @function - @abstract Reset a hash table without deallocating memory. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - */ -#define kh_clear(name, h) kh_clear_##name(h) - -/*! @function - @abstract Resize a hash table. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - @param s New size [khint_t] - */ -#define kh_resize(name, h, s) kh_resize_##name(h, s) - -/*! @function - @abstract Insert a key to the hash table. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - @param k Key [type of keys] - @param r Extra return code: -1 if the operation failed; - 0 if the key is present in the hash table; - 1 if the bucket is empty (never used); 2 if the element in - the bucket has been deleted [int*] - @return Iterator to the inserted element [khint_t] - */ -#define kh_put(name, h, k, r) kh_put_##name(h, k, r) - -/*! @function - @abstract Retrieve a key from the hash table. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - @param k Key [type of keys] - @return Iterator to the found element, or kh_end(h) if the element is absent [khint_t] - */ -#define kh_get(name, h, k) kh_get_##name(h, k) - -/*! @function - @abstract Remove a key from the hash table. - @param name Name of the hash table [symbol] - @param h Pointer to the hash table [khash_t(name)*] - @param k Iterator to the element to be deleted [khint_t] - */ -#define kh_del(name, h, k) kh_del_##name(h, k) - -/*! @function - @abstract Test whether a bucket contains data. - @param h Pointer to the hash table [khash_t(name)*] - @param x Iterator to the bucket [khint_t] - @return 1 if containing data; 0 otherwise [int] - */ -#define kh_exist(h, x) (!__ac_iseither((h)->flags, (x))) - -/*! @function - @abstract Get key given an iterator - @param h Pointer to the hash table [khash_t(name)*] - @param x Iterator to the bucket [khint_t] - @return Key [type of keys] - */ -#define kh_key(h, x) ((h)->keys[x]) - -/*! @function - @abstract Get value given an iterator - @param h Pointer to the hash table [khash_t(name)*] - @param x Iterator to the bucket [khint_t] - @return Value [type of values] - @discussion For hash sets, calling this results in segfault. - */ -#define kh_val(h, x) ((h)->vals[x]) - -/*! @function - @abstract Alias of kh_val() - */ -#define kh_value(h, x) ((h)->vals[x]) - -/*! @function - @abstract Get the start iterator - @param h Pointer to the hash table [khash_t(name)*] - @return The start iterator [khint_t] - */ -#define kh_begin(h) (khint_t)(0) - -/*! @function - @abstract Get the end iterator - @param h Pointer to the hash table [khash_t(name)*] - @return The end iterator [khint_t] - */ -#define kh_end(h) ((h)->n_buckets) - -/*! @function - @abstract Get the number of elements in the hash table - @param h Pointer to the hash table [khash_t(name)*] - @return Number of elements in the hash table [khint_t] - */ -#define kh_size(h) ((h)->size) - -/*! @function - @abstract Get the number of buckets in the hash table - @param h Pointer to the hash table [khash_t(name)*] - @return Number of buckets in the hash table [khint_t] - */ -#define kh_n_buckets(h) ((h)->n_buckets) - -/*! @function - @abstract Iterate over the entries in the hash table - @param h Pointer to the hash table [khash_t(name)*] - @param kvar Variable to which key will be assigned - @param vvar Variable to which value will be assigned - @param code Block of code to execute - */ -#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \ - for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ - if (!kh_exist(h, __i)) continue; \ - (kvar) = kh_key(h, __i); \ - (vvar) = kh_val(h, __i); \ - code; \ - } } - -/*! @function - @abstract Iterate over the values in the hash table - @param h Pointer to the hash table [khash_t(name)*] - @param vvar Variable to which value will be assigned - @param code Block of code to execute - */ -#define kh_foreach_value(h, vvar, code) { khint_t __i; \ - for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \ - if (!kh_exist(h, __i)) continue; \ - (vvar) = kh_val(h, __i); \ - code; \ - } } - -/*! @function - @abstract Iterate over the keys in the hash table - @param h Pointer to the hash table [khash_t(name)*] - @param kvar Variable to which value will be assigned - @param code Block of code to execute - */ -#define kh_foreach_key(h, kvar, code) \ - { \ - khint_t __i; \ - for (__i = kh_begin(h); __i != kh_end(h); __i++) { \ - if (!kh_exist(h, __i)) { \ - continue; \ - } \ - (kvar) = kh_key(h, __i); \ - code; \ - } \ - } - -// More convenient interfaces - -/*! @function - @abstract Instantiate a hash set containing integer keys - @param name Name of the hash table [symbol] - */ -#define KHASH_SET_INIT_INT(name) \ - KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal) - -/*! @function - @abstract Instantiate a hash map containing integer keys - @param name Name of the hash table [symbol] - @param khval_t Type of values [type] - */ -#define KHASH_MAP_INIT_INT(name, khval_t) \ - KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) - -/*! @function - @abstract Instantiate a hash map containing 64-bit integer keys - @param name Name of the hash table [symbol] - */ -#define KHASH_SET_INIT_INT64(name) \ - KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) - -/*! @function - @abstract Instantiate a hash map containing 64-bit integer keys - @param name Name of the hash table [symbol] - @param khval_t Type of values [type] - */ -#define KHASH_MAP_INIT_INT64(name, khval_t) \ - KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) - -typedef const char *kh_cstr_t; -/*! @function - @abstract Instantiate a hash map containing const char* keys - @param name Name of the hash table [symbol] - */ -#define KHASH_SET_INIT_STR(name) \ - KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal) - -/*! @function - @abstract Instantiate a hash map containing const char* keys - @param name Name of the hash table [symbol] - @param khval_t Type of values [type] - */ -#define KHASH_MAP_INIT_STR(name, khval_t) \ - KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal) - -/*! @function - @abstract Return a literal for an empty hash table. - @param name Name of the hash table [symbol] - */ -#define KHASH_EMPTY_TABLE(name) \ - ((kh_##name##_t) { \ - .n_buckets = 0, \ - .size = 0, \ - .n_occupied = 0, \ - .upper_bound = 0, \ - .flags = NULL, \ - .keys = NULL, \ - .vals = NULL, \ - }) -#endif // NVIM_LIB_KHASH_H diff --git a/src/nvim/lib/klist.h b/src/nvim/lib/klist.h deleted file mode 100644 index a9abbc6dc2..0000000000 --- a/src/nvim/lib/klist.h +++ /dev/null @@ -1,144 +0,0 @@ -/* The MIT License - - Copyright (c) 2008-2009, by Attractive Chaos - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - */ - -#ifndef _AC_KLIST_H -#define _AC_KLIST_H - -#include -#include - -#include "nvim/func_attr.h" -#include "nvim/memory.h" - -#define KMEMPOOL_INIT(name, kmptype_t, kmpfree_f) \ - typedef struct { \ - size_t cnt, n, max; \ - kmptype_t **buf; \ - } kmp_##name##_t; \ - static inline kmp_##name##_t *kmp_init_##name(void) { \ - return xcalloc(1, sizeof(kmp_##name##_t)); \ - } \ - static inline void kmp_destroy_##name(kmp_##name##_t *mp) \ - REAL_FATTR_UNUSED; \ - static inline void kmp_destroy_##name(kmp_##name##_t *mp) { \ - size_t k; \ - for (k = 0; k < mp->n; k++) { \ - kmpfree_f(mp->buf[k]); XFREE_CLEAR(mp->buf[k]); \ - } \ - XFREE_CLEAR(mp->buf); XFREE_CLEAR(mp); \ - } \ - static inline kmptype_t *kmp_alloc_##name(kmp_##name##_t *mp) { \ - mp->cnt++; \ - if (mp->n == 0) { \ - return xcalloc(1, sizeof(kmptype_t)); \ - } \ - return mp->buf[--mp->n]; \ - } \ - static inline void kmp_free_##name(kmp_##name##_t *mp, kmptype_t *p) { \ - mp->cnt--; \ - if (mp->n == mp->max) { \ - mp->max = mp->max ? (mp->max << 1) : 16; \ - mp->buf = xrealloc(mp->buf, sizeof(kmptype_t *) * mp->max); \ - } \ - mp->buf[mp->n++] = p; \ - } - -#define kmempool_t(name) kmp_##name##_t -#define kmp_init(name) kmp_init_##name() -#define kmp_destroy(name, mp) kmp_destroy_##name(mp) -#define kmp_alloc(name, mp) kmp_alloc_##name(mp) -#define kmp_free(name, mp, p) kmp_free_##name(mp, p) - -#define KLIST_INIT(name, kltype_t, kmpfree_t) \ - struct __kl1_##name { \ - kltype_t data; \ - struct __kl1_##name *next; \ - }; \ - typedef struct __kl1_##name kl1_##name; \ - KMEMPOOL_INIT(name, kl1_##name, kmpfree_t) \ - typedef struct { \ - kl1_##name *head, *tail; \ - kmp_##name##_t *mp; \ - size_t size; \ - } kl_##name##_t; \ - static inline kl_##name##_t *kl_init_##name(void) { \ - kl_##name##_t *kl = xcalloc(1, sizeof(kl_##name##_t)); \ - kl->mp = kmp_init(name); \ - kl->head = kl->tail = kmp_alloc(name, kl->mp); \ - kl->head->next = 0; \ - return kl; \ - } \ - static inline void kl_destroy_##name(kl_##name##_t *kl) \ - REAL_FATTR_UNUSED; \ - static inline void kl_destroy_##name(kl_##name##_t *kl) { \ - kl1_##name *p; \ - for (p = kl->head; p != kl->tail; p = p->next) { \ - kmp_free(name, kl->mp, p); \ - } \ - kmp_free(name, kl->mp, p); \ - kmp_destroy(name, kl->mp); \ - XFREE_CLEAR(kl); \ - } \ - static inline void kl_push_##name(kl_##name##_t *kl, kltype_t d) { \ - kl1_##name *q, *p = kmp_alloc(name, kl->mp); \ - q = kl->tail; p->next = 0; kl->tail->next = p; kl->tail = p; \ - kl->size++; \ - q->data = d; \ - } \ - static inline kltype_t kl_shift_at_##name(kl_##name##_t *kl, \ - kl1_##name **n) { \ - assert((*n)->next); \ - kl1_##name *p; \ - kl->size--; \ - p = *n; \ - *n = (*n)->next; \ - if (p == kl->head) { \ - kl->head = *n; \ - } \ - kltype_t d = p->data; \ - kmp_free(name, kl->mp, p); \ - return d; \ - } - -#define kliter_t(name) kl1_##name -#define klist_t(name) kl_##name##_t -#define kl_val(iter) ((iter)->data) -#define kl_next(iter) ((iter)->next) -#define kl_begin(kl) ((kl)->head) -#define kl_end(kl) ((kl)->tail) - -#define kl_init(name) kl_init_##name() -#define kl_destroy(name, kl) kl_destroy_##name(kl) -#define kl_push(name, kl, d) kl_push_##name(kl, d) -#define kl_shift_at(name, kl, node) kl_shift_at_##name(kl, node) -#define kl_shift(name, kl) kl_shift_at(name, kl, &kl->head) -#define kl_empty(kl) ((kl)->size == 0) -// Iteration macros. It's ok to modify the list while iterating as long as a -// `break` statement is executed before the next iteration. -#define kl_iter(name, kl, p) kl_iter_at(name, kl, p, NULL) -#define kl_iter_at(name, kl, p, h) \ - for (kl1_##name **p = h ? h : &kl->head; *p != kl->tail; p = &(*p)->next) - -#endif diff --git a/src/nvim/lib/kvec.h b/src/nvim/lib/kvec.h deleted file mode 100644 index b5b3adf7d2..0000000000 --- a/src/nvim/lib/kvec.h +++ /dev/null @@ -1,236 +0,0 @@ -// The MIT License -// -// Copyright (c) 2008, by Attractive Chaos -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -// An example: -// -// #include "kvec.h" -// int main() { -// kvec_t(int) array = KV_INITIAL_VALUE; -// kv_push(array, 10); // append -// kv_a(array, 20) = 5; // dynamic -// kv_A(array, 20) = 4; // static -// kv_destroy(array); -// return 0; -// } - -#ifndef NVIM_LIB_KVEC_H -#define NVIM_LIB_KVEC_H - -#include -#include - -#include "nvim/memory.h" -#include "nvim/os/os_defs.h" - -#define kv_roundup32(x) \ - ((--(x)), \ - ((x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16), \ - (++(x))) - -#define KV_INITIAL_VALUE { .size = 0, .capacity = 0, .items = NULL } - -#define kvec_t(type) \ - struct { \ - size_t size; \ - size_t capacity; \ - type *items; \ - } - -#define kv_init(v) ((v).size = (v).capacity = 0, (v).items = 0) -#define kv_destroy(v) \ - do { \ - xfree((v).items); \ - kv_init(v); \ - } while (0) -#define kv_A(v, i) ((v).items[(i)]) -#define kv_pop(v) ((v).items[--(v).size]) -#define kv_size(v) ((v).size) -#define kv_max(v) ((v).capacity) -#define kv_Z(v, i) kv_A(v, kv_size(v) - (i) - 1) -#define kv_last(v) kv_Z(v, 0) - -/// Drop last n items from kvec without resizing -/// -/// Previously spelled as `(void)kv_pop(v)`, repeated n times. -/// -/// @param[out] v Kvec to drop items from. -/// @param[in] n Number of elements to drop. -#define kv_drop(v, n) ((v).size -= (n)) - -#define kv_resize(v, s) \ - ((v).capacity = (s), \ - (v).items = xrealloc((v).items, sizeof((v).items[0]) * (v).capacity)) - -#define kv_resize_full(v) \ - kv_resize(v, (v).capacity ? (v).capacity << 1 : 8) - -#define kv_copy(v1, v0) \ - do { \ - if ((v1).capacity < (v0).size) { \ - kv_resize(v1, (v0).size); \ - } \ - (v1).size = (v0).size; \ - memcpy((v1).items, (v0).items, sizeof((v1).items[0]) * (v0).size); \ - } while (0) - -/// fit at least "len" more items -#define kv_ensure_space(v, len) \ - do { \ - if ((v).capacity < (v).size + len) { \ - (v).capacity = (v).size + len; \ - kv_roundup32((v).capacity); \ - kv_resize((v), (v).capacity); \ - } \ - } while (0) - -#define kv_concat_len(v, data, len) \ - do { \ - kv_ensure_space(v, len); \ - memcpy((v).items + (v).size, data, sizeof((v).items[0]) * len); \ - (v).size = (v).size + len; \ - } while (0) - -#define kv_concat(v, str) kv_concat_len(v, str, STRLEN(str)) -#define kv_splice(v1, v0) kv_concat_len(v1, (v0).items, (v0).size) - -#define kv_pushp(v) \ - ((((v).size == (v).capacity) ? (kv_resize_full(v), 0) : 0), \ - ((v).items + ((v).size++))) - -#define kv_push(v, x) \ - (*kv_pushp(v) = (x)) - -#define kv_pushp_c(v) ((v).items + ((v).size++)) -#define kv_push_c(v, x) (*kv_pushp_c(v) = (x)) - -#define kv_a(v, i) \ - (*(((v).capacity <= (size_t)(i) \ - ? ((v).capacity = (v).size = (i) + 1, \ - kv_roundup32((v).capacity), \ - kv_resize((v), (v).capacity), 0UL) \ - : ((v).size <= (size_t)(i) \ - ? (v).size = (i) + 1 \ - : 0UL)), \ - &(v).items[(i)])) - -#define kv_printf(v, ...) kv_do_printf(&(v), __VA_ARGS__) - -/// Type of a vector with a few first members allocated on stack -/// -/// Is compatible with #kv_A, #kv_pop, #kv_size, #kv_max, #kv_last. -/// Is not compatible with #kv_resize, #kv_resize_full, #kv_copy, #kv_push, -/// #kv_pushp, #kv_a, #kv_destroy. -/// -/// @param[in] type Type of vector elements. -/// @param[in] init_size Number of the elements in the initial array. -#define kvec_withinit_t(type, INIT_SIZE) \ - struct { \ - size_t size; \ - size_t capacity; \ - type *items; \ - type init_array[INIT_SIZE]; \ - } - -/// Initialize vector with preallocated array -/// -/// @param[out] v Vector to initialize. -#define kvi_init(v) \ - ((v).capacity = ARRAY_SIZE((v).init_array), \ - (v).size = 0, \ - (v).items = (v).init_array) - -/// Move data to a new destination and free source -static inline void *_memcpy_free(void *const restrict dest, void *const restrict src, - const size_t size) - FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_ALWAYS_INLINE -{ - memcpy(dest, src, size); - XFREE_CLEAR(src); - return dest; -} - -// -V:kvi_push:512 - -/// Resize vector with preallocated array -/// -/// @note May not resize to an array smaller then init_array: if requested, -/// init_array will be used. -/// -/// @param[out] v Vector to resize. -/// @param[in] s New size. -#define kvi_resize(v, s) \ - ((v).capacity = ((s) > ARRAY_SIZE((v).init_array) \ - ? (s) \ - : ARRAY_SIZE((v).init_array)), \ - (v).items = ((v).capacity == ARRAY_SIZE((v).init_array) \ - ? ((v).items == (v).init_array \ - ? (v).items \ - : _memcpy_free((v).init_array, (v).items, \ - (v).size * sizeof((v).items[0]))) \ - : ((v).items == (v).init_array \ - ? memcpy(xmalloc((v).capacity * sizeof((v).items[0])), \ - (v).items, \ - (v).size * sizeof((v).items[0])) \ - : xrealloc((v).items, \ - (v).capacity * sizeof((v).items[0]))))) - -/// Resize vector with preallocated array when it is full -/// -/// @param[out] v Vector to resize. -#define kvi_resize_full(v) \ - /* ARRAY_SIZE((v).init_array) is the minimal capacity of this vector. */ \ - /* Thus when vector is full capacity may not be zero and it is safe */ \ - /* not to bother with checking whether (v).capacity is 0. But now */ \ - /* capacity is not guaranteed to have size that is a power of 2, it is */ \ - /* hard to fix this here and is not very necessary if users will use */ \ - /* 2^x initial array size. */ \ - kvi_resize(v, (v).capacity << 1) - -/// Get location where to store new element to a vector with preallocated array -/// -/// @param[in,out] v Vector to push to. -/// -/// @return Pointer to the place where new value should be stored. -#define kvi_pushp(v) \ - ((((v).size == (v).capacity) ? (kvi_resize_full(v), 0) : 0), \ - ((v).items + ((v).size++))) - -/// Push value to a vector with preallocated array -/// -/// @param[out] v Vector to push to. -/// @param[in] x Value to push. -#define kvi_push(v, x) \ - (*kvi_pushp(v) = (x)) - -/// Free array of elements of a vector with preallocated array if needed -/// -/// @param[out] v Vector to free. -#define kvi_destroy(v) \ - do { \ - if ((v).items != (v).init_array) { \ - XFREE_CLEAR((v).items); \ - } \ - } while (0) - -#endif // NVIM_LIB_KVEC_H diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c index 735a75a6f1..bdb0719809 100644 --- a/src/nvim/lua/converter.c +++ b/src/nvim/lua/converter.c @@ -15,12 +15,12 @@ #include "nvim/memory.h" // FIXME: vim.h is not actually needed, but otherwise it states MAXPATHL is // redefined +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/eval/decode.h" #include "nvim/eval/typval.h" #include "nvim/eval/userfunc.h" #include "nvim/globals.h" -#include "nvim/lib/kvec.h" #include "nvim/lua/converter.h" #include "nvim/lua/executor.h" #include "nvim/macros.h" diff --git a/src/nvim/lua/treesitter.c b/src/nvim/lua/treesitter.c index f3c67e265f..64cace9ab4 100644 --- a/src/nvim/lua/treesitter.c +++ b/src/nvim/lua/treesitter.c @@ -16,9 +16,9 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/private/helpers.h" #include "nvim/buffer.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/lua/treesitter.h" #include "nvim/map.h" diff --git a/src/nvim/map.c b/src/nvim/map.c index 1561b089a7..24478c6091 100644 --- a/src/nvim/map.c +++ b/src/nvim/map.c @@ -14,7 +14,7 @@ #include #include -#include "nvim/lib/khash.h" +#include "klib/khash.h" #include "nvim/map.h" #include "nvim/map_defs.h" #include "nvim/memory.h" diff --git a/src/nvim/map_defs.h b/src/nvim/map_defs.h index 7b4596ce2e..61afedbe50 100644 --- a/src/nvim/map_defs.h +++ b/src/nvim/map_defs.h @@ -1,7 +1,7 @@ #ifndef NVIM_MAP_DEFS_H #define NVIM_MAP_DEFS_H -#include "nvim/lib/khash.h" +#include "klib/khash.h" typedef const char *cstr_t; typedef void *ptr_t; diff --git a/src/nvim/marktree.c b/src/nvim/marktree.c index 03340a99d6..ad1680322c 100644 --- a/src/nvim/marktree.c +++ b/src/nvim/marktree.c @@ -49,8 +49,8 @@ #include +#include "klib/kvec.h" #include "nvim/garray.h" -#include "nvim/lib/kvec.h" #include "nvim/marktree.h" #define T MT_BRANCH_FACTOR diff --git a/src/nvim/message.h b/src/nvim/message.h index 811e621c11..31cd54f18c 100644 --- a/src/nvim/message.h +++ b/src/nvim/message.h @@ -5,9 +5,9 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/private/defs.h" #include "nvim/grid_defs.h" -#include "nvim/lib/kvec.h" #include "nvim/macros.h" #include "nvim/types.h" diff --git a/src/nvim/msgpack_rpc/channel.c b/src/nvim/msgpack_rpc/channel.c index d22bcb29d5..71ed5ccf81 100644 --- a/src/nvim/msgpack_rpc/channel.c +++ b/src/nvim/msgpack_rpc/channel.c @@ -7,6 +7,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/private/helpers.h" #include "nvim/api/ui.h" #include "nvim/api/vim.h" @@ -18,7 +19,6 @@ #include "nvim/event/rstream.h" #include "nvim/event/socket.h" #include "nvim/event/wstream.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/main.h" #include "nvim/map.h" diff --git a/src/nvim/msgpack_rpc/helpers.c b/src/nvim/msgpack_rpc/helpers.c index 488321be42..ddca9afad0 100644 --- a/src/nvim/msgpack_rpc/helpers.c +++ b/src/nvim/msgpack_rpc/helpers.c @@ -5,10 +5,10 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/private/dispatch.h" #include "nvim/api/private/helpers.h" #include "nvim/assert.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/memory.h" #include "nvim/msgpack_rpc/helpers.h" diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 6391644f83..dee23e9193 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -9,6 +9,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/assert.h" #include "nvim/buffer.h" @@ -28,7 +29,6 @@ #include "nvim/globals.h" #include "nvim/indent.h" #include "nvim/indent_c.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/macros.h" #include "nvim/mark.h" diff --git a/src/nvim/os/pty_conpty_win.h b/src/nvim/os/pty_conpty_win.h index 15e7c3da0c..0c25a5970e 100644 --- a/src/nvim/os/pty_conpty_win.h +++ b/src/nvim/os/pty_conpty_win.h @@ -1,7 +1,7 @@ #ifndef NVIM_OS_PTY_CONPTY_WIN_H #define NVIM_OS_PTY_CONPTY_WIN_H -#include "nvim/lib/kvec.h" +#include "klib/kvec.h" #include "nvim/os/input.h" #ifndef HPCON diff --git a/src/nvim/os/pty_process_unix.c b/src/nvim/os/pty_process_unix.c index c5d6af0ff6..0b7af87267 100644 --- a/src/nvim/os/pty_process_unix.c +++ b/src/nvim/os/pty_process_unix.c @@ -31,11 +31,11 @@ #include +#include "klib/klist.h" #include "nvim/event/loop.h" #include "nvim/event/process.h" #include "nvim/event/rstream.h" #include "nvim/event/wstream.h" -#include "nvim/lib/klist.h" #include "nvim/log.h" #include "nvim/os/os.h" #include "nvim/os/pty_process_unix.h" diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c index ca3e32e871..9766c8f3d9 100644 --- a/src/nvim/os/shell.c +++ b/src/nvim/os/shell.c @@ -7,6 +7,7 @@ #include #include +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/charset.h" #include "nvim/eval.h" @@ -15,7 +16,6 @@ #include "nvim/event/rstream.h" #include "nvim/ex_cmds.h" #include "nvim/fileio.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/main.h" #include "nvim/memline.h" diff --git a/src/nvim/shada.c b/src/nvim/shada.c index f735829030..7580cc8897 100644 --- a/src/nvim/shada.c +++ b/src/nvim/shada.c @@ -11,6 +11,8 @@ #include #include +#include "klib/khash.h" +#include "klib/kvec.h" #include "nvim/api/private/defs.h" #include "nvim/api/private/helpers.h" #include "nvim/ascii.h" @@ -25,8 +27,6 @@ #include "nvim/fileio.h" #include "nvim/garray.h" #include "nvim/globals.h" -#include "nvim/lib/khash.h" -#include "nvim/lib/kvec.h" #include "nvim/macros.h" #include "nvim/mark.h" #include "nvim/memory.h" diff --git a/src/nvim/state.c b/src/nvim/state.c index 8b07c484e6..0353e61742 100644 --- a/src/nvim/state.c +++ b/src/nvim/state.c @@ -3,6 +3,7 @@ #include +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/autocmd.h" #include "nvim/drawscreen.h" @@ -10,7 +11,6 @@ #include "nvim/ex_docmd.h" #include "nvim/getchar.h" #include "nvim/insexpand.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/main.h" #include "nvim/option.h" diff --git a/src/nvim/strings.h b/src/nvim/strings.h index 9ef1eb5816..6ad9daf5bf 100644 --- a/src/nvim/strings.h +++ b/src/nvim/strings.h @@ -5,8 +5,8 @@ #include #include +#include "klib/kvec.h" #include "nvim/eval/typval.h" -#include "nvim/lib/kvec.h" #include "nvim/types.h" /// Append string to string and return pointer to the next byte diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 5a331463e3..4eabecb74a 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -13,13 +13,13 @@ # include #endif +#include "klib/kvec.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" #include "nvim/ascii.h" #include "nvim/event/loop.h" #include "nvim/event/signal.h" #include "nvim/highlight.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/main.h" #include "nvim/map.h" diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c index f23615180e..8ef24b484e 100644 --- a/src/nvim/ui_compositor.c +++ b/src/nvim/ui_compositor.c @@ -11,12 +11,12 @@ #include #include +#include "klib/kvec.h" #include "nvim/api/private/helpers.h" #include "nvim/ascii.h" #include "nvim/grid.h" #include "nvim/highlight.h" #include "nvim/highlight_group.h" -#include "nvim/lib/kvec.h" #include "nvim/log.h" #include "nvim/lua/executor.h" #include "nvim/main.h" diff --git a/src/nvim/undo.c b/src/nvim/undo.c index 0a5a3133df..d67863f84f 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -81,6 +81,7 @@ #include #include "auto/config.h" +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/buffer.h" #include "nvim/buffer_updates.h" @@ -94,7 +95,6 @@ #include "nvim/fold.h" #include "nvim/garray.h" #include "nvim/getchar.h" -#include "nvim/lib/kvec.h" #include "nvim/mark.h" #include "nvim/memline.h" #include "nvim/memory.h" diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c index d12a690b83..4564831824 100644 --- a/src/nvim/viml/parser/expressions.c +++ b/src/nvim/viml/parser/expressions.c @@ -55,11 +55,11 @@ #include #include +#include "klib/kvec.h" #include "nvim/ascii.h" #include "nvim/assert.h" #include "nvim/charset.h" #include "nvim/eval/typval.h" -#include "nvim/lib/kvec.h" #include "nvim/memory.h" #include "nvim/types.h" #include "nvim/vim.h" diff --git a/src/nvim/viml/parser/parser.h b/src/nvim/viml/parser/parser.h index 55f54cedbe..404dc5a0d1 100644 --- a/src/nvim/viml/parser/parser.h +++ b/src/nvim/viml/parser/parser.h @@ -5,8 +5,8 @@ #include #include +#include "klib/kvec.h" #include "nvim/func_attr.h" -#include "nvim/lib/kvec.h" #include "nvim/mbyte.h" #include "nvim/memory.h" -- cgit From fded344f38f0814256b3acd01d94d5942a22f7fc Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 25 Sep 2022 21:38:46 +0800 Subject: fix(extmarks): make virt_lines always start at 0 virtcol --- src/nvim/drawline.c | 2 +- test/functional/ui/decorations_spec.lua | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c index 5c3fa3d3b0..10e1d95730 100644 --- a/src/nvim/drawline.c +++ b/src/nvim/drawline.c @@ -2607,7 +2607,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange, assert(i >= 0); int offset = kv_A(virt_lines, i).left_col ? 0 : win_col_offset; draw_virt_text_item(buf, offset, kv_A(virt_lines, i).line, - kHlModeReplace, grid->cols, offset); + kHlModeReplace, grid->cols, 0); } } else { draw_virt_text(wp, buf, win_col_offset, &draw_col, grid->cols, row); diff --git a/test/functional/ui/decorations_spec.lua b/test/functional/ui/decorations_spec.lua index eff6fe6d23..44b88d702f 100644 --- a/test/functional/ui/decorations_spec.lua +++ b/test/functional/ui/decorations_spec.lua @@ -1550,6 +1550,38 @@ if (h->n_buckets < new_n_buckets) { // expand } | | ]]} + + command 'set number' + screen:expect{grid=[[ + {9: 1 }^if (h->n_buckets < new_n_buckets) { // expand | + {9: 2 } khkey_t *new_keys = (khkey_t *)krealloc((voi| + {9: }d *)h->keys, new_n_buckets * sizeof(khkey_t));| + {9: }{1:>>}{2: very tabby}text with tabs | + {9: 3 } h->keys = new_keys; | + {9: 4 } if (kh_is_map && val_size) { | + {9: 5 } char *new_vals = krealloc( h->vals_buf, ne| + {9: }w_n_buckets * val_size); | + {9: 6 } h->vals_buf = new_vals; | + {9: 7 } } | + {9: 8 }} | + | + ]]} + + command 'set tabstop&' + screen:expect{grid=[[ + {9: 1 }^if (h->n_buckets < new_n_buckets) { // expand | + {9: 2 } khkey_t *new_keys = (khkey_t *)krealloc((voi| + {9: }d *)h->keys, new_n_buckets * sizeof(khkey_t));| + {9: }{1:>>}{2: very tabby}text with tabs | + {9: 3 } h->keys = new_keys; | + {9: 4 } if (kh_is_map && val_size) { | + {9: 5 } char *new_vals = krealloc( h->vals_buf, ne| + {9: }w_n_buckets * val_size); | + {9: 6 } h->vals_buf = new_vals; | + {9: 7 } } | + {9: 8 }} | + | + ]]} end) end) -- cgit From f8a1cadccff39923643fdea2e282be9fffa60e99 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sun, 25 Sep 2022 22:29:25 +0800 Subject: fix(filetype): use :setf instead of nvim_buf_set_option (#20334) --- runtime/filetype.lua | 8 ++++++-- test/functional/lua/filetype_spec.lua | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/runtime/filetype.lua b/runtime/filetype.lua index c50ba6453d..ee9d5a0a75 100644 --- a/runtime/filetype.lua +++ b/runtime/filetype.lua @@ -14,10 +14,14 @@ vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile', 'StdinReadPost' }, { -- Generic configuration file used as fallback ft = require('vim.filetype.detect').conf(args.file, args.buf) if ft then - vim.api.nvim_cmd({ cmd = 'setf', args = { 'FALLBACK', ft } }, {}) + vim.api.nvim_buf_call(args.buf, function() + vim.api.nvim_cmd({ cmd = 'setf', args = { 'FALLBACK', ft } }, {}) + end) end else - vim.api.nvim_buf_set_option(args.buf, 'filetype', ft) + vim.api.nvim_buf_call(args.buf, function() + vim.api.nvim_cmd({ cmd = 'setf', args = { ft } }, {}) + end) if on_detect then on_detect(args.buf) end diff --git a/test/functional/lua/filetype_spec.lua b/test/functional/lua/filetype_spec.lua index be57b2db31..2a7be53164 100644 --- a/test/functional/lua/filetype_spec.lua +++ b/test/functional/lua/filetype_spec.lua @@ -1,6 +1,7 @@ local helpers = require('test.functional.helpers')(after_each) local exec_lua = helpers.exec_lua local eq = helpers.eq +local meths = helpers.meths local clear = helpers.clear local pathroot = helpers.pathroot local command = helpers.command @@ -94,3 +95,10 @@ describe('vim.filetype', function() ]]) end) end) + +describe('filetype.lua', function() + it('does not override user autocommands that set filetype #20333', function() + clear({args={'--clean', '--cmd', 'autocmd BufRead *.md set filetype=notmarkdown', 'README.md'}}) + eq('notmarkdown', meths.buf_get_option(0, 'filetype')) + end) +end) -- cgit From a6c9764edaa349f5f268e5e3bf8b940e137fb5c4 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 26 Sep 2022 07:00:37 +0800 Subject: fix(inccommand): deal with unsynced undo (#20041) --- src/nvim/ex_getln.c | 9 +++++++++ test/functional/ui/inccommand_spec.lua | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 2d39ced582..0ccc12c9b4 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -136,6 +136,7 @@ typedef struct cmdpreview_win_info { typedef struct cmdpreview_buf_info { buf_T *buf; + bool save_b_u_synced; time_t save_b_u_time_cur; long save_b_u_seq_cur; u_header_T *save_b_u_newhead; @@ -2131,6 +2132,7 @@ static void cmdpreview_prepare(CpInfo *cpinfo) CpBufInfo cp_bufinfo; cp_bufinfo.buf = buf; + cp_bufinfo.save_b_u_synced = buf->b_u_synced; cp_bufinfo.save_b_u_time_cur = buf->b_u_time_cur; cp_bufinfo.save_b_u_seq_cur = buf->b_u_seq_cur; cp_bufinfo.save_b_u_newhead = buf->b_u_newhead; @@ -2168,6 +2170,8 @@ static void cmdpreview_prepare(CpInfo *cpinfo) cmdmod.cmod_split = 0; // Disable :leftabove/botright modifiers cmdmod.cmod_tab = 0; // Disable :tab modifier cmdmod.cmod_flags |= CMOD_NOSWAPFILE; // Disable swap for preview buffer + + u_sync(true); } // Restore the state of buffers and windows before command preview. @@ -2200,6 +2204,11 @@ static void cmdpreview_restore_state(CpInfo *cpinfo) buf->b_u_newhead = cp_bufinfo.save_b_u_newhead; buf->b_u_time_cur = cp_bufinfo.save_b_u_time_cur; } + + if (buf->b_u_curhead == NULL) { + buf->b_u_synced = cp_bufinfo.save_b_u_synced; + } + if (cp_bufinfo.save_changedtick != buf_get_changedtick(buf)) { buf_set_changedtick(buf, cp_bufinfo.save_changedtick); } diff --git a/test/functional/ui/inccommand_spec.lua b/test/functional/ui/inccommand_spec.lua index 49b3c7a655..6fbf9b72c8 100644 --- a/test/functional/ui/inccommand_spec.lua +++ b/test/functional/ui/inccommand_spec.lua @@ -3047,6 +3047,43 @@ it(":substitute doesn't crash with inccommand, if undo is empty #12932", functio assert_alive() end) +it(':substitute with inccommand works properly if undo is not synced #20029', function() + local screen = Screen.new(30, 6) + clear() + common_setup(screen, 'nosplit', 'foo\nbar\nbaz') + meths.set_keymap('x', '', '``>obbbbb asdfV`lljj') + screen:expect([[ + aaaaa | + foo | + bar | + baz | + bbbbb | + :'<,'>s/asdf/^ | + ]]) + feed('hjkl') + screen:expect([[ + aaaaa {12:hjkl} | + foo | + bar | + baz | + bbbbb {12:hjkl} | + :'<,'>s/asdf/hjkl^ | + ]]) + feed('') + expect([[ + aaaaa hjkl + foo + bar + baz + bbbbb hjkl]]) + feed('u') + expect([[ + foo + bar + baz]]) +end) + it('long :%s/ with inccommand does not collapse cmdline', function() local screen = Screen.new(10,5) clear() -- cgit From ac66f5af06ac1f306b0ddb366ba81093508546c4 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 26 Sep 2022 07:15:07 +0800 Subject: fix!: make :undo! notify buffer update callbacks (#20344) When :undo! was introduced to Nvim the implementation of 'inccommand' preview callback hasn't been fully decided yet, so not notifying buffer update callbacks made sense for 'inccommand' preview callback in case it needs to undo the changes itself. Now it turns out that the undo-and-forget is done automatically for 'inccommand', so it doesn't make sense for :undo! to avoid notifying buffer update callbacks anymore. --- src/nvim/ex_docmd.c | 4 ++-- src/nvim/ex_getln.c | 2 +- src/nvim/undo.c | 8 ++++---- test/functional/lua/buffer_updates_spec.lua | 18 ++++++++++++++++++ 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 085948f7b1..7ece195374 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -5867,7 +5867,7 @@ static void ex_undo(exarg_T *eap) { if (eap->addr_count != 1) { if (eap->forceit) { - u_undo_and_forget(1); // :undo! + u_undo_and_forget(1, true); // :undo! } else { u_undo(1); // :undo } @@ -5894,7 +5894,7 @@ static void ex_undo(exarg_T *eap) emsg(_(e_undobang_cannot_redo_or_move_branch)); return; } - u_undo_and_forget(count); + u_undo_and_forget(count, true); } else { // :undo 123 undo_time(step, false, false, true); } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 0ccc12c9b4..bc31f5a6cf 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -2194,7 +2194,7 @@ static void cmdpreview_restore_state(CpInfo *cpinfo) aco_save_T aco; aucmd_prepbuf(&aco, buf); // Undo invisibly. This also moves the cursor! - if (!u_undo_and_forget(count)) { + if (!u_undo_and_forget(count, false)) { abort(); } aucmd_restbuf(&aco); diff --git a/src/nvim/undo.c b/src/nvim/undo.c index d67863f84f..1a9066d7f1 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -1771,16 +1771,16 @@ void u_redo(int count) /// Undo and remove the branch from the undo tree. /// Also moves the cursor (as a "normal" undo would). -bool u_undo_and_forget(int count) +/// +/// @param do_buf_event If `true`, send the changedtick with the buffer updates +bool u_undo_and_forget(int count, bool do_buf_event) { if (curbuf->b_u_synced == false) { u_sync(true); count = 1; } undo_undoes = true; - u_doit(count, true, - // Don't send nvim_buf_lines_event for u_undo_and_forget(). - false); + u_doit(count, true, do_buf_event); if (curbuf->b_u_curhead == NULL) { // nothing was undone. diff --git a/test/functional/lua/buffer_updates_spec.lua b/test/functional/lua/buffer_updates_spec.lua index 10de45274c..c6c0964ddb 100644 --- a/test/functional/lua/buffer_updates_spec.lua +++ b/test/functional/lua/buffer_updates_spec.lua @@ -118,6 +118,24 @@ describe('lua buffer event callbacks: on_lines', function() } tick = tick + 1 + tick = tick + 1 + command('redo') + check_events { + { "test1", "lines", 1, tick, 3, 5, 4, 32 }; + { "test2", "lines", 1, tick, 3, 5, 4, 32 }; + { "test2", "changedtick", 1, tick+1 }; + } + tick = tick + 1 + + tick = tick + 1 + command('undo!') + check_events { + { "test1", "lines", 1, tick, 3, 4, 5, 13 }; + { "test2", "lines", 1, tick, 3, 4, 5, 13 }; + { "test2", "changedtick", 1, tick+1 }; + } + tick = tick + 1 + -- simulate next callback returning true exec_lua("test_unreg = 'test1'") -- cgit From 9ffa041a9a5fc8cd9acca97cae16f66ba0c82805 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 26 Sep 2022 07:46:58 +0800 Subject: vim-patch:9.0.0586: missing change in test (#20347) Problem: Missing change in test. Solution: Add the test change. https://github.com/vim/vim/commit/124af71a28a633fa655cff41bc21d398481ce45f vim-patch:9.0.0585: when long message test fails the error message is not visible Problem: When long message test fails the error message is not visible. Solution: Dump more lines. https://github.com/vim/vim/commit/6a879878f4e1918a05244e6acd4c73c3135cf941 --- src/nvim/testdir/test_messages.vim | 7 +++---- test/functional/legacy/messages_spec.lua | 10 +++++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/nvim/testdir/test_messages.vim b/src/nvim/testdir/test_messages.vim index 2672fcb69d..8e66a2c529 100644 --- a/src/nvim/testdir/test_messages.vim +++ b/src/nvim/testdir/test_messages.vim @@ -357,15 +357,14 @@ func Test_quit_long_message() let content =<< trim END echom range(9999)->join("\x01") END - call writefile(content, 'Xtest_quit_message') - let buf = RunVimInTerminal('-S Xtest_quit_message', #{rows: 6, wait_for_ruler: 0}) - call WaitForAssert({-> assert_match('^-- More --', term_getline(buf, 6))}) + call writefile(content, 'Xtest_quit_message', 'D') + let buf = RunVimInTerminal('-S Xtest_quit_message', #{rows: 10, wait_for_ruler: 0}) + call WaitForAssert({-> assert_match('^-- More --', term_getline(buf, 10))}) call term_sendkeys(buf, "q") call VerifyScreenDump(buf, 'Test_quit_long_message', {}) " clean up call StopVimInTerminal(buf) - call delete('Xtest_quit_message') endfunc " this was missing a terminating NUL diff --git a/test/functional/legacy/messages_spec.lua b/test/functional/legacy/messages_spec.lua index c76ce62ef0..5b671bbfdf 100644 --- a/test/functional/legacy/messages_spec.lua +++ b/test/functional/legacy/messages_spec.lua @@ -352,7 +352,7 @@ describe('messages', function() -- oldtest: Test_quit_long_message() it('with control characters can be quit vim-patch:8.2.1844', function() - screen:try_resize(40, 6) + screen:try_resize(40, 10) feed([[:echom range(9999)->join("\x01")]]) screen:expect([[ 0{3:^A}1{3:^A}2{3:^A}3{3:^A}4{3:^A}5{3:^A}6{3:^A}7{3:^A}8{3:^A}9{3:^A}10{3:^A}11{3:^A}12| @@ -360,6 +360,10 @@ describe('messages', function() {3:^A}23{3:^A}24{3:^A}25{3:^A}26{3:^A}27{3:^A}28{3:^A}29{3:^A}30{3:^A}31{3:^A}32| {3:^A}33{3:^A}34{3:^A}35{3:^A}36{3:^A}37{3:^A}38{3:^A}39{3:^A}40{3:^A}41{3:^A}42| {3:^A}43{3:^A}44{3:^A}45{3:^A}46{3:^A}47{3:^A}48{3:^A}49{3:^A}50{3:^A}51{3:^A}52| + {3:^A}53{3:^A}54{3:^A}55{3:^A}56{3:^A}57{3:^A}58{3:^A}59{3:^A}60{3:^A}61{3:^A}62| + {3:^A}63{3:^A}64{3:^A}65{3:^A}66{3:^A}67{3:^A}68{3:^A}69{3:^A}70{3:^A}71{3:^A}72| + {3:^A}73{3:^A}74{3:^A}75{3:^A}76{3:^A}77{3:^A}78{3:^A}79{3:^A}80{3:^A}81{3:^A}82| + {3:^A}83{3:^A}84{3:^A}85{3:^A}86{3:^A}87{3:^A}88{3:^A}89{3:^A}90{3:^A}91{3:^A}92| {1:-- More --}^ | ]]) feed('q') @@ -368,6 +372,10 @@ describe('messages', function() {0:~ }| {0:~ }| {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| {0:~ }| | ]]) -- cgit From 63be7651829f8b77c4974d08ebe09f7775e41a8a Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 25 Sep 2022 19:58:27 -0400 Subject: fix(docs): invalid :help links #20345 Fix those naughty single quotes. closes #20159 --- runtime/doc/api.txt | 38 ++--- runtime/doc/autocmd.txt | 6 +- runtime/doc/builtin.txt | 32 ++-- runtime/doc/cmdline.txt | 2 +- runtime/doc/ft_ada.txt | 30 ++-- runtime/doc/ft_rust.txt | 8 +- runtime/doc/ft_sql.txt | 2 +- runtime/doc/help.txt | 1 - runtime/doc/index.txt | 23 ++- runtime/doc/insert.txt | 4 +- runtime/doc/lsp.txt | 75 ++++---- runtime/doc/lua.txt | 26 +-- runtime/doc/luaref.txt | 323 ++++++++++++++--------------------- runtime/doc/map.txt | 2 +- runtime/doc/mbyte.txt | 5 +- runtime/doc/options.txt | 6 +- runtime/doc/pi_netrw.txt | 14 +- runtime/doc/print.txt | 2 +- runtime/doc/provider.txt | 2 +- runtime/doc/quickfix.txt | 6 +- runtime/doc/quickref.txt | 7 - runtime/doc/repeat.txt | 2 +- runtime/doc/starting.txt | 2 - runtime/doc/syntax.txt | 16 +- runtime/doc/treesitter.txt | 16 +- runtime/doc/ui.txt | 4 +- runtime/doc/userfunc.txt | 5 +- runtime/doc/usr_41.txt | 2 +- runtime/doc/usr_45.txt | 3 +- runtime/doc/vim_diff.txt | 33 ++-- runtime/lua/vim/_editor.lua | 4 +- runtime/lua/vim/highlight.lua | 2 +- runtime/lua/vim/lsp.lua | 22 +-- runtime/lua/vim/lsp/buf.lua | 14 +- runtime/lua/vim/lsp/handlers.lua | 2 +- runtime/lua/vim/lsp/rpc.lua | 2 +- runtime/lua/vim/lsp/util.lua | 6 +- runtime/lua/vim/shared.lua | 2 +- runtime/lua/vim/treesitter/query.lua | 8 +- src/nvim/api/autocmd.c | 8 +- src/nvim/api/extmark.c | 6 +- src/nvim/api/options.c | 4 +- src/nvim/api/vim.c | 14 +- src/nvim/api/win_config.c | 2 +- src/nvim/api/window.c | 2 +- src/nvim/mapping.c | 2 +- src/nvim/mapping.h | 2 +- 47 files changed, 363 insertions(+), 436 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 7e55bb8f4e..ec16d5c650 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -345,7 +345,7 @@ LUA ~ In-process Lua plugins can receive buffer updates in the form of Lua callbacks. These callbacks are called frequently in various contexts; |textlock| prevents changing buffer contents and window layout (use -|vim.schedule| to defer such operations to the main loop instead). +|vim.schedule()| to defer such operations to the main loop instead). |nvim_buf_attach()| will take keyword args for the callbacks. "on_lines" will receive parameters ("lines", {buf}, {changedtick}, {firstline}, {lastline}, @@ -989,7 +989,7 @@ nvim_get_proc_children({pid}) *nvim_get_proc_children()* nvim_get_runtime_file({name}, {all}) *nvim_get_runtime_file()* Find files in runtime directories - 'name' can contain wildcards. For example + "name" can contain wildcards. For example nvim_get_runtime_file("colors/*.vim", true) will return all color scheme files. Always use forward slashes (/) in the search pattern for subdirectories regardless of platform. @@ -1164,7 +1164,7 @@ nvim_open_term({buffer}, {opts}) *nvim_open_term()* terminal mode. Note: keypresses are sent raw as they would be to the pty master end. For instance, a carriage return is sent as a "\r", not as a "\n". |textlock| applies. It - is possible to call |nvim_chan_send| directly in the + is possible to call |nvim_chan_send()| directly in the callback however. ["input", term, bufnr, data] Return: ~ @@ -1396,15 +1396,15 @@ nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()* • link: name of another highlight group to link to, see |:hi-link|. • default: Don't override existing definition |:hi-default| - • ctermfg: Sets foreground of cterm color |highlight-ctermfg| - • ctermbg: Sets background of cterm color |highlight-ctermbg| + • ctermfg: Sets foreground of cterm color |ctermfg| + • ctermbg: Sets background of cterm color |ctermbg| • cterm: cterm attribute map, like |highlight-args|. If not set, cterm attributes will match those from the attribute map documented above. nvim_set_hl_ns({ns_id}) *nvim_set_hl_ns()* Set active namespace for highlights. This can be set for a single window, - see |nvim_win_set_hl_ns|. + see |nvim_win_set_hl_ns()|. Parameters: ~ {ns_id} the namespace to use @@ -1413,7 +1413,7 @@ nvim_set_hl_ns_fast({ns_id}) *nvim_set_hl_ns_fast()* Set active namespace for highlights while redrawing. This function meant to be called while redrawing, primarily from - |nvim_set_decoration_provider| on_win and on_line callbacks, which are + |nvim_set_decoration_provider()| on_win and on_line callbacks, which are allowed to change the namespace during a redraw cycle. Attributes: ~ @@ -1445,7 +1445,7 @@ nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()* {rhs} Right-hand-side |{rhs}| of the mapping. {opts} Optional parameters map: keys are |:map-arguments|, values are booleans (default false). Accepts all |:map-arguments| as keys - excluding || but including |noremap| and "desc". + excluding || but including |:noremap| and "desc". Unknown key is an error. "desc" can be used to give a description to the mapping. When called from Lua, also accepts a "callback" key that takes a Lua function to call when the @@ -1886,7 +1886,7 @@ nvim_get_all_options_info() *nvim_get_all_options_info()* Gets the option information for all options. The dictionary has the full option names as keys and option metadata - dictionaries as detailed at |nvim_get_option_info|. + dictionaries as detailed at |nvim_get_option_info()|. Return: ~ dictionary of all options @@ -1960,7 +1960,7 @@ nvim_set_option_value({name}, {value}, {*opts}) {name} Option name {value} New option value {opts} Optional parameters - • scope: One of 'global' or 'local'. Analogous to + • scope: One of "global" or "local". Analogous to |:setglobal| and |:setlocal|, respectively. • win: |window-ID|. Used for setting window local option. • buf: Buffer number. Used for setting buffer local option. @@ -2576,7 +2576,7 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) highlight groups that will be stacked (highest priority last). A highlight group can be supplied either as a string or as an integer, the latter which can be obtained - using |nvim_get_hl_id_by_name|. + using |nvim_get_hl_id_by_name()|. • virt_text_pos : position of virtual text. Possible values: • "eol": right after eol character (default) • "overlay": display over the specified column, without @@ -2608,7 +2608,7 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts}) • virt_lines_above: place virtual lines above instead. • virt_lines_leftcol: Place extmarks in the leftmost column of the window, bypassing sign and number columns. - • ephemeral : for use with |nvim_set_decoration_provider| + • 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. @@ -2686,7 +2686,7 @@ nvim_set_decoration_provider({ns_id}, {*opts}) 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 + |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 ). @@ -2844,7 +2844,7 @@ nvim_win_hide({window}) *nvim_win_hide()* Like |:hide| the buffer becomes hidden unless another window is editing it, or 'bufhidden' is `unload`, `delete` or `wipe` as opposed to |:close| - or |nvim_win_close|, which will close the buffer. + or |nvim_win_close()|, which will close the buffer. Attributes: ~ not allowed when |textlock| is active @@ -3012,7 +3012,7 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()* options. 'signcolumn' is changed to `auto` and 'colorcolumn' is cleared. The end-of-buffer region is hidden by setting `eob` flag of 'fillchars' to a space - char, and clearing the |EndOfBuffer| region in + char, and clearing the |hl-EndOfBuffer| region in 'winhighlight'. • border: Style of (optional) window border. This can either @@ -3148,7 +3148,7 @@ Autocmd Functions *api-autocmd* nvim_clear_autocmds({*opts}) *nvim_clear_autocmds()* Clear all autocommands that match the corresponding {opts}. To delete a - particular autocmd, see |nvim_del_autocmd|. + particular autocmd, see |nvim_del_autocmd()|. Parameters: ~ {opts} Parameters @@ -3295,7 +3295,7 @@ nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* To get a group id one can use |nvim_get_autocmds()|. - NOTE: behavior differs from |augroup-delete|. When deleting a group, + NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in this group will also be deleted and cleared. This group will no longer exist. @@ -3309,7 +3309,7 @@ nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()* nvim_del_augroup_by_name({name}) *nvim_del_augroup_by_name()* Delete an autocommand group by name. - NOTE: behavior differs from |augroup-delete|. When deleting a group, + NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in this group will also be deleted and cleared. This group will no longer exist. @@ -3317,7 +3317,7 @@ nvim_del_augroup_by_name({name}) *nvim_del_augroup_by_name()* {name} String The name of the group. See also: ~ - |autocommand-groups| + |autocmd-groups| nvim_del_autocmd({id}) *nvim_del_autocmd()* Delete an autocommand by id. diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt index e55534b163..97a1bdc134 100644 --- a/runtime/doc/autocmd.txt +++ b/runtime/doc/autocmd.txt @@ -835,13 +835,13 @@ QuitPre When using `:quit`, `:wq` or `:qall`, before See also |ExitPre|, |WinClosed|. *RemoteReply* RemoteReply When a reply from a Vim that functions as - server was received |server2client()|. The + server was received server2client(). The pattern is matched against the {serverid}. is equal to the {serverid} from which the reply was sent, and is the actual reply string. Note that even if an autocommand is defined, - the reply should be read with |remote_read()| + the reply should be read with remote_read() to consume it. *SearchWrapped* SearchWrapped After making a search with |n| or |N| if the @@ -1206,7 +1206,7 @@ still executed. ============================================================================== 7. Buffer-local autocommands *autocmd-buflocal* *autocmd-buffer-local* - ** ** *E680* + ** ** ** *E680* Buffer-local autocommands are attached to a specific buffer. They are useful if the buffer does not have a name and when the name does not match a specific diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 7b1a50c1fb..77b85406b9 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -1537,7 +1537,7 @@ cursor({list}) debugbreak({pid}) *debugbreak()* Specifically used to interrupt a program being debugged. It will cause process {pid} to get a SIGTRAP. Behavior for other - processes is undefined. See |terminal-debugger|. + processes is undefined. See |terminal-debug|. {Sends a SIGINT to a process {pid} other than MS-Windows} Returns |TRUE| if successfully interrupted the program. @@ -3289,18 +3289,18 @@ getmatches([{win}]) *getmatches()* an empty list is returned. Example: > :echo getmatches() -< [{'group': 'MyGroup1', 'pattern': 'TODO', - 'priority': 10, 'id': 1}, {'group': 'MyGroup2', - 'pattern': 'FIXME', 'priority': 10, 'id': 2}] > +< [{"group": "MyGroup1", "pattern": "TODO", + "priority": 10, "id": 1}, {"group": "MyGroup2", + "pattern": "FIXME", "priority": 10, "id": 2}] > :let m = getmatches() :call clearmatches() :echo getmatches() < [] > :call setmatches(m) :echo getmatches() -< [{'group': 'MyGroup1', 'pattern': 'TODO', - 'priority': 10, 'id': 1}, {'group': 'MyGroup2', - 'pattern': 'FIXME', 'priority': 10, 'id': 2}] > +< [{"group": "MyGroup1", "pattern": "TODO", + "priority": 10, "id": 1}, {"group": "MyGroup2", + "pattern": "FIXME", "priority": 10, "id": 2}] > :unlet m < getmousepos() *getmousepos()* @@ -3499,7 +3499,7 @@ getreginfo([{regname}]) *getreginfo()* Dictionary with the following entries: regcontents List of lines contained in register {regname}, like - |getreg|({regname}, 1, 1). + getreg({regname}, 1, 1). regtype the type of register {regname}, as in |getregtype()|. isunnamed Boolean flag, v:true if this register @@ -4415,7 +4415,7 @@ jobstart({cmd} [, {opts}]) *jobstart()* killed when Nvim exits. If the process exits before Nvim, `on_exit` will be invoked. env: (dict) Map of environment variable name:value - pairs extending (or replacing with |clear_env|) + pairs extending (or replace with "clear_env") the current environment. |jobstart-env| height: (number) Height of the `pty` terminal. |on_exit|: (function) Callback invoked when the job exits. @@ -5209,12 +5209,12 @@ matchfuzzypos({list}, {str} [, {dict}]) *matchfuzzypos()* Example: > :echo matchfuzzypos(['testing'], 'tsg') -< results in [['testing'], [[0, 2, 6]], [99]] > +< results in [["testing"], [[0, 2, 6]], [99]] > :echo matchfuzzypos(['clay', 'lacy'], 'la') -< results in [['lacy', 'clay'], [[0, 1], [1, 2]], [153, 133]] > +< results in [["lacy", "clay"], [[0, 1], [1, 2]], [153, 133]] > :echo [{'text': 'hello', 'id' : 10}] \ ->matchfuzzypos('ll', {'key' : 'text'}) -< results in [[{'id': 10, 'text': 'hello'}], [[2, 3]], [127]] +< results in [[{"id": 10, "text": "hello"}], [[2, 3]], [127]] matchlist({expr}, {pat} [, {start} [, {count}]]) *matchlist()* Same as |match()|, but return a |List|. The first item in the @@ -8247,7 +8247,7 @@ synIDattr({synID}, {what} [, {mode}]) *synIDattr()* "bg" background color (as with "fg") "font" font name (only available in the GUI) |highlight-font| - "sp" special color (as with "fg") |highlight-guisp| + "sp" special color (as with "fg") |guisp| "fg#" like "fg", but for the GUI and the GUI is running the name in "#RRGGBB" form "bg#" like "fg#" for "bg" @@ -9106,12 +9106,12 @@ winlayout([{tabnr}]) *winlayout()* returns an empty list. For a leaf window, it returns: - ['leaf', {winid}] + ["leaf", {winid}] For horizontally split windows, which form a column, it returns: - ['col', [{nested list of windows}]] + ["col", [{nested list of windows}]] For vertically split windows, which form a row, it returns: - ['row', [{nested list of windows}]] + ["row", [{nested list of windows}]] Example: > " Only one window in the tab page diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt index f19671e713..b1013420fa 100644 --- a/runtime/doc/cmdline.txt +++ b/runtime/doc/cmdline.txt @@ -764,7 +764,7 @@ Count and Range *N:* When giving a count before entering ":", this is translated into: :.,.+(count - 1) -In words: The 'count' lines at and after the cursor. Example: To delete +In words: The "count" lines at and after the cursor. Example: To delete three lines: > 3:d is translated into: .,.+2d < diff --git a/runtime/doc/ft_ada.txt b/runtime/doc/ft_ada.txt index f6dfa708fb..fa069057c4 100644 --- a/runtime/doc/ft_ada.txt +++ b/runtime/doc/ft_ada.txt @@ -288,7 +288,7 @@ g:ada_rainbow_color bool (true when exists) rainbow_parenthesis for this to work. *g:ada_folding* -g:ada_folding set ('sigpft') +g:ada_folding set ("sigpft") Use folding for Ada sources. 's': activate syntax folding on load 'p': fold packages @@ -296,10 +296,10 @@ g:ada_folding set ('sigpft') 't': fold types 'c': fold conditionals 'g': activate gnat pretty print folding on load - 'i': lone 'is' folded with line above - 'b': lone 'begin' folded with line above - 'p': lone 'private' folded with line above - 'x': lone 'exception' folded with line above + 'i': lone "is" folded with line above + 'b': lone "begin" folded with line above + 'p': lone "private" folded with line above + 'x': lone "exception" folded with line above 'i': activate indent folding on load Note: Syntax folding is in an early (unusable) stage and @@ -334,10 +334,10 @@ g:ada_omni_with_keywords completion (|i_CTRL-X_CTRL-U|). *g:ada_extended_tagging* -g:ada_extended_tagging enum ('jump', 'list') +g:ada_extended_tagging enum ("jump", "list") use extended tagging, two options are available - 'jump': use tjump to jump. - 'list': add tags quick fix list. + "jump": use tjump to jump. + "list": add tags quick fix list. Normal tagging does not support function or operator overloading as these features are not available in C and tagging was originally developed for C. @@ -359,8 +359,8 @@ g:ada_with_gnat_project_files bool (true when exists) *g:ada_default_compiler* g:ada_default_compiler string - set default compiler. Currently supported are 'gnat' and - 'decada'. + set default compiler. Currently supported are "gnat" and + "decada". An "exists" type is a boolean considered true when the variable is defined and false when the variable is undefined. The value to which the variable is set @@ -406,14 +406,14 @@ makes no difference. g:gnat object Control object which manages GNAT compiles. The object is created when the first Ada source code is loaded provided - that |g:ada_default_compiler| is set to 'gnat'. See + that |g:ada_default_compiler| is set to "gnat". See |gnat_members| for details. *g:decada* g:decada object Control object which manages Dec Ada compiles. The object is created when the first Ada source code is loaded provided - that |g:ada_default_compiler| is set to 'decada'. See + that |g:ada_default_compiler| is set to "decada". See |decada_members| for details. ------------------------------------------------------------------------------ @@ -459,11 +459,11 @@ ada#List_Tag([{line}, {col}]) *ada#Listtags()* ada#Jump_Tag ({ident}, {mode}) *ada#Jump_Tag()* List all occurrences of the Ada entity under the cursor (or at given line/column) in the tag jump list. Mode can either be - 'tjump' or 'stjump'. + "tjump" or "stjump". ada#Create_Tags ({option}) *ada#Create_Tags()* - Creates tag file using Ctags. The option can either be 'file' - for the current file, 'dir' for the directory of the current + Creates tag file using Ctags. The option can either be "file" + for the current file, "dir" for the directory of the current file or a file name. gnat#Insert_Tags_Header() *gnat#Insert_Tags_Header()* diff --git a/runtime/doc/ft_rust.txt b/runtime/doc/ft_rust.txt index 5c8782ec7a..34932c48fb 100644 --- a/runtime/doc/ft_rust.txt +++ b/runtime/doc/ft_rust.txt @@ -92,8 +92,8 @@ g:ftplugin_rust_source_path~ *g:rustfmt_command* g:rustfmt_command~ - Set this option to the name of the 'rustfmt' executable in your $PATH. If - not specified it defaults to 'rustfmt' : > + Set this option to the name of the "rustfmt" executable in your $PATH. If + not specified it defaults to "rustfmt" : > let g:rustfmt_command = 'rustfmt' < *g:rustfmt_autosave* @@ -104,14 +104,14 @@ g:rustfmt_autosave~ < *g:rustfmt_fail_silently* g:rustfmt_fail_silently~ - Set this option to 1 to prevent 'rustfmt' from populating the + Set this option to 1 to prevent "rustfmt" from populating the |location-list| with errors. If not specified it defaults to 0: > let g:rustfmt_fail_silently = 0 < *g:rustfmt_options* g:rustfmt_options~ Set this option to a string of options to pass to 'rustfmt'. The - write-mode is already set to 'overwrite'. If not specified it + write-mode is already set to "overwrite". If not specified it defaults to '' : > let g:rustfmt_options = '' < diff --git a/runtime/doc/ft_sql.txt b/runtime/doc/ft_sql.txt index 335faf266e..685726de90 100644 --- a/runtime/doc/ft_sql.txt +++ b/runtime/doc/ft_sql.txt @@ -244,7 +244,7 @@ key to complete the optional parameter. After typing the function name and a space, you can use the completion to supply a parameter. The function takes the name of the Vim script you want to source. Using the |cmdline-completion| feature, the SQLSetType function will -search the |'runtimepath'| for all Vim scripts with a name containing 'sql'. +search the |'runtimepath'| for all Vim scripts with a name containing "sql". This takes the guess work out of the spelling of the names. The following are examples: > :SQLSetType diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt index 34213f7512..a1bedfa500 100644 --- a/runtime/doc/help.txt +++ b/runtime/doc/help.txt @@ -98,7 +98,6 @@ General subjects ~ |help.txt| overview and quick reference (this file) |helphelp.txt| about using the help files |index.txt| alphabetical index of all commands -|help-tags| all the tags you can jump to (index of tags) |tips.txt| various tips on using Vim |message.txt| (error) messages and explanations |develop.txt| development of Nvim diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt index 7f3ef20762..f9ef99f819 100644 --- a/runtime/doc/index.txt +++ b/runtime/doc/index.txt @@ -13,7 +13,6 @@ to look for deleting something, use: "/delete". For an overview of options see |option-list|. For an overview of built-in functions see |functions|. For a list of Vim variables see |vim-variable|. -For a complete listing of all help items see |help-tags|. Type |gO| to see the table of contents. @@ -61,7 +60,7 @@ tag char action in Insert mode ~ |i_CTRL-Q| CTRL-Q same as CTRL-V, unless used for terminal control flow |i_CTRL-SHIFT-Q| CTRL-SHIFT-Q {char} - like CTRL-Q unless |modifyOtherKeys| is active + like CTRL-Q unless |tui-modifyOtherKeys| is active |i_CTRL-R| CTRL-R {register} insert the contents of a register |i_CTRL-R_CTRL-R| CTRL-R CTRL-R {register} @@ -79,7 +78,7 @@ tag char action in Insert mode ~ line |i_CTRL-V| CTRL-V {char} insert next non-digit literally |i_CTRL-SHIFT-V| CTRL-SHIFT-V {char} - like CTRL-V unless |modifyOtherKeys| is active + like CTRL-V unless |tui-modifyOtherKeys| is active |i_CTRL-V_digit| CTRL-V {number} insert three digit decimal number as a single byte. |i_CTRL-W| CTRL-W delete word before the cursor @@ -454,14 +453,14 @@ tag char note action in Normal mode ~ || 1 same as CTRL-B || 2 same as "u" || 1 same as "k" -|| move window three lines down -|| move window one page down -|| move window three lines up -|| move window one page up -|| move window six columns left -|| move window one page left -|| move window six columns right -|| move window one page right +** move window three lines down +** move window one page down +** move window three lines up +** move window one page up +** move window six columns left +** move window one page left +** move window six columns right +** move window one page right ============================================================================== 2.1 Text objects *objects* @@ -700,7 +699,7 @@ tag char note action in Normal mode ~ tag char note action in Normal mode ~ ------------------------------------------------------------------------------ -|g_CTRL-A| g CTRL-A dump a memory profile +g_CTRL-A g CTRL-A dump a memory profile |g_CTRL-G| g CTRL-G show information about current cursor position |g_CTRL-H| g CTRL-H start Select block mode diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt index 6b0899334b..f4ef8e65c4 100644 --- a/runtime/doc/insert.txt +++ b/runtime/doc/insert.txt @@ -1519,7 +1519,7 @@ RUBY *ft-ruby-omni* NOTE: |compl-omni| for Ruby code requires |provider-ruby| to be installed. Ruby completion will parse your buffer on demand in order to provide a list of -completions. These completions will be drawn from modules loaded by 'require' +completions. These completions will be drawn from modules loaded by "require" and modules defined in the current buffer. The completions provided by CTRL-X CTRL-O are sensitive to the context: @@ -1759,7 +1759,7 @@ In the example four special elements are visible: dialect. 2. If the list containing possible values of attributes has one element and this element is equal to the name of the attribute this attribute will be - treated as boolean and inserted as 'attrname' and not as 'attrname="' + treated as boolean and inserted as "attrname" and not as 'attrname="' 3. "vimxmltaginfo" - a special key with a Dictionary containing tag names as keys and two element List as values, for additional menu info and the long description. diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt index 00aaf759e2..26bca21507 100644 --- a/runtime/doc/lsp.txt +++ b/runtime/doc/lsp.txt @@ -40,7 +40,7 @@ Follow these steps to get LSP features: root_dir = vim.fs.dirname(vim.fs.find({'setup.py', 'pyproject.toml'}, { upward = true })[1]), }) < - See |vim.lsp.start| for details. + See |vim.lsp.start()| for details. 3. Configure keymaps and autocmds to utilize LSP features. See |lsp-config|. @@ -48,19 +48,19 @@ Follow these steps to get LSP features: *lsp-config* Starting a LSP client will automatically report diagnostics via -|vim.diagnostic|. Read |vim.diagnostic.config| to learn how to customize the +|vim.diagnostic|. Read |vim.diagnostic.config()| to learn how to customize the display. It also sets some buffer options if the options are otherwise empty and if the language server supports the functionality. -- |omnifunc| is set to |vim.lsp.omnifunc|. This allows to trigger completion - using |i_CTRL-X_CTRL-o| -- |tagfunc| is set to |vim.lsp.tagfunc|. This enables features like +- 'omnifunc' is set to |vim.lsp.omnifunc()|. This allows to trigger completion + using |i_CTRL-X_CTRL-O| +- 'tagfunc' is set to |vim.lsp.tagfunc()|. This enables features like go-to-definition, |:tjump|, and keymaps like |CTRL-]|, |CTRL-W_]|, |CTRL-W_}| to utilize the language server. -- |formatexpr| is set to |vim.lsp.formatexpr| if both |formatprg| and - |formatexpr| are empty. This allows to format lines via |gq| if the language +- 'formatexpr' is set to |vim.lsp.formatexpr()| if both 'formatprg' and + 'formatexpr' are empty. This allows to format lines via |gq| if the language server supports it. To use other LSP features like hover, rename, etc. you can setup some @@ -245,7 +245,7 @@ For |lsp-request|, each |lsp-handler| has this signature: > Where `err` must be shaped like an RPC error: `{ code, message, data? }` - You can use |vim.lsp.rpc_response_error()| to create this object. + You can use |vim.lsp.rpc.rpc_response_error()| to create this object. For |lsp-notification|, each |lsp-handler| has this signature: > @@ -338,8 +338,8 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method } < Some handlers do not have an explicitly named handler function (such as - |on_publish_diagnostics()|). To override these, first create a reference - to the existing handler: > + ||vim.lsp.diagnostic.on_publish_diagnostics()|). To override these, first + create a reference to the existing handler: > local on_references = vim.lsp.handlers["textDocument/references"] vim.lsp.handlers["textDocument/references"] = vim.lsp.with( @@ -360,7 +360,7 @@ Handlers can be set by: vim.lsp.handlers["textDocument/definition"] = my_custom_default_definition < -- The {handlers} parameter for |vim.lsp.start_client|. +- The {handlers} parameter for |vim.lsp.start_client()|. This will set the |lsp-handler| as the default handler for this server. For example: > @@ -514,7 +514,7 @@ callback in the "data" table. Example: > end, }) < -In addition, the following |User| |autocommands| are provided: +Also the following |User| |autocommand|s are provided: LspProgressUpdate *LspProgressUpdate* Upon receipt of a progress notification from the server. See @@ -788,7 +788,8 @@ start({config}, {opts}) *vim.lsp.start()* }) < - See |lsp.start_client| for all available options. The most important are: + See |vim.lsp.start_client()| for all available options. The most important + are: `name` is an arbitrary name for the LSP client. It should be unique per language server. @@ -798,9 +799,9 @@ start({config}, {opts}) *vim.lsp.start()* constructs like `~` are NOT expanded. `root_dir` path to the project root. By default this is used to decide if - an existing client should be re-used. The example above uses |vim.fs.find| - and |vim.fs.dirname| to detect the root by traversing the file system - upwards starting from the current directory until either a + an existing client should be re-used. The example above uses + |vim.fs.find()| and |vim.fs.dirname()| to detect the root by traversing + the file system upwards starting from the current directory until either a `pyproject.toml` or `setup.py` file is found. `workspace_folders` a list of { uri:string, name: string } tables. The @@ -812,13 +813,13 @@ start({config}, {opts}) *vim.lsp.start()* the project folder. To ensure a language server is only started for languages it can handle, - make sure to call |vim.lsp.start| within a |FileType| autocmd. Either use - |:au|, |nvim_create_autocmd()| or put the call in a + make sure to call |vim.lsp.start()| within a |FileType| autocmd. Either + use |:au|, |nvim_create_autocmd()| or put the call in a `ftplugin/.lua` (See |ftplugin-name|) Parameters: ~ {config} (table) Same configuration as documented in - |lsp.start_client()| + |vim.lsp.start_client()| {opts} nil|table Optional keyword arguments: • reuse_client (fun(client: client, config: table): boolean) Predicate used to decide if a client should be re-used. @@ -837,15 +838,16 @@ start_client({config}) *vim.lsp.start_client()* Parameters: ~ {cmd} (table|string|fun(dispatchers: table):table) - command string or list treated like |jobstart|. + command string or list treated like |jobstart()|. The command must launch the language server process. `cmd` can also be a function that creates an RPC client. The function receives a dispatchers table and must return a table with the functions `request`, `notify`, `is_closing` - and `terminate` See |vim.lsp.rpc.request| and - |vim.lsp.rpc.notify| For TCP there is a built-in - rpc client factory: |vim.lsp.rpc.connect| + and `terminate` See |vim.lsp.rpc.request()| and + |vim.lsp.rpc.notify()| For TCP there is a + built-in rpc client factory: + |vim.lsp.rpc.connect()| {cmd_cwd} (string, default=|getcwd()|) Directory to launch the `cmd` process. Not related to `root_dir`. {cmd_env} (table) Environment flags to pass to the LSP on @@ -900,7 +902,7 @@ start_client({config}) *vim.lsp.start_client()* when the client operation throws an error. `code` is a number describing the error. Other arguments may be passed depending on the error kind. See - |vim.lsp.rpc.client_errors| for possible errors. + `vim.lsp.rpc.client_errors` for possible errors. Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name. {before_init} Callback with parameters (initialize_params, @@ -945,9 +947,9 @@ start_client({config}) *vim.lsp.start_client()* debounce occurs if nil • exit_timeout (number|boolean, default false): Milliseconds to wait for server to exit cleanly - after sending the 'shutdown' request before + after sending the "shutdown" request before sending kill -15. If set to false, nvim exits - immediately after sending the 'shutdown' + immediately after sending the "shutdown" request to the server. {root_dir} (string) Directory where the LSP server will base its workspaceFolders, rootUri, and rootPath on @@ -1047,7 +1049,7 @@ completion({context}) *vim.lsp.buf.completion()* character, if applicable) See also: ~ - |vim.lsp.protocol.constants.CompletionTriggerKind| + vim.lsp.protocol.constants.CompletionTriggerKind declaration({options}) *vim.lsp.buf.declaration()* Jumps to the declaration of the symbol under the cursor. @@ -1084,7 +1086,8 @@ document_highlight() *vim.lsp.buf.document_highlight()* Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups to be defined or you won't be able to see the actual - highlights. |LspReferenceText| |LspReferenceRead| |LspReferenceWrite| + highlights. |hl-LspReferenceText| |hl-LspReferenceRead| + |hl-LspReferenceWrite| document_symbol({options}) *vim.lsp.buf.document_symbol()* Lists all symbols in the current buffer in the quickfix window. @@ -1193,7 +1196,7 @@ formatting_sync({options}, {timeout_ms}) {timeout_ms} (number) Request timeout See also: ~ - |vim.lsp.buf.formatting_seq_sync| + |vim.lsp.buf.format()| hover() *vim.lsp.buf.hover()* Displays hover information about the symbol under the cursor in a floating @@ -1211,7 +1214,7 @@ implementation({options}) *vim.lsp.buf.implementation()* incoming_calls() *vim.lsp.buf.incoming_calls()* Lists all the call sites of the symbol under the cursor in the |quickfix| window. If the symbol can resolve to multiple items, the user can pick one - in the |inputlist|. + in the |inputlist()|. list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* List workspace folders. @@ -1219,7 +1222,7 @@ list_workspace_folders() *vim.lsp.buf.list_workspace_folders()* outgoing_calls() *vim.lsp.buf.outgoing_calls()* Lists all the items that are called by the symbol under the cursor in the |quickfix| window. If the symbol can resolve to multiple items, the user - can pick one in the |inputlist|. + can pick one in the |inputlist()|. *vim.lsp.buf.range_code_action()* range_code_action({context}, {start_pos}, {end_pos}) @@ -1434,7 +1437,7 @@ signature_help({_}, {result}, {ctx}, {config}) {config} (table) Configuration table. • border: (default=nil) • Add borders to the floating window - • See |vim.api.nvim_open_win()| + • See |nvim_open_win()| ============================================================================== @@ -1565,7 +1568,7 @@ get_effective_tabstop({bufnr}) *vim.lsp.util.get_effective_tabstop()* (number) indentation size See also: ~ - |shiftwidth| + 'shiftwidth' *vim.lsp.util.jump_to_location()* jump_to_location({location}, {offset_encoding}, {reuse_win}) @@ -1722,7 +1725,7 @@ open_floating_preview({contents}, {syntax}, {opts}) {contents} (table) of lines to show in window {syntax} (string) of syntax to set for opened buffer {opts} (table) with optional fields (additional keys are passed - on to |vim.api.nvim_open_win()|) + on to |nvim_open_win()|) • height: (number) height of floating window • width: (number) width of floating window • wrap: (boolean, default true) wrap long lines @@ -1859,7 +1862,7 @@ try_trim_markdown_code_blocks({lines}) {lines} (table) list of lines Return: ~ - (string) filetype or 'markdown' if it was unchanged. + (string) filetype or "markdown" if it was unchanged. ============================================================================== @@ -1964,7 +1967,7 @@ start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params}) Starts an LSP server process and create an LSP RPC client object to interact with it. Communication with the spawned process happens via stdio. For communication via TCP, spawn a process manually and use - |vim.lsp.rpc.connect| + |vim.lsp.rpc.connect()| Parameters: ~ {cmd} (string) Command to start the LSP server. diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 88547edfe5..0c6eb6af78 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -285,7 +285,7 @@ These commands execute a Lua chunk from either the command line (:lua, :luado) or a file (:luafile) on the given line [range]. As always in Lua, each chunk has its own scope (closure), so only global variables are shared between command calls. The |lua-stdlib| modules, user modules, and anything else on -|lua-package-path| are available. +|package.path| are available. The Lua print() function redirects its output to the Nvim message area, with arguments separated by " " (space) instead of "\t" (tab). @@ -617,7 +617,7 @@ A subset of the `vim.*` API is available in threads. This includes: - `vim.loop` with a separate event loop per thread. - `vim.mpack` and `vim.json` (useful for serializing messages between threads) -- `require` in threads can use lua packages from the global |lua-package-path| +- `require` in threads can use lua packages from the global |package.path| - `print()` and `vim.inspect` - `vim.diff` - most utility functions in `vim.*` for working with pure lua values @@ -663,7 +663,7 @@ vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts}) {finish} finish position (tuple {line,col}) {opts} optional parameters: • `regtype`: type of range (characterwise, linewise, - or blockwise, see |setreg|), default `'v'` + or blockwise, see |setreg()|), default `'v'` • `inclusive`: range includes end position, default `false` • `priority`: priority of highlight, default @@ -906,7 +906,7 @@ vim.defer_fn({fn}, {timeout}) *vim.defer_fn* Defers calling {fn} until {timeout} ms passes. Use to do a one-shot timer that calls {fn}. - Note: The {fn} is |schedule_wrap|ped automatically, so API functions are + Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are safe to call. Parameters: ~ @@ -1160,7 +1160,7 @@ window-scoped options. Note that this must NOT be confused with global value of a |global-local| option, see |:setglobal|. vim.o *vim.o* - Get or set an |option|. Like `:set`. Invalid key is an error. + Get or set |options|. Like `:set`. Invalid key is an error. Note: this works on both buffer-scoped and window-scoped options using the current buffer and window. @@ -1171,7 +1171,7 @@ vim.o *vim.o* print(vim.o.foo) -- error: invalid key < vim.go *vim.go* - Get or set a global |option|. Like `:setglobal`. Invalid key is + Get or set global |options|. Like `:setglobal`. Invalid key is an error. Note: this is different from |vim.o| because this accesses the global @@ -1260,7 +1260,7 @@ offers object-oriented method for adding and removing entries. Note that |vim.opt| returns an `Option` object, not the value of the option, -which is accessed through |Option:get()|: +which is accessed through |vim.opt:get()|: Examples: ~ @@ -1275,8 +1275,8 @@ which is accessed through |Option:get()|: `vim.pretty_print(vim.opt.wildignore:get())` -In any of the above examples, to replicate the behavior |setlocal|, use -`vim.opt_local`. Additionally, to replicate the behavior of |setglobal|, use +In any of the above examples, to replicate the behavior |:setlocal|, use +`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use `vim.opt_global`. @@ -1406,8 +1406,8 @@ connection_failure_errmsg({consequence}) defer_fn({fn}, {timeout}) *vim.defer_fn()* Defers calling `fn` until `timeout` ms passes. - Use to do a one-shot timer that calls `fn` Note: The {fn} is |schedule_wrap|ped automatically, so API functions are - safe to call. + Use to do a one-shot timer that calls `fn` Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions + are safe to call. Parameters: ~ {fn} Callback to call once `timeout` expires @@ -1541,7 +1541,7 @@ region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()* {bufnr} (number) of buffer {pos1} (line, column) tuple marking beginning of region {pos2} (line, column) tuple marking end of region - {regtype} type of selection (:help setreg) + {regtype} type of selection, see |setreg()| {inclusive} (boolean) indicating whether the selection is end-inclusive @@ -1773,7 +1773,7 @@ tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()* (table) Merged table See also: ~ - |tbl_extend()| + |vim.tbl_extend()| tbl_extend({behavior}, {...}) *vim.tbl_extend()* Merges two or more map-like tables. diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt index 9dbd2d4de5..ecb92d4bb6 100644 --- a/runtime/doc/luaref.txt +++ b/runtime/doc/luaref.txt @@ -20,72 +20,7 @@ See |luaref-copyright| for copyright and licenses. - CONTENTS - ============ - - 1 INTRODUCTION........................|luaref-intro| - - 2 THE LANGUAGE........................|luaref-language| - 2.1 Lexical Conventions...............|luaref-langLexConv| - 2.2 Values and Types..................|luaref-langValTypes| - 2.2.1 Coercion........................|luaref-langCoercion| - 2.3 Variables.........................|luaref-langVariables| - 2.4 Statements........................|luaref-langStats| - 2.4.1 Chunks..........................|luaref-langChunks| - 2.4.2 Blocks..........................|luaref-langBlocks| - 2.4.3 Assignment......................|luaref-langAssign| - 2.4.4 Control Structures..............|luaref-langContStructs| - 2.4.5 For Statement...................|luaref-langForStat| - 2.4.6 Function Calls as Statements....|luaref-langFuncStat| - 2.4.7 Local Declarations..............|luaref-langLocalDec| - 2.5 Expressions.......................|luaref-langExpressions| - 2.5.1 Arithmetic Operators............|luaref-langArithOp| - 2.5.2 Relational Operators............|luaref-langRelOp| - 2.5.3 Logical Operators...............|luaref-langLogOp| - 2.5.4 Concatenation...................|luaref-langConcat| - 2.5.5 The Length Operator.............|luaref-langLength| - 2.5.6 Precedence......................|luaref-langPrec| - 2.5.7 Table Constructors..............|luaref-langTableConst| - 2.5.8 Function Calls..................|luaref-langFuncCalls| - 2.5.9 Function Definitions............|luaref-langFuncDefs| - 2.6 Visibility Rules..................|luaref-langVisibRules| - 2.7 Error Handling....................|luaref-langError| - 2.8 Metatables........................|luaref-langMetatables| - 2.9 Environments......................|luaref-langEnvironments| - 2.10 Garbage Collection...............|luaref-langGC| - 2.10.1 Garbage-Collection Metamethods.|luaref-langGCMeta| - 2.10.2 Weak Tables....................|luaref-langWeaktables| - 2.11 Coroutines.......................|luaref-langCoro| - - 3 THE APPLICATION PROGRAM INTERFACE...|luaref-api| - 3.1 The Stack.........................|luaref-apiStack| - 3.2 Stack Size........................|luaref-apiStackSize| - 3.3 Pseudo-Indices....................|luaref-apiPseudoIndices| - 3.4 C Closures........................|luaref-apiCClosures| - 3.5 Registry..........................|luaref-apiRegistry| - 3.6 Error Handling in C...............|luaref-apiError| - 3.7 Functions and Types...............|luaref-apiFunctions| - 3.8 The Debug Interface...............|luaref-apiDebug| - - 4 THE AUXILIARY LIBRARY...............|luaref-aux| - 4.1 Functions and Types...............|luaref-auxFunctions| - - 5 STANDARD LIBRARIES..................|luaref-lib| - 5.1 Basic Functions...................|luaref-libBasic| - 5.2 Coroutine Manipulation............|luaref-libCoro| - 5.3 Modules...........................|luaref-libModule| - 5.4 String Manipulation...............|luaref-libString| - 5.4.1 Patterns........................|luaref-libStringPat| - 5.5 Table Manipulation................|luaref-libTable| - 5.6 Mathematical Functions............|luaref-libMath| - 5.7 Input and Output Facilities.......|luaref-libIO| - 5.8 Operating System Facilities.......|luaref-libOS| - 5.9 The Debug Library.................|luaref-libDebug| - - A BIBLIOGRAPHY........................|luaref-bibliography| - B COPYRIGHT & LICENSES................|luaref-copyright| - C LUAREF DOC..........................|luaref-doc| - +Type |gO| to see the table of contents. ============================================================================== 1 INTRODUCTION *luaref-intro* @@ -292,7 +227,7 @@ parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy. The library function `type` returns a string describing the type of a given -value (see |luaref-type|). +value (see |luaref-type()|). ------------------------------------------------------------------------------ 2.2.1 Coercion *luaref-langCoercion* @@ -303,7 +238,7 @@ string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control of how numbers are converted to strings, use the `format` function from the string library (see -|luaref-string.format|). +|string.format()|). ============================================================================== 2.3 Variables *luaref-langVariables* @@ -344,7 +279,7 @@ has its own reference to an environment, so that all global variables in this function will refer to this environment table. When a function is created, it inherits the environment from the function that created it. To get the environment table of a Lua function, you call `getfenv` (see -|luaref-getfenv|). To replace it, you call `setfenv` (see |luaref-setfenv|). +|lua_getfenv()|). To replace it, you call `setfenv` (see |luaref-setfenv()|). (You can only manipulate the environment of C functions through the debug library; see |luaref-libDebug|.) @@ -634,7 +569,7 @@ they are explained in |luaref-langFuncDefs|. Binary operators comprise arithmetic operators (see |luaref-langArithOp|), relational operators (see |luaref-langRelOp|), logical operators (see |luaref-langLogOp|), and the concatenation operator (see |luaref-langConcat|). -Unary operators comprise the unary minus (see |luaref-labgArithOp|), the unary +Unary operators comprise the unary minus (see |luaref-langArithOp|), the unary `not` (see |luaref-langLogOp|), and the unary length operator (see |luaref-langLength|). @@ -1050,13 +985,13 @@ them share the same `x`. Because Lua is an embedded extension language, all Lua actions start from C code in the host program calling a function from the Lua library (see -|luaref-lua_pcall|). Whenever an error occurs during Lua compilation or +|lua_pcall()|). Whenever an error occurs during Lua compilation or execution, control returns to C, which can take appropriate measures (such as print an error message). Lua code can explicitly generate an error by calling the `error` function (see -|luaref-error|). If you need to catch errors in Lua, you can use -the `pcall` function (see |luaref-pcall|). +|luaref-error()|). If you need to catch errors in Lua, you can use +the `pcall` function (see |luaref-pcall()|). ============================================================================== 2.8 Metatables *luaref-metatable* *luaref-langMetatables* @@ -1074,10 +1009,10 @@ previous example, the event is "add" and the metamethod is the function that performs the addition. You can query the metatable of any value through the `getmetatable` function -(see |luaref-getmetatable|). +(see |luaref-getmetatable()|). You can replace the metatable of tables through the `setmetatable` function (see -|luaref-setmetatable|). You cannot change the metatable of other types from Lua +|luaref-setmetatable()|). You cannot change the metatable of other types from Lua (except using the debug library); you must use the C API for that. Tables and userdata have individual metatables (although multiple tables and @@ -1385,8 +1320,8 @@ convenience feature for programmers to associate a table to a userdata. Environments associated with threads are called global environments. They are used as the default environment for their threads and non-nested functions -created by the thread (through `loadfile` |luaref-loadfile|, `loadstring` -|luaref-loadstring| or `load` |luaref-load|) and can be directly accessed by C +created by the thread (through `loadfile` |luaref-loadfile()|, `loadstring` +|luaref-loadstring()| or `load` |luaref-load()|) and can be directly accessed by C code (see |luaref-apiPseudoIndices|). Environments associated with C functions can be directly accessed by C code @@ -1399,10 +1334,10 @@ used as the default environment for other Lua functions created by the function. You can change the environment of a Lua function or the running thread by -calling `setfenv` (see |luaref-setenv|). You can get the environment of a Lua -function or the running thread by calling `getfenv` (see |luaref-getfenv|). To -manipulate the environment of other objects (userdata, C functions, other -threads) you must use the C API. +calling `setfenv`. You can get the environment of a Lua function or the +running thread by calling `getfenv` (see |lua_getfenv()|). To manipulate the +environment of other objects (userdata, C functions, other threads) you must +use the C API. ============================================================================== 2.10 Garbage Collection *luaref-langGC* @@ -1432,8 +1367,8 @@ collector too slow and may result in the collector never finishing a cycle. The default, 2, means that the collector runs at "twice" the speed of memory allocation. -You can change these numbers by calling `lua_gc` (see |luaref-lua_gc|) in C or -`collectgarbage` (see |luaref-collectgarbage|) in Lua. Both get percentage +You can change these numbers by calling `lua_gc` (see |lua_gc()|) in C or +`collectgarbage` (see |luaref-collectgarbage()|) in Lua. Both get percentage points as arguments (so an argument of 100 means a real value of 1). With these functions you can also control the collector directly (e.g., stop and restart it). @@ -1496,12 +1431,12 @@ multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. You create a coroutine with a call to `coroutine.create` (see -|luaref-coroutine.create|). Its sole argument is a function that is the main +|coroutine.create()|). Its sole argument is a function that is the main function of the coroutine. The `create` function only creates a new coroutine and returns a handle to it (an object of type `thread`); it does not start the coroutine execution. -When you first call `coroutine.resume` (see |luaref-coroutine.resume|), +When you first call `coroutine.resume` (see |coroutine.resume()|), passing as its first argument the thread returned by `coroutine.create`, the coroutine starts its execution, at the first line of its main function. Extra arguments passed to `coroutine.resume` are passed on to the coroutine main @@ -1516,7 +1451,7 @@ main function. In case of errors, `coroutine.resume` returns `false` plus an error message. A coroutine yields by calling `coroutine.yield` (see -|luaref-coroutine.yield|). When a coroutine yields, the corresponding +|coroutine.yield()|). When a coroutine yields, the corresponding `coroutine.resume` returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, @@ -1526,7 +1461,7 @@ its execution from the point where it yielded, with the call to `coroutine.yield` returning any extra arguments passed to `coroutine.resume`. Like `coroutine.create`, the `coroutine.wrap` function (see -|luaref-coroutine.wrap|) also creates a coroutine, but instead of returning +|coroutine.wrap()|) also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to `coroutine.resume`. `coroutine.wrap` returns all the values returned by @@ -1595,7 +1530,7 @@ Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active. This stack initially contains any arguments to the C function and it is where the C function pushes its results to be returned to the caller (see -|luaref-lua_CFunction|). +|lua_CFunction()|). *luaref-stackindex* For convenience, most query operations in the API do not follow a strict stack @@ -1615,7 +1550,7 @@ if `1 <= abs(index) <= top`). When you interact with Lua API, you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. You can use the function `lua_checkstack` to grow the stack size (see -|luaref-lua_checkstack|). +|lua_checkstack()|). Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions are available. `LUA_MINSTACK` is defined as 20, so that usually you do not @@ -1656,14 +1591,14 @@ global variable, do When a C function is created, it is possible to associate some values with it, thus creating a C closure; these values are called upvalues and are accessible -to the function whenever it is called (see |luaref-lua_pushcclosure|). +to the function whenever it is called (see |lua_pushcclosure()|). Whenever a C function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro -`lua_upvalueindex` (see |luaref-lua_upvalueindex|). The first value associated -with a function is at position `lua_upvalueindex(1)`, and so on. Any access to -`lua_upvalueindex(` `n` `)`, where `n` is greater than the number of upvalues of -the current function, produces an acceptable (but invalid) index. +`lua_upvalueindex`. The first value associated with a function is at position +`lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(` `n` `)`, +where `n` is greater than the number of upvalues of the current function, +produces an acceptable (but invalid) index. ============================================================================== 3.5 Registry *luaref-registry* *luaref-apiRegistry* @@ -1694,11 +1629,11 @@ Almost any function in the API may raise an error, for instance due to a memory allocation error. The following functions run in protected mode (that is, they create a protected environment to run), so they never raise an error: `lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see -|luaref-lua_newstate|, |luaref-lua_close|, |luaref-lua_load|, -|luaref-lua_pcall|, and |luaref-lua_cpcall|). +|lua_newstate()|, |lua_close()|, |lua_load()|, +|lua_pcall()|, and |lua_cpcall()|). Inside a C function you can raise an error by calling `lua_error` (see -|luaref-lua_error|). +|lua_error()|). ============================================================================== 3.7 Functions and Types *luaref-apiFunctions* @@ -1715,7 +1650,7 @@ lua_Alloc *lua_Alloc()* The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to `realloc`, but not exactly the same. Its arguments are `ud`, an opaque pointer - passed to `lua_newstate` (see |luaref-lua_newstate|); `ptr`, a pointer + passed to `lua_newstate` (see |lua_newstate()|); `ptr`, a pointer to the block being allocated/reallocated/freed; `osize`, the original size of the block; `nsize`, the new size of the block. `ptr` is `NULL` if and only if `osize` is zero. When `nsize` is zero, the allocator @@ -1729,7 +1664,7 @@ lua_Alloc *lua_Alloc()* Here is a simple implementation for the allocator function. It is used in the auxiliary library by `luaL_newstate` (see - |luaref-luaL_newstate|). + |luaL_newstate()|). > static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { @@ -1813,7 +1748,7 @@ lua_CFunction *luaref-cfunction* *lua_CFunction()* following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the - function starts, `lua_gettop(L)` (see |luaref-lua_gettop|) returns the + function starts, `lua_gettop(L)` (see |lua_gettop()|) returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index `lua_gettop(L)`. To return values to Lua, a C function just pushes them onto the stack, @@ -1881,7 +1816,7 @@ lua_cpcall *lua_cpcall()* Calls the C function `func` in protected mode. `func` starts with only one element in its stack, a light userdata containing `ud`. In case of errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see - |luaref-lua_pcall|), plus the error object on the top of the stack; + |lua_pcall()|), plus the error object on the top of the stack; otherwise, it returns zero, and does not change the stack. All values returned by `func` are discarded. @@ -1893,7 +1828,7 @@ lua_createtable *lua_createtable()* has space pre-allocated for `narr` array elements and `nrec` non-array elements. This pre-allocation is useful when you know exactly how many elements the table will have. Otherwise you can use the function - `lua_newtable` (see |luaref-lua_newtable|). + `lua_newtable` (see |lua_newtable()|). lua_dump *lua_dump()* > @@ -1903,7 +1838,7 @@ lua_dump *lua_dump()* of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, `lua_dump` calls function `writer` (see - |luaref-lua_Writer|) with the given `data` to write them. + |lua_Writer()|) with the given `data` to write them. The value returned is the error code returned by the last call to the writer; 0 means no errors. @@ -1925,7 +1860,7 @@ lua_error *lua_error()* < Generates a Lua error. The error message (which can actually be a Lua value of any type) must be on the stack top. This function does a long - jump, and therefore never returns (see |luaref-luaL_error|). + jump, and therefore never returns (see |luaL_error()|). lua_gc *lua_gc()* > @@ -1965,7 +1900,7 @@ lua_getallocf *lua_getallocf()* < Returns the memory-allocation function of a given state. If `ud` is not `NULL`, Lua stores in `*ud` the opaque pointer passed to - `lua_newstate` (see |luaref-lua_newstate|). + `lua_newstate` (see |lua_newstate()|). lua_getfenv *lua_getfenv()* > @@ -2136,10 +2071,10 @@ lua_load *lua_load()* This function only loads a chunk; it does not run it. `lua_load` automatically detects whether the chunk is text or binary, - and loads it accordingly (see program `luac`, |luaref-luac|). + and loads it accordingly (see program `luac`). The `lua_load` function uses a user-supplied `reader` function to read - the chunk (see |luaref-lua_Reader|). The `data` argument is an opaque + the chunk (see |lua_Reader()|). The `data` argument is an opaque value passed to the reader function. The `chunkname` argument gives a name to the chunk, which is used for @@ -2161,14 +2096,14 @@ lua_newtable *lua_newtable()* < Creates a new empty table and pushes it onto the stack. It is equivalent to `lua_createtable(L, 0, 0)` (see - |luaref-lua_createtable|). + |lua_createtable()|). lua_newthread *lua_newthread()* > lua_State *lua_newthread (lua_State *L); < Creates a new thread, pushes it on the stack, and returns a pointer to - a `lua_State` (see |luaref-lua_State|) that represents this new + a `lua_State` (see |lua_State()|) that represents this new thread. The new state returned by this function shares with the original state all global objects (such as tables), but has an independent execution stack. @@ -2218,7 +2153,7 @@ lua_next *lua_next()* } < While traversing a table, do not call `lua_tolstring` (see - |luaref-lua_tolstring|) directly on a key, unless you know that the + |lua_tolstring()|) directly on a key, unless you know that the key is actually a string. Recall that `lua_tolstring` `changes` the value at the given index; this confuses the next call to `lua_next`. @@ -2248,7 +2183,7 @@ lua_pcall *lua_pcall()* Calls a function in protected mode. Both `nargs` and `nresults` have the same meaning as in `lua_call` - (see |luaref-lua_call|). If there are no errors during the call, + (see |lua_call()|). If there are no errors during the call, `lua_pcall` behaves exactly like `lua_call`. However, if there is any error, `lua_pcall` catches it, pushes a single value on the stack (the error message), and returns an error code. Like `lua_call`, @@ -2314,7 +2249,7 @@ lua_pushcfunction *lua_pushcfunction()* Any function to be registered in Lua must follow the correct protocol to receive its parameters and return its results (see - |luaref-lua_CFunction|). + |lua_CFunction()|). `lua_pushcfunction` is defined as a macro: > @@ -2408,7 +2343,7 @@ lua_pushvfstring *lua_pushvfstring()* const char *fmt, va_list argp); < - Equivalent to `lua_pushfstring` (see |luaref-pushfstring|), except + Equivalent to `lua_pushfstring` (see |lua_pushfstring()|), except that it receives a `va_list` instead of a variable number of arguments. @@ -2425,7 +2360,7 @@ lua_rawget *lua_rawget()* > void lua_rawget (lua_State *L, int index); < - Similar to `lua_gettable` (see |luaref-lua_gettable|), but does a raw + Similar to `lua_gettable` (see |lua_gettable()|), but does a raw access (i.e., without metamethods). lua_rawgeti *lua_rawgeti()* @@ -2440,7 +2375,7 @@ lua_rawset *lua_rawset()* > void lua_rawset (lua_State *L, int index); < - Similar to `lua_settable` (see |luaref-lua_settable|), but does a raw + Similar to `lua_settable` (see |lua_settable()|), but does a raw assignment (i.e., without metamethods). lua_rawseti *lua_rawseti()* @@ -2459,7 +2394,7 @@ lua_Reader *lua_Reader()* void *data, size_t *size); < - The reader function used by `lua_load` (see |luaref-lua_load|). Every + The reader function used by `lua_load` (see |lua_load()|). Every time it needs another piece of the chunk, `lua_load` calls the reader, passing along its `data` parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set `size` to @@ -2504,15 +2439,15 @@ lua_resume *lua_resume()* Starts and resumes a coroutine in a given thread. To start a coroutine, you first create a new thread (see - |luaref-lua_newthread|); then you push onto its stack the main + |lua_newthread()|); then you push onto its stack the main function plus any arguments; then you call `lua_resume` (see - |luaref-lua_resume|) with `narg` being the number of arguments. This + |lua_resume()|) with `narg` being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to `lua_yield` - (see |luaref-lua_yield|), or all values returned by the body function. + (see |lua_yield()|), or all values returned by the body function. `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the coroutine finishes its execution without errors, or an error code in - case of errors (see |luaref-lua_pcall|). In case of errors, the stack + case of errors (see |lua_pcall()|). In case of errors, the stack is not unwound, so you can use the debug API over it. The error message is on the top of the stack. To restart a coroutine, you put on its stack only the values to be passed as results from `lua_yield`, @@ -2593,7 +2528,7 @@ lua_State *lua_State()* A pointer to this state must be passed as the first argument to every function in the library, except to `lua_newstate` (see - |luaref-lua_newstate|), which creates a Lua state from scratch. + |lua_newstate()|), which creates a Lua state from scratch. lua_status *lua_status()* > @@ -2614,7 +2549,7 @@ lua_toboolean *lua_toboolean()* any Lua value different from `false` and `nil`; otherwise it returns 0. It also returns 0 when called with a non-valid index. (If you want to accept only actual boolean values, use `lua_isboolean` - |luaref-lua_isboolean| to test the value's type.) + |lua_isboolean()| to test the value's type.) lua_tocfunction *lua_tocfunction()* > @@ -2628,7 +2563,7 @@ lua_tointeger *lua_tointeger()* lua_Integer lua_tointeger (lua_State *L, int idx); < Converts the Lua value at the given acceptable index to the signed - integral type `lua_Integer` (see |luaref-lua_Integer|). The Lua value + integral type `lua_Integer` (see |lua_Integer()|). The Lua value must be a number or a string convertible to a number (see |luaref-langCoercion|); otherwise, `lua_tointeger` returns 0. @@ -2644,7 +2579,7 @@ lua_tolstring *lua_tolstring()* Lua value must be a string or a number; otherwise, the function returns `NULL`. If the value is a number, then `lua_tolstring` also `changes the actual value in the stack to a` `string`. (This change - confuses `lua_next` |luaref-lua_next| when `lua_tolstring` is applied + confuses `lua_next` |lua_next()| when `lua_tolstring` is applied to keys during a table traversal.) `lua_tolstring` returns a fully aligned pointer to a string inside the @@ -2659,7 +2594,7 @@ lua_tonumber *lua_tonumber()* lua_Number lua_tonumber (lua_State *L, int index); < Converts the Lua value at the given acceptable index to the C type - `lua_Number` (see |luaref-lua_Number|). The Lua value must be a number + `lua_Number` (see |lua_Number()|). The Lua value must be a number or a string convertible to a number (see |luaref-langCoercion|); otherwise, `lua_tonumber` returns 0. @@ -2679,7 +2614,7 @@ lua_tostring *lua_tostring()* > const char *lua_tostring (lua_State *L, int index); < - Equivalent to `lua_tolstring` (see |luaref-lua_tolstring|) with `len` + Equivalent to `lua_tolstring` (see |lua_tolstring()|) with `len` equal to `NULL`. lua_tothread *lua_tothread()* @@ -2687,7 +2622,7 @@ lua_tothread *lua_tothread()* lua_State *lua_tothread (lua_State *L, int index); < Converts the value at the given acceptable index to a Lua thread - (represented as `lua_State*` |luaref-lua_State|). This value must be a + (represented as `lua_State*` |lua_State()|). This value must be a thread; otherwise, the function returns `NULL`. lua_touserdata *lua_touserdata()* @@ -2723,7 +2658,7 @@ lua_Writer *lua_Writer()* size_t sz, void* ud); < - The writer function used by `lua_dump` (see |luaref-lua_dump|). Every + The writer function used by `lua_dump` (see |lua_dump()|). Every time it produces another piece of chunk, `lua_dump` calls the writer, passing along the buffer to be written (`p`), its size (`sz`), and the `data` parameter supplied to `lua_dump`. @@ -2753,7 +2688,7 @@ lua_yield *lua_yield()* < When a C function calls `lua_yield` in that way, the running coroutine suspends its execution, and the call to `lua_resume` (see - |luaref-lua_resume|) that started this coroutine returns. The + |lua_resume()|) that started this coroutine returns. The parameter `nresults` is the number of values from the stack that are passed as results to `lua_resume`. @@ -2798,9 +2733,9 @@ lua_Debug *lua_Debug()* `} lua_Debug;` A structure used to carry different pieces of information about an active -function. `lua_getstack` (see |luaref-lua_getstack|) fills only the private part +function. `lua_getstack` (see |lua_getstack()|) fills only the private part of this structure, for later use. To fill the other fields of `lua_Debug` with -useful information, call `lua_getinfo` (see |luaref-lua_getinfo|). +useful information, call `lua_getinfo` (see |lua_getinfo()|). The fields of `lua_Debug` have the following meaning: @@ -2858,8 +2793,8 @@ lua_getinfo *lua_getinfo()* To get information about a function invocation, the parameter `ar` must be a valid activation record that was filled by a previous call - to `lua_getstack` (see |luaref-lua_getstack|) or given as argument to - a hook (see |luaref-lua_Hook|). + to `lua_getstack` (see |lua_getstack()|) or given as argument to + a hook (see |lua_Hook()|). To get information about a function you push it onto the stack and start the `what` string with the character `>`. (In that case, @@ -2896,8 +2831,8 @@ lua_getlocal *lua_getlocal()* < Gets information about a local variable of a given activation record. The parameter `ar` must be a valid activation record that was filled - by a previous call to `lua_getstack` (see |luaref-lua_getstack|) or - given as argument to a hook (see |luaref-lua_Hook|). The index `n` + by a previous call to `lua_getstack` (see |lua_getstack()|) or + given as argument to a hook (see |lua_Hook()|). The index `n` selects which local variable to inspect (1 is the first parameter or active local variable, and so on, until the last active local variable). `lua_getlocal` pushes the variable's value onto the stack @@ -2916,7 +2851,7 @@ lua_getstack *lua_getstack()* < Gets information about the interpreter runtime stack. - This function fills parts of a `lua_Debug` (see |luaref-lua_Debug|) + This function fills parts of a `lua_Debug` (see |lua_Debug()|) structure with an identification of the `activation record` of the function executing at a given level. Level 0 is the current running function, whereas level `n+1` is the function that has called level @@ -2951,7 +2886,7 @@ lua_Hook *lua_Hook()* `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for line events, the field `currentline` is also set. To get the value of any other field in `ar`, the hook must call `lua_getinfo` (see - |luaref-lua_getinfo|). For return events, `event` may be + |lua_getinfo()|). For return events, `event` may be `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter case, Lua is simulating a return from a function that did a tail call; in this case, it is useless to call `lua_getinfo`. @@ -2996,7 +2931,7 @@ lua_setlocal *lua_setlocal()* < Sets the value of a local variable of a given activation record. Parameters `ar` and `n` are as in `lua_getlocal` (see - |luaref-lua_getlocal|). `lua_setlocal` assigns the value at the top of + |lua_getlocal()|). `lua_setlocal` assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack. @@ -3010,7 +2945,7 @@ lua_setupvalue *lua_setupvalue()* Sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. Parameters `funcindex` and `n` are as in the - `lua_getupvalue` (see |luaref-lua_getupvalue|). + `lua_getupvalue` (see |lua_getupvalue()|). Returns `NULL` (and pops nothing) when the index is greater than the number of upvalues. @@ -3071,36 +3006,36 @@ luaL_addchar *luaL_addchar()* > void luaL_addchar (luaL_Buffer *B, char c); < - Adds the character `c` to the buffer `B` (see |luaref-luaL_Buffer|). + Adds the character `c` to the buffer `B` (see |luaL_Buffer()|). luaL_addlstring *luaL_addlstring()* > void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); < Adds the string pointed to by `s` with length `l` to the buffer `B` - (see |luaref-luaL_Buffer|). The string may contain embedded zeros. + (see |luaL_Buffer()|). The string may contain embedded zeros. luaL_addsize *luaL_addsize()* > void luaL_addsize (luaL_Buffer *B, size_t n); < - Adds to the buffer `B` (see |luaref-luaL_Buffer|) a string of length + Adds to the buffer `B` (see |luaL_Buffer()|) a string of length `n` previously copied to the buffer area (see - |luaref-luaL_prepbuffer|). + |luaL_prepbuffer()|). luaL_addstring *luaL_addstring()* > void luaL_addstring (luaL_Buffer *B, const char *s); < Adds the zero-terminated string pointed to by `s` to the buffer `B` - (see |luaref-luaL_Buffer|). The string may not contain embedded zeros. + (see |luaL_Buffer()|). The string may not contain embedded zeros. luaL_addvalue *luaL_addvalue()* > void luaL_addvalue (luaL_Buffer *B); < Adds the value at the top of the stack to the buffer `B` (see - |luaref-luaL_Buffer|). Pops the value. + |luaL_Buffer()|). Pops the value. This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be @@ -3142,11 +3077,11 @@ luaL_Buffer *luaL_Buffer()* - First you declare a variable `b` of type `luaL_Buffer`. - Then you initialize it with a call `luaL_buffinit(L, &b)` (see - |luaref-luaL_buffinit|). + |luaL_buffinit()|). - Then you add string pieces to the buffer calling any of the `luaL_add*` functions. - You finish by calling `luaL_pushresult(&b)` (see - |luaref-luaL_pushresult|). This call leaves the final string on the + |luaL_pushresult()|). This call leaves the final string on the top of the stack. During its normal operation, a string buffer uses a variable number of @@ -3156,7 +3091,7 @@ luaL_Buffer *luaL_Buffer()* that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is `luaL_addvalue` - |luaref-luaL_addvalue|.) After calling `luaL_pushresult` the stack is + |luaL_addvalue()|.) After calling `luaL_pushresult` the stack is back to its level when the buffer was initialized, plus the final string on its top. @@ -3165,7 +3100,7 @@ luaL_buffinit *luaL_buffinit()* void luaL_buffinit (lua_State *L, luaL_Buffer *B); < Initializes a buffer `B`. This function does not allocate any space; - the buffer must be declared as a variable (see |luaref-luaL_Buffer|). + the buffer must be declared as a variable (see |luaL_Buffer()|). luaL_callmeta *luaL_callmeta()* > @@ -3199,7 +3134,7 @@ luaL_checkinteger *luaL_checkinteger()* lua_Integer luaL_checkinteger (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns - this number cast to a `lua_Integer` (see |luaref-lua_Integer|). + this number cast to a `lua_Integer` (see |lua_Integer()|). luaL_checklong *luaL_checklong()* > @@ -3220,7 +3155,7 @@ luaL_checknumber *luaL_checknumber()* lua_Number luaL_checknumber (lua_State *L, int narg); < Checks whether the function argument `narg` is a number and returns - this number (see |luaref-lua_Number|). + this number (see |lua_Number()|). luaL_checkoption *luaL_checkoption()* > @@ -3262,14 +3197,14 @@ luaL_checktype *luaL_checktype()* void luaL_checktype (lua_State *L, int narg, int t); < Checks whether the function argument `narg` has type `t` (see - |luaref-lua_type|). + |lua_type()|). luaL_checkudata *luaL_checkudata()* > void *luaL_checkudata (lua_State *L, int narg, const char *tname); < Checks whether the function argument `narg` is a userdata of the type - `tname` (see |luaref-luaL_newmetatable|). + `tname` (see |luaL_newmetatable()|). luaL_dofile *luaL_dofile()* > @@ -3297,7 +3232,7 @@ luaL_error *luaL_error()* < Raises an error. The error message format is given by `fmt` plus any extra arguments, following the same rules of `lua_pushfstring` (see - |luaref-lua_pushfstring|). It also adds at the beginning of the + |lua_pushfstring()|). It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available. @@ -3317,7 +3252,7 @@ luaL_getmetatable *luaL_getmetatable()* void luaL_getmetatable (lua_State *L, const char *tname); < Pushes onto the stack the metatable associated with name `tname` in - the registry (see |luaref-luaL_newmetatable|). + the registry (see |luaL_newmetatable()|). luaL_gsub *luaL_gsub()* > @@ -3338,7 +3273,7 @@ luaL_loadbuffer *luaL_loadbuffer()* const char *name); < Loads a buffer as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the buffer pointed to by + |lua_load()|) to load the chunk in the buffer pointed to by `buff` with size `sz`. This function returns the same results as `lua_load`. `name` is the @@ -3349,7 +3284,7 @@ luaL_loadfile *luaL_loadfile()* int luaL_loadfile (lua_State *L, const char *filename); < Loads a file as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the file named `filename`. If + |lua_load()|) to load the chunk in the file named `filename`. If `filename` is `NULL`, then it loads from the standard input. The first line in the file is ignored if it starts with a `#`. @@ -3363,7 +3298,7 @@ luaL_loadstring *luaL_loadstring()* int luaL_loadstring (lua_State *L, const char *s); < Loads a string as a Lua chunk. This function uses `lua_load` (see - |luaref-lua_load|) to load the chunk in the zero-terminated string + |lua_load()|) to load the chunk in the zero-terminated string `s`. This function returns the same results as `lua_load`. @@ -3387,9 +3322,9 @@ luaL_newstate *luaL_newstate()* lua_State *luaL_newstate (void); < Creates a new Lua state. It calls `lua_newstate` (see - |luaref-lua_newstate|) with an allocator based on the standard C + |lua_newstate()|) with an allocator based on the standard C `realloc` function and then sets a panic function (see - |luaref-lua_atpanic|) that prints an error message to the standard + |lua_atpanic()|) that prints an error message to the standard error output in case of fatal errors. Returns the new state, or `NULL` if there is a memory allocation @@ -3417,7 +3352,7 @@ luaL_optinteger *luaL_optinteger()* lua_Integer d); < If the function argument `narg` is a number, returns this number cast - to a `lua_Integer` (see |luaref-lua_Integer|). If this argument is + to a `lua_Integer` (see |lua_Integer()|). If this argument is absent or is `nil`, returns `d`. Otherwise, raises an error. luaL_optlong *luaL_optlong()* @@ -3464,9 +3399,9 @@ luaL_prepbuffer *luaL_prepbuffer()* char *luaL_prepbuffer (luaL_Buffer *B); < Returns an address to a space of size `LUAL_BUFFERSIZE` where you can - copy a string to be added to buffer `B` (see |luaref-luaL_Buffer|). + copy a string to be added to buffer `B` (see |luaL_Buffer()|). After copying the string into this space you must call `luaL_addsize` - (see |luaref-luaL_addsize|) with the size of the string to actually + (see |luaL_addsize()|) with the size of the string to actually add it to the buffer. luaL_pushresult *luaL_pushresult()* @@ -3486,8 +3421,8 @@ luaL_ref *luaL_ref()* A reference is a unique integer key. As long as you do not manually add integer keys into table `t`, `luaL_ref` ensures the uniqueness of the key it returns. You can retrieve an object referred by reference - `r` by calling `lua_rawgeti(L, t, r)` (see |luaref-lua_rawgeti|). - Function `luaL_unref` (see |luaref-luaL_unref|) frees a reference and + `r` by calling `lua_rawgeti(L, t, r)` (see |lua_rawgeti()|). + Function `luaL_unref` (see |luaL_unref()|) frees a reference and its associated object. If the object at the top of the stack is `nil`, `luaL_ref` returns the @@ -3502,7 +3437,7 @@ luaL_Reg *luaL_Reg()* } luaL_Reg; < Type for arrays of functions to be registered by `luaL_register` (see - |luaref-luaL_register|). `name` is the function name and `func` is a + |luaL_register()|). `name` is the function name and `func` is a pointer to the function. Any array of `luaL_Reg` must end with a sentinel entry in which both `name` and `func` are `NULL`. @@ -3515,7 +3450,7 @@ luaL_register *luaL_register()* Opens a library. When called with `libname` equal to `NULL`, it simply registers all - functions in the list `l` (see |luaref-luaL_Reg|) into the table on + functions in the list `l` (see |luaL_Reg()|) into the table on the top of the stack. When called with a non-null `libname`, `luaL_register` creates a new @@ -3543,7 +3478,7 @@ luaL_typerror *luaL_typerror()* `expected, got` `rt` `)` where `location` is produced by `luaL_where` (see - |luaref-luaL_where|), `func` is the name of the current function, and + |luaL_where()|), `func` is the name of the current function, and `rt` is the type name of the actual argument. luaL_unref *luaL_unref()* @@ -3551,7 +3486,7 @@ luaL_unref *luaL_unref()* void luaL_unref (lua_State *L, int t, int ref); < Releases reference `ref` from the table at index `t` (see - |luaref-luaL_ref|). The entry is removed from the table, so that the + |luaL_ref()|). The entry is removed from the table, so that the referred object can be collected. The reference `ref` is also freed to be used again. @@ -3601,14 +3536,14 @@ functions as fields of a global table or as methods of its objects. *luaref-openlibs* To have access to these libraries, the C host program should call the `luaL_openlibs` function, which opens all standard libraries (see -|luaref-luaL_openlibs|). Alternatively, the host program can open the libraries +|luaL_openlibs()|). Alternatively, the host program can open the libraries individually by calling `luaopen_base` (for the basic library), `luaopen_package` (for the package library), `luaopen_string` (for the string library), `luaopen_table` (for the table library), `luaopen_math` (for the mathematical library), `luaopen_io` (for the I/O and the Operating System libraries), and `luaopen_debug` (for the debug library). These functions are declared in `lualib.h` and should not be called directly: you must call them -like any other Lua C function, e.g., by using `lua_call` (see |luaref-lua_call|). +like any other Lua C function, e.g., by using `lua_call` (see |lua_call()|). ============================================================================== 5.1 Basic Functions *luaref-libBasic* @@ -3700,11 +3635,11 @@ load({func} [, {chunkname}]) *luaref-load()* information. loadfile([{filename}]) *luaref-loadfile()* - Similar to `load` (see |luaref-load|), but gets the chunk from file + Similar to `load` (see |luaref-load()|), but gets the chunk from file {filename} or from the standard input, if no file name is given. loadstring({string} [, {chunkname}]) *luaref-loadstring()* - Similar to `load` (see |luaref-load|), but gets the chunk from the + Similar to `load` (see |luaref-load()|), but gets the chunk from the given {string}. To load and run a given string, use the idiom @@ -3724,14 +3659,14 @@ next({table} [, {index}]) *luaref-next()* The order in which the indices are enumerated is not specified, `even for` `numeric indices`. (To traverse a table in numeric order, use a - numerical `for` or the `ipairs` |luaref-ipairs| function.) + numerical `for` or the `ipairs` |luaref-ipairs()| function.) The behavior of `next` is `undefined` if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields. pairs({t}) *luaref-pairs()* - Returns three values: the `next` |luaref-next| function, the table + Returns three values: the `next` |luaref-next()| function, the table {t}, and `nil`, so that the construction `for k,v in pairs(t) do` `body` `end` @@ -3749,10 +3684,10 @@ pcall({f}, {arg1}, {...}) *luaref-pcall()* print({...}) *luaref-print()* Receives any number of arguments, and prints their values to `stdout`, - using the `tostring` |luaref-tostring| function to convert them to + using the `tostring` |luaref-tostring()| function to convert them to strings. `print` is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted - output, use `string.format` (see |luaref-string.format|). + output, use `string.format` (see |string.format()|). rawequal({v1}, {v2}) *luaref-rawequal()* Checks whether {v1} is equal to {v2}, without invoking any metamethod. @@ -3807,7 +3742,7 @@ tonumber({e} [, {base}]) *luaref-tonumber()* tostring({e}) *luaref-tostring()* Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, - use `string.format` (see |luaref-string.format|). + use `string.format` (see |string.format()|). *__tostring* If the metatable of {e} has a `"__tostring"` field, `tostring` calls @@ -3836,7 +3771,7 @@ _VERSION *luaref-_VERSION()* `"Lua 5.1"` . xpcall({f}, {err}) *luaref-xpcall()* - This function is similar to `pcall` (see |luaref-pcall|), except that + This function is similar to `pcall` (see |luaref-pcall()|), except that you can set a new error handler. `xpcall` calls function {f} in protected mode, using {err} as the @@ -3901,7 +3836,7 @@ coroutine.yield({...}) *coroutine.yield()* The package library provides basic facilities for loading and building modules in Lua. It exports two of its functions directly in the global environment: -`require` and `module` (see |luaref-require| and |luaref-module|). Everything else is +`require` and `module` (see |luaref-require()| and |luaref-module()|). Everything else is exported in a table `package`. module({name} [, {...}]) *luaref-module()* @@ -3914,7 +3849,7 @@ module({name} [, {...}]) *luaref-module()* `t._PACKAGE` with the package name (the full module name minus last component; see below). Finally, `module` sets `t` as the new environment of the current function and the new value of - `package.loaded[name]`, so that `require` (see |luaref-require|) + `package.loaded[name]`, so that `require` (see |luaref-require()|) returns `t`. If {name} is a compound name (that is, one with components separated @@ -3968,7 +3903,7 @@ require({modname}) *luaref-require()* If there is any error loading or running the module, or if it cannot find any loader for the module, then `require` signals an error. -package.cpath *package.cpath()* +package.cpath *package.cpath* The path used by `require` to search for a C loader. Lua initializes the C path `package.cpath` in the same way it @@ -3985,7 +3920,7 @@ package.loadlib({libname}, {funcname}) *package.loadlib()* Dynamically links the host program with the C library {libname}. Inside this library, looks for a function {funcname} and returns this function as a C function. (So, {funcname} must follow the protocol - (see |luaref-lua_CFunction|)). + (see |lua_CFunction()|)). This is a low-level function. It completely bypasses the package and module system. Unlike `require`, it does not perform any path @@ -3998,7 +3933,7 @@ package.loadlib({libname}, {funcname}) *package.loadlib()* available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the `dlfcn` standard). -package.path *package.path()* +package.path *package.path* The path used by `require` to search for a Lua loader. At start-up, Lua initializes this variable with the value of the @@ -4019,7 +3954,7 @@ package.path *package.path()* order. package.preload *package.preload()* - A table to store loaders for specific modules (see |luaref-require|). + A table to store loaders for specific modules (see |luaref-require()|). package.seeall({module}) *package.seeall()* Sets a metatable for {module} with its `__index` field referring to @@ -4059,7 +3994,7 @@ string.char({...}) *string.char()* string.dump({function}) *string.dump()* Returns a string containing a binary representation of the given - function, so that a later |luaref-loadstring| on this string returns a + function, so that a later |luaref-loadstring()| on this string returns a copy of the function. {function} must be a Lua function without upvalues. @@ -4341,7 +4276,7 @@ table.foreach({table}, {f}) *table.foreach()* returns a non-`nil` value, then the loop is broken, and this value is returned as the final value of `table.foreach`. - See |luaref-next| for extra information about table traversals. + See |luaref-next()| for extra information about table traversals. table.foreachi({table}, {f}) *table.foreachi()* Executes the given {f} over the numerical indices of {table}. For each @@ -4658,7 +4593,7 @@ file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* immediately. `"full"` full buffering; output operation is performed only when the buffer is full (or when you explicitly `flush` the file - (see |luaref-io.flush|). + (see |io.flush()|). `"line"` line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device). @@ -4669,7 +4604,7 @@ file:setvbuf({mode} [, {size}]) *luaref-file:setvbuf()* file:write({...}) *luaref-file:write()* Writes the value of each of its arguments to `file`. The arguments must be strings or numbers. To write other values, use `tostring` - |luaref-tostring| or `string.format` |luaref-string.format| before + |luaref-tostring()| or `string.format` |string.format()| before `write`. ============================================================================== @@ -4686,7 +4621,7 @@ os.date([{format} [, {time}]]) *os.date()* according to the given string {format}. If the {time} argument is present, this is the time to be formatted - (see the `os.time` function |luaref-os.time| for a description of this + (see the `os.time` function |os.time()| for a description of this value). Otherwise, `date` formats the current time. If {format} starts with `!`, then the date is formatted in @@ -4744,7 +4679,7 @@ os.time([{table}]) *os.time()* representing the date and time specified by the given table. This table must have fields `year`, `month`, and `day`, and may have fields `hour`, `min`, `sec`, and `isdst` (for a description of these fields, - see the `os.date` function |luaref-os.date|). + see the `os.date` function |os.date()|). The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the @@ -4802,7 +4737,7 @@ debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()* functions, then `getinfo` returns `nil`. The returned table may contain all the fields returned by - `lua_getinfo` (see |luaref-lua_getinfo|), with the string {what} + `lua_getinfo` (see |lua_getinfo()|), with the string {what} describing which fields to fill in. The default for {what} is to get all information available, except the table of valid lines. If present, the option `f` adds a field named `func` with the function @@ -4821,7 +4756,7 @@ debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()* last active local variable.) The function returns `nil` if there is no local variable with the given index, and raises an error when called with a {level} out of range. (You can call `debug.getinfo` - |luaref-debug.getinfo| to check whether the level is valid.) + |debug.getinfo()| to check whether the level is valid.) Variable names starting with `(` (open parentheses) represent internal variables (loop control variables, temporaries, and C @@ -4953,7 +4888,7 @@ C LUAREF DOC *luarefvim* *luarefvimdoc* *luaref-help* *luaref-d This is a Vim help file containing a reference for Lua 5.1, and it is -- with a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual (see |luaref-bibliography|). For usage information, refer to -|luaref-docUsage|. For copyright information, see |luaref-copyright|. +|luaref-doc|. For copyright information, see |luaref-copyright|. The main ideas and concepts on how to implement this reference were taken from Christian Habermann's CRefVim project diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt index da6a305e89..e5d22de748 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -1673,7 +1673,7 @@ backslash followed by a character other than white space or a backslash remains unmodified. Overview: command ~ - XX ab 'ab' + XX ab "ab" XX a\b 'a\b' XX a\ b 'a b' XX a\ b 'a ', 'b' diff --git a/runtime/doc/mbyte.txt b/runtime/doc/mbyte.txt index 2aa49cee1e..7a76c57fc2 100644 --- a/runtime/doc/mbyte.txt +++ b/runtime/doc/mbyte.txt @@ -86,9 +86,8 @@ You can also set 'guifont' alone, the Nvim GUI will try to find a matching INPUT There are several ways to enter multibyte characters: -- For X11 XIM can be used. See |XIM|. -- For MS-Windows IME can be used. See |IME|. -- For all systems keymaps can be used. See |mbyte-keymap|. +- Your system IME can be used. +- Keymaps can be used. See |mbyte-keymap|. The options 'iminsert', 'imsearch' and 'imcmdline' can be used to choose the different input methods or disable them temporarily. diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 14b7eb2d71..e5ad61062f 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -5704,7 +5704,7 @@ A jump table for the options with a short description can be found at |Q_op|. "yes:[1-9]" always, with fixed space for signs up to the given number (maximum 9), e.g. "yes:3" "number" display signs in the 'number' column. If the number - column is not present, then behaves like 'auto'. + column is not present, then behaves like "auto". Note regarding 'orphaned signs': with signcolumn numbers higher than 1, deleting lines will also remove the associated signs automatically, @@ -6481,7 +6481,7 @@ A jump table for the options with a short description can be found at |Q_op|. 'termguicolors' 'tgc' boolean (default off) global Enables 24-bit RGB color in the |TUI|. Uses "gui" |:highlight| - attributes instead of "cterm" attributes. |highlight-guifg| + attributes instead of "cterm" attributes. |guifg| Requires an ISO-8613-3 compatible terminal. *'termpastefilter'* *'tpf'* @@ -7136,7 +7136,7 @@ A jump table for the options with a short description can be found at |Q_op|. the window. Note: highlight namespaces take precedence over 'winhighlight'. - See |nvim_win_set_hl_ns| and |nvim_set_hl|. + See |nvim_win_set_hl_ns()| and |nvim_set_hl()|. Highlights of vertical separators are determined by the window to the left of the separator. The 'tabline' highlight of a tabpage is diff --git a/runtime/doc/pi_netrw.txt b/runtime/doc/pi_netrw.txt index 1eaa76264f..ae0169491b 100644 --- a/runtime/doc/pi_netrw.txt +++ b/runtime/doc/pi_netrw.txt @@ -2353,7 +2353,7 @@ MARKED FILES: DIFF *netrw-md* {{{2 (See |netrw-mf| and |netrw-mr| for how to mark files) (uses the global marked file list) -Use |vimdiff| to visualize difference between selected files (two or +Use vimdiff to visualize difference between selected files (two or three may be selected for this). Uses the global marked file list. MARKED FILES: EDITING *netrw-me* {{{2 @@ -3469,7 +3469,7 @@ Example: Clear netrw's marked file list via a mapping on gu > *netrw-p4* P4. I would like long listings to be the default. {{{2 - Put the following statement into your |.vimrc|: > + Put the following statement into your |vimrc|: > let g:netrw_liststyle= 1 < @@ -3482,7 +3482,7 @@ Example: Clear netrw's marked file list via a mapping on gu > Does your system's strftime() accept the "%c" to yield dates such as "Sun Apr 27 11:49:23 1997"? If not, do a "man strftime" and find out what option should be used. Then - put it into your |.vimrc|: > + put it into your |vimrc|: > let g:netrw_timefmt= "%X" (where X is the option) < @@ -3490,7 +3490,7 @@ Example: Clear netrw's marked file list via a mapping on gu > P6. I want my current directory to track my browsing. {{{2 How do I do that? - Put the following line in your |.vimrc|: + Put the following line in your |vimrc|: > let g:netrw_keepdir= 0 < @@ -3839,7 +3839,7 @@ netrw: or http://vim.sourceforge.net/scripts/script.php?script_id=120 - Decho.vim is provided as a "vimball"; see |vimball-intro|. You + Decho.vim is provided as a "vimball". You should edit the Decho.vba.gz file and source it in: > vim Decho.vba.gz @@ -3917,7 +3917,7 @@ netrw: * Installed |g:netrw_clipboard| setting * Installed option bypass for |'guioptions'| a/A settings - * Changed popup_beval() to |popup_atcursor()| + * Changed popup_beval() to popup_atcursor() in netrw#ErrorMsg (lacygoill). Apparently popup_beval doesn't reliably close the popup when the mouse is moved. @@ -3943,7 +3943,7 @@ netrw: did not restore options correctly that had a single quote in the option string. Apr 13, 2020 * implemented error handling via popup - windows (see |popup_beval()|) + windows (see popup_beval()) Apr 30, 2020 * (reported by Manatsu Takahashi) while using Lexplore, a modified file could be overwritten. Sol'n: will not overwrite, diff --git a/runtime/doc/print.txt b/runtime/doc/print.txt index 924fab175e..0e02c7d42d 100644 --- a/runtime/doc/print.txt +++ b/runtime/doc/print.txt @@ -659,7 +659,7 @@ It is possible to achieve a poor man's version of duplex printing using the PS utility psselect. This utility has options -e and -o for printing just the even or odd pages of a PS file respectively. -First generate a PS file with the 'hardcopy' command, then generate new +First generate a PS file with the ":hardcopy" command, then generate new files with all the odd and even numbered pages with: > psselect -o test.ps odd.ps diff --git a/runtime/doc/provider.txt b/runtime/doc/provider.txt index 9fd35f19c5..782bd19441 100644 --- a/runtime/doc/provider.txt +++ b/runtime/doc/provider.txt @@ -240,7 +240,7 @@ a list of lines and `regtype` is a register type conforming to |setreg()|. Paste *provider-paste* *paste* "Paste" is a separate concept from |clipboard|: paste means "dump a bunch of -text to the editor", whereas clipboard provides features like |quote-+| to get +text to the editor", whereas clipboard provides features like |quote+| to get and set the OS clipboard directly. For example, middle-click or CTRL-SHIFT-v (macOS: CMD-v) in your terminal is "paste", not "clipboard": the terminal application (Nvim) just gets a stream of text, it does not interact with the diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt index dab3bfa280..80110211f9 100644 --- a/runtime/doc/quickfix.txt +++ b/runtime/doc/quickfix.txt @@ -466,7 +466,7 @@ You can parse a list of lines using 'errorformat' without creating or modifying a quickfix list using the |getqflist()| function. Examples: > echo getqflist({'lines' : ["F1:10:Line10", "F2:20:Line20"]}) echo getqflist({'lines' : systemlist('grep -Hn quickfix *')}) -This returns a dictionary where the 'items' key contains the list of quickfix +This returns a dictionary where the "items" key contains the list of quickfix entries parsed from lines. The following shows how to use a custom 'errorformat' to parse the lines without modifying the 'errorformat' option: > echo getqflist({'efm' : '%f#%l#%m', 'lines' : ['F1#10#Line']}) @@ -585,7 +585,7 @@ can go back to the unfiltered list using the |:colder|/|:lolder| command. quickfix command or function, the |b:changedtick| variable is incremented. You can get the number of this buffer using the getqflist() and getloclist() - functions by passing the 'qfbufnr' item. For a + functions by passing the "qfbufnr" item. For a location list, this buffer is wiped out when the location list is removed. @@ -1965,7 +1965,7 @@ The function should return a single line of text to display in the quickfix window for each entry from start_idx to end_idx. The function can obtain information about the entries using the |getqflist()| function and specifying the quickfix list identifier "id". For a location list, getloclist() function -can be used with the 'winid' argument. If an empty list is returned, then the +can be used with the "winid" argument. If an empty list is returned, then the default format is used to display all the entries. If an item in the returned list is an empty string, then the default format is used to display the corresponding entry. diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt index 9f3993506a..cb065cef2c 100644 --- a/runtime/doc/quickref.txt +++ b/runtime/doc/quickref.txt @@ -615,10 +615,6 @@ Short explanation of each option: *option-list* 'backupdir' 'bdir' list of directories for the backup file 'backupext' 'bex' extension used for the backup file 'backupskip' 'bsk' no backup for files that match these patterns -'balloondelay' 'bdlay' delay in mS before a balloon may pop up -'ballooneval' 'beval' switch on balloon evaluation in the GUI -'balloonevalterm' 'bevalterm' switch on balloon evaluation in the terminal -'balloonexpr' 'bexpr' expression to show in balloon 'belloff' 'bo' do not ring the bell for these reasons 'binary' 'bin' read/write/edit file in binary mode 'bomb' prepend a Byte Order Mark to the file @@ -817,8 +813,6 @@ Short explanation of each option: *option-list* 'printoptions' 'popt' controls the format of :hardcopy output 'pumheight' 'ph' maximum height of the popup menu 'pumwidth' 'pw' minimum width of the popup menu -'pythondll' name of the Python 2 dynamic library -'pythonthreedll' name of the Python 3 dynamic library 'pyxversion' 'pyx' Python version used for pyx* commands 'quoteescape' 'qe' escape characters used in a string 'readonly' 'ro' disallow writing the buffer @@ -829,7 +823,6 @@ Short explanation of each option: *option-list* 'revins' 'ri' inserting characters will work backwards 'rightleft' 'rl' window is right-to-left oriented 'rightleftcmd' 'rlc' commands for which editing works right-to-left -'rubydll' name of the Ruby dynamic library 'ruler' 'ru' show cursor line and column in the status line 'rulerformat' 'ruf' custom format for the ruler 'runtimepath' 'rtp' list of directories used for runtime files diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt index 508565dea4..0b316b4727 100644 --- a/runtime/doc/repeat.txt +++ b/runtime/doc/repeat.txt @@ -591,7 +591,7 @@ This could be done if some conditions are met. For example, depending on whether Vim supports a feature or a dependency is missing. You can also load an optional plugin at startup, by putting this command in -your |.vimrc|: > +your |config|: > :packadd! foodebug The extra "!" is so that the plugin isn't loaded if Vim was started with |--noplugin|. diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt index d57a85423c..351fe868d9 100644 --- a/runtime/doc/starting.txt +++ b/runtime/doc/starting.txt @@ -82,12 +82,10 @@ argument. --help *-h* *--help* *-?* -? -h Give usage (help) message and exit. - See |info-message| about capturing the text. --version *-v* *--version* -v Print version information and exit. Same output as for |:version| command. - See |info-message| about capturing the text. *--clean* --clean Mimics a fresh install of Nvim: diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 6fcf292513..1368814952 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -3118,7 +3118,7 @@ The default is to use the twice sh_minlines. Set it to a smaller number to speed up displaying. The disadvantage is that highlight errors may appear. syntax/sh.vim tries to flag certain problems as errors; usually things like -extra ']'s, 'done's, 'fi's, etc. If you find the error handling problematic +extra "]"s, "done"s, "fi"s, etc. If you find the error handling problematic for your purposes, you may suppress such error highlighting by putting the following line in your .vimrc: > @@ -4935,7 +4935,7 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418* have the same effect. "undercurl", "underdouble", "underdotted", and "underdashed" fall back to "underline" in a terminal that does not support them. The color is - set using |highlight-guisp|. + set using |guisp|. start={term-list} *highlight-start* *E422* stop={term-list} *term-list* *highlight-stop* @@ -4956,8 +4956,8 @@ stop={term-list} *term-list* *highlight-stop* like "" and "". Example: start=[27h;[r; -ctermfg={color-nr} *highlight-ctermfg* *E421* -ctermbg={color-nr} *highlight-ctermbg* +ctermfg={color-nr} *ctermfg* *E421* +ctermbg={color-nr} *ctermbg* The {color-nr} argument is a color number. Its range is zero to (not including) the number of |tui-colors| available. The actual color with this number depends on the type of terminal @@ -5064,9 +5064,9 @@ font={font-name} *highlight-font* Example: > :hi comment font='Monospace 10' -guifg={color-name} *highlight-guifg* -guibg={color-name} *highlight-guibg* -guisp={color-name} *highlight-guisp* +guifg={color-name} *guifg* +guibg={color-name} *guibg* +guisp={color-name} *guisp* These give the foreground (guifg), background (guibg) and special (guisp) color to use in the GUI. "guisp" is used for various underlines. @@ -5123,7 +5123,7 @@ Cursor Character under the cursor. lCursor Character under the cursor when |language-mapping| is used (see 'guicursor'). *hl-CursorIM* -CursorIM Like Cursor, but used when in IME mode. |CursorIM| +CursorIM Like Cursor, but used when in IME mode. *CursorIM* *hl-CursorColumn* CursorColumn Screen-column at the cursor, when 'cursorcolumn' is set. *hl-CursorLine* diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 3102c6da9a..75395e89ac 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -50,13 +50,13 @@ Whenever you need to access the current syntax tree, parse the buffer: > tstree = tsparser:parse() < -This will return a table of immutable |lua-treesitter-tree|s that represent the +This will return a table of immutable |treesitter-tree|s that represent the current state of the buffer. When the plugin wants to access the state after a (possible) edit it should call `parse()` again. If the buffer wasn't edited, the same tree will be returned again without extra work. If the buffer was parsed before, incremental parsing will be done of the changed parts. -Note: To use the parser directly inside a |nvim_buf_attach/)| Lua callback, you +Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, you must call |get_parser()| before you register your callback. But preferably parsing shouldn't be done directly in the change callback anyway as they will be very frequent. Rather a plugin that does any kind of analysis on a tree @@ -233,7 +233,7 @@ The following predicates are built in: node's text. `lua-match?` *treesitter-predicate-lua-match?* - Match a |lua-pattern| against the text corresponding to a node, + Match |lua-patterns| against the text corresponding to a node, similar to `match?` `contains?` *treesitter-predicate-contains?* @@ -394,7 +394,7 @@ still highlighted the same as other operators: > "!=" @operator (#set! conceal "≠") < -Conceals specified in this way respect |conceallevel|. +Conceals specified in this way respect 'conceallevel'. *treesitter-highlight-priority* Treesitter uses |nvim_buf_set_extmark()| to set highlights with a default @@ -650,7 +650,7 @@ get_query({lang}, {query_name}) *get_query()* Parameters: ~ {lang} (string) Language to use for the query - {query_name} (string) Name of the query (e.g. 'highlights') + {query_name} (string) Name of the query (e.g. "highlights") Return: ~ Query Parsed query @@ -661,7 +661,7 @@ get_query_files({lang}, {query_name}, {is_included}) Parameters: ~ {lang} (string) Language to get query for - {query_name} (string) Name of the query to load (e.g., 'highlights') + {query_name} (string) Name of the query to load (e.g., "highlights") {is_included} (boolean|nil) Internal parameter, most of the time left as `nil` @@ -742,7 +742,7 @@ Query:iter_matches({self}, {node}, {source}, {start}, {stop}) Iterates the matches of self on a given range. Iterate over all matches within a {node}. The arguments are the same as - for |query:iter_captures()| but the iterated values are different: an + for |Query:iter_captures()| but the iterated values are different: an (1-based) index of the pattern in the query, a table mapping capture indices to nodes, and metadata from any directives processing the match. If the query has more than one pattern, the capture table might be sparse @@ -780,7 +780,7 @@ set_query({lang}, {query_name}, {text}) *set_query()* Parameters: ~ {lang} (string) Language to use for the query - {query_name} (string) Name of the query (e.g., 'highlights') + {query_name} (string) Name of the query (e.g., "highlights") {text} (string) Query text (unparsed). diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt index 955af84679..2d0c8d3b75 100644 --- a/runtime/doc/ui.txt +++ b/runtime/doc/ui.txt @@ -576,7 +576,7 @@ The multigrid extension gives UIs more control over how windows are displayed: per-window. Or reserve space around the border of the window for its own elements, such as scrollbars from the UI toolkit. - A dedicated grid is used for messages, which may scroll over the window - area. (Alternatively |ext_messages| can be used). + area. (Alternatively |ui-messages| can be used). By default, the grid size is handled by Nvim and set to the outer grid size (i.e. the size of the window frame in Nvim) whenever the split is created. @@ -618,7 +618,7 @@ tabs. flag). The Builtin TUI draws a full line filled with `sep_char` and |hl-MsgSeparator| highlight. - When |ext_messages| is active, no message grid is used, and this event + When |ui-messages| is active, no message grid is used, and this event will not be sent. ["win_viewport", grid, win, topline, botline, curline, curcol] diff --git a/runtime/doc/userfunc.txt b/runtime/doc/userfunc.txt index c015b12c27..32c5b0b671 100644 --- a/runtime/doc/userfunc.txt +++ b/runtime/doc/userfunc.txt @@ -214,7 +214,7 @@ It is allowed to define another function inside a function body. You can provide default values for positional named arguments. This makes them optional for function calls. When a positional argument is not specified at a call, the default expression is used to initialize it. -This only works for functions declared with |function|, not for +This only works for functions declared with |:function|, not for lambda expressions |expr-lambda|. Example: > @@ -422,8 +422,7 @@ Also note that if you have two script files, and one calls a function in the other and vice versa, before the used function is defined, it won't work. Avoid using the autoload functionality at the toplevel. -Hint: If you distribute a bunch of scripts you can pack them together with the -|vimball| utility. Also read the user manual |distribute-script|. +Hint: If you distribute a bunch of scripts read |distribute-script|. vim:tw=78:ts=8:noet:ft=help:norl: diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 1aa9aaa0c4..adb5130a53 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -1710,7 +1710,7 @@ There is a little "catch" with comments for some commands. Examples: > :execute cmd " do it :!ls *.c " list C files -The abbreviation 'dev' will be expanded to 'development " shorthand'. The +The abbreviation "dev" will be expanded to 'development " shorthand'. The mapping of will actually be the whole line after the 'o# ....' including the '" insert include'. The "execute" command will give an error. The "!" command will send everything after it to the shell, causing an error for an diff --git a/runtime/doc/usr_45.txt b/runtime/doc/usr_45.txt index 3199c4d8ea..0d23ef50fd 100644 --- a/runtime/doc/usr_45.txt +++ b/runtime/doc/usr_45.txt @@ -300,8 +300,7 @@ can use digraphs. This was already explained in |24.9|. keyboard, you will want to use an Input Method (IM). This requires learning the translation from typed keys to resulting character. When you need an IM you probably already have one on your system. It should work with Vim like -with other programs. For details see |mbyte-XIM| for the X Window system and -|mbyte-IME| for MS-Windows. +with other programs. KEYMAPS diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index e254e5edd0..672d064478 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -417,8 +417,8 @@ Normal commands: Options: 'ttimeout', 'ttimeoutlen' behavior was simplified - |jumpoptions| "stack" behavior - |jumpoptions| "view" tries to restore the |mark-view| when moving through + 'jumpoptions' "stack" behavior + 'jumpoptions' "view" tries to restore the |mark-view| when moving through the |jumplist|, |changelist|, |alternate-file| or using |mark-motions|. 'shortmess' the "F" flag does not affect output from autocommands @@ -498,13 +498,16 @@ Working directory (Vim implemented some of these later than Nvim): ============================================================================== 5. Missing legacy features *nvim-features-missing* -Some legacy Vim features are not implemented: +Some legacy Vim features are not yet implemented: -- |if_lua|: Nvim Lua API is not compatible with Vim's "if_lua" +- *if_lua* : Nvim |Lua| API is not compatible with Vim's "if_lua" - *if_mzscheme* -- |if_py|: *python-bindeval* *python-Function* are not supported +- |if_pyth|: *python-bindeval* *python-Function* are not supported - *if_tcl* +*:gui* +*:gvim* + ============================================================================== 6. Removed features *nvim-features-removed* @@ -566,18 +569,18 @@ Highlight groups: < Options: - 'antialias' + antialias *'balloondelay'* *'bdlay'* *'ballooneval'* *'beval'* *'noballooneval'* *'nobeval'* *'balloonexpr'* *'bexpr'* - 'bioskey' (MS-DOS) - 'conskey' (MS-DOS) + bioskey (MS-DOS) + conskey (MS-DOS) *'cp'* *'nocompatible'* *'nocp'* *'compatible'* (Nvim is always "nocompatible".) 'cpoptions' (gjkHw<*- and all POSIX flags were removed) *'cryptmethod'* *'cm'* *'key'* (Vim encryption implementation) *'ed'* *'edcompatible'* *'noed'* *'noedcompatible'* 'encoding' ("utf-8" is always used) - 'esckeys' + esckeys 'guioptions' "t" flag was removed *'guifontset'* *'gfs'* (Use 'guifont' instead.) *'guipty'* (Nvim uses pipes and PTYs consistently on all platforms.) @@ -618,18 +621,18 @@ Options: Nvim always displays up to 6 combining characters. You can still edit text with more than 6 combining characters, you just can't see them. Use |g8| or |ga|. See |mbyte-combining|. - 'maxmem' Nvim delegates memory-management to the OS. - 'maxmemtot' Nvim delegates memory-management to the OS. + *'maxmem'* Nvim delegates memory-management to the OS. + *'maxmemtot'* Nvim delegates memory-management to the OS. *'prompt'* *'noprompt'* *'remap'* *'noremap'* *'restorescreen'* *'rs'* *'norestorescreen'* *'nors'* - 'shelltype' + *'shelltype'* *'shortname'* *'sn'* *'noshortname'* *'nosn'* *'swapsync'* *'sws'* *'termencoding'* *'tenc'* (Vim 7.4.852 also removed this for Windows) *'terse'* *'noterse'* (Add "s" to 'shortmess' instead) - 'textauto' - 'textmode' + textauto + textmode *'toolbar'* *'tb'* *'toolbariconsize'* *'tbis'* *'ttybuiltin'* *'tbi'* *'nottybuiltin'* *'notbi'* @@ -637,7 +640,7 @@ Options: *'ttymouse'* *'ttym'* *'ttyscroll'* *'tsl'* *'ttytype'* *'tty'* - 'weirdinvert' + weirdinvert Startup: --literal (file args are always literal; to expand wildcards on Windows, use diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua index b8a7f71145..96a87b8bb9 100644 --- a/runtime/lua/vim/_editor.lua +++ b/runtime/lua/vim/_editor.lua @@ -401,7 +401,7 @@ end ---@param bufnr number of buffer ---@param pos1 (line, column) tuple marking beginning of region ---@param pos2 (line, column) tuple marking end of region ----@param regtype type of selection (:help setreg) +---@param regtype type of selection, see |setreg()| ---@param inclusive boolean indicating whether the selection is end-inclusive ---@return region lua table of the form {linenr = {startcol,endcol}} function vim.region(bufnr, pos1, pos2, regtype, inclusive) @@ -448,7 +448,7 @@ end --- Defers calling `fn` until `timeout` ms passes. --- --- Use to do a one-shot timer that calls `fn` ---- Note: The {fn} is |schedule_wrap|ped automatically, so API functions are +--- Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are --- safe to call. ---@param fn Callback to call once `timeout` expires ---@param timeout Number of milliseconds to wait before calling `fn` diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua index ddd504a0e0..0fde515bd9 100644 --- a/runtime/lua/vim/highlight.lua +++ b/runtime/lua/vim/highlight.lua @@ -41,7 +41,7 @@ end ---@param start first position (tuple {line,col}) ---@param finish second position (tuple {line,col}) ---@param opts table with options: --- - regtype type of range (:help setreg, default charwise) +-- - regtype type of range (see |setreg()|, default charwise) -- - inclusive boolean indicating whether the range is end-inclusive (default false) -- - priority number indicating priority of highlight (default priorities.user) function M.range(bufnr, ns, higroup, start, finish, opts) diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 22933d8143..a64facf214 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -823,7 +823,7 @@ end --- }) --- --- ---- See |lsp.start_client| for all available options. The most important are: +--- See |vim.lsp.start_client()| for all available options. The most important are: --- --- `name` is an arbitrary name for the LSP client. It should be unique per --- language server. @@ -834,7 +834,7 @@ end --- --- `root_dir` path to the project root. --- By default this is used to decide if an existing client should be re-used. ---- The example above uses |vim.fs.find| and |vim.fs.dirname| to detect the +--- The example above uses |vim.fs.find()| and |vim.fs.dirname()| to detect the --- root by traversing the file system upwards starting --- from the current directory until either a `pyproject.toml` or `setup.py` --- file is found. @@ -849,11 +849,11 @@ end --- --- --- To ensure a language server is only started for languages it can handle, ---- make sure to call |vim.lsp.start| within a |FileType| autocmd. +--- make sure to call |vim.lsp.start()| within a |FileType| autocmd. --- Either use |:au|, |nvim_create_autocmd()| or put the call in a --- `ftplugin/.lua` (See |ftplugin-name|) --- ----@param config table Same configuration as documented in |lsp.start_client()| +---@param config table Same configuration as documented in |vim.lsp.start_client()| ---@param opts nil|table Optional keyword arguments: --- - reuse_client (fun(client: client, config: table): boolean) --- Predicate used to decide if a client should be re-used. @@ -902,12 +902,12 @@ end --- --- ---@param cmd: (table|string|fun(dispatchers: table):table) command string or ---- list treated like |jobstart|. The command must launch the language server +--- list treated like |jobstart()|. The command must launch the language server --- process. `cmd` can also be a function that creates an RPC client. --- The function receives a dispatchers table and must return a table with the --- functions `request`, `notify`, `is_closing` and `terminate` ---- See |vim.lsp.rpc.request| and |vim.lsp.rpc.notify| ---- For TCP there is a built-in rpc client factory: |vim.lsp.rpc.connect| +--- See |vim.lsp.rpc.request()| and |vim.lsp.rpc.notify()| +--- For TCP there is a built-in rpc client factory: |vim.lsp.rpc.connect()| --- ---@param cmd_cwd: (string, default=|getcwd()|) Directory to launch --- the `cmd` process. Not related to `root_dir`. @@ -963,7 +963,7 @@ end ---@param on_error Callback with parameters (code, ...), invoked --- when the client operation throws an error. `code` is a number describing --- the error. Other arguments may be passed depending on the error kind. See ---- |vim.lsp.rpc.client_errors| for possible errors. +--- `vim.lsp.rpc.client_errors` for possible errors. --- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name. --- ---@param before_init Callback with parameters (initialize_params, config) @@ -999,8 +999,8 @@ end --- notifications to the server by the given number in milliseconds. No debounce --- occurs if nil --- - exit_timeout (number|boolean, default false): Milliseconds to wait for server to ---- exit cleanly after sending the 'shutdown' request before sending kill -15. ---- If set to false, nvim exits immediately after sending the 'shutdown' request to the server. +--- exit cleanly after sending the "shutdown" request before sending kill -15. +--- If set to false, nvim exits immediately after sending the "shutdown" request to the server. --- ---@param root_dir string Directory where the LSP --- server will base its workspaceFolders, rootUri, and rootPath @@ -1078,7 +1078,7 @@ function lsp.start_client(config) --- ---@param code (number) Error code ---@param err (...) Other arguments may be passed depending on the error kind - ---@see |vim.lsp.rpc.client_errors| for possible errors. Use + ---@see `vim.lsp.rpc.client_errors` for possible errors. Use ---`vim.lsp.rpc.client_errors[code]` to get a human-friendly name. function dispatch.on_error(code, err) local _ = log.error() diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 8567619228..b9aaacb437 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -111,7 +111,7 @@ end --- about the context in which a completion was triggered (how it was triggered, --- and by which trigger character, if applicable) --- ----@see |vim.lsp.protocol.constants.CompletionTriggerKind| +---@see vim.lsp.protocol.constants.CompletionTriggerKind function M.completion(context) local params = util.make_position_params() params.context = context @@ -317,7 +317,7 @@ end --- ---@param options table|nil with valid `FormattingOptions` entries ---@param timeout_ms (number) Request timeout ----@see |vim.lsp.buf.formatting_seq_sync| +---@see |vim.lsp.buf.format()| function M.formatting_sync(options, timeout_ms) vim.notify_once( 'vim.lsp.buf.formatting_sync is deprecated. Use vim.lsp.buf.format instead', @@ -614,14 +614,14 @@ end --- Lists all the call sites of the symbol under the cursor in the --- |quickfix| window. If the symbol can resolve to multiple ---- items, the user can pick one in the |inputlist|. +--- items, the user can pick one in the |inputlist()|. function M.incoming_calls() call_hierarchy('callHierarchy/incomingCalls') end --- Lists all the items that are called by the symbol under the --- cursor in the |quickfix| window. If the symbol can resolve to ---- multiple items, the user can pick one in the |inputlist|. +--- multiple items, the user can pick one in the |inputlist()|. function M.outgoing_calls() call_hierarchy('callHierarchy/outgoingCalls') end @@ -730,9 +730,9 @@ end --- --- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups --- to be defined or you won't be able to see the actual highlights. ---- |LspReferenceText| ---- |LspReferenceRead| ---- |LspReferenceWrite| +--- |hl-LspReferenceText| +--- |hl-LspReferenceRead| +--- |hl-LspReferenceWrite| function M.document_highlight() local params = util.make_position_params() request('textDocument/documentHighlight', params) diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 624436bc9b..a32c59dd17 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -389,7 +389,7 @@ M['textDocument/implementation'] = location_handler ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window ---- - See |vim.api.nvim_open_win()| +--- - See |nvim_open_win()| function M.signature_help(_, result, ctx, config) config = config or {} config.focus_id = ctx.method diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index 755c0ffc6f..842a0ce329 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -635,7 +635,7 @@ end --- Starts an LSP server process and create an LSP RPC client object to --- interact with it. Communication with the spawned process happens via stdio. For ---- communication via TCP, spawn a process manually and use |vim.lsp.rpc.connect| +--- communication via TCP, spawn a process manually and use |vim.lsp.rpc.connect()| --- ---@param cmd (string) Command to start the LSP server. ---@param cmd_args (table) List of additional string arguments to pass to {cmd}. diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 64512a9739..dbc18963f9 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1504,7 +1504,7 @@ end --- ---@param contents table of lines to show in window ---@param syntax string of syntax to set for opened buffer ----@param opts table with optional fields (additional keys are passed on to |vim.api.nvim_open_win()|) +---@param opts table with optional fields (additional keys are passed on to |nvim_open_win()|) --- - height: (number) height of floating window --- - width: (number) width of floating window --- - wrap: (boolean, default true) wrap long lines @@ -1819,7 +1819,7 @@ end --- CAUTION: Modifies the input in-place! --- ---@param lines (table) list of lines ----@returns (string) filetype or 'markdown' if it was unchanged. +---@returns (string) filetype or "markdown" if it was unchanged. function M.try_trim_markdown_code_blocks(lines) local language_id = lines[1]:match('^```(.*)') if language_id then @@ -1992,7 +1992,7 @@ function M.make_workspace_params(added, removed) end --- Returns indentation size. --- ----@see |shiftwidth| +---@see 'shiftwidth' ---@param bufnr (number|nil): Buffer handle, defaults to current ---@returns (number) indentation size function M.get_effective_tabstop(bufnr) diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index de5f7240aa..c5c31b6ddf 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -302,7 +302,7 @@ end --- Merges recursively two or more map-like tables. --- ----@see |tbl_extend()| +---@see |vim.tbl_extend()| --- ---@param behavior string Decides what to do if a key is found in more than one map: --- - "error": raise an error diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua index d1dc29969b..1e46daaccf 100644 --- a/runtime/lua/vim/treesitter/query.lua +++ b/runtime/lua/vim/treesitter/query.lua @@ -54,7 +54,7 @@ end --- Gets the list of files used to make up a query --- ---@param lang string Language to get query for ----@param query_name string Name of the query to load (e.g., 'highlights') +---@param query_name string Name of the query to load (e.g., "highlights") ---@param is_included (boolean|nil) Internal parameter, most of the time left as `nil` ---@return string[] query_files List of files to load for given query and language function M.get_query_files(lang, query_name, is_included) @@ -162,7 +162,7 @@ local explicit_queries = setmetatable({}, { --- set by plugins. --- ---@param lang string Language to use for the query ----@param query_name string Name of the query (e.g., 'highlights') +---@param query_name string Name of the query (e.g., "highlights") ---@param text string Query text (unparsed). function M.set_query(lang, query_name, text) explicit_queries[lang][query_name] = M.parse_query(lang, text) @@ -171,7 +171,7 @@ end --- Returns the runtime query {query_name} for {lang}. --- ---@param lang string Language to use for the query ----@param query_name string Name of the query (e.g. 'highlights') +---@param query_name string Name of the query (e.g. "highlights") --- ---@return Query Parsed query function M.get_query(lang, query_name) @@ -596,7 +596,7 @@ end --- Iterates the matches of self on a given range. --- --- Iterate over all matches within a {node}. The arguments are the same as ---- for |query:iter_captures()| but the iterated values are different: +--- for |Query:iter_captures()| but the iterated values are different: --- an (1-based) index of the pattern in the query, a table mapping --- capture indices to nodes, and metadata from any directives processing the match. --- If the query has more than one pattern, the capture table might be sparse diff --git a/src/nvim/api/autocmd.c b/src/nvim/api/autocmd.c index ac4cb953b8..b5c695b9ce 100644 --- a/src/nvim/api/autocmd.c +++ b/src/nvim/api/autocmd.c @@ -599,7 +599,7 @@ void nvim_del_autocmd(Integer id, Error *err) } /// Clear all autocommands that match the corresponding {opts}. To delete -/// a particular autocmd, see |nvim_del_autocmd|. +/// a particular autocmd, see |nvim_del_autocmd()|. /// @param opts Parameters /// - event: (string|table) /// Examples: @@ -728,7 +728,7 @@ Integer nvim_create_augroup(uint64_t channel_id, String name, Dict(create_augrou /// /// To get a group id one can use |nvim_get_autocmds()|. /// -/// NOTE: behavior differs from |augroup-delete|. When deleting a group, autocommands contained in +/// NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in /// this group will also be deleted and cleared. This group will no longer exist. /// @param id Integer The id of the group. /// @see |nvim_del_augroup_by_name()| @@ -746,10 +746,10 @@ void nvim_del_augroup_by_id(Integer id, Error *err) /// Delete an autocommand group by name. /// -/// NOTE: behavior differs from |augroup-delete|. When deleting a group, autocommands contained in +/// NOTE: behavior differs from |:augroup-delete|. When deleting a group, autocommands contained in /// this group will also be deleted and cleared. This group will no longer exist. /// @param name String The name of the group. -/// @see |autocommand-groups| +/// @see |autocmd-groups| void nvim_del_augroup_by_name(String name, Error *err) FUNC_API_SINCE(9) { diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index edcea52838..c92a97519d 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -393,7 +393,7 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e /// multiple highlight groups that will be stacked /// (highest priority last). A highlight group can be supplied /// either as a string or as an integer, the latter which -/// can be obtained using |nvim_get_hl_id_by_name|. +/// can be obtained using |nvim_get_hl_id_by_name()|. /// - virt_text_pos : position of virtual text. Possible values: /// - "eol": right after eol character (default) /// - "overlay": display over the specified column, without @@ -430,7 +430,7 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e /// column of the window, bypassing /// sign and number columns. /// -/// - ephemeral : for use with |nvim_set_decoration_provider| +/// - 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. @@ -958,7 +958,7 @@ void nvim_buf_clear_namespace(Buffer buffer, Integer ns_id, Integer line_start, /// 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 +/// 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 ). diff --git a/src/nvim/api/options.c b/src/nvim/api/options.c index 867584dd71..ec1f19cf6a 100644 --- a/src/nvim/api/options.c +++ b/src/nvim/api/options.c @@ -147,7 +147,7 @@ Object nvim_get_option_value(String name, Dict(option) *opts, Error *err) /// @param name Option name /// @param value New option value /// @param opts Optional parameters -/// - scope: One of 'global' or 'local'. Analogous to +/// - scope: One of "global" or "local". Analogous to /// |:setglobal| and |:setlocal|, respectively. /// - win: |window-ID|. Used for setting window local option. /// - buf: Buffer number. Used for setting buffer local option. @@ -202,7 +202,7 @@ void nvim_set_option_value(String name, Object value, Dict(option) *opts, Error /// Gets the option information for all options. /// /// The dictionary has the full option names as keys and option metadata -/// dictionaries as detailed at |nvim_get_option_info|. +/// dictionaries as detailed at |nvim_get_option_info()|. /// /// @return dictionary of all options Dictionary nvim_get_all_options_info(Error *err) diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index ad9ed72f43..d65127e406 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -160,8 +160,8 @@ Dictionary nvim__get_hl_defs(Integer ns_id, Arena *arena, Error *err) /// - nocombine: boolean /// - link: name of another highlight group to link to, see |:hi-link|. /// - default: Don't override existing definition |:hi-default| -/// - ctermfg: Sets foreground of cterm color |highlight-ctermfg| -/// - ctermbg: Sets background of cterm color |highlight-ctermbg| +/// - ctermfg: Sets foreground of cterm color |ctermfg| +/// - ctermbg: Sets background of cterm color |ctermbg| /// - cterm: cterm attribute map, like |highlight-args|. If not set, /// cterm attributes will match those from the attribute map /// documented above. @@ -185,7 +185,7 @@ void nvim_set_hl(Integer ns_id, String name, Dict(highlight) *val, Error *err) } /// Set active namespace for highlights. This can be set for a single window, -/// see |nvim_win_set_hl_ns|. +/// see |nvim_win_set_hl_ns()|. /// /// @param ns_id the namespace to use /// @param[out] err Error details, if any @@ -205,7 +205,7 @@ void nvim_set_hl_ns(Integer ns_id, Error *err) /// Set active namespace for highlights while redrawing. /// /// This function meant to be called while redrawing, primarily from -/// |nvim_set_decoration_provider| on_win and on_line callbacks, which +/// |nvim_set_decoration_provider()| on_win and on_line callbacks, which /// are allowed to change the namespace during a redraw cycle. /// /// @param ns_id the namespace to activate @@ -523,7 +523,7 @@ Array nvim__runtime_inspect(void) /// Find files in runtime directories /// -/// 'name' can contain wildcards. For example +/// "name" can contain wildcards. For example /// nvim_get_runtime_file("colors/*.vim", true) will return all color /// scheme files. Always use forward slashes (/) in the search pattern for /// subdirectories regardless of platform. @@ -964,7 +964,7 @@ fail: /// mode. Note: keypresses are sent raw as they would be to the pty /// master end. For instance, a carriage return is sent /// as a "\r", not as a "\n". |textlock| applies. It is possible -/// to call |nvim_chan_send| directly in the callback however. +/// to call |nvim_chan_send()| directly in the callback however. /// ["input", term, bufnr, data] /// @param[out] err Error details, if any /// @return Channel id, or 0 on error @@ -1452,7 +1452,7 @@ ArrayOf(Dictionary) nvim_get_keymap(String mode) /// @param rhs Right-hand-side |{rhs}| of the mapping. /// @param opts Optional parameters map: keys are |:map-arguments|, values are booleans (default /// false). Accepts all |:map-arguments| as keys excluding || but including -/// |noremap| and "desc". Unknown key is an error. +/// |:noremap| and "desc". Unknown key is an error. /// "desc" can be used to give a description to the mapping. /// When called from Lua, also accepts a "callback" key that takes a Lua function to /// call when the mapping is executed. diff --git a/src/nvim/api/win_config.c b/src/nvim/api/win_config.c index 96c560efa1..636b9566ce 100644 --- a/src/nvim/api/win_config.c +++ b/src/nvim/api/win_config.c @@ -109,7 +109,7 @@ /// is changed to `auto` and 'colorcolumn' is cleared. The /// end-of-buffer region is hidden by setting `eob` flag of /// 'fillchars' to a space char, and clearing the -/// |EndOfBuffer| region in 'winhighlight'. +/// |hl-EndOfBuffer| region in 'winhighlight'. /// - border: Style of (optional) window border. This can either be a string /// or an array. The string values are /// - "none": No border (default). diff --git a/src/nvim/api/window.c b/src/nvim/api/window.c index 5203003369..59e806adb1 100644 --- a/src/nvim/api/window.c +++ b/src/nvim/api/window.c @@ -340,7 +340,7 @@ Boolean nvim_win_is_valid(Window window) /// /// Like |:hide| the buffer becomes hidden unless another window is editing it, /// or 'bufhidden' is `unload`, `delete` or `wipe` as opposed to |:close| or -/// |nvim_win_close|, which will close the buffer. +/// |nvim_win_close()|, which will close the buffer. /// /// @param window Window handle, or 0 for current window /// @param[out] err Error details, if any diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c index 6267e1c875..001bbf7e48 100644 --- a/src/nvim/mapping.c +++ b/src/nvim/mapping.c @@ -890,7 +890,7 @@ theend: /// /// @param maptype MAPTYPE_MAP for |:map| /// MAPTYPE_UNMAP for |:unmap| -/// MAPTYPE_NOREMAP for |noremap|. +/// MAPTYPE_NOREMAP for |:noremap|. /// @param arg C-string containing the arguments of the map/abbrev /// command, i.e. everything except the initial `:[X][nore]map`. /// - Cannot be a read-only string; it will be modified. diff --git a/src/nvim/mapping.h b/src/nvim/mapping.h index 182d1a48cb..156187b5d8 100644 --- a/src/nvim/mapping.h +++ b/src/nvim/mapping.h @@ -9,7 +9,7 @@ /// All possible |:map-arguments| usable in a |:map| command. /// /// The argument has no effect on mappings and is excluded from this -/// struct declaration. |noremap| is included, since it behaves like a map +/// struct declaration. |:noremap| is included, since it behaves like a map /// argument when used in a mapping. /// /// @see mapblock_T -- cgit From 4bb1d1df79bd1f125499e556d5d4e21ac2ff1e5a Mon Sep 17 00:00:00 2001 From: Andrey Bushev Date: Sat, 24 Sep 2022 22:54:30 -0700 Subject: feat(terminal): recognize underdouble and undercurl --- src/nvim/terminal.c | 18 +++++++++++++++++- test/functional/terminal/helpers.lua | 4 ++++ test/functional/terminal/highlight_spec.lua | 10 ++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c index 326c868be8..8ec51438fb 100644 --- a/src/nvim/terminal.c +++ b/src/nvim/terminal.c @@ -759,6 +759,22 @@ static int get_rgb(VTermState *state, VTermColor color) return RGB_(color.rgb.red, color.rgb.green, color.rgb.blue); } +static int get_underline_hl_flag(VTermScreenCellAttrs attrs) +{ + switch (attrs.underline) { + case VTERM_UNDERLINE_OFF: + return 0; + case VTERM_UNDERLINE_SINGLE: + return HL_UNDERLINE; + case VTERM_UNDERLINE_DOUBLE: + return HL_UNDERDOUBLE; + case VTERM_UNDERLINE_CURLY: + return HL_UNDERCURL; + default: + return HL_UNDERLINE; + } +} + void terminal_get_line_attributes(Terminal *term, win_T *wp, int linenr, int *term_attrs) { int height, width; @@ -795,7 +811,7 @@ void terminal_get_line_attributes(Terminal *term, win_T *wp, int linenr, int *te int hl_attrs = (cell.attrs.bold ? HL_BOLD : 0) | (cell.attrs.italic ? HL_ITALIC : 0) | (cell.attrs.reverse ? HL_INVERSE : 0) - | (cell.attrs.underline ? HL_UNDERLINE : 0) + | get_underline_hl_flag(cell.attrs) | (cell.attrs.strike ? HL_STRIKETHROUGH: 0) | ((fg_indexed && !fg_set) ? HL_FG_INDEXED : 0) | ((bg_indexed && !bg_set) ? HL_BG_INDEXED : 0); diff --git a/test/functional/terminal/helpers.lua b/test/functional/terminal/helpers.lua index bcfd3559e6..d69f3207f1 100644 --- a/test/functional/terminal/helpers.lua +++ b/test/functional/terminal/helpers.lua @@ -31,6 +31,8 @@ local function set_bg(num) feed_termcode('[48;5;'..num..'m') end local function set_bold() feed_termcode('[1m') end local function set_italic() feed_termcode('[3m') end local function set_underline() feed_termcode('[4m') end +local function set_underdouble() feed_termcode('[4:2m') end +local function set_undercurl() feed_termcode('[4:3m') end local function set_strikethrough() feed_termcode('[9m') end local function clear_attrs() feed_termcode('[0;10m') end -- mouse @@ -116,6 +118,8 @@ return { set_bold = set_bold, set_italic = set_italic, set_underline = set_underline, + set_underdouble = set_underdouble, + set_undercurl = set_undercurl, set_strikethrough = set_strikethrough, clear_attrs = clear_attrs, enable_mouse = enable_mouse, diff --git a/test/functional/terminal/highlight_spec.lua b/test/functional/terminal/highlight_spec.lua index 28ca07d815..a119d4acd3 100644 --- a/test/functional/terminal/highlight_spec.lua +++ b/test/functional/terminal/highlight_spec.lua @@ -26,6 +26,8 @@ describe(':terminal highlight', function() [9] = {foreground = 130}, [10] = {reverse = true}, [11] = {background = 11}, + [12] = {bold = true, underdouble = true}, + [13] = {italic = true, undercurl = true}, }) screen:attach({rgb=false}) command(("enew | call termopen(['%s'])"):format(testprg('tty-test'))) @@ -114,6 +116,14 @@ describe(':terminal highlight', function() thelpers.set_underline() thelpers.set_strikethrough() end) + descr('bold and underdouble', 12, function() + thelpers.set_bold() + thelpers.set_underdouble() + end) + descr('italics and undercurl', 13, function() + thelpers.set_italic() + thelpers.set_undercurl() + end) end) it(':terminal highlight has lower precedence than editor #9964', function() -- cgit From db0ea1ab444c5e45fe02e1f2984aefc2eb613096 Mon Sep 17 00:00:00 2001 From: bfredl Date: Mon, 26 Sep 2022 10:40:34 +0200 Subject: fix(messages): validate msg_grid before silent! message with cmdheight=0 fixes #20316 --- src/nvim/message.c | 1 + test/functional/ui/cmdline_spec.lua | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/nvim/message.c b/src/nvim/message.c index 0b9cbfe474..b3e99d99a1 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -1401,6 +1401,7 @@ void msg_start(void) if (!msg_scroll && full_screen) { // overwrite last message if (cmdline_row >= Rows && !ui_has(kUIMessages)) { + msg_grid_validate(); msg_scroll_up(false, true); msg_scrolled++; cmdline_row = Rows - 1; diff --git a/test/functional/ui/cmdline_spec.lua b/test/functional/ui/cmdline_spec.lua index 92eb853686..3669352901 100644 --- a/test/functional/ui/cmdline_spec.lua +++ b/test/functional/ui/cmdline_spec.lua @@ -1183,4 +1183,17 @@ describe('cmdheight=0', function() {1:~ }| ]]} end) + + it('with silent! at startup', function() + clear{args={'-c', 'set cmdheight=0', '-c', 'autocmd VimEnter * silent! call Foo()'}} + screen:attach() + -- doesn't crash while not displaying silent! error message + screen:expect{grid=[[ + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + ]]} + end) end) -- cgit From c815aadfccd6bada47ecfb09fe188ee7f7c5caf3 Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Mon, 26 Sep 2022 11:43:23 +0200 Subject: docs: fix typos (#20150) Co-authored-by: Miguel Carneiro Co-authored-by: Gregory Anders Co-authored-by: Raphael Co-authored-by: C.D. MacEachern Co-authored-by: zeertzjq --- runtime/doc/api.txt | 6 +++--- runtime/doc/builtin.txt | 19 +++++++++++-------- runtime/doc/diagnostic.txt | 2 +- runtime/doc/eval.txt | 13 ++++++++----- runtime/doc/insert.txt | 3 ++- runtime/doc/motion.txt | 12 ++++++------ runtime/doc/options.txt | 6 +++--- runtime/doc/pi_health.txt | 2 +- runtime/doc/quickfix.txt | 4 ++-- runtime/doc/syntax.txt | 8 ++++---- runtime/doc/tabpage.txt | 2 +- runtime/doc/userfunc.txt | 2 +- runtime/doc/usr_22.txt | 2 +- runtime/doc/usr_41.txt | 1 + runtime/doc/windows.txt | 11 ++++++----- src/nvim/api/ui.c | 4 ++-- src/nvim/buffer_defs.h | 2 +- src/nvim/debugger.c | 2 +- src/nvim/if_cscope.c | 2 +- src/nvim/keycodes.c | 9 ++++----- test/functional/vimscript/map_functions_spec.lua | 9 +++------ 21 files changed, 63 insertions(+), 58 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index ec16d5c650..ce59f5ad52 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -3435,8 +3435,8 @@ nvim_ui_detach() *nvim_ui_detach()* *nvim_ui_pum_set_bounds()* nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) - Tells Nvim the geometry of the popumenu, to align floating windows with an - external popup menu. + Tells Nvim the geometry of the popupmenu, to align floating windows with + an external popup menu. Note that this method is not to be confused with |nvim_ui_pum_set_height()|, which sets the number of visible items in the @@ -3455,7 +3455,7 @@ nvim_ui_pum_set_bounds({width}, {height}, {row}, {col}) {col} Popupmenu height. nvim_ui_pum_set_height({height}) *nvim_ui_pum_set_height()* - Tells Nvim the number of elements displaying in the popumenu, to decide + Tells Nvim the number of elements displaying in the popupmenu, to decide and movement. Attributes: ~ diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 77b85406b9..735116f9a0 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -1131,13 +1131,14 @@ chdir({dir}) *chdir()* directory (|:tcd|) then changes the tabpage local directory. - Otherwise, changes the global directory. + {dir} must be a String. If successful, returns the previous working directory. Pass this to another chdir() to restore the directory. On failure, returns an empty string. Example: > let save_dir = chdir(newdir) - if save_dir + if save_dir != "" " ... do some work call chdir(save_dir) endif @@ -3240,7 +3241,7 @@ getloclist({nr} [, {what}]) *getloclist()* In addition to the items supported by |getqflist()| in {what}, the following item is supported by |getloclist()|: - filewinid id of the window used to display files + filewinid id of the window used to display files from the location list. This field is applicable only when called from a location list window. See @@ -6069,6 +6070,8 @@ rand([{expr}]) *rand()* *readdir()* readdir({directory} [, {expr}]) Return a list with file and directory names in {directory}. + You can also use |glob()| if you don't need to do complicated + things, such as limiting the number of matches. When {expr} is omitted all entries are included. When {expr} is given, it is evaluated to check what to do: @@ -8303,12 +8306,12 @@ synconcealed({lnum}, {col}) *synconcealed()* the text is "123456" and both "23" and "45" are concealed and replaced by the character "X", then: call returns ~ - synconcealed(lnum, 1) [0, '', 0] - synconcealed(lnum, 2) [1, 'X', 1] - synconcealed(lnum, 3) [1, 'X', 1] - synconcealed(lnum, 4) [1, 'X', 2] - synconcealed(lnum, 5) [1, 'X', 2] - synconcealed(lnum, 6) [0, '', 0] + synconcealed(lnum, 1) [0, '', 0] + synconcealed(lnum, 2) [1, 'X', 1] + synconcealed(lnum, 3) [1, 'X', 1] + synconcealed(lnum, 4) [1, 'X', 2] + synconcealed(lnum, 5) [1, 'X', 2] + synconcealed(lnum, 6) [0, '', 0] synstack({lnum}, {col}) *synstack()* diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index 78254c6f2b..ada7b93f7c 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -296,7 +296,7 @@ EVENTS *diagnostic-events* *DiagnosticChanged* DiagnosticChanged After diagnostics have changed. When used from Lua, - the new diagnostics are passed to the autocmcd + the new diagnostics are passed to the autocmd callback in the "data" table. Example: > diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index 3e068e3b4e..bfaa3b12e8 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -457,7 +457,7 @@ String automatically. Thus the String '4' and the number 4 will find the same entry. Note that the String '04' and the Number 04 are different, since the Number will be converted to the String '4', leading zeros are dropped. The empty string can also be used as a key. - *literal-Dict* + *literal-Dict* *#{}* To avoid having to put quotes around every key the #{} form can be used. This does require the key to consist only of ASCII letters, digits, '-' and '_'. Example: > @@ -681,7 +681,7 @@ similar to -1. > :let shortblob = myblob[2:2] " Blob with one byte: 0z22 :let otherblob = myblob[:] " make a copy of the Blob -If the first index is beyond the last byte of the Blob or the second byte is +If the first index is beyond the last byte of the Blob or the second index is before the first index, the result is an empty Blob. There is no error message. @@ -704,8 +704,8 @@ The length of the replaced bytes must be exactly the same as the value provided. *E972* To change part of a blob you can specify the first and last byte to be -modified. The value must at least have the number of bytes in the range: > - :let blob[3:5] = [3, 4, 5] +modified. The value must have the same number of bytes in the range: > + :let blob[3:5] = 0z334455 You can also use the functions |add()|, |remove()| and |insert()|. @@ -1228,7 +1228,10 @@ And NOT: > \ ->map(mapexpr) \ ->sort() \ ->join() -< + +When using the lambda form there must be no white space between the } and the +(. + *expr9* number diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt index f4ef8e65c4..9ea963c812 100644 --- a/runtime/doc/insert.txt +++ b/runtime/doc/insert.txt @@ -1126,7 +1126,8 @@ that contains the List. The Dict can have these items: leading text is changed. Other items are ignored. -For acting upon end of completion, see the |CompleteDone| autocommand event. +For acting upon end of completion, see the |CompleteDonePre| and +|CompleteDone| autocommand event. For example, the function can contain this: > let matches = ... list of words ... diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt index 511b1bd7b2..77b6b83289 100644 --- a/runtime/doc/motion.txt +++ b/runtime/doc/motion.txt @@ -831,12 +831,12 @@ deletes the lines from the cursor position to mark 't'. Hint: Use mark 't' for Top, 'b' for Bottom, etc.. Lowercase marks are restored when using undo and redo. -Uppercase marks 'A to 'Z include the file name. -You can use them to jump from file to file. You can only use an uppercase -mark with an operator if the mark is in the current file. The line number of -the mark remains correct, even if you insert/delete lines or edit another file -for a moment. When the 'shada' option is not empty, uppercase marks are -kept in the .shada file. See |shada-file-marks|. +Uppercase marks 'A to 'Z include the file name. You can use them to jump from +file to file. You can only use an uppercase mark with an operator if the mark +is in the current file. The line number of the mark remains correct, even if +you insert/delete lines or edit another file for a moment. When the 'shada' +option is not empty, uppercase marks are kept in the .shada file. See +|shada-file-marks|. Numbered marks '0 to '9 are quite different. They can not be set directly. They are only present when using a shada file |shada-file|. Basically '0 diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index e5ad61062f..c1a0836f5b 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -6748,11 +6748,11 @@ A jump table for the options with a short description can be found at |Q_op|. final value applying to all subsequent tabs. For example, when editing assembly language files where statements - start in the 8th column and comments in the 40th, it may be useful + start in the 9th column and comments in the 41st, it may be useful to use the following: > :set varsofttabstop=8,32,8 -< This will set soft tabstops at the 8th and 40th columns, and at every - 8th column thereafter. +< This will set soft tabstops with 8 and 8 + 32 spaces, and 8 more + for every column thereafter. Note that the value of |'softtabstop'| will be ignored while 'varsofttabstop' is set. diff --git a/runtime/doc/pi_health.txt b/runtime/doc/pi_health.txt index cc36e7186c..8a6437fdc8 100644 --- a/runtime/doc/pi_health.txt +++ b/runtime/doc/pi_health.txt @@ -75,7 +75,7 @@ vim.health.report_error({msg} [, {advice}]) *vim.health.report_error Create a healthcheck *health-dev* Healthchecks are functions that check the user environment, configuration, or -any other prerequisities that a plugin cares about. Nvim ships with +any other prerequisites that a plugin cares about. Nvim ships with healthchecks in: - $VIMRUNTIME/autoload/health/ - $VIMRUNTIME/lua/vim/lsp/health.lua diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt index 80110211f9..924a6d4743 100644 --- a/runtime/doc/quickfix.txt +++ b/runtime/doc/quickfix.txt @@ -916,7 +916,7 @@ To get the number of the current list in the stack: > screen). 5. The errorfile is read using 'errorformat'. 6. All relevant |QuickFixCmdPost| autocommands are - executed. See example below. + executed. See example below. 7. If [!] is not given the first error is jumped to. 8. The errorfile is deleted. 9. You can now move through the errors with commands @@ -1939,7 +1939,7 @@ list window is: The values displayed in each line correspond to the "bufnr", "lnum", "col" and "text" fields returned by the |getqflist()| function. -For some quickfix/location lists, the displayed text need to be customized. +For some quickfix/location lists, the displayed text needs to be customized. For example, if only the filename is present for a quickfix entry, then the two "|" field separator characters after the filename are not needed. Another use case is to customize the path displayed for a filename. By default, the diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 1368814952..83f19db4a9 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -2057,7 +2057,7 @@ The g:lisp_rainbow option provides 10 levels of individual colorization for the parentheses and backquoted parentheses. Because of the quantity of colorization levels, unlike non-rainbow highlighting, the rainbow mode specifies its highlighting using ctermfg and guifg, thereby bypassing the -usual colorscheme control using standard highlighting groups. The actual +usual color scheme control using standard highlighting groups. The actual highlighting used depends on the dark/bright setting (see |'bg'|). @@ -4838,7 +4838,7 @@ in their own color. To customize a color scheme use another name, e.g. "~/.config/nvim/colors/mine.vim", and use `:runtime` to - load the original colorscheme: > + load the original color scheme: > runtime colors/evening.vim hi Statement ctermfg=Blue guifg=Blue @@ -4846,7 +4846,7 @@ in their own color. |ColorSchemePre| autocommand event is triggered. After the color scheme has been loaded the |ColorScheme| autocommand event is triggered. - For info about writing a colorscheme file: > + For info about writing a color scheme file: > :edit $VIMRUNTIME/colors/README.txt :hi[ghlight] List all the current highlight groups that have @@ -5016,7 +5016,7 @@ ctermbg={color-nr} *ctermbg* explicitly. This causes the highlight groups that depend on 'background' to change! This means you should set the colors for Normal first, before setting other colors. - When a colorscheme is being used, changing 'background' causes it to + When a color scheme is being used, changing 'background' causes it to be reloaded, which may reset all colors (including Normal). First delete the "g:colors_name" variable when you don't want this. diff --git a/runtime/doc/tabpage.txt b/runtime/doc/tabpage.txt index 9197710819..49b2773253 100644 --- a/runtime/doc/tabpage.txt +++ b/runtime/doc/tabpage.txt @@ -186,8 +186,8 @@ gt *i_CTRL-* *i_* :+2tabnext " go to the two next tab page :1tabnext " go to the first tab page :$tabnext " go to the last tab page - :tabnext # " go to the last accessed tab page :tabnext $ " as above + :tabnext # " go to the last accessed tab page :tabnext - " go to the previous tab page :tabnext -1 " as above :tabnext + " go to the next tab page diff --git a/runtime/doc/userfunc.txt b/runtime/doc/userfunc.txt index 32c5b0b671..5462fa952c 100644 --- a/runtime/doc/userfunc.txt +++ b/runtime/doc/userfunc.txt @@ -214,7 +214,7 @@ It is allowed to define another function inside a function body. You can provide default values for positional named arguments. This makes them optional for function calls. When a positional argument is not specified at a call, the default expression is used to initialize it. -This only works for functions declared with |:function|, not for +This only works for functions declared with `:function`, not for lambda expressions |expr-lambda|. Example: > diff --git a/runtime/doc/usr_22.txt b/runtime/doc/usr_22.txt index f53d578456..539bda3980 100644 --- a/runtime/doc/usr_22.txt +++ b/runtime/doc/usr_22.txt @@ -220,7 +220,7 @@ a tab page share this directory except for windows with a window-local directory. Any new windows opened in this tab page will use this directory as the current working directory. Using a `:cd` command in a tab page will not change the working directory of tab pages which have a tab local directory. -When the global working directory is changed using the ":cd" command in a tab +When the global working directory is changed using the `:cd` command in a tab page, it will also change the current tab page working directory. diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index adb5130a53..4e7ec00148 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -1016,6 +1016,7 @@ Testing: *test-functions* assert_beeps() assert that a command beeps assert_nobeep() assert that a command does not cause a beep assert_fails() assert that a command fails + assert_report() report a test failure Timers: *timer-functions* timer_start() create a timer diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 6386e4ace1..3dc718a68f 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -148,7 +148,7 @@ CTRL-W CTRL-S *CTRL-W_CTRL-S* Note: CTRL-S does not work on all terminals and might block further input, use CTRL-Q to get going again. Also see |++opt| and |+cmd|. - *E242* + *E242* *E1159* Be careful when splitting a window in an autocommand, it may mess up the window layout if this happens while making other window layout changes. @@ -291,9 +291,8 @@ Closing a window :{count}q[uit] *:count_quit* CTRL-W q *CTRL-W_q* CTRL-W CTRL-Q *CTRL-W_CTRL-Q* - Without {count}: Quit the current window. If {count} is - given quit the {count} window - + Without {count}: Quit the current window. If {count} is + given quit the {count} window. *edit-window* When quitting the last edit window (not counting help or preview windows), exit Vim. @@ -352,7 +351,7 @@ CTRL-W CTRL-C *CTRL-W_CTRL-C* window, but that does not work, because the CTRL-C cancels the command. - *:hide* + *:hide* :hid[e] :{count}hid[e] Without {count}: Quit the current window, unless it is the @@ -751,6 +750,7 @@ can also get to them with the buffer list commands, like ":bnext". the current window. {cmd} can contain '|' to concatenate several commands. {cmd} must not open or close windows or reorder them. + Also see |:tabdo|, |:argdo|, |:bufdo|, |:cdo|, |:ldo|, |:cfdo| and |:lfdo|. @@ -778,6 +778,7 @@ can also get to them with the buffer list commands, like ":bnext". autocommand event is disabled by adding it to 'eventignore'. This considerably speeds up editing each buffer. + Also see |:tabdo|, |:argdo|, |:windo|, |:cdo|, |:ldo|, |:cfdo| and |:lfdo|. diff --git a/src/nvim/api/ui.c b/src/nvim/api/ui.c index 45c20d07e1..e6d8cb2fdb 100644 --- a/src/nvim/api/ui.c +++ b/src/nvim/api/ui.c @@ -453,7 +453,7 @@ void nvim_ui_try_resize_grid(uint64_t channel_id, Integer grid, Integer width, I } } -/// Tells Nvim the number of elements displaying in the popumenu, to decide +/// Tells Nvim the number of elements displaying in the popupmenu, to decide /// and movement. /// /// @param channel_id @@ -483,7 +483,7 @@ void nvim_ui_pum_set_height(uint64_t channel_id, Integer height, Error *err) ui->pum_nlines = (int)height; } -/// Tells Nvim the geometry of the popumenu, to align floating windows with an +/// Tells Nvim the geometry of the popupmenu, to align floating windows with an /// external popup menu. /// /// Note that this method is not to be confused with |nvim_ui_pum_set_height()|, diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index c18a8209cf..a8834b85aa 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -618,7 +618,7 @@ struct file_buffer { bool b_u_synced; // entry lists are synced long b_u_seq_last; // last used undo sequence number long b_u_save_nr_last; // counter for last file write - long b_u_seq_cur; // hu_seq of header below which we are now + long b_u_seq_cur; // uh_seq of header below which we are now time_t b_u_time_cur; // uh_time of header below which we are now long b_u_save_nr_cur; // file write nr after which we are now diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c index 8adeb19082..3e0cf82740 100644 --- a/src/nvim/debugger.c +++ b/src/nvim/debugger.c @@ -128,7 +128,7 @@ void do_debug(char *cmd) ignore_script = true; } - // don't debug any function call, e.g. from an expresion mapping + // don't debug any function call, e.g. from an expression mapping n = debug_break_level; debug_break_level = -1; diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c index a23fa22da2..bc31d702f4 100644 --- a/src/nvim/if_cscope.c +++ b/src/nvim/if_cscope.c @@ -649,7 +649,7 @@ static char *cs_create_cmd(char *csoption, char *pattern) return NULL; } - // Skip white space before the patter, except for text and pattern search, + // Skip white space before the pattern, except for text and pattern search, // they may want to use the leading white space. pat = pattern; if (search != 4 && search != 6) { diff --git a/src/nvim/keycodes.c b/src/nvim/keycodes.c index 9ec37fd564..61dc2ac035 100644 --- a/src/nvim/keycodes.c +++ b/src/nvim/keycodes.c @@ -861,10 +861,9 @@ int get_mouse_button(int code, bool *is_click, bool *is_drag) /// @param[in] from What characters to replace. /// @param[in] from_len Length of the "from" argument. /// @param[out] bufp Location where results were saved in case of success (allocated). -/// if *bufp is non-NULL, it will be used directly. it is -/// assumed to be 128 bytes long (enough for transcoding LHS -/// of mapping) -/// Will be set to NULL in case of failure. +/// If `*bufp` is non-NULL, it will be used directly, +/// and is assumed to be 128 bytes long (enough for transcoding LHS of mapping), +/// and will be set to NULL in case of failure. /// @param[in] flags REPTERM_FROM_PART see above /// REPTERM_DO_LT also translate /// REPTERM_NO_SPECIAL do not accept notation @@ -872,7 +871,7 @@ int get_mouse_button(int code, bool *is_click, bool *is_drag) /// @param[out] did_simplify set when some code was simplied, unless it is NULL. /// @param[in] cpo_flags Relevant flags derived from p_cpo, see CPO_TO_CPO_FLAGS. /// -/// @return Pointer to an allocated memory, which is also saved to "bufp". +/// @return The same as what `*bufp` is set to. char *replace_termcodes(const char *const from, const size_t from_len, char **const bufp, const int flags, bool *const did_simplify, const int cpo_flags) FUNC_ATTR_NONNULL_ARG(1, 3) diff --git a/test/functional/vimscript/map_functions_spec.lua b/test/functional/vimscript/map_functions_spec.lua index ed1863754a..8645b1e506 100644 --- a/test/functional/vimscript/map_functions_spec.lua +++ b/test/functional/vimscript/map_functions_spec.lua @@ -176,15 +176,12 @@ describe('mapset()', function() it('can restore mapping description from the dict returned by maparg()', function() meths.set_keymap('n', 'lhs', 'rhs', {desc = 'map description'}) - eq('\nn lhs rhs\n map description', - helpers.exec_capture("nmap lhs")) + eq('\nn lhs rhs\n map description', exec_capture("nmap lhs")) local mapargs = funcs.maparg('lhs', 'n', false, true) meths.set_keymap('n', 'lhs', 'rhs', {desc = 'MAP DESCRIPTION'}) - eq('\nn lhs rhs\n MAP DESCRIPTION', - helpers.exec_capture("nmap lhs")) + eq('\nn lhs rhs\n MAP DESCRIPTION', exec_capture("nmap lhs")) funcs.mapset('n', false, mapargs) - eq('\nn lhs rhs\n map description', - helpers.exec_capture("nmap lhs")) + eq('\nn lhs rhs\n map description', exec_capture("nmap lhs")) end) it('can restore "replace_keycodes" from the dict returned by maparg()', function() -- cgit From be72af2f9b6aa9ff57ef21eb4e517a74b7c2a2da Mon Sep 17 00:00:00 2001 From: bfredl Date: Mon, 26 Sep 2022 11:40:06 +0200 Subject: fix(cmdline): don't send invalid cursor with incsearch and cmdheight=0 fixes #20306 --- src/nvim/message.c | 14 +++++++------ test/functional/ui/cmdline_spec.lua | 42 +++++++++++++++++++++++++++++++++++++ test/functional/ui/screen.lua | 1 + 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/nvim/message.c b/src/nvim/message.c index b3e99d99a1..e0b0dfb0bc 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -1399,13 +1399,15 @@ void msg_start(void) msg_clr_eos(); } + // if cmdheight=0, we need to scroll in the first line of msg_grid upon the screen + if (p_ch == 0 && !ui_has(kUIMessages) && !msg_scrolled) { + msg_grid_validate(); + msg_scroll_up(false, true); + msg_scrolled++; + cmdline_row = Rows - 1; + } + if (!msg_scroll && full_screen) { // overwrite last message - if (cmdline_row >= Rows && !ui_has(kUIMessages)) { - msg_grid_validate(); - msg_scroll_up(false, true); - msg_scrolled++; - cmdline_row = Rows - 1; - } msg_row = cmdline_row; msg_col = cmdmsg_rl ? Columns - 1 : 0; } else if (msg_didout || (p_ch == 0 && !ui_has(kUIMessages))) { // start message on next line diff --git a/test/functional/ui/cmdline_spec.lua b/test/functional/ui/cmdline_spec.lua index 3669352901..845291b2eb 100644 --- a/test/functional/ui/cmdline_spec.lua +++ b/test/functional/ui/cmdline_spec.lua @@ -1196,4 +1196,46 @@ describe('cmdheight=0', function() {1:~ }| ]]} end) + + it('with multigrid', function() + clear{args={'--cmd', 'set cmdheight=0'}} + screen:attach{ext_multigrid=true} + screen:expect{grid=[[ + ## grid 1 + [2:-------------------------]| + [2:-------------------------]| + [2:-------------------------]| + [2:-------------------------]| + [2:-------------------------]| + ## grid 2 + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + ## grid 3 + ]], win_viewport={ + [2] = {win = {id = 1000}, topline = 0, botline = 2, curline = 0, curcol = 0, linecount = 1}; + }} + + feed '/p' + screen:expect{grid=[[ + ## grid 1 + [2:-------------------------]| + [2:-------------------------]| + [2:-------------------------]| + [2:-------------------------]| + [3:-------------------------]| + ## grid 2 + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + ## grid 3 + /p^ | + ]], win_viewport={ + [2] = {win = {id = 1000}, topline = 0, botline = 2, curline = 0, curcol = 0, linecount = 1}; + }} + end) end) diff --git a/test/functional/ui/screen.lua b/test/functional/ui/screen.lua index 6ee9e7b393..028fa2825d 100644 --- a/test/functional/ui/screen.lua +++ b/test/functional/ui/screen.lua @@ -769,6 +769,7 @@ end function Screen:_handle_grid_cursor_goto(grid, row, col) self._cursor.grid = grid + assert(row >= 0 and col >= 0) self._cursor.row = row + 1 self._cursor.col = col + 1 end -- cgit From be693462d5a5fd696b46ea4ea854c924421089b4 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Mon, 26 Sep 2022 21:23:43 +0800 Subject: fix(ui): allow redrawing statusline when msgsep is used (#20337) --- src/nvim/ex_docmd.c | 2 +- src/nvim/ex_getln.c | 4 +- test/functional/ui/cmdline_spec.lua | 128 ++++++++++++++++++++++++++++++++++-- 3 files changed, 127 insertions(+), 7 deletions(-) diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 7ece195374..96f98b92ca 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -6088,7 +6088,7 @@ static void ex_redrawstatus(exarg_T *eap) } else { status_redraw_curbuf(); } - if (msg_scrolled && (State & MODE_CMDLINE)) { + if (msg_scrolled && !msg_use_msgsep() && (State & MODE_CMDLINE)) { return; // redraw later } diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index bc31f5a6cf..4b54b58ac1 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -774,11 +774,11 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init // Redraw the statusline in case it uses the current mode using the mode() // function. - if (!cmd_silent && msg_scrolled == 0) { + if (!cmd_silent && (msg_scrolled == 0 || msg_use_msgsep())) { bool found_one = false; FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { - if (*p_stl != NUL || *wp->w_p_stl != NUL) { + if (*p_stl != NUL || *wp->w_p_stl != NUL || *p_wbr != NUL || *wp->w_p_wbr != NUL) { wp->w_redr_status = true; found_one = true; } diff --git a/test/functional/ui/cmdline_spec.lua b/test/functional/ui/cmdline_spec.lua index 845291b2eb..d7f2b2335e 100644 --- a/test/functional/ui/cmdline_spec.lua +++ b/test/functional/ui/cmdline_spec.lua @@ -5,6 +5,7 @@ local source = helpers.source local command = helpers.command local assert_alive = helpers.assert_alive local uname = helpers.uname +local exec = helpers.exec local eval = helpers.eval local eq = helpers.eq @@ -821,12 +822,23 @@ describe('statusline is redrawn on entering cmdline', function() ]]} end) - it('but not with scrolled messages', function() - command('set statusline=%{mode()}') - screen:try_resize(35,10) + it('with scrolled messages and msgsep', function() + screen:try_resize(35,14) + exec([[ + let g:count = 0 + autocmd CmdlineEnter * let g:count += 1 + split + resize 1 + setlocal statusline=%{mode()}%{g:count} + setlocal winbar=%{mode()}%{g:count} + ]]) feed(':echoerr doesnotexist') screen:expect{grid=[[ + {9:c1 }| | + {3:c1 }| + | + {1:~ }| {1:~ }| {1:~ }| {1:~ }| @@ -839,8 +851,27 @@ describe('statusline is redrawn on entering cmdline', function() ]]} feed(':echoerr doesnotexist') screen:expect{grid=[[ + {9:c2 }| + | + {3:c2 }| | {1:~ }| + {1:~ }| + {3: }| + {4:E121: Undefined variable: doesnotex}| + {4:ist} | + {5:Press ENTER or type command to cont}| + {4:E121: Undefined variable: doesnotex}| + {4:ist} | + {5:Press ENTER or type command to cont}| + {5:inue}^ | + ]]} + + feed(':echoerr doesnotexist') + screen:expect{grid=[[ + {9:c3 }| + | + {3:c3 }| {3: }| {4:E121: Undefined variable: doesnotex}| {4:ist} | @@ -848,6 +879,63 @@ describe('statusline is redrawn on entering cmdline', function() {4:E121: Undefined variable: doesnotex}| {4:ist} | {5:Press ENTER or type command to cont}| + {4:E121: Undefined variable: doesnotex}| + {4:ist} | + {5:Press ENTER or type command to cont}| + {5:inue}^ | + ]]} + + feed('') + screen:expect{grid=[[ + {9:n3 }| + ^ | + {3:n3 }| + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {2:[No Name] }| + | + ]]} + end) + + it('but not with scrolled messages without msgsep', function() + screen:try_resize(35,10) + exec([[ + let g:count = 0 + autocmd CmdlineEnter * let g:count += 1 + set display-=msgsep + set statusline=%{mode()}%{g:count} + ]]) + feed(':echoerr doesnotexist') + screen:expect{grid=[[ + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {3:c1 }| + {4:E121: Undefined variable: doesnotex}| + {4:ist} | + {5:Press ENTER or type command to cont}| + {5:inue}^ | + ]]} + feed(':echoerr doesnotexist') + screen:expect{grid=[[ + {1:~ }| + {1:~ }| + {3:c1 }| + {4:E121: Undefined variable: doesnotex}| + {4:ist} | + {5:Press ENTER or type command to cont}| + {4:E121: Undefined variable: doesnotex}| + {4:ist} | + {5:Press ENTER or type command to cont}| {5:inue}^ | ]]} @@ -875,7 +963,7 @@ describe('statusline is redrawn on entering cmdline', function() {1:~ }| {1:~ }| {1:~ }| - {3:n }| + {3:n3 }| | ]]} end) @@ -1238,4 +1326,36 @@ describe('cmdheight=0', function() [2] = {win = {id = 1000}, topline = 0, botline = 2, curline = 0, curcol = 0, linecount = 1}; }} end) + + it('winbar is redrawn on entering cmdline and :redrawstatus #20336', function() + exec([[ + set cmdheight=0 + set winbar=%{mode()}%=:%{getcmdline()} + ]]) + feed(':') + screen:expect([[ + {3:c :}| + | + {1:~ }| + {1:~ }| + :^ | + ]]) + feed('echo') + -- not redrawn yet + screen:expect([[ + {3:c :}| + | + {1:~ }| + {1:~ }| + :echo^ | + ]]) + command('redrawstatus') + screen:expect([[ + {3:c :echo}| + | + {1:~ }| + {1:~ }| + :echo^ | + ]]) + end) end) -- cgit From 9a5ac065093b58cceb676700b988584931cef150 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Mon, 26 Sep 2022 09:56:07 -0400 Subject: fix(docs): invalid :help links #20353 ref #20159 --- runtime/doc/builtin.txt | 8 ++++---- runtime/doc/eval.txt | 4 ++-- runtime/doc/ft_rust.txt | 2 +- runtime/doc/ft_sql.txt | 2 +- runtime/doc/insert.txt | 2 +- runtime/doc/pi_netrw.txt | 2 +- runtime/doc/quickref.txt | 1 - runtime/doc/usr_41.txt | 2 +- runtime/doc/windows.txt | 2 +- 9 files changed, 12 insertions(+), 13 deletions(-) diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 735116f9a0..4a889c67be 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -2628,7 +2628,7 @@ get({dict}, {key} [, {default}]) {default} is omitted. Useful example: > let val = get(g:, 'var_name', 'default') < This gets the value of g:var_name if it exists, and uses - 'default' when it does not exist. + "default" when it does not exist. get({func}, {what}) Get item {what} from Funcref {func}. Possible values for {what} are: @@ -3035,7 +3035,7 @@ getcurpos([{winid}]) cursor vertically. Also see |getcursorcharpos()| and |getpos()|. The first "bufnum" item is always zero. The byte position of - the cursor is returned in 'col'. To get the character + the cursor is returned in "col". To get the character position, use |getcursorcharpos()|. The optional {winid} argument can specify the window. It can @@ -3414,7 +3414,7 @@ getqflist([{what}]) *getqflist()* |quickfix-ID|; zero means the id for the current list or the list specified by "nr" idx get information for the quickfix entry at this - index in the list specified by 'id' or 'nr'. + index in the list specified by "id" or "nr". If set to zero, then uses the current entry. See |quickfix-index| items quickfix list entries @@ -7226,7 +7226,7 @@ setqflist({list} [, {action} [, {what}]]) *setqflist()* See |quickfix-parse| id quickfix list identifier |quickfix-ID| idx index of the current entry in the quickfix - list specified by 'id' or 'nr'. If set to '$', + list specified by "id" or "nr". If set to '$', then the last entry in the list is set as the current entry. See |quickfix-index| items list of quickfix entries. Same as the {list} diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index bfaa3b12e8..ae28977556 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -40,7 +40,7 @@ List An ordered sequence of items, see |List| for details. Dictionary An associative, unordered array: Each entry has a key and a value. |Dictionary| Examples: - {'blue': "#0000ff", 'red': "#ff0000"} + {"blue": "#0000ff", "red": "#ff0000"} #{blue: "#0000ff", red: "#ff0000"} Blob Binary Large Object. Stores any sequence of bytes. See |Blob| @@ -2531,7 +2531,7 @@ text... echo 'done' endif END -< Results in: ["if ok", " echo 'done'", "endif"] +< Results in: `["if ok", " echo 'done'", "endif"]` The marker must line up with "let" and the indentation of the first line is removed from all the text lines. Specifically: all the leading indentation exactly diff --git a/runtime/doc/ft_rust.txt b/runtime/doc/ft_rust.txt index 34932c48fb..3a0bf2293e 100644 --- a/runtime/doc/ft_rust.txt +++ b/runtime/doc/ft_rust.txt @@ -110,7 +110,7 @@ g:rustfmt_fail_silently~ < *g:rustfmt_options* g:rustfmt_options~ - Set this option to a string of options to pass to 'rustfmt'. The + Set this option to a string of options to pass to "rustfmt". The write-mode is already set to "overwrite". If not specified it defaults to '' : > let g:rustfmt_options = '' diff --git a/runtime/doc/ft_sql.txt b/runtime/doc/ft_sql.txt index 685726de90..03d9082aab 100644 --- a/runtime/doc/ft_sql.txt +++ b/runtime/doc/ft_sql.txt @@ -757,7 +757,7 @@ the syntax items for Perl. Step 2 ------ -Manually setting the filetype to 'sql' will also fire the appropriate filetype +Manually setting the filetype to "sql" will also fire the appropriate filetype files ftplugin/sql.vim. This file will define a number of buffer specific maps for SQL completion, see |sql-completion-maps|. Now these maps have been created and the SQL completion plugin has been initialized. All SQL diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt index 9ea963c812..63ceab78a8 100644 --- a/runtime/doc/insert.txt +++ b/runtime/doc/insert.txt @@ -1534,7 +1534,7 @@ The completions provided by CTRL-X CTRL-O are sensitive to the context: 3. After '.', '::' or ':' Methods applicable to the object being dereferenced - 4. After ':' or ':foo' Symbol name (beginning with 'foo') + 4. After ':' or ':foo' Symbol name (beginning with "foo") Notes: - Vim will load/evaluate code in order to provide completions. This may diff --git a/runtime/doc/pi_netrw.txt b/runtime/doc/pi_netrw.txt index ae0169491b..63d4496dc4 100644 --- a/runtime/doc/pi_netrw.txt +++ b/runtime/doc/pi_netrw.txt @@ -3569,7 +3569,7 @@ Example: Clear netrw's marked file list via a mapping on gu > http://www.chiark.greenend.org.uk/~sgtatham/putty/0.60/htmldoc/Chapter8.html#pubkey-gettingready (8.3 Getting ready for public key authentication) < - How to use a private key with 'pscp': > + How to use a private key with "pscp": > http://www.chiark.greenend.org.uk/~sgtatham/putty/0.60/htmldoc/Chapter5.html (5.2.4 Using public key authentication with PSCP) diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt index cb065cef2c..23ce16a40a 100644 --- a/runtime/doc/quickref.txt +++ b/runtime/doc/quickref.txt @@ -798,7 +798,6 @@ Short explanation of each option: *option-list* 'patchexpr' 'pex' expression used to patch a file 'patchmode' 'pm' keep the oldest version of a file 'path' 'pa' list of directories searched with "gf" et.al. -'perldll' name of the Perl dynamic library 'preserveindent' 'pi' preserve the indent structure when reindenting 'previewheight' 'pvh' height of the preview window 'previewpopup' 'pvp' use popup window for preview diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt index 4e7ec00148..fb9d59f885 100644 --- a/runtime/doc/usr_41.txt +++ b/runtime/doc/usr_41.txt @@ -1762,7 +1762,7 @@ does not exist as a mapped sequence. An error will be issued, which is very hard to identify, because the ending whitespace character in ":unmap ,ab " is not visible. -And this is the same as what happens when one uses a comment after an 'unmap' +And this is the same as what happens when one uses a comment after an "unmap" command: > :unmap ,ab " comment diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 3dc718a68f..45cedd2cd8 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -119,7 +119,7 @@ windows. *filler-lines* The lines after the last buffer line in a window are called filler lines. By -default, these lines start with a tilde (~) character. The 'eob' item in the +default, these lines start with a tilde (~) character. The "eob" item in the 'fillchars' option can be used to change this character. By default, these characters are highlighted as NonText (|hl-NonText|). The EndOfBuffer highlight group (|hl-EndOfBuffer|) can be used to change the highlighting of -- cgit From 7e98821e56a88487f24584463869432d8373a28e Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 27 Sep 2022 06:33:48 +0800 Subject: fix(ui): redraw end of buffer if last line is modified (#20354) --- src/nvim/drawscreen.c | 3 +- test/functional/ui/decorations_spec.lua | 104 ++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 1 deletion(-) diff --git a/src/nvim/drawscreen.c b/src/nvim/drawscreen.c index c95f3f3550..fdf70a081c 100644 --- a/src/nvim/drawscreen.c +++ b/src/nvim/drawscreen.c @@ -1965,7 +1965,8 @@ win_update_start: if (mid_end >= row) { lastline = MIN(lastline, mid_start); } - if (mod_bot > buf->b_ml.ml_line_count + 1) { + // if (mod_bot > buf->b_ml.ml_line_count + 1) { + if (mod_bot > buf->b_ml.ml_line_count) { lastline = 0; } diff --git a/test/functional/ui/decorations_spec.lua b/test/functional/ui/decorations_spec.lua index eff6fe6d23..9b48f0ac35 100644 --- a/test/functional/ui/decorations_spec.lua +++ b/test/functional/ui/decorations_spec.lua @@ -1281,6 +1281,110 @@ if (h->n_buckets < new_n_buckets) { // expand ]]} end) + it('works beyond end of the buffer with virt_lines_above', function() + insert(example_text) + feed 'G' + + screen:expect{grid=[[ + if (h->n_buckets < new_n_buckets) { // expand | + khkey_t *new_keys = (khkey_t *)krealloc((void *)| + h->keys, new_n_buckets * sizeof(khkey_t)); | + h->keys = new_keys; | + if (kh_is_map && val_size) { | + char *new_vals = krealloc( h->vals_buf, new_n_| + buckets * val_size); | + h->vals_buf = new_vals; | + } | + ^} | + {1:~ }| + | + ]]} + + local id = meths.buf_set_extmark(0, ns, 8, 0, { + virt_lines={{{"Grugg"}}}; + virt_lines_above = true, + }) + + screen:expect{grid=[[ + if (h->n_buckets < new_n_buckets) { // expand | + khkey_t *new_keys = (khkey_t *)krealloc((void *)| + h->keys, new_n_buckets * sizeof(khkey_t)); | + h->keys = new_keys; | + if (kh_is_map && val_size) { | + char *new_vals = krealloc( h->vals_buf, new_n_| + buckets * val_size); | + h->vals_buf = new_vals; | + } | + ^} | + Grugg | + | + ]]} + + feed('dd') + screen:expect{grid=[[ + if (h->n_buckets < new_n_buckets) { // expand | + khkey_t *new_keys = (khkey_t *)krealloc((void *)| + h->keys, new_n_buckets * sizeof(khkey_t)); | + h->keys = new_keys; | + if (kh_is_map && val_size) { | + char *new_vals = krealloc( h->vals_buf, new_n_| + buckets * val_size); | + h->vals_buf = new_vals; | + ^} | + Grugg | + {1:~ }| + | + ]]} + + feed('dk') + screen:expect{grid=[[ + if (h->n_buckets < new_n_buckets) { // expand | + khkey_t *new_keys = (khkey_t *)krealloc((void *)| + h->keys, new_n_buckets * sizeof(khkey_t)); | + h->keys = new_keys; | + if (kh_is_map && val_size) { | + ^char *new_vals = krealloc( h->vals_buf, new_n_| + buckets * val_size); | + Grugg | + {1:~ }| + {1:~ }| + {1:~ }| + | + ]]} + + feed('dgg') + screen:expect{grid=[[ + ^ | + Grugg | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + --No lines in buffer-- | + ]]} + + meths.buf_del_extmark(0, ns, id) + screen:expect{grid=[[ + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + --No lines in buffer-- | + ]]} + end) + it('does not cause syntax ml_get error at the end of a buffer #17816', function() command([[syntax region foo keepend start='^foo' end='^$']]) command('syntax sync minlines=100') -- cgit From 1d337d4e2f2265b13ecf19a3bc17ad302d3b0d96 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Tue, 27 Sep 2022 08:29:21 +0800 Subject: vim-patch:9.0.0595: extra newline in messages after a verbose shell message (#20359) Problem: Extra newline in messages after a verbose shell message. Solution: Output the newline with msg_putchar_attr(). (closes vim/vim#11233) Make it possible to filter a screendump before comparing it. https://github.com/vim/vim/commit/1190139ed01c27539615beea9559a88b2551daf3 Cherry-pick Test_message_more_scrolledback() from patch 9.0.0592 because Nvim already behaves as intended. --- src/nvim/message.c | 2 +- src/nvim/testdir/test_messages.vim | 60 ++++++++++++ test/functional/legacy/messages_spec.lua | 152 +++++++++++++++++++++++++++---- 3 files changed, 197 insertions(+), 17 deletions(-) diff --git a/src/nvim/message.c b/src/nvim/message.c index e0b0dfb0bc..fd20d9dd81 100644 --- a/src/nvim/message.c +++ b/src/nvim/message.c @@ -2315,7 +2315,7 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse) if (t_col > 0) { t_puts(&t_col, t_s, s, attr); } - if (p_more && !recurse) { + if (p_more && !recurse && !(s == sb_str + 1 && *sb_str == '\n')) { store_sb_text((char **)&sb_str, (char *)s, attr, &sb_col, false); } diff --git a/src/nvim/testdir/test_messages.vim b/src/nvim/testdir/test_messages.vim index 8e66a2c529..42a1fdcfe2 100644 --- a/src/nvim/testdir/test_messages.vim +++ b/src/nvim/testdir/test_messages.vim @@ -316,6 +316,66 @@ func Test_message_more() call StopVimInTerminal(buf) endfunc +" Test more-prompt scrollback +func Test_message_more_scrollback() + CheckRunVimInTerminal + + let lines =<< trim END + set t_ut= + hi Normal ctermfg=15 ctermbg=0 + for i in range(100) + echo i + endfor + END + call writefile(lines, 'XmoreScrollback', 'D') + let buf = RunVimInTerminal('-S XmoreScrollback', {'rows': 10}) + call VerifyScreenDump(buf, 'Test_more_scrollback_1', {}) + + call term_sendkeys(buf, 'f') + call TermWait(buf) + call term_sendkeys(buf, 'b') + call VerifyScreenDump(buf, 'Test_more_scrollback_2', {}) + + call term_sendkeys(buf, 'q') + call TermWait(buf) + call StopVimInTerminal(buf) +endfunc + +" Test verbose message before echo command +func Test_echo_verbose_system() + CheckRunVimInTerminal + CheckUnix + + let buf = RunVimInTerminal('', {'rows': 10}) + call term_sendkeys(buf, ":4 verbose echo system('seq 20')\") + " Note that the screendump is filtered to remove the name of the temp file + call VerifyScreenDump(buf, 'Test_verbose_system_1', {}) + + " display a page and go back, results in exactly the same view + call term_sendkeys(buf, ' ') + call TermWait(buf) + call term_sendkeys(buf, 'b') + call VerifyScreenDump(buf, 'Test_verbose_system_1', {}) + + " do the same with 'cmdheight' set to 2 + call term_sendkeys(buf, 'q') + call TermWait(buf) + call term_sendkeys(buf, ":set ch=2\") + call TermWait(buf) + call term_sendkeys(buf, ":4 verbose echo system('seq 20')\") + call VerifyScreenDump(buf, 'Test_verbose_system_2', {}) + + call term_sendkeys(buf, ' ') + call TermWait(buf) + call term_sendkeys(buf, 'b') + call VerifyScreenDump(buf, 'Test_verbose_system_2', {}) + + call term_sendkeys(buf, 'q') + call TermWait(buf) + call StopVimInTerminal(buf) +endfunc + + func Test_ask_yesno() CheckRunVimInTerminal let buf = RunVimInTerminal('', {'rows': 6}) diff --git a/test/functional/legacy/messages_spec.lua b/test/functional/legacy/messages_spec.lua index 5b671bbfdf..71a53c8381 100644 --- a/test/functional/legacy/messages_spec.lua +++ b/test/functional/legacy/messages_spec.lua @@ -4,6 +4,8 @@ local clear = helpers.clear local command = helpers.command local exec = helpers.exec local feed = helpers.feed +local meths = helpers.meths +local nvim_dir = helpers.nvim_dir before_each(clear) @@ -49,19 +51,18 @@ describe('messages', function() describe('more prompt', function() before_each(function() + command('set more') + end) + + -- oldtest: Test_message_more() + it('works', function() screen = Screen.new(75, 6) screen:set_default_attr_ids({ - [0] = {bold = true, foreground = Screen.colors.Blue}, -- NonText [1] = {bold = true, foreground = Screen.colors.SeaGreen}, -- MoreMsg [2] = {foreground = Screen.colors.Brown}, -- LineNr - [3] = {foreground = Screen.colors.Blue}, -- SpecialKey }) screen:attach() - command('set more') - end) - -- oldtest: Test_message_more() - it('works', function() command('call setline(1, range(1, 100))') feed(':%pfoo#') @@ -350,20 +351,139 @@ describe('messages', function() ]]) end) + -- oldtest: Test_echo_verbose_system() + it('verbose message before echo command', function() + screen = Screen.new(60, 10) + screen:set_default_attr_ids({ + [0] = {bold = true, foreground = Screen.colors.Blue}, -- NonText + [1] = {bold = true, foreground = Screen.colors.SeaGreen}, -- MoreMsg + }) + screen:attach() + + command('cd '..nvim_dir) + meths.set_option('shell', './shell-test') + meths.set_option('shellcmdflag', 'REP 20') + meths.set_option('shellxquote', '') -- win: avoid extra quotes + + -- display a page and go back, results in exactly the same view + feed([[:4 verbose echo system('foo')]]) + screen:expect([[ + Executing command: "'./shell-test' 'REP' '20' 'foo'" | + | + 0: foo | + 1: foo | + 2: foo | + 3: foo | + 4: foo | + 5: foo | + 6: foo | + {1:-- More --}^ | + ]]) + feed('') + screen:expect([[ + 7: foo | + 8: foo | + 9: foo | + 10: foo | + 11: foo | + 12: foo | + 13: foo | + 14: foo | + 15: foo | + {1:-- More --}^ | + ]]) + feed('b') + screen:expect([[ + Executing command: "'./shell-test' 'REP' '20' 'foo'" | + | + 0: foo | + 1: foo | + 2: foo | + 3: foo | + 4: foo | + 5: foo | + 6: foo | + {1:-- More --}^ | + ]]) + + -- do the same with 'cmdheight' set to 2 + feed('q') + command('set ch=2') + command('mode') -- FIXME: bottom is invalid after scrolling + screen:expect([[ + ^ | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + | + | + ]]) + feed([[:4 verbose echo system('foo')]]) + screen:expect([[ + Executing command: "'./shell-test' 'REP' '20' 'foo'" | + | + 0: foo | + 1: foo | + 2: foo | + 3: foo | + 4: foo | + 5: foo | + 6: foo | + {1:-- More --}^ | + ]]) + feed('') + screen:expect([[ + 7: foo | + 8: foo | + 9: foo | + 10: foo | + 11: foo | + 12: foo | + 13: foo | + 14: foo | + 15: foo | + {1:-- More --}^ | + ]]) + feed('b') + screen:expect([[ + Executing command: "'./shell-test' 'REP' '20' 'foo'" | + | + 0: foo | + 1: foo | + 2: foo | + 3: foo | + 4: foo | + 5: foo | + 6: foo | + {1:-- More --}^ | + ]]) + end) + -- oldtest: Test_quit_long_message() it('with control characters can be quit vim-patch:8.2.1844', function() - screen:try_resize(40, 10) + screen = Screen.new(40, 10) + screen:set_default_attr_ids({ + [0] = {bold = true, foreground = Screen.colors.Blue}, -- NonText + [1] = {bold = true, foreground = Screen.colors.SeaGreen}, -- MoreMsg + [2] = {foreground = Screen.colors.Blue}, -- SpecialKey + }) + screen:attach() + feed([[:echom range(9999)->join("\x01")]]) screen:expect([[ - 0{3:^A}1{3:^A}2{3:^A}3{3:^A}4{3:^A}5{3:^A}6{3:^A}7{3:^A}8{3:^A}9{3:^A}10{3:^A}11{3:^A}12| - {3:^A}13{3:^A}14{3:^A}15{3:^A}16{3:^A}17{3:^A}18{3:^A}19{3:^A}20{3:^A}21{3:^A}22| - {3:^A}23{3:^A}24{3:^A}25{3:^A}26{3:^A}27{3:^A}28{3:^A}29{3:^A}30{3:^A}31{3:^A}32| - {3:^A}33{3:^A}34{3:^A}35{3:^A}36{3:^A}37{3:^A}38{3:^A}39{3:^A}40{3:^A}41{3:^A}42| - {3:^A}43{3:^A}44{3:^A}45{3:^A}46{3:^A}47{3:^A}48{3:^A}49{3:^A}50{3:^A}51{3:^A}52| - {3:^A}53{3:^A}54{3:^A}55{3:^A}56{3:^A}57{3:^A}58{3:^A}59{3:^A}60{3:^A}61{3:^A}62| - {3:^A}63{3:^A}64{3:^A}65{3:^A}66{3:^A}67{3:^A}68{3:^A}69{3:^A}70{3:^A}71{3:^A}72| - {3:^A}73{3:^A}74{3:^A}75{3:^A}76{3:^A}77{3:^A}78{3:^A}79{3:^A}80{3:^A}81{3:^A}82| - {3:^A}83{3:^A}84{3:^A}85{3:^A}86{3:^A}87{3:^A}88{3:^A}89{3:^A}90{3:^A}91{3:^A}92| + 0{2:^A}1{2:^A}2{2:^A}3{2:^A}4{2:^A}5{2:^A}6{2:^A}7{2:^A}8{2:^A}9{2:^A}10{2:^A}11{2:^A}12| + {2:^A}13{2:^A}14{2:^A}15{2:^A}16{2:^A}17{2:^A}18{2:^A}19{2:^A}20{2:^A}21{2:^A}22| + {2:^A}23{2:^A}24{2:^A}25{2:^A}26{2:^A}27{2:^A}28{2:^A}29{2:^A}30{2:^A}31{2:^A}32| + {2:^A}33{2:^A}34{2:^A}35{2:^A}36{2:^A}37{2:^A}38{2:^A}39{2:^A}40{2:^A}41{2:^A}42| + {2:^A}43{2:^A}44{2:^A}45{2:^A}46{2:^A}47{2:^A}48{2:^A}49{2:^A}50{2:^A}51{2:^A}52| + {2:^A}53{2:^A}54{2:^A}55{2:^A}56{2:^A}57{2:^A}58{2:^A}59{2:^A}60{2:^A}61{2:^A}62| + {2:^A}63{2:^A}64{2:^A}65{2:^A}66{2:^A}67{2:^A}68{2:^A}69{2:^A}70{2:^A}71{2:^A}72| + {2:^A}73{2:^A}74{2:^A}75{2:^A}76{2:^A}77{2:^A}78{2:^A}79{2:^A}80{2:^A}81{2:^A}82| + {2:^A}83{2:^A}84{2:^A}85{2:^A}86{2:^A}87{2:^A}88{2:^A}89{2:^A}90{2:^A}91{2:^A}92| {1:-- More --}^ | ]]) feed('q') -- cgit From 760a8754c07a62afa4d83f4e254b1d45ae8cfc65 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 27 Sep 2022 12:36:33 +0200 Subject: vim-patch:9.0.0599: latexmkrc files are not recognized Problem: Latexmkrc files are not recognized. Solution: Use Perl filetype for latexmkrc files. (closes vim/vim#11241) https://github.com/vim/vim/commit/cde031938537970938437cdbb235bc0da755ae4a --- runtime/filetype.vim | 3 +++ runtime/lua/vim/filetype.lua | 2 ++ src/nvim/testdir/test_filetype.vim | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 11536adf69..ef04943d45 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1027,6 +1027,9 @@ au BufNewFile,BufRead Kconfig,Kconfig.debug setf kconfig " Lace (ISE) au BufNewFile,BufRead *.ace,*.ACE setf lace +" Latexmkrc +au BufNewFile,BufRead .latexmkrc,latexmkrc setf perl + " Latte au BufNewFile,BufRead *.latte,*.lte setf latte diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index bd317baae9..642f783e78 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -1496,6 +1496,8 @@ local filename = { ['/etc/shadow-'] = 'passwd', ['/etc/shadow'] = 'passwd', ['/etc/passwd.edit'] = 'passwd', + ['latexmkrc'] = 'perl', + ['.latexmkrc'] = 'perl', ['pf.conf'] = 'pf', ['main.cf'] = 'pfmain', pinerc = 'pine', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 4755d39cd3..6525bb3f62 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -412,7 +412,7 @@ let s:filename_checks = { \ 'pccts': ['file.g'], \ 'pcmk': ['file.pcmk'], \ 'pdf': ['file.pdf'], - \ 'perl': ['file.plx', 'file.al', 'file.psgi', 'gitolite.rc', '.gitolite.rc', 'example.gitolite.rc'], + \ 'perl': ['file.plx', 'file.al', 'file.psgi', 'gitolite.rc', '.gitolite.rc', 'example.gitolite.rc', '.latexmkrc', 'latexmkrc'], \ 'pf': ['pf.conf'], \ 'pfmain': ['main.cf'], \ 'php': ['file.php', 'file.php9', 'file.phtml', 'file.ctp', 'file.phpt', 'file.theme'], -- cgit From e176f9dacf28f56e91fcbc92f392228588a46c85 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 27 Sep 2022 12:38:31 +0200 Subject: vim-patch:9.0.0600: GYP files are not recognized Problem: GYP files are not recognized. Solution: Recognize GYP files. (closes vim/vim#11242) https://github.com/vim/vim/commit/d32474229213276c64cb293885a975dcb406fbc9 --- runtime/filetype.vim | 3 +++ runtime/lua/vim/filetype.lua | 2 ++ src/nvim/testdir/test_filetype.vim | 1 + 3 files changed, 6 insertions(+) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index ef04943d45..5f58ad87b8 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -803,6 +803,9 @@ au BufNewFile,BufRead */etc/group,*/etc/group-,*/etc/group.edit,*/etc/gshadow,*/ " GTK RC au BufNewFile,BufRead .gtkrc,gtkrc setf gtkrc +" GYP +au BufNewFile,BufRead *.gyp,*.gypi setf gyp + " Hack au BufRead,BufNewFile *.hack,*.hackpartial setf hack diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 642f783e78..66b89a7078 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -448,6 +448,8 @@ local extension = { gsp = 'gsp', gjs = 'javascript.glimmer', gts = 'typescript.glimmer', + gyp = 'gyp', + gypi = 'gyp', hack = 'hack', hackpartial = 'hack', haml = 'haml', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 6525bb3f62..746ca3318f 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -240,6 +240,7 @@ let s:filename_checks = { \ 'grub': ['/boot/grub/menu.lst', '/boot/grub/grub.conf', '/etc/grub.conf', 'any/boot/grub/grub.conf', 'any/boot/grub/menu.lst', 'any/etc/grub.conf'], \ 'gsp': ['file.gsp'], \ 'gtkrc': ['.gtkrc', 'gtkrc', '.gtkrc-file', 'gtkrc-file'], + \ 'gyp': ['file.gyp', 'file.gypi'], \ 'hack': ['file.hack', 'file.hackpartial'], \ 'haml': ['file.haml'], \ 'hamster': ['file.hsm'], -- cgit From fe0727a1bfebdb8dc27bd8c276566f203b4d6a18 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Tue, 27 Sep 2022 13:03:28 +0200 Subject: vim-patch:9.0.0602: new TypeScript extensions are not recognized Problem: New TypeScript extensions are not recognized. Solution: Recognize .mts and .cts files. (closes vim/vim#11237) https://github.com/vim/vim/commit/7fc6c0e4dab4e80b9806a973936af54276468513 --- runtime/filetype.vim | 11 +++++++---- runtime/lua/vim/filetype.lua | 2 ++ src/nvim/testdir/test_filetype.vim | 1 + 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 5f58ad87b8..3042e62508 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -771,8 +771,8 @@ au BufNewFile,BufRead gitolite.conf setf gitolite au BufNewFile,BufRead {,.}gitolite.rc,example.gitolite.rc setf perl " Glimmer-flavored TypeScript and JavaScript -au BufNewFile,BufRead *.gts setf typescript.glimmer -au BufNewFile,BufRead *.gjs setf javascript.glimmer +au BufNewFile,BufRead *.gts setf typescript.glimmer +au BufNewFile,BufRead *.gjs setf javascript.glimmer " Gnuplot scripts au BufNewFile,BufRead *.gpi,.gnuplot setf gnuplot @@ -2090,7 +2090,7 @@ au BufNewFile,BufReadPost *.tutor setf tutor " TWIG files au BufNewFile,BufReadPost *.twig setf twig -" Typescript or Qt translation file (which is XML) +" TypeScript or Qt translation file (which is XML) au BufNewFile,BufReadPost *.ts \ if getline(1) =~ ' Date: Sat, 14 Aug 2021 12:19:05 -0500 Subject: fix(api): notify dict watchers on nvim_set_var and vim.g setter Co-authored-by: bfredl Co-authored-by: Christian Clason --- src/nvim/api/private/helpers.c | 18 +++++++ src/nvim/eval/typval.c | 2 +- src/nvim/eval/vars.c | 8 +-- src/nvim/lua/stdlib.c | 19 +++++++ .../functional/ex_cmds/dict_notifications_spec.lua | 63 ++++++++++++++++++++++ 5 files changed, 103 insertions(+), 7 deletions(-) diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c index b888d09343..73b5489d5c 100644 --- a/src/nvim/api/private/helpers.c +++ b/src/nvim/api/private/helpers.c @@ -218,6 +218,8 @@ Object dict_set_var(dict_T *dict, String key, Object value, bool del, bool retva return rv; } + bool watched = tv_dict_is_watched(dict); + if (del) { // Delete the key if (di == NULL) { @@ -225,6 +227,10 @@ Object dict_set_var(dict_T *dict, String key, Object value, bool del, bool retva api_set_error(err, kErrorTypeValidation, "Key not found: %s", key.data); } else { + // Notify watchers + if (watched) { + tv_dict_watcher_notify(dict, key.data, NULL, &di->di_tv); + } // Return the old value if (retval) { rv = vim_to_object(&di->di_tv); @@ -241,11 +247,16 @@ Object dict_set_var(dict_T *dict, String key, Object value, bool del, bool retva return rv; } + typval_T oldtv = TV_INITIAL_VALUE; + if (di == NULL) { // Need to create an entry di = tv_dict_item_alloc_len(key.data, key.size); tv_dict_add(dict, di); } else { + if (watched) { + tv_copy(&di->di_tv, &oldtv); + } // Return the old value if (retval) { rv = vim_to_object(&di->di_tv); @@ -255,6 +266,13 @@ Object dict_set_var(dict_T *dict, String key, Object value, bool del, bool retva // Update the value tv_copy(&tv, &di->di_tv); + + // Notify watchers + if (watched) { + tv_dict_watcher_notify(dict, key.data, &tv, &oldtv); + tv_clear(&oldtv); + } + // Clear the temporary variable tv_clear(&tv); } diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index f9aed7a966..5639414dad 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -1781,7 +1781,7 @@ void tv_dict_watcher_notify(dict_T *const dict, const char *const key, typval_T tv_dict_add(argv[2].vval.v_dict, v); } - if (oldtv) { + if (oldtv && oldtv->v_type != VAR_UNKNOWN) { dictitem_T *const v = tv_dict_item_alloc_len(S_LEN("old")); tv_copy(oldtv, &v->di_tv); tv_dict_add(argv[2].vval.v_dict, v); diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index 1c07fc4d45..4d7214205d 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -1348,12 +1348,8 @@ void set_var_const(const char *name, const size_t name_len, typval_T *const tv, } if (watched) { - if (oldtv.v_type == VAR_UNKNOWN) { - tv_dict_watcher_notify(dict, (char *)v->di_key, &v->di_tv, NULL); - } else { - tv_dict_watcher_notify(dict, (char *)v->di_key, &v->di_tv, &oldtv); - tv_clear(&oldtv); - } + tv_dict_watcher_notify(dict, (char *)v->di_key, &v->di_tv, &oldtv); + tv_clear(&oldtv); } if (is_const) { diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c index 9b1890403e..498f956ed9 100644 --- a/src/nvim/lua/stdlib.c +++ b/src/nvim/lua/stdlib.c @@ -369,12 +369,19 @@ int nlua_setvar(lua_State *lstate) return 0; } + bool watched = tv_dict_is_watched(dict); + if (del) { // Delete the key if (di == NULL) { // Doesn't exist, nothing to do return 0; } else { + // Notify watchers + if (watched) { + tv_dict_watcher_notify(dict, key.data, NULL, &di->di_tv); + } + // Delete the entry tv_dict_item_remove(dict, di); } @@ -388,17 +395,29 @@ int nlua_setvar(lua_State *lstate) return luaL_error(lstate, "Couldn't convert lua value"); } + typval_T oldtv = TV_INITIAL_VALUE; + if (di == NULL) { // Need to create an entry di = tv_dict_item_alloc_len(key.data, key.size); tv_dict_add(dict, di); } else { + if (watched) { + tv_copy(&di->di_tv, &oldtv); + } // Clear the old value tv_clear(&di->di_tv); } // Update the value tv_copy(&tv, &di->di_tv); + + // Notify watchers + if (watched) { + tv_dict_watcher_notify(dict, key.data, &tv, &oldtv); + tv_clear(&oldtv); + } + // Clear the temporary variable tv_clear(&tv); } diff --git a/test/functional/ex_cmds/dict_notifications_spec.lua b/test/functional/ex_cmds/dict_notifications_spec.lua index 21adcf37da..afa6b519d5 100644 --- a/test/functional/ex_cmds/dict_notifications_spec.lua +++ b/test/functional/ex_cmds/dict_notifications_spec.lua @@ -4,6 +4,7 @@ local clear, nvim, source = helpers.clear, helpers.nvim, helpers.source local insert = helpers.insert local eq, next_msg = helpers.eq, helpers.next_msg local exc_exec = helpers.exc_exec +local exec_lua = helpers.exec_lua local command = helpers.command local eval = helpers.eval @@ -21,6 +22,8 @@ describe('VimL dictionary notifications', function() -- t:) and a dictionary variable, so we generate them in the following -- function. local function gentests(dict_expr, dict_init) + local is_g = dict_expr == 'g:' + local function update(opval, key) if not key then key = 'watched' @@ -32,6 +35,28 @@ describe('VimL dictionary notifications', function() end end + local function update_with_api(opval, key) + if not key then + key = 'watched' + end + if opval == '' then + exec_lua(('vim.api.nvim_del_var(\'%s\')'):format(key)) + else + exec_lua(('vim.api.nvim_set_var(\'%s\', %s)'):format(key, opval)) + end + end + + local function update_with_vim_g(opval, key) + if not key then + key = 'watched' + end + if opval == '' then + exec_lua(('vim.g.%s = nil'):format(key)) + else + exec_lua(('vim.g.%s %s'):format(key, opval)) + end + end + local function verify_echo() -- helper to verify that no notifications are sent after certain change -- to a dict @@ -76,6 +101,18 @@ describe('VimL dictionary notifications', function() update('', 'watched2') update('') verify_echo() + if is_g then + update_with_api('"test"') + update_with_api('"test2"', 'watched2') + update_with_api('', 'watched2') + update_with_api('') + verify_echo() + update_with_vim_g('= "test"') + update_with_vim_g('= "test2"', 'watched2') + update_with_vim_g('', 'watched2') + update_with_vim_g('') + verify_echo() + end end) it('is not triggered when unwatched keys are updated', function() @@ -83,6 +120,16 @@ describe('VimL dictionary notifications', function() update('.= "noop2"', 'unwatched') update('', 'unwatched') verify_echo() + if is_g then + update_with_api('"noop"', 'unwatched') + update_with_api('vim.g.unwatched .. "noop2"', 'unwatched') + update_with_api('', 'unwatched') + verify_echo() + update_with_vim_g('= "noop"', 'unwatched') + update_with_vim_g('= vim.g.unwatched .. "noop2"', 'unwatched') + update_with_vim_g('', 'unwatched') + verify_echo() + end end) it('is triggered by remove()', function() @@ -92,6 +139,22 @@ describe('VimL dictionary notifications', function() verify_value({old = 'test'}) end) + if is_g then + it('is triggered by remove() when updated with nvim_*_var', function() + update_with_api('"test"') + verify_value({new = 'test'}) + nvim('command', 'call remove('..dict_expr..', "watched")') + verify_value({old = 'test'}) + end) + + it('is triggered by remove() when updated with vim.g', function() + update_with_vim_g('= "test"') + verify_value({new = 'test'}) + nvim('command', 'call remove('..dict_expr..', "watched")') + verify_value({old = 'test'}) + end) + end + it('is triggered by extend()', function() update('= "xtend"') verify_value({new = 'xtend'}) -- cgit From 6afe5cce7964258f7ee0b25ae08faa551bc76090 Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Tue, 27 Sep 2022 14:53:48 +0200 Subject: ci(backport): bump to backport-action@v0.0.8 #20366 Primary bug fix is allowing backports with empty PR description. --- .github/workflows/backport.yml | 2 +- MAINTAIN.md | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml index b5fd22d036..910df32a51 100644 --- a/.github/workflows/backport.yml +++ b/.github/workflows/backport.yml @@ -21,7 +21,7 @@ jobs: fetch-depth: 0 ref: ${{ github.event.pull_request.head.sha }} - name: Create backport PRs - uses: zeebe-io/backport-action@v0.0.7 + uses: zeebe-io/backport-action@v0.0.8 with: github_token: ${{ secrets.GITHUB_TOKEN }} github_workspace: ${{ github.workspace }} diff --git a/MAINTAIN.md b/MAINTAIN.md index 9a8531fbd9..36ba07593d 100644 --- a/MAINTAIN.md +++ b/MAINTAIN.md @@ -57,8 +57,7 @@ has a major bug: The neovim repository includes a backport [github action](https://github.com/zeebe-io/backport-action). In order to trigger the action, a PR must be labeled with a label matching the -form `backport release-0.X`. Note, the PR must have a description in the issue body, -or the backport will fail. +form `backport release-0.X`. Third-party dependencies -------------- -- cgit From f46060c4cbc1efe100019075214def53fe4d47b3 Mon Sep 17 00:00:00 2001 From: ObserverOfTime Date: Tue, 27 Sep 2022 17:10:19 +0300 Subject: vim-patch:9.0.0604: luacheckrc file is not recognized (#20371) Problem: Luacheckrc file is not recognized. Solution: Use lua filetype for luacheckrc. (closes vim/vim#11236) https://github.com/vim/vim/commit/49c311c9b18e18c05f93728d1f8a552923a18423 --- runtime/filetype.vim | 3 +++ runtime/lua/vim/filetype.lua | 1 + src/nvim/testdir/test_filetype.vim | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 3042e62508..204bf1865f 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1113,6 +1113,9 @@ au BufNewFile,BufRead *.lou,*.lout setf lout " Lua au BufNewFile,BufRead *.lua setf lua +" Luacheck +au BufNewFile,BufRead .luacheckrc setf lua + " Luarocks au BufNewFile,BufRead *.rockspec setf lua diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index a7a34a54cd..d584d2659d 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -1455,6 +1455,7 @@ local filename = { ['.sawfishrc'] = 'lisp', ['/etc/login.access'] = 'loginaccess', ['/etc/login.defs'] = 'logindefs', + ['.luacheckrc'] = 'lua', ['lynx.cfg'] = 'lynx', ['m3overrides'] = 'm3build', ['m3makefile'] = 'm3build', diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 6f7d9f75e6..05aee9b31d 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -328,7 +328,7 @@ let s:filename_checks = { \ 'lpc': ['file.lpc', 'file.ulpc'], \ 'lsl': ['file.lsl'], \ 'lss': ['file.lss'], - \ 'lua': ['file.lua', 'file.rockspec', 'file.nse'], + \ 'lua': ['file.lua', 'file.rockspec', 'file.nse', '.luacheckrc'], \ 'lynx': ['lynx.cfg'], \ 'lyrics': ['file.lrc'], \ 'm3build': ['m3makefile', 'm3overrides'], -- cgit From e6c214033a4fadf60faf99e95f8e9787e3c5e630 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 28 Sep 2022 06:22:11 +0800 Subject: fix(window): fix equalization with cmdheight=0 (#20369) --- src/nvim/window.c | 2 +- test/functional/ui/cmdline_spec.lua | 57 +++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/nvim/window.c b/src/nvim/window.c index 22c1b77570..5523c3df8b 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -2239,7 +2239,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int // Compute maximum number of windows vertically in this frame. n = frame_minheight(topfr, NOWIN); // add one for the bottom window if it doesn't have a statusline or separator - if (row + height == cmdline_row && p_ls == 0) { + if (row + height >= cmdline_row && p_ls == 0) { extra_sep = STATUS_HEIGHT; } else if (global_stl_height() > 0) { extra_sep = 1; diff --git a/test/functional/ui/cmdline_spec.lua b/test/functional/ui/cmdline_spec.lua index d7f2b2335e..1528b5307d 100644 --- a/test/functional/ui/cmdline_spec.lua +++ b/test/functional/ui/cmdline_spec.lua @@ -1358,4 +1358,61 @@ describe('cmdheight=0', function() :echo^ | ]]) end) + + it('window equalization with laststatus=0 #20367', function() + screen:try_resize(60, 9) + command('set cmdheight=0 laststatus=0') + command('vsplit') + screen:expect([[ + ^ │ | + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + ]]) + feed(':') + command('split') + feed('') + screen:expect([[ + ^ │ | + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {2:[No Name] }│{1:~ }| + │{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + ]]) + command('resize 2') + screen:expect([[ + ^ │ | + {1:~ }│{1:~ }| + {2:[No Name] }│{1:~ }| + │{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + ]]) + feed(':') + command('wincmd =') + feed('') + screen:expect([[ + ^ │ | + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {2:[No Name] }│{1:~ }| + │{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + {1:~ }│{1:~ }| + ]]) + end) end) -- cgit From 4b7904d16b11915b16ea46b96f1ea6e28d87d5fd Mon Sep 17 00:00:00 2001 From: Famiu Haque Date: Tue, 27 Sep 2022 21:16:28 +0600 Subject: refactor: replace unnecessary helper functions in optionstr.c Replaces unnecessary helper functions in `optionstr.c` such as `get_option_flags()`, `get_option_fullname()`, `set_option_flag()`, `is_global_option()`, etc. with a single `get_option()` helper function that allows direct access to the `options` array. Also refactors `f_exists()` to use `get_varp_scope` instead of using `get_option_tv`. This opens up the path for removing `getoptions_T` altogether later down the line since the hidden option logic is no longer needed. --- src/nvim/eval.c | 5 --- src/nvim/eval/funcs.c | 11 ++++-- src/nvim/option.c | 101 ++----------------------------------------------- src/nvim/option_defs.h | 37 ++++++++++++++++++ src/nvim/optionstr.c | 76 +++++++++++++++++++------------------ 5 files changed, 89 insertions(+), 141 deletions(-) diff --git a/src/nvim/eval.c b/src/nvim/eval.c index c2a7b6bba5..6eaf3d1f5e 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -3659,7 +3659,6 @@ static int eval_index(char **arg, typval_T *rettv, int evaluate, int verbose) int get_option_tv(const char **const arg, typval_T *const rettv, const bool evaluate) FUNC_ATTR_NONNULL_ARG(1) { - bool working = (**arg == '+'); // has("+option") int opt_flags; // Isolate the option name and find its value. @@ -3704,10 +3703,6 @@ int get_option_tv(const char **const arg, typval_T *const rettv, const bool eval rettv->v_type = VAR_STRING; rettv->vval.v_string = stringval; } - } else if (working && (opt_type == gov_hidden_bool - || opt_type == gov_hidden_number - || opt_type == gov_hidden_string)) { - ret = FAIL; } *option_end = c; // put back for error messages diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 9ba2ce2365..f2ef8e5cdd 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -1938,9 +1938,14 @@ static void f_exists(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) xfree(exp); } } else if (*p == '&' || *p == '+') { // Option. - n = (get_option_tv(&p, NULL, true) == OK); - if (*skipwhite(p) != NUL) { - n = false; // Trailing garbage. + bool working = (*p == '+'); // whether option needs to be working + int opt_flags; + + if (find_option_end(&p, &opt_flags) != NULL) { + int opt_idx = findoption(p); + n = (opt_idx >= 0 && (!working || get_varp_scope(get_option(opt_idx), opt_flags) != NULL)); + } else { + n = false; } } else if (*p == '*') { // Internal or user defined function. n = function_exists(p + 1, false); diff --git a/src/nvim/option.c b/src/nvim/option.c index 5b67f0e471..e7d0b171f6 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -106,30 +106,6 @@ static char e_number_required_after_equal[] static char e_preview_window_already_exists[] = N_("E590: A preview window already exists"); -// The options that are local to a window or buffer have "indir" set to one of -// these values. Special values: -// PV_NONE: global option. -// PV_WIN is added: window-local option -// PV_BUF is added: buffer-local option -// PV_BOTH is added: global option which also has a local value. -#define PV_BOTH 0x1000 -#define PV_WIN 0x2000 -#define PV_BUF 0x4000 -#define PV_MASK 0x0fff -#define OPT_WIN(x) (idopt_T)(PV_WIN + (int)(x)) -#define OPT_BUF(x) (idopt_T)(PV_BUF + (int)(x)) -#define OPT_BOTH(x) (idopt_T)(PV_BOTH + (int)(x)) - -// WV_ and BV_ values get typecasted to this for the "indir" field -typedef enum { - PV_NONE = 0, - PV_MAXVAL = 0xffff, // to avoid warnings for value out of range -} idopt_T; - -// Options local to a window have a value local to a buffer and global to all -// buffers. Indicate this by setting "var" to VAR_WIN. -#define VAR_WIN ((char_u *)-1) - static char *p_term = NULL; static char *p_ttytype = NULL; @@ -147,19 +123,6 @@ static long p_tw_nopaste; static long p_wm_nopaste; static char *p_vsts_nopaste; -typedef struct vimoption { - char *fullname; // full option name - char *shortname; // permissible abbreviation - uint32_t flags; // see below - char_u *var; // global option: pointer to variable; - // window-local option: VAR_WIN; - // buffer-local option: global value - idopt_T indir; // global option: PV_NONE; - // local option: indirect option index - char *def_val; // default values for variable (neovim!!) - LastSet last_set; // script in which the option was last set -} vimoption_T; - // options[] is initialized here. // The order of the options MUST be alphabetic for ":set all" and findoption(). // All option names MUST start with a lowercase letter (for findoption()). @@ -3047,47 +3010,10 @@ int get_option_value_strict(char *name, int64_t *numval, char **stringval, int o return rv; } -/// Return the flags for the option at 'opt_idx'. -uint32_t get_option_flags(int opt_idx) -{ - return options[opt_idx].flags; -} - -/// Set a flag for the option at 'opt_idx'. -void set_option_flag(int opt_idx, uint32_t flag) -{ - options[opt_idx].flags |= flag; -} - -/// Clear a flag for the option at 'opt_idx'. -void clear_option_flag(int opt_idx, uint32_t flag) -{ - options[opt_idx].flags &= ~flag; -} - -/// Returns true if the option at 'opt_idx' is a global option -bool is_global_option(int opt_idx) -{ - return options[opt_idx].indir == PV_NONE; -} - -/// Returns true if the option at 'opt_idx' is a global option which also has a -/// local value. -int is_global_local_option(int opt_idx) +// Return information for option at 'opt_idx' +vimoption_T *get_option(int opt_idx) { - return options[opt_idx].indir & PV_BOTH; -} - -/// Returns true if the option at 'opt_idx' is a window-local option -bool is_window_local_option(int opt_idx) -{ - return options[opt_idx].var == VAR_WIN; -} - -/// Returns true if the option at 'opt_idx' is a hidden option -bool is_hidden_option(int opt_idx) -{ - return options[opt_idx].var == NULL; + return &options[opt_idx]; } /// Set the value of an option @@ -3761,7 +3687,7 @@ void unset_global_local_option(char *name, void *from) } /// Get pointer to option variable, depending on local or global scope. -static char *get_varp_scope(vimoption_T *p, int opt_flags) +char *get_varp_scope(vimoption_T *p, int opt_flags) { if ((opt_flags & OPT_GLOBAL) && p->indir != PV_NONE) { if (p->var == VAR_WIN) { @@ -3833,13 +3759,6 @@ static char *get_varp_scope(vimoption_T *p, int opt_flags) return (char *)get_varp(p); } -/// Get pointer to option variable at 'opt_idx', depending on local or global -/// scope. -char *get_option_varp_scope(int opt_idx, int opt_flags) -{ - return get_varp_scope(&(options[opt_idx]), opt_flags); -} - /// Get pointer to option variable. static char_u *get_varp(vimoption_T *p) { @@ -4149,18 +4068,6 @@ static char_u *get_varp(vimoption_T *p) return (char_u *)&(curbuf->b_p_wm); } -/// Return a pointer to the variable for option at 'opt_idx' -char_u *get_option_var(int opt_idx) -{ - return options[opt_idx].var; -} - -/// Return the full name of the option at 'opt_idx' -char *get_option_fullname(int opt_idx) -{ - return options[opt_idx].fullname; -} - /// Get the value of 'equalprg', either the buffer-local one or the global one. char_u *get_equalprg(void) { diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index e8cf338cf1..e27607d7a8 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -990,4 +990,41 @@ typedef struct { uint64_t channel_id; /// Only used when script_id is SID_API_CLIENT. } LastSet; +// WV_ and BV_ values get typecasted to this for the "indir" field +typedef enum { + PV_NONE = 0, + PV_MAXVAL = 0xffff, // to avoid warnings for value out of range +} idopt_T; + +typedef struct vimoption { + char *fullname; // full option name + char *shortname; // permissible abbreviation + uint32_t flags; // see below + char_u *var; // global option: pointer to variable; + // window-local option: VAR_WIN; + // buffer-local option: global value + idopt_T indir; // global option: PV_NONE; + // local option: indirect option index + char *def_val; // default values for variable (neovim!!) + LastSet last_set; // script in which the option was last set +} vimoption_T; + +// The options that are local to a window or buffer have "indir" set to one of +// these values. Special values: +// PV_NONE: global option. +// PV_WIN is added: window-local option +// PV_BUF is added: buffer-local option +// PV_BOTH is added: global option which also has a local value. +#define PV_BOTH 0x1000 +#define PV_WIN 0x2000 +#define PV_BUF 0x4000 +#define PV_MASK 0x0fff +#define OPT_WIN(x) (idopt_T)(PV_WIN + (int)(x)) +#define OPT_BUF(x) (idopt_T)(PV_BUF + (int)(x)) +#define OPT_BOTH(x) (idopt_T)(PV_BOTH + (int)(x)) + +// Options local to a window have a value local to a buffer and global to all +// buffers. Indicate this by setting "var" to VAR_WIN. +#define VAR_WIN ((char_u *)-1) + #endif // NVIM_OPTION_DEFS_H diff --git a/src/nvim/optionstr.c b/src/nvim/optionstr.c index 7278b1a12d..aff88a755b 100644 --- a/src/nvim/optionstr.c +++ b/src/nvim/optionstr.c @@ -178,7 +178,7 @@ void trigger_optionsset_string(int opt_idx, int opt_flags, char *oldval, char *o set_vim_var_string(VV_OPTION_COMMAND, "modeline", -1); set_vim_var_string(VV_OPTION_OLDLOCAL, oldval, -1); } - apply_autocmds(EVENT_OPTIONSET, get_option_fullname(opt_idx), NULL, false, NULL); + apply_autocmds(EVENT_OPTIONSET, get_option(opt_idx)->fullname, NULL, false, NULL); reset_v_option_vars(); } } @@ -280,19 +280,19 @@ void check_string_option(char **pp) /// Set global value for string option when it's a local option. /// -/// @param opt_idx option index +/// @param opt option /// @param varp pointer to option variable -static void set_string_option_global(int opt_idx, char **varp) +static void set_string_option_global(vimoption_T *opt, char **varp) { char **p; // the global value is always allocated - if (is_window_local_option(opt_idx)) { + if (opt->var == VAR_WIN) { p = (char **)GLOBAL_WO(varp); } else { - p = (char **)get_option_var(opt_idx); + p = (char **)opt->var; } - if (!is_global_option(opt_idx) && p != varp) { + if (opt->indir != PV_NONE && p != varp) { char *s = xstrdup(*varp); free_string_option(*p); *p = s; @@ -324,30 +324,32 @@ void set_string_option_direct(const char *name, int opt_idx, const char *val, in } } - if (is_hidden_option(idx)) { // can't set hidden option + vimoption_T *opt = get_option(idx); + + if (opt->var == NULL) { // can't set hidden option return; } - assert((void *)get_option_var(idx) != (void *)&p_shada); + assert((void *)opt->var != (void *)&p_shada); s = xstrdup(val); { - varp = (char **)get_option_varp_scope(idx, both ? OPT_LOCAL : opt_flags); - if ((opt_flags & OPT_FREE) && (get_option_flags(idx) & P_ALLOCED)) { + varp = (char **)get_varp_scope(opt, both ? OPT_LOCAL : opt_flags); + if ((opt_flags & OPT_FREE) && (opt->flags & P_ALLOCED)) { free_string_option(*varp); } *varp = s; // For buffer/window local option may also set the global value. if (both) { - set_string_option_global(idx, varp); + set_string_option_global(opt, varp); } - set_option_flag(idx, P_ALLOCED); + opt->flags |= P_ALLOCED; // When setting both values of a global option with a local value, // make the local value empty, so that the global value is used. - if (is_global_local_option(idx) && both) { + if ((opt->indir & PV_BOTH) && both) { free_string_option(*varp); *varp = empty_option; } @@ -393,24 +395,24 @@ void set_string_option_direct_in_win(win_T *wp, const char *name, int opt_idx, c char *set_string_option(const int opt_idx, const char *const value, const int opt_flags) FUNC_ATTR_NONNULL_ARG(2) FUNC_ATTR_WARN_UNUSED_RESULT { - if (is_hidden_option(opt_idx)) { // don't set hidden option + vimoption_T *opt = get_option(opt_idx); + + if (opt->var == NULL) { // don't set hidden option return NULL; } char *const s = xstrdup(value); char **const varp - = (char **)get_option_varp_scope(opt_idx, - (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 - ? (is_global_local_option(opt_idx) - ? OPT_GLOBAL : OPT_LOCAL) - : opt_flags); + = (char **)get_varp_scope(opt, ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 + ? ((opt->indir & PV_BOTH) ? OPT_GLOBAL : OPT_LOCAL) + : opt_flags)); char *const oldval = *varp; char *oldval_l = NULL; char *oldval_g = NULL; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0) { - oldval_l = *(char **)get_option_varp_scope(opt_idx, OPT_LOCAL); - oldval_g = *(char **)get_option_varp_scope(opt_idx, OPT_GLOBAL); + oldval_l = *(char **)get_varp_scope(opt, OPT_LOCAL); + oldval_g = *(char **)get_varp_scope(opt, OPT_GLOBAL); } *varp = s; @@ -434,8 +436,8 @@ char *set_string_option(const int opt_idx, const char *const value, const int op trigger_optionsset_string(opt_idx, opt_flags, saved_oldval, saved_oldval_l, saved_oldval_g, saved_newval); } - if (get_option_flags(opt_idx) & P_UI_OPTION) { - ui_call_option_set(cstr_as_string(get_option_fullname(opt_idx)), + if (opt->flags & P_UI_OPTION) { + ui_call_option_set(cstr_as_string(opt->fullname), STRING_OBJ(cstr_as_string(saved_newval))); } } @@ -638,20 +640,21 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf char *errmsg = NULL; char *s, *p; int did_chartab = false; - bool free_oldval = (get_option_flags(opt_idx) & P_ALLOCED); + vimoption_T *opt = get_option(opt_idx); + bool free_oldval = (opt->flags & P_ALLOCED); bool value_changed = false; // Get the global option to compare with, otherwise we would have to check // two values for all local options. - char **gvarp = (char **)get_option_varp_scope(opt_idx, OPT_GLOBAL); + char **gvarp = (char **)get_varp_scope(opt, OPT_GLOBAL); // Disallow changing some options from secure mode if ((secure || sandbox != 0) - && (get_option_flags(opt_idx) & P_SECURE)) { + && (opt->flags & P_SECURE)) { errmsg = e_secure; - } else if (((get_option_flags(opt_idx) & P_NFNAME) + } else if (((opt->flags & P_NFNAME) && strpbrk(*varp, (secure ? "/\\*?[|;&<>\r\n" : "/\\*?[<>\r\n")) != NULL) - || ((get_option_flags(opt_idx) & P_NDNAME) + || ((opt->flags & P_NDNAME) && strpbrk(*varp, "*?[|;&<>\r\n") != NULL)) { // Check for a "normal" directory or file name in some options. Disallow a // path separator (slash and/or backslash), wildcards and characters that @@ -986,13 +989,14 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } else if (varp == &p_shada) { // 'shada' // TODO(ZyX-I): Remove this code in the future, alongside with &viminfo // option. - opt_idx = ((get_option_fullname(opt_idx)[0] == 'v') + opt_idx = ((opt->fullname[0] == 'v') ? (shada_idx == -1 ? ((shada_idx = findoption("shada"))) : shada_idx) : opt_idx); + opt = get_option(opt_idx); // Update free_oldval now that we have the opt_idx for 'shada', otherwise // there would be a disconnect between the check for P_ALLOCED at the start // of the function and the set of P_ALLOCED at the end of the function. - free_oldval = (get_option_flags(opt_idx) & P_ALLOCED); + free_oldval = (opt->flags & P_ALLOCED); for (s = p_shada; *s;) { // Check it's a valid character if (vim_strchr("!\"%'/:<@cfhnrs", *s) == NULL) { @@ -1522,18 +1526,18 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf if (free_oldval) { free_string_option(oldval); } - set_option_flag(opt_idx, P_ALLOCED); + opt->flags |= P_ALLOCED; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 - && is_global_local_option(opt_idx)) { + && (opt->indir & PV_BOTH)) { // global option with local value set to use global value; free // the local value and make it empty - p = get_option_varp_scope(opt_idx, OPT_LOCAL); + p = get_varp_scope(opt, OPT_LOCAL); free_string_option(*(char **)p); *(char **)p = empty_option; } else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL) { // May set global value for local option. - set_string_option_global(opt_idx, varp); + set_string_option_global(opt, varp); } // Trigger the autocommand only after setting the flags. @@ -1604,11 +1608,11 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf } if (curwin->w_curswant != MAXCOL - && (get_option_flags(opt_idx) & (P_CURSWANT | P_RALL)) != 0) { + && (opt->flags & (P_CURSWANT | P_RALL)) != 0) { curwin->w_set_curswant = true; } - check_redraw(get_option_flags(opt_idx)); + check_redraw(opt->flags); return errmsg; } -- cgit From 6427dc8ab66e5885c133698e3e96e82ab74a89f3 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Wed, 28 Sep 2022 09:28:15 +0200 Subject: build(deps): require libtermkey version 0.22 Reduces #ifdef code. --- CMakeLists.txt | 2 +- src/nvim/tui/input.c | 4 ---- src/nvim/tui/input.h | 2 -- src/nvim/tui/tui.c | 8 ++------ 4 files changed, 3 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 81a0a2f667..034c349c9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -498,7 +498,7 @@ if(FEAT_TUI) add_definitions(-DNVIM_UNIBI_HAS_VAR_FROM) endif() - find_package(LibTermkey 0.18 REQUIRED) + find_package(LibTermkey 0.22 REQUIRED) include_directories(SYSTEM ${LIBTERMKEY_INCLUDE_DIRS}) endif() diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index 998e8cfed0..fbeca26274 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -159,14 +159,10 @@ void tinput_init(TermInput *input, Loop *loop) term = ""; // termkey_new_abstract assumes non-null (#2745) } -#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18 input->tk = termkey_new_abstract(term, TERMKEY_FLAG_UTF8 | TERMKEY_FLAG_NOSTART); termkey_hook_terminfo_getstr(input->tk, input->tk_ti_hook_fn, NULL); termkey_start(input->tk); -#else - input->tk = termkey_new_abstract(term, TERMKEY_FLAG_UTF8); -#endif int curflags = termkey_get_canonflags(input->tk); termkey_set_canonflags(input->tk, curflags | TERMKEY_CANON_DELBS); diff --git a/src/nvim/tui/input.h b/src/nvim/tui/input.h index 51df57938c..0b60394850 100644 --- a/src/nvim/tui/input.h +++ b/src/nvim/tui/input.h @@ -26,9 +26,7 @@ typedef struct term_input { ExtkeysType extkeys_type; long ttimeoutlen; TermKey *tk; -#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18 TermKey_Terminfo_Getstr_Hook *tk_ti_hook_fn; ///< libtermkey terminfo hook -#endif TimeWatcher timer_handle; Loop *loop; Stream read_stream; diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 4eabecb74a..b483ad3486 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -485,9 +485,7 @@ static void tui_main(UIBridgeData *bridge, UI *ui) // TODO(bfredl): zero hl is empty, send this explicitly? kv_push(data->attrs, HLATTRS_INIT); -#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18 data->input.tk_ti_hook_fn = tui_tk_ti_getstr; -#endif tinput_init(&data->input, &tui_loop); tui_terminal_start(ui); @@ -2278,7 +2276,6 @@ static void flush_buf(UI *ui) data->overflow = false; } -#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18 /// Try to get "kbs" code from stty because "the terminfo kbs entry is extremely /// unreliable." (Vim, Bash, and tmux also do this.) /// @@ -2287,14 +2284,14 @@ static void flush_buf(UI *ui) static const char *tui_get_stty_erase(void) { static char stty_erase[2] = { 0 }; -# if defined(HAVE_TERMIOS_H) +#if defined(HAVE_TERMIOS_H) struct termios t; if (tcgetattr(input_global_fd(), &t) != -1) { stty_erase[0] = (char)t.c_cc[VERASE]; stty_erase[1] = '\0'; DLOG("stty/termios:erase=%s", stty_erase); } -# endif +#endif return stty_erase; } @@ -2328,4 +2325,3 @@ static const char *tui_tk_ti_getstr(const char *name, const char *value, void *d return value; } -#endif -- cgit From 6917a2e569e9f7306a9858f1aeeb32dd1c3ece4e Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Wed, 28 Sep 2022 09:30:47 +0200 Subject: build(deps): require libvterm version 0.3 --- CMakeLists.txt | 2 +- src/nvim/terminal.c | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 81a0a2f667..5a613a812c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -502,7 +502,7 @@ if(FEAT_TUI) include_directories(SYSTEM ${LIBTERMKEY_INCLUDE_DIRS}) endif() -find_package(LIBVTERM 0.1 REQUIRED) +find_package(LIBVTERM 0.3 REQUIRED) include_directories(SYSTEM ${LIBVTERM_INCLUDE_DIRS}) option(CLANG_ASAN_UBSAN "Enable Clang address & undefined behavior sanitizer for nvim binary." OFF) diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c index 8ec51438fb..c52586fea2 100644 --- a/src/nvim/terminal.c +++ b/src/nvim/terminal.c @@ -908,7 +908,6 @@ static int term_settermprop(VTermProp prop, VTermValue *val, void *data) case VTERM_PROP_TITLE: { buf_T *buf = handle_get_buffer(term->buf_handle); -#if VTERM_VERSION_MAJOR > 0 || (VTERM_VERSION_MAJOR == 0 && VTERM_VERSION_MINOR >= 2) VTermStringFragment frag = val->string; if (frag.initial && frag.final) { @@ -933,9 +932,6 @@ static int term_settermprop(VTermProp prop, VTermValue *val, void *data) xfree(term->title); term->title = NULL; } -#else - buf_set_term_title(buf, val->string, strlen(val->string)); -#endif break; } -- cgit From d7358118aa57ec636ef6f84c6ac96f26d8bed32c Mon Sep 17 00:00:00 2001 From: dundargoc <33953936+dundargoc@users.noreply.github.com> Date: Wed, 28 Sep 2022 10:53:44 +0200 Subject: fix: compiler warnings from clang 15 (#20321) Add -Wno-strict-prototypes flag to external dependencies to suppress cjson warnings. These needs to be fixed upstream first. --- src/nvim/CMakeLists.txt | 2 +- src/nvim/eval/typval.c | 2 -- src/nvim/input.c | 5 +---- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt index f28b7a7e28..6f5f2b53f6 100755 --- a/src/nvim/CMakeLists.txt +++ b/src/nvim/CMakeLists.txt @@ -159,7 +159,7 @@ list(REMOVE_ITEM NVIM_SOURCES ${to_remove}) if(NOT MSVC) # xdiff, mpack, lua-cjson: inlined external project, we don't maintain it. #9306 set_source_files_properties( - ${EXTERNAL_SOURCES} PROPERTIES COMPILE_FLAGS "${COMPILE_FLAGS} -Wno-conversion -Wno-missing-noreturn -Wno-missing-format-attribute -Wno-double-promotion") + ${EXTERNAL_SOURCES} PROPERTIES COMPILE_FLAGS "${COMPILE_FLAGS} -Wno-conversion -Wno-missing-noreturn -Wno-missing-format-attribute -Wno-double-promotion -Wno-strict-prototypes") endif() if(NOT "${MIN_LOG_LEVEL}" MATCHES "^$") diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index 5639414dad..961c963170 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -1249,14 +1249,12 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) item_compare_func_ptr = item_compare_keeping_zero; } - int idx = 0; for (listitem_T *li = TV_LIST_ITEM_NEXT(l, tv_list_first(l)) ; li != NULL;) { listitem_T *const prev_li = TV_LIST_ITEM_PREV(l, li); if (item_compare_func_ptr(&prev_li, &li) == 0) { li = tv_list_item_remove(l, li); } else { - idx++; li = TV_LIST_ITEM_NEXT(l, li); } if (info.item_compare_func_err) { // -V547 diff --git a/src/nvim/input.c b/src/nvim/input.c index 0aa9feaca3..681d9d5f9c 100644 --- a/src/nvim/input.c +++ b/src/nvim/input.c @@ -83,7 +83,6 @@ int get_keystroke(MultiQueue *events) int len = 0; int n; int save_mapped_ctrl_c = mapped_ctrl_c; - int waited = 0; mapped_ctrl_c = 0; // mappings are not used here for (;;) { @@ -110,10 +109,8 @@ int get_keystroke(MultiQueue *events) // Replace zero and K_SPECIAL by a special key code. n = fix_input_buffer(buf + len, n); len += n; - waited = 0; - } else if (len > 0) { - waited++; // keep track of the waiting time } + if (n > 0) { // found a termcode: adjust length len = n; } -- cgit From eb4844b5ed9bcf8c434a93b9f9def4fe81557f37 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Wed, 28 Sep 2022 11:06:11 +0200 Subject: build(macos): restore and test universal build (#20383) Build tree-sitter parsers for arm64 as well as x86 Check that all created binaries contain both architectures --- .github/workflows/release.yml | 5 +++++ cmake.deps/cmake/BuildTreesitterParsers.cmake | 2 ++ 2 files changed, 7 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5e0ea5e5f4..5fc40a2471 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -113,6 +113,11 @@ jobs: DEPS_CMAKE_FLAGS="$OSX_FLAGS" make DESTDIR="$GITHUB_WORKSPACE/build/release/nvim-macos" install cd "$GITHUB_WORKSPACE/build/" + # Make sure we build everything for M1 as well + for macho in bin/* lib/nvim/parser/*.so + do + lipo -info "$macho" | grep -q arm64 || exit 1 + done cpack -C "$NVIM_BUILD_TYPE" - uses: actions/upload-artifact@v3 with: diff --git a/cmake.deps/cmake/BuildTreesitterParsers.cmake b/cmake.deps/cmake/BuildTreesitterParsers.cmake index 25d2fd21a3..e08792f62a 100644 --- a/cmake.deps/cmake/BuildTreesitterParsers.cmake +++ b/cmake.deps/cmake/BuildTreesitterParsers.cmake @@ -4,6 +4,8 @@ function(BuildTSParser LANG TS_URL TS_SHA256 TS_CMAKE_FILE) PREFIX ${DEPS_BUILD_DIR} URL ${TREESITTER_C_URL} DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/${NAME} + CMAKE_CACHE_ARGS + -DCMAKE_OSX_ARCHITECTURES:STRING=${CMAKE_OSX_ARCHITECTURES} DOWNLOAD_COMMAND ${CMAKE_COMMAND} -DPREFIX=${DEPS_BUILD_DIR} -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/${NAME} -- cgit From 35e2c4a2edd28f72c48c70530c5486365c2502a4 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 28 Sep 2022 18:27:59 +0800 Subject: fix(lua): fix architecture-dependent behavior in usercmd "reg" (#20384) I don't think using an integer as a NUL-terminated string can work on big-endian systems, at least. This is also not tested. Add a test. Also fix a mistake in the docs of nvim_parse_cmd. --- runtime/doc/api.txt | 2 +- src/nvim/api/command.c | 6 ++---- src/nvim/lua/executor.c | 3 ++- test/functional/api/command_spec.lua | 37 ++++++++++++++++++++++++++++++++++++ 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index ce59f5ad52..f0145344a4 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -1811,7 +1811,7 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()* range items were specified. • count: (number) Any || that was supplied to the command. -1 if command cannot take a count. - • reg: (number) The optional command ||, if specified. Empty + • reg: (string) The optional command ||, if specified. Empty string if not specified or if command cannot take a register. • bang: (boolean) Whether command contains a || (!) modifier. • args: (array) Command arguments. diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index ed0907e8f8..699c62c15c 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -37,7 +37,7 @@ /// specified and two elements if both range items were specified. /// - count: (number) Any || that was supplied to the command. -1 if command cannot /// take a count. -/// - reg: (number) The optional command ||, if specified. Empty string if not +/// - reg: (string) The optional command ||, if specified. Empty string if not /// specified or if command cannot take a register. /// - bang: (boolean) Whether command contains a || (!) modifier. /// - args: (array) Command arguments. @@ -165,9 +165,7 @@ Dictionary nvim_parse_cmd(String str, Dictionary opts, Error *err) PUT(result, "count", INTEGER_OBJ(-1)); } - char reg[2]; - reg[0] = (char)ea.regname; - reg[1] = '\0'; + char reg[2] = { (char)ea.regname, NUL }; PUT(result, "reg", CSTR_TO_OBJ(reg)); PUT(result, "bang", BOOLEAN_OBJ(ea.forceit)); diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 6063414a02..f3821f149a 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -2036,7 +2036,8 @@ int nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap, bool preview) } lua_setfield(lstate, -2, "fargs"); - lua_pushstring(lstate, (const char *)&eap->regname); + char reg[2] = { (char)eap->regname, NUL }; + lua_pushstring(lstate, reg); lua_setfield(lstate, -2, "reg"); lua_pushinteger(lstate, eap->addr_count); diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua index 44a19d8348..f19d7a362b 100644 --- a/test/functional/api/command_spec.lua +++ b/test/functional/api/command_spec.lua @@ -423,6 +423,7 @@ describe('nvim_create_user_command', function() nargs = 0, bang = true, count = 2, + register = true, }) ]] eq({ @@ -460,6 +461,42 @@ describe('nvim_create_user_command', function() vim.cmd('CommandWithNoArgs') return result ]]) + -- register can be specified + eq({ + args = "", + fargs = {}, + bang = false, + line1 = 1, + line2 = 1, + mods = "", + smods = { + browse = false, + confirm = false, + emsg_silent = false, + hide = false, + horizontal = false, + keepalt = false, + keepjumps = false, + keepmarks = false, + keeppatterns = false, + lockmarks = false, + noautocmd = false, + noswapfile = false, + sandbox = false, + silent = false, + split = "", + tab = -1, + unsilent = false, + verbose = -1, + vertical = false, + }, + range = 0, + count = 2, + reg = "+", + }, exec_lua [[ + vim.cmd('CommandWithNoArgs +') + return result + ]]) end) -- cgit From 9ca313fb968448011aae0509e6552c52b9f8aa8c Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Wed, 28 Sep 2022 12:48:36 +0200 Subject: vim-patch:9fbdbb814f4a (#20376) Update runtime files https://github.com/vim/vim/commit/9fbdbb814f4ad67a14979aba4a6a49800c2f1a99 Skip ftplugin/vim.vim (vim9script change) Drop indent/vim.vim and autoload/dist/vimindent.vim (vim9script rewrite) --- runtime/compiler/hare.vim | 31 +++ runtime/doc/map.txt | 14 +- runtime/doc/motion.txt | 2 +- runtime/doc/repeat.txt | 3 +- runtime/doc/syntax.txt | 2 +- runtime/filetype.vim | 2 +- runtime/ftplugin/chatito.vim | 15 ++ runtime/ftplugin/elixir.vim | 6 +- runtime/ftplugin/gyp.vim | 14 ++ runtime/ftplugin/hare.vim | 27 +++ runtime/ftplugin/heex.vim | 16 ++ runtime/indent/chatito.vim | 32 +++ runtime/indent/gyp.vim | 7 + runtime/indent/hare.vim | 138 +++++++++++++ runtime/indent/solidity.vim | 442 +++++++++++++++++++++++++++++++++++++++++ runtime/indent/vue.vim | 12 ++ runtime/syntax/chatito.vim | 62 ++++++ runtime/syntax/desktop.vim | 6 +- runtime/syntax/gyp.vim | 49 +++++ runtime/syntax/hare.vim | 133 +++++++++++++ runtime/syntax/help.vim | 3 +- runtime/syntax/hlsplaylist.vim | 120 +++++++++++ runtime/syntax/plsql.vim | 68 ++++--- runtime/syntax/solidity.vim | 173 ++++++++++++++++ runtime/syntax/vim.vim | 2 +- 25 files changed, 1339 insertions(+), 40 deletions(-) create mode 100644 runtime/compiler/hare.vim create mode 100644 runtime/ftplugin/chatito.vim create mode 100644 runtime/ftplugin/gyp.vim create mode 100644 runtime/ftplugin/hare.vim create mode 100644 runtime/ftplugin/heex.vim create mode 100644 runtime/indent/chatito.vim create mode 100644 runtime/indent/gyp.vim create mode 100644 runtime/indent/hare.vim create mode 100644 runtime/indent/solidity.vim create mode 100644 runtime/indent/vue.vim create mode 100644 runtime/syntax/chatito.vim create mode 100644 runtime/syntax/gyp.vim create mode 100644 runtime/syntax/hare.vim create mode 100644 runtime/syntax/hlsplaylist.vim create mode 100644 runtime/syntax/solidity.vim diff --git a/runtime/compiler/hare.vim b/runtime/compiler/hare.vim new file mode 100644 index 0000000000..c0fa68cc00 --- /dev/null +++ b/runtime/compiler/hare.vim @@ -0,0 +1,31 @@ +" Vim compiler file +" Compiler: Hare Compiler +" Maintainer: Amelia Clarke +" Last Change: 2022-09-21 + +if exists("g:current_compiler") + finish +endif +let g:current_compiler = "hare" + +let s:cpo_save = &cpo +set cpo&vim + +if exists(':CompilerSet') != 2 + command -nargs=* CompilerSet setlocal +endif + +if filereadable("Makefile") || filereadable("makefile") + CompilerSet makeprg=make +else + CompilerSet makeprg=hare\ build +endif + +CompilerSet errorformat= + \Error\ %f:%l:%c:\ %m, + \Syntax\ error:\ %.%#\ at\ %f:%l:%c\\,\ %m, + \%-G%.%# + +let &cpo = s:cpo_save +unlet s:cpo_save +" vim: tabstop=2 shiftwidth=2 expandtab diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt index e5d22de748..cbc92a8cb5 100644 --- a/runtime/doc/map.txt +++ b/runtime/doc/map.txt @@ -1660,7 +1660,8 @@ The valid escape sequences are If the first two characters of an escape sequence are "q-" (for example, ) then the value is quoted in such a way as to make it a valid value for use in an expression. This uses the argument as one single value. -When there is no argument is an empty string. +When there is no argument is an empty string. See the +|q-args-example| below. ** To allow commands to pass their arguments on to a user-defined function, there is a special form ("function args"). This splits the command @@ -1670,7 +1671,7 @@ See the Mycmd example below. If no arguments are given is removed. To embed whitespace into an argument of , prepend a backslash. replaces every pair of backslashes (\\) with one backslash. A backslash followed by a character other than white space or a backslash -remains unmodified. Overview: +remains unmodified. Also see |f-args-example| below. Overview: command ~ XX ab "ab" @@ -1684,7 +1685,8 @@ remains unmodified. Overview: XX a\\\\b 'a\\b' XX a\\\\ b 'a\\', 'b' -Examples > + +Examples for user commands: > " Delete everything after here to the end :com Ddel +,$d @@ -1700,7 +1702,8 @@ Examples > " Count the number of lines in the range :com! -range -nargs=0 Lines echo - + 1 "lines" - " Call a user function (example of ) +< *f-args-example* +Call a user function (example of ) > :com -nargs=* Mycmd call Myfunc() When executed as: > @@ -1708,7 +1711,8 @@ When executed as: > This will invoke: > :call Myfunc("arg1","arg2") - :" A more substantial example +< *q-args-example* +A more substantial example: > :function Allargs(command) : let i = 0 : while i < argc() diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt index 77b6b83289..8ff4ed4f96 100644 --- a/runtime/doc/motion.txt +++ b/runtime/doc/motion.txt @@ -1172,7 +1172,7 @@ g; Go to [count] older position in change list. (not a motion command) *g,* *E663* -g, Go to [count] newer cursor position in change list. +g, Go to [count] newer position in change list. Just like |g;| but in the opposite direction. (not a motion command) diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt index 0b316b4727..b0332269d7 100644 --- a/runtime/doc/repeat.txt +++ b/runtime/doc/repeat.txt @@ -83,7 +83,8 @@ pattern and do not match another pattern: > This first finds all lines containing "found", but only executes {cmd} when there is no match for "notfound". -To execute a non-Ex command, you can use the `:normal` command: > +Any Ex command can be used, see |ex-cmd-index|. To execute a Normal mode +command, you can use the `:normal` command: > :g/pat/normal {commands} Make sure that {commands} ends with a whole command, otherwise Vim will wait for you to type the rest of the command for each match. The screen will not diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 83f19db4a9..c97376a629 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -3118,7 +3118,7 @@ The default is to use the twice sh_minlines. Set it to a smaller number to speed up displaying. The disadvantage is that highlight errors may appear. syntax/sh.vim tries to flag certain problems as errors; usually things like -extra "]"s, "done"s, "fi"s, etc. If you find the error handling problematic +unmatched "]", "done", "fi", etc. If you find the error handling problematic for your purposes, you may suppress such error highlighting by putting the following line in your .vimrc: > diff --git a/runtime/filetype.vim b/runtime/filetype.vim index 204bf1865f..475dafb9e9 100644 --- a/runtime/filetype.vim +++ b/runtime/filetype.vim @@ -1,7 +1,7 @@ " Vim support file to detect file types " " Maintainer: Bram Moolenaar -" Last Change: 2022 Sep 11 +" Last Change: 2022 Sep 27 " Only run this if enabled if !exists("do_legacy_filetype") diff --git a/runtime/ftplugin/chatito.vim b/runtime/ftplugin/chatito.vim new file mode 100644 index 0000000000..af212e9581 --- /dev/null +++ b/runtime/ftplugin/chatito.vim @@ -0,0 +1,15 @@ +" Vim filetype plugin +" Language: Chatito +" Maintainer: ObserverOfTime +" Last Change: 2022 Sep 19 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal comments=:#,:// commentstring=#\ %s +" indent of 4 spaces is mandated by the spec +setlocal expandtab softtabstop=4 shiftwidth=4 + +let b:undo_ftplugin = 'setl com< cms< et< sts< sw<' diff --git a/runtime/ftplugin/elixir.vim b/runtime/ftplugin/elixir.vim index c423c2acb7..50f63673dc 100644 --- a/runtime/ftplugin/elixir.vim +++ b/runtime/ftplugin/elixir.vim @@ -1,7 +1,7 @@ " Elixir filetype plugin " Language: Elixir " Maintainer: Mitchell Hanberg -" Last Change: 2022 August 10 +" Last Change: 2022 Sep 20 if exists("b:did_ftplugin") finish @@ -23,7 +23,11 @@ if exists('loaded_matchit') && !exists('b:match_words') \ ',{:},\[:\],(:)' endif +setlocal shiftwidth=2 softtabstop=2 expandtab iskeyword+=!,? +setlocal comments=:# setlocal commentstring=#\ %s +let b:undo_ftplugin = 'setlocal sw< sts< et< isk< com< cms<' + let &cpo = s:save_cpo unlet s:save_cpo diff --git a/runtime/ftplugin/gyp.vim b/runtime/ftplugin/gyp.vim new file mode 100644 index 0000000000..becfcadb6d --- /dev/null +++ b/runtime/ftplugin/gyp.vim @@ -0,0 +1,14 @@ +" Vim filetype plugin +" Language: GYP +" Maintainer: ObserverOfTime +" Last Change: 2022 Sep 27 + +if exists('b:did_ftplugin') + finish +endif +let b:did_ftplugin = 1 + +setlocal formatoptions-=t +setlocal commentstring=#\ %s comments=b:#,fb:- + +let b:undo_ftplugin = 'setlocal fo< cms< com<' diff --git a/runtime/ftplugin/hare.vim b/runtime/ftplugin/hare.vim new file mode 100644 index 0000000000..bb10daf38c --- /dev/null +++ b/runtime/ftplugin/hare.vim @@ -0,0 +1,27 @@ +" Vim filetype plugin +" Language: Hare +" Maintainer: Amelia Clarke +" Previous Maintainer: Drew DeVault +" Last Updated: 2022-09-21 + +" Only do this when not done yet for this buffer +if exists('b:did_ftplugin') + finish +endif + +" Don't load another plugin for this buffer +let b:did_ftplugin = 1 + +setlocal noexpandtab +setlocal tabstop=8 +setlocal shiftwidth=0 +setlocal softtabstop=0 +setlocal textwidth=80 +setlocal commentstring=//\ %s + +" Set 'formatoptions' to break comment lines but not other lines, +" and insert the comment leader when hitting or using "o". +setlocal fo-=t fo+=croql + +compiler hare +" vim: tabstop=2 shiftwidth=2 expandtab diff --git a/runtime/ftplugin/heex.vim b/runtime/ftplugin/heex.vim new file mode 100644 index 0000000000..5274d59fbf --- /dev/null +++ b/runtime/ftplugin/heex.vim @@ -0,0 +1,16 @@ +" Elixir filetype plugin +" Language: HEEx +" Maintainer: Mitchell Hanberg +" Last Change: 2022 Sep 21 + +if exists("b:did_ftplugin") + finish +endif +let b:did_ftplugin = 1 + +setlocal shiftwidth=2 softtabstop=2 expandtab + +setlocal comments=:<%!-- +setlocal commentstring=<%!--\ %s\ --%> + +let b:undo_ftplugin = 'set sw< sts< et< com< cms<' diff --git a/runtime/indent/chatito.vim b/runtime/indent/chatito.vim new file mode 100644 index 0000000000..1ff5e9e3f1 --- /dev/null +++ b/runtime/indent/chatito.vim @@ -0,0 +1,32 @@ +" Vim indent file +" Language: Chatito +" Maintainer: ObserverOfTime +" Last Change: 2022 Sep 20 + +if exists('b:did_indent') + finish +endif +let b:did_indent = 1 + +setlocal indentexpr=GetChatitoIndent() +setlocal indentkeys=o,O,*,0#,!^F + +let b:undo_indent = 'setl inde< indk<' + +if exists('*GetChatitoIndent') + finish +endif + +function GetChatitoIndent() + let l:prev = v:lnum - 1 + if getline(prevnonblank(l:prev)) =~# '^[~%@]\[' + " shift indent after definitions + return shiftwidth() + elseif getline(l:prev) !~# '^\s*$' + " maintain indent in sentences + return indent(l:prev) + else + " reset indent after a blank line + return 0 + end +endfunction diff --git a/runtime/indent/gyp.vim b/runtime/indent/gyp.vim new file mode 100644 index 0000000000..c3980ac568 --- /dev/null +++ b/runtime/indent/gyp.vim @@ -0,0 +1,7 @@ +" Vim indent file +" Language: GYP +" Maintainer: ObserverOfTime +" Last Change: 2022 Sep 27 + +" JSON indent works well +runtime! indent/json.vim diff --git a/runtime/indent/hare.vim b/runtime/indent/hare.vim new file mode 100644 index 0000000000..bc4fea4e61 --- /dev/null +++ b/runtime/indent/hare.vim @@ -0,0 +1,138 @@ +" Vim indent file +" Language: Hare +" Maintainer: Amelia Clarke +" Last Change: 2022 Sep 22 + +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +if !has("cindent") || !has("eval") + finish +endif + +setlocal cindent + +" L0 -> don't deindent labels +" (s -> use one indent after a trailing ( +" m1 -> if ) starts a line, indent it the same as its matching ( +" ks -> add an extra indent to extra lines in an if expression or for expression +" j1 -> indent code inside {} one level when in parentheses +" J1 -> see j1 +" *0 -> don't search for unclosed block comments +" #1 -> don't deindent lines that begin with # +setlocal cinoptions=L0,(s,m1,ks,j1,J1,*0,#1 + +" Controls which keys reindent the current line. +" 0{ -> { at beginning of line +" 0} -> } at beginning of line +" 0) -> ) at beginning of line +" 0] -> ] at beginning of line +" !^F -> (not inserted) +" o -> or `o` command +" O -> `O` command +" e -> else +" 0=case -> case +setlocal indentkeys=0{,0},0),0],!^F,o,O,e,0=case + +setlocal cinwords=if,else,for,switch,match + +setlocal indentexpr=GetHareIndent() + +function! FloorCindent(lnum) + return cindent(a:lnum) / shiftwidth() * shiftwidth() +endfunction + +function! GetHareIndent() + let line = getline(v:lnum) + let prevlnum = prevnonblank(v:lnum - 1) + let prevline = getline(prevlnum) + let prevprevline = getline(prevnonblank(prevlnum - 1)) + + " This is all very hacky and imperfect, but it's tough to do much better when + " working with regex-based indenting rules. + + " If the previous line ended with =, indent by one shiftwidth. + if prevline =~# '\v\=\s*(//.*)?$' + return indent(prevlnum) + shiftwidth() + endif + + " If the previous line ended in a semicolon and the line before that ended + " with =, deindent by one shiftwidth. + if prevline =~# '\v;\s*(//.*)?$' && prevprevline =~# '\v\=\s*(//.*)?$' + return indent(prevlnum) - shiftwidth() + endif + + " TODO: The following edge-case is still indented incorrectly: + " case => + " if (foo) { + " bar; + " }; + " | // cursor is incorrectly deindented by one shiftwidth. + " + " This only happens if the {} block is the first statement in the case body. + " If `case` is typed, the case will also be incorrectly deindented by one + " shiftwidth. Are you having fun yet? + + " Deindent cases. + if line =~# '\v^\s*case' + " If the previous line was also a case, don't do any special indenting. + if prevline =~# '\v^\s*case' + return indent(prevlnum) + end + + " If the previous line was a multiline case, deindent by one shiftwidth. + if prevline =~# '\v\=\>\s*(//.*)?$' + return indent(prevlnum) - shiftwidth() + endif + + " If the previous line started a block, deindent by one shiftwidth. + " This handles the first case in a switch/match block. + if prevline =~# '\v\{\s*(//.*)?$' + return FloorCindent(v:lnum) - shiftwidth() + end + + " If the previous line ended in a semicolon and the line before that wasn't + " a case, deindent by one shiftwidth. + if prevline =~# '\v;\s*(//.*)?$' && prevprevline !~# '\v\=\>\s*(//.*)?$' + return FloorCindent(v:lnum) - shiftwidth() + end + + let l:indent = FloorCindent(v:lnum) + + " If a normal cindent would indent the same amount as the previous line, + " deindent by one shiftwidth. This fixes some issues with `case let` blocks. + if l:indent == indent(prevlnum) + return l:indent - shiftwidth() + endif + + " Otherwise, do a normal cindent. + return l:indent + endif + + " Don't indent an extra shiftwidth for cases which span multiple lines. + if prevline =~# '\v\=\>\s*(//.*)?$' && prevline !~# '\v^\s*case\W' + return indent(prevlnum) + endif + + " Indent the body of a case. + " If the previous line ended in a semicolon and the line before that was a + " case, don't do any special indenting. + if prevline =~# '\v;\s*(//.*)?$' && prevprevline =~# '\v\=\>\s*(//.*)?$' && line !~# '\v^\s*}' + return indent(prevlnum) + endif + + let l:indent = FloorCindent(v:lnum) + + " If the previous line was a case and a normal cindent wouldn't indent, indent + " an extra shiftwidth. + if prevline =~# '\v\=\>\s*(//.*)?$' && l:indent == indent(prevlnum) + return l:indent + shiftwidth() + endif + + " If everything above is false, do a normal cindent. + return l:indent +endfunction + +" vim: tabstop=2 shiftwidth=2 expandtab diff --git a/runtime/indent/solidity.vim b/runtime/indent/solidity.vim new file mode 100644 index 0000000000..caed726c0a --- /dev/null +++ b/runtime/indent/solidity.vim @@ -0,0 +1,442 @@ +" Vim indent file +" Language: Solidity +" Acknowledgement: Based off of vim-javascript +" Maintainer: Cothi (jiungdev@gmail.com) +" Original Author: tomlion (https://github.com/tomlion/vim-solidity) +" Last Changed: 2022 Sep 27 +" +" 0. Initialization {{{1 +" ================= + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +setlocal nosmartindent + +" Now, set up our indentation expression and keys that trigger it. +setlocal indentexpr=GetSolidityIndent() +setlocal indentkeys=0{,0},0),0],0\,,!^F,o,O,e + +" Only define the function once. +if exists("*GetSolidityIndent") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +" 1. Variables {{{1 +" ============ + +let s:js_keywords = '^\s*\(break\|case\|catch\|continue\|debugger\|default\|delete\|do\|else\|finally\|for\|function\|if\|in\|instanceof\|new\|return\|switch\|this\|throw\|try\|typeof\|var\|void\|while\|with\)' + +" Regex of syntax group names that are or delimit string or are comments. +let s:syng_strcom = 'string\|regex\|comment\c' + +" Regex of syntax group names that are strings. +let s:syng_string = 'regex\c' + +" Regex of syntax group names that are strings or documentation. +let s:syng_multiline = 'comment\c' + +" Regex of syntax group names that are line comment. +let s:syng_linecom = 'linecomment\c' + +" Expression used to check whether we should skip a match with searchpair(). +let s:skip_expr = "synIDattr(synID(line('.'),col('.'),1),'name') =~ '".s:syng_strcom."'" + +let s:line_term = '\s*\%(\%(\/\/\).*\)\=$' + +" Regex that defines continuation lines, not including (, {, or [. +let s:continuation_regex = '\%([\\*+/.:]\|\%(<%\)\@[^{;]*' . s:line_term + +" Regex that defines blocks. +let s:block_regex = '\%([{[]\)\s*\%(|\%([*@]\=\h\w*,\=\s*\)\%(,\s*[*@]\=\h\w*\)*|\)\=' . s:line_term + +let s:var_stmt = '^\s*var' + +let s:comma_first = '^\s*,' +let s:comma_last = ',\s*$' + +let s:ternary = '^\s\+[?|:]' +let s:ternary_q = '^\s\+?' + +" 2. Auxiliary Functions {{{1 +" ====================== + +" Check if the character at lnum:col is inside a string, comment, or is ascii. +function s:IsInStringOrComment(lnum, col) + return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_strcom +endfunction + +" Check if the character at lnum:col is inside a string. +function s:IsInString(lnum, col) + return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_string +endfunction + +" Check if the character at lnum:col is inside a multi-line comment. +function s:IsInMultilineComment(lnum, col) + return !s:IsLineComment(a:lnum, a:col) && synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_multiline +endfunction + +" Check if the character at lnum:col is a line comment. +function s:IsLineComment(lnum, col) + return synIDattr(synID(a:lnum, a:col, 1), 'name') =~ s:syng_linecom +endfunction + +" Find line above 'lnum' that isn't empty, in a comment, or in a string. +function s:PrevNonBlankNonString(lnum) + let in_block = 0 + let lnum = prevnonblank(a:lnum) + while lnum > 0 + " Go in and out of blocks comments as necessary. + " If the line isn't empty (with opt. comment) or in a string, end search. + let line = getline(lnum) + if line =~ '/\*' + if in_block + let in_block = 0 + else + break + endif + elseif !in_block && line =~ '\*/' + let in_block = 1 + elseif !in_block && line !~ '^\s*\%(//\).*$' && !(s:IsInStringOrComment(lnum, 1) && s:IsInStringOrComment(lnum, strlen(line))) + break + endif + let lnum = prevnonblank(lnum - 1) + endwhile + return lnum +endfunction + +" Find line above 'lnum' that started the continuation 'lnum' may be part of. +function s:GetMSL(lnum, in_one_line_scope) + " Start on the line we're at and use its indent. + let msl = a:lnum + let lnum = s:PrevNonBlankNonString(a:lnum - 1) + while lnum > 0 + " If we have a continuation line, or we're in a string, use line as MSL. + " Otherwise, terminate search as we have found our MSL already. + let line = getline(lnum) + let col = match(line, s:msl_regex) + 1 + if (col > 0 && !s:IsInStringOrComment(lnum, col)) || s:IsInString(lnum, strlen(line)) + let msl = lnum + else + " Don't use lines that are part of a one line scope as msl unless the + " flag in_one_line_scope is set to 1 + " + if a:in_one_line_scope + break + end + let msl_one_line = s:Match(lnum, s:one_line_scope_regex) + if msl_one_line == 0 + break + endif + endif + let lnum = s:PrevNonBlankNonString(lnum - 1) + endwhile + return msl +endfunction + +function s:RemoveTrailingComments(content) + let single = '\/\/\(.*\)\s*$' + let multi = '\/\*\(.*\)\*\/\s*$' + return substitute(substitute(a:content, single, '', ''), multi, '', '') +endfunction + +" Find if the string is inside var statement (but not the first string) +function s:InMultiVarStatement(lnum) + let lnum = s:PrevNonBlankNonString(a:lnum - 1) + +" let type = synIDattr(synID(lnum, indent(lnum) + 1, 0), 'name') + + " loop through previous expressions to find a var statement + while lnum > 0 + let line = getline(lnum) + + " if the line is a js keyword + if (line =~ s:js_keywords) + " check if the line is a var stmt + " if the line has a comma first or comma last then we can assume that we + " are in a multiple var statement + if (line =~ s:var_stmt) + return lnum + endif + + " other js keywords, not a var + return 0 + endif + + let lnum = s:PrevNonBlankNonString(lnum - 1) + endwhile + + " beginning of program, not a var + return 0 +endfunction + +" Find line above with beginning of the var statement or returns 0 if it's not +" this statement +function s:GetVarIndent(lnum) + let lvar = s:InMultiVarStatement(a:lnum) + let prev_lnum = s:PrevNonBlankNonString(a:lnum - 1) + + if lvar + let line = s:RemoveTrailingComments(getline(prev_lnum)) + + " if the previous line doesn't end in a comma, return to regular indent + if (line !~ s:comma_last) + return indent(prev_lnum) - &sw + else + return indent(lvar) + &sw + endif + endif + + return -1 +endfunction + + +" Check if line 'lnum' has more opening brackets than closing ones. +function s:LineHasOpeningBrackets(lnum) + let open_0 = 0 + let open_2 = 0 + let open_4 = 0 + let line = getline(a:lnum) + let pos = match(line, '[][(){}]', 0) + while pos != -1 + if !s:IsInStringOrComment(a:lnum, pos + 1) + let idx = stridx('(){}[]', line[pos]) + if idx % 2 == 0 + let open_{idx} = open_{idx} + 1 + else + let open_{idx - 1} = open_{idx - 1} - 1 + endif + endif + let pos = match(line, '[][(){}]', pos + 1) + endwhile + return (open_0 > 0) . (open_2 > 0) . (open_4 > 0) +endfunction + +function s:Match(lnum, regex) + let col = match(getline(a:lnum), a:regex) + 1 + return col > 0 && !s:IsInStringOrComment(a:lnum, col) ? col : 0 +endfunction + +function s:IndentWithContinuation(lnum, ind, width) + " Set up variables to use and search for MSL to the previous line. + let p_lnum = a:lnum + let lnum = s:GetMSL(a:lnum, 1) + let line = getline(lnum) + + " If the previous line wasn't a MSL and is continuation return its indent. + " TODO: the || s:IsInString() thing worries me a bit. + if p_lnum != lnum + if s:Match(p_lnum,s:continuation_regex)||s:IsInString(p_lnum,strlen(line)) + return a:ind + endif + endif + + " Set up more variables now that we know we aren't continuation bound. + let msl_ind = indent(lnum) + + " If the previous line ended with [*+/.-=], start a continuation that + " indents an extra level. + if s:Match(lnum, s:continuation_regex) + if lnum == p_lnum + return msl_ind + a:width + else + return msl_ind + endif + endif + + return a:ind +endfunction + +function s:InOneLineScope(lnum) + let msl = s:GetMSL(a:lnum, 1) + if msl > 0 && s:Match(msl, s:one_line_scope_regex) + return msl + endif + return 0 +endfunction + +function s:ExitingOneLineScope(lnum) + let msl = s:GetMSL(a:lnum, 1) + if msl > 0 + " if the current line is in a one line scope .. + if s:Match(msl, s:one_line_scope_regex) + return 0 + else + let prev_msl = s:GetMSL(msl - 1, 1) + if s:Match(prev_msl, s:one_line_scope_regex) + return prev_msl + endif + endif + endif + return 0 +endfunction + +" 3. GetSolidityIndent Function {{{1 +" ========================= + +function GetSolidityIndent() + " 3.1. Setup {{{2 + " ---------- + + " Set up variables for restoring position in file. Could use v:lnum here. + let vcol = col('.') + + " 3.2. Work on the current line {{{2 + " ----------------------------- + + let ind = -1 + " Get the current line. + let line = getline(v:lnum) + " previous nonblank line number + let prevline = prevnonblank(v:lnum - 1) + + " If we got a closing bracket on an empty line, find its match and indent + " according to it. For parentheses we indent to its column - 1, for the + " others we indent to the containing line's MSL's level. Return -1 if fail. + let col = matchend(line, '^\s*[],})]') + if col > 0 && !s:IsInStringOrComment(v:lnum, col) + call cursor(v:lnum, col) + + let lvar = s:InMultiVarStatement(v:lnum) + if lvar + let prevline_contents = s:RemoveTrailingComments(getline(prevline)) + + " check for comma first + if (line[col - 1] =~ ',') + " if the previous line ends in comma or semicolon don't indent + if (prevline_contents =~ '[;,]\s*$') + return indent(s:GetMSL(line('.'), 0)) + " get previous line indent, if it's comma first return prevline indent + elseif (prevline_contents =~ s:comma_first) + return indent(prevline) + " otherwise we indent 1 level + else + return indent(lvar) + &sw + endif + endif + endif + + + let bs = strpart('(){}[]', stridx(')}]', line[col - 1]) * 2, 2) + if searchpair(escape(bs[0], '\['), '', bs[1], 'bW', s:skip_expr) > 0 + if line[col-1]==')' && col('.') != col('$') - 1 + let ind = virtcol('.')-1 + else + let ind = indent(s:GetMSL(line('.'), 0)) + endif + endif + return ind + endif + + " If the line is comma first, dedent 1 level + if (getline(prevline) =~ s:comma_first) + return indent(prevline) - &sw + endif + + if (line =~ s:ternary) + if (getline(prevline) =~ s:ternary_q) + return indent(prevline) + else + return indent(prevline) + &sw + endif + endif + + " If we are in a multi-line comment, cindent does the right thing. + if s:IsInMultilineComment(v:lnum, 1) && !s:IsLineComment(v:lnum, 1) + return cindent(v:lnum) + endif + + " Check for multiple var assignments +" let var_indent = s:GetVarIndent(v:lnum) +" if var_indent >= 0 +" return var_indent +" endif + + " 3.3. Work on the previous line. {{{2 + " ------------------------------- + + " If the line is empty and the previous nonblank line was a multi-line + " comment, use that comment's indent. Deduct one char to account for the + " space in ' */'. + if line =~ '^\s*$' && s:IsInMultilineComment(prevline, 1) + return indent(prevline) - 1 + endif + + " Find a non-blank, non-multi-line string line above the current line. + let lnum = s:PrevNonBlankNonString(v:lnum - 1) + + " If the line is empty and inside a string, use the previous line. + if line =~ '^\s*$' && lnum != prevline + return indent(prevnonblank(v:lnum)) + endif + + " At the start of the file use zero indent. + if lnum == 0 + return 0 + endif + + " Set up variables for current line. + let line = getline(lnum) + let ind = indent(lnum) + + " If the previous line ended with a block opening, add a level of indent. + if s:Match(lnum, s:block_regex) + return indent(s:GetMSL(lnum, 0)) + &sw + endif + + " If the previous line contained an opening bracket, and we are still in it, + " add indent depending on the bracket type. + if line =~ '[[({]' + let counts = s:LineHasOpeningBrackets(lnum) + if counts[0] == '1' && searchpair('(', '', ')', 'bW', s:skip_expr) > 0 + if col('.') + 1 == col('$') + return ind + &sw + else + return virtcol('.') + endif + elseif counts[1] == '1' || counts[2] == '1' + return ind + &sw + else + call cursor(v:lnum, vcol) + end + endif + + " 3.4. Work on the MSL line. {{{2 + " -------------------------- + + let ind_con = ind + let ind = s:IndentWithContinuation(lnum, ind_con, &sw) + + " }}}2 + " + " + let ols = s:InOneLineScope(lnum) + if ols > 0 + let ind = ind + &sw + else + let ols = s:ExitingOneLineScope(lnum) + while ols > 0 && ind > 0 + let ind = ind - &sw + let ols = s:InOneLineScope(ols - 1) + endwhile + endif + + return ind +endfunction + +" }}}1 + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/indent/vue.vim b/runtime/indent/vue.vim new file mode 100644 index 0000000000..7ff623b3d1 --- /dev/null +++ b/runtime/indent/vue.vim @@ -0,0 +1,12 @@ +" Vim indent file placeholder +" Language: Vue +" Maintainer: None, please volunteer if you have a real Vue indent script + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif +let b:did_indent = 1 + +" Html comes closest +runtime! indent/html.vim diff --git a/runtime/syntax/chatito.vim b/runtime/syntax/chatito.vim new file mode 100644 index 0000000000..d89307cf06 --- /dev/null +++ b/runtime/syntax/chatito.vim @@ -0,0 +1,62 @@ +" Vim syntax file +" Language: Chatito +" Maintainer: ObserverOfTime +" Filenames: *.chatito +" Last Change: 2022 Sep 19 + +if exists('b:current_syntax') + finish +endif + +" Comment +syn keyword chatitoTodo contained TODO FIXME XXX +syn match chatitoComment /^#.*/ contains=chatitoTodo,@Spell +syn match chatitoComment +^//.*+ contains=chatitoTodo,@Spell + +" Import +syn match chatitoImport /^import \+.*$/ transparent contains=chatitoImportKeyword,chatitoImportFile +syn keyword chatitoImportKeyword import contained nextgroup=chatitoImportFile +syn match chatitoImportFile /.*$/ contained skipwhite + +" Intent +syn match chatitoIntent /^%\[[^\]?]\+\]\((.\+)\)\=$/ contains=chatitoArgs + +" Slot +syn match chatitoSlot /^@\[[^\]?#]\+\(#[^\]?#]\+\)\=\]\((.\+)\)\=$/ contains=chatitoArgs,chatitoVariation +syn match chatitoSlot /@\[[^\]?#]\+\(#[^\]?#]\+\)\=?\=\]/ contained contains=chatitoOpt,chatitoVariation + +" Alias +syn match chatitoAlias /^\~\[[^\]?]\+\]\=$/ +syn match chatitoAlias /\~\[[^\]?]\+?\=\]/ contained contains=chatitoOpt + +" Probability +syn match chatitoProbability /\*\[\d\+\(\.\d\+\)\=%\=\]/ contained + +" Optional +syn match chatitoOpt '?' contained + +" Arguments +syn match chatitoArgs /(.\+)/ contained + +" Variation +syn match chatitoVariation /#[^\]?#]\+/ contained + +" Value +syn match chatitoValue /^ \{4\}\zs.\+$/ contains=chatitoProbability,chatitoSlot,chatitoAlias,@Spell + +" Errors +syn match chatitoError /^\t/ + +hi def link chatitoAlias String +hi def link chatitoArgs Special +hi def link chatitoComment Comment +hi def link chatitoError Error +hi def link chatitoImportKeyword Include +hi def link chatitoIntent Statement +hi def link chatitoOpt SpecialChar +hi def link chatitoProbability Number +hi def link chatitoSlot Identifier +hi def link chatitoTodo Todo +hi def link chatitoVariation Special + +let b:current_syntax = 'chatito' diff --git a/runtime/syntax/desktop.vim b/runtime/syntax/desktop.vim index 2c1102238d..461ba855b9 100644 --- a/runtime/syntax/desktop.vim +++ b/runtime/syntax/desktop.vim @@ -3,7 +3,7 @@ " Filenames: *.desktop, *.directory " Maintainer: Eisuke Kawashima ( e.kawaschima+vim AT gmail.com ) " Previous Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl ) -" Last Change: 2020-06-11 +" Last Change: 2022 Sep 22 " Version Info: desktop.vim 1.5 " References: " - https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.5.html (2020-04-27) @@ -60,10 +60,10 @@ syn match dtLocaleSuffix " Boolean Value {{{2 syn match dtBoolean - \ /^\%(DBusActivatable\|Hidden\|NoDisplay\|PrefersNonDefaultGPU\|StartupNotify\|Terminal\)\s*=\s*\%(true\|false\)/ + \ /^\%(DBusActivatable\|Hidden\|NoDisplay\|PrefersNonDefaultGPU\|SingleMainWindow\|StartupNotify\|Terminal\)\s*=\s*\%(true\|false\)/ \ contains=dtBooleanKey,dtDelim,dtBooleanValue transparent syn keyword dtBooleanKey - \ DBusActivatable Hidden NoDisplay PrefersNonDefaultGPU StartupNotify Terminal + \ DBusActivatable Hidden NoDisplay PrefersNonDefaultGPU SingleMainWindow StartupNotify Terminal \ contained nextgroup=dtDelim if s:desktop_enable_kde diff --git a/runtime/syntax/gyp.vim b/runtime/syntax/gyp.vim new file mode 100644 index 0000000000..14c07b8726 --- /dev/null +++ b/runtime/syntax/gyp.vim @@ -0,0 +1,49 @@ +" Vim syntax file +" Language: GYP +" Maintainer: ObserverOfTime +" Filenames: *.gyp,*.gypi +" Last Change: 2022 Sep 27 + +if !exists('g:main_syntax') + if exists('b:current_syntax') && b:current_syntax ==# 'gyp' + finish + endif + let g:main_syntax = 'gyp' +endif + +" Based on JSON syntax +runtime! syntax/json.vim + +" Single quotes are allowed +syn clear jsonStringSQError + +syn match jsonKeywordMatch /'\([^']\|\\\'\)\+'[[:blank:]\r\n]*\:/ contains=jsonKeyword +if has('conceal') && (!exists('g:vim_json_conceal') || g:vim_json_conceal==1) + syn region jsonKeyword matchgroup=jsonQuote start=/'/ end=/'\ze[[:blank:]\r\n]*\:/ concealends contained +else + syn region jsonKeyword matchgroup=jsonQuote start=/'/ end=/'\ze[[:blank:]\r\n]*\:/ contained +endif + +syn match jsonStringMatch /'\([^']\|\\\'\)\+'\ze[[:blank:]\r\n]*[,}\]]/ contains=jsonString +if has('conceal') && (!exists('g:vim_json_conceal') || g:vim_json_conceal==1) + syn region jsonString oneline matchgroup=jsonQuote start=/'/ skip=/\\\\\|\\'/ end=/'/ concealends contains=jsonEscape contained +else + syn region jsonString oneline matchgroup=jsonQuote start=/'/ skip=/\\\\\|\\'/ end=/'/ contains=jsonEscape contained +endif + +" Trailing commas are allowed +if !exists('g:vim_json_warnings') || g:vim_json_warnings==1 + syn clear jsonTrailingCommaError +endif + +" Python-style comments are allowed +syn match jsonComment /#.*$/ contains=jsonTodo,@Spell +syn keyword jsonTodo FIXME NOTE TODO XXX TBD contained + +hi def link jsonComment Comment +hi def link jsonTodo Todo + +let b:current_syntax = 'gyp' +if g:main_syntax ==# 'gyp' + unlet g:main_syntax +endif diff --git a/runtime/syntax/hare.vim b/runtime/syntax/hare.vim new file mode 100644 index 0000000000..07cf33fb11 --- /dev/null +++ b/runtime/syntax/hare.vim @@ -0,0 +1,133 @@ +" PRELUDE {{{1 +" Vim syntax file +" Language: Hare +" Maintainer: Amelia Clarke +" Last Change: 2022-09-21 + +if exists("b:current_syntax") + finish +endif +let b:current_syntax = "hare" + +" SYNTAX {{{1 +syn case match + +" KEYWORDS {{{2 +syn keyword hareConditional if else match switch +syn keyword hareKeyword break continue return yield +syn keyword hareKeyword defer +syn keyword hareKeyword fn +syn keyword hareKeyword let +syn keyword hareLabel case +syn keyword hareOperator as is +syn keyword hareRepeat for +syn keyword hareStorageClass const def export nullable static +syn keyword hareStructure enum struct union +syn keyword hareTypedef type + +" C ABI. +syn keyword hareKeyword vastart vaarg vaend + +" BUILTINS {{{2 +syn keyword hareBuiltin abort +syn keyword hareBuiltin alloc free +syn keyword hareBuiltin append delete insert +syn keyword hareBuiltin assert +syn keyword hareBuiltin len offset + +" TYPES {{{2 +syn keyword hareType bool +syn keyword hareType char str +syn keyword hareType f32 f64 +syn keyword hareType u8 u16 u32 u64 i8 i16 i32 i64 +syn keyword hareType uint int +syn keyword hareType rune +syn keyword hareType uintptr +syn keyword hareType void + +" C ABI. +syn keyword hareType valist + +" LITERALS {{{2 +syn keyword hareBoolean true false +syn keyword hareNull null + +" Number literals. +syn match hareNumber "\v(\.@1" display +syn match hareNumber "\v(\.@1" display +syn match hareNumber "\v(\.@1" display +syn match hareNumber "\v(\.@1" display + +" Floating-point number literals. +syn match hareFloat "\v<\d+\.\d+([Ee][+-]?\d+)?(f32|f64)?>" display +syn match hareFloat "\v<\d+([Ee][+-]?\d+)?(f32|f64)>" display + +" String and rune literals. +syn match hareEscape "\\[\\'"0abfnrtv]" contained display +syn match hareEscape "\v\\(x\x{2}|u\x{4}|U\x{8})" contained display +syn match hareFormat "\v\{\d*(\%\d*|(:[ 0+-]?\d*(\.\d+)?[Xbox]?))?}" contained display +syn match hareFormat "\({{\|}}\)" contained display +syn region hareRune start="'" end="'\|$" skip="\\'" contains=hareEscape display extend +syn region hareString start=+"+ end=+"\|$+ skip=+\\"+ contains=hareEscape,hareFormat display extend +syn region hareString start="`" end="`\|$" contains=hareFormat display + +" MISCELLANEOUS {{{2 +syn keyword hareTodo FIXME TODO XXX contained + +" Attributes. +syn match hareAttribute "@[a-z]*" + +" Blocks. +syn region hareBlock start="{" end="}" fold transparent + +" Comments. +syn region hareComment start="//" end="$" contains=hareCommentDoc,hareTodo,@Spell display keepend +syn region hareCommentDoc start="\[\[" end="]]\|\ze\_s" contained display + +" The size keyword can be either a builtin or a type. +syn match hareBuiltin "\v\ze(\_s*//.*\_$)*\_s*\(" contains=hareComment +syn match hareType "\v((\_s*//.*\_$)*\_s*\()@!" contains=hareComment + +" Trailing whitespace. +syn match hareSpaceError "\v\s+$" display excludenl +syn match hareSpaceError "\v\zs +\ze\t" display + +" Use statement. +syn region hareUse start="\v^\s*\zsuse>" end=";" contains=hareComment display + +syn match hareErrorAssertion "\v(^([^/]|//@!)*\)\_s*)@<=!\=@!" +syn match hareQuestionMark "?" + +" DEFAULT HIGHLIGHTING {{{1 +hi def link hareAttribute Keyword +hi def link hareBoolean Boolean +hi def link hareBuiltin Function +hi def link hareComment Comment +hi def link hareCommentDoc SpecialComment +hi def link hareConditional Conditional +hi def link hareEscape SpecialChar +hi def link hareFloat Float +hi def link hareFormat SpecialChar +hi def link hareKeyword Keyword +hi def link hareLabel Label +hi def link hareNull Constant +hi def link hareNumber Number +hi def link hareOperator Operator +hi def link hareQuestionMark Special +hi def link hareRepeat Repeat +hi def link hareRune Character +hi def link hareStorageClass StorageClass +hi def link hareString String +hi def link hareStructure Structure +hi def link hareTodo Todo +hi def link hareType Type +hi def link hareTypedef Typedef +hi def link hareUse PreProc + +hi def link hareSpaceError Error +autocmd InsertEnter * hi link hareSpaceError NONE +autocmd InsertLeave * hi link hareSpaceError Error + +hi def hareErrorAssertion ctermfg=red cterm=bold guifg=red gui=bold + +" vim: tabstop=8 shiftwidth=2 expandtab diff --git a/runtime/syntax/help.vim b/runtime/syntax/help.vim index 01915d23d7..5773e94c3e 100644 --- a/runtime/syntax/help.vim +++ b/runtime/syntax/help.vim @@ -1,7 +1,7 @@ " Vim syntax file " Language: Vim help file " Maintainer: Bram Moolenaar (Bram@vim.org) -" Last Change: 2021 Jun 13 +" Last Change: 2022 Sep 26 " Quit when a (custom) syntax file was already loaded if exists("b:current_syntax") @@ -39,6 +39,7 @@ syn match helpVim "VIM REFERENCE.*" syn match helpVim "NVIM REFERENCE.*" syn match helpOption "'[a-z]\{2,\}'" syn match helpOption "'t_..'" +syn match helpNormal "'ab'" syn match helpCommand "`[^` \t]\+`"hs=s+1,he=e-1 contains=helpBacktick syn match helpCommand "\(^\|[^a-z"[]\)\zs`[^`]\+`\ze\([^a-z\t."']\|$\)"hs=s+1,he=e-1 contains=helpBacktick syn match helpHeader "\s*\zs.\{-}\ze\s\=\~$" nextgroup=helpIgnore diff --git a/runtime/syntax/hlsplaylist.vim b/runtime/syntax/hlsplaylist.vim new file mode 100644 index 0000000000..245eee213b --- /dev/null +++ b/runtime/syntax/hlsplaylist.vim @@ -0,0 +1,120 @@ +" Vim syntax file +" Language: HLS Playlist +" Maintainer: Benoît Ryder +" Latest Revision: 2022-09-23 + +if exists("b:current_syntax") + finish +endif + +let s:cpo_save = &cpo +set cpo&vim + +" Comment line +syn match hlsplaylistComment "^#\(EXT\)\@!.*$" +" Segment URL +syn match hlsplaylistUrl "^[^#].*$" + +" Unknown tags, assume an attribute list or nothing +syn match hlsplaylistTagUnknown "^#EXT[^:]*$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagUnknown start="^#EXT[^:]*\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Basic Tags +syn match hlsplaylistTagHeader "^#EXTM3U$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-VERSION\ze:" end="$" keepend contains=hlsplaylistValueInt + +" Media or Multivariant Playlist Tags +syn match hlsplaylistTagHeader "^#EXT-X-INDEPENDENT-SEGMENTS$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagDelimiter start="^#EXT-X-START\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-DEFINE\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Media Playlist Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-TARGETDURATION\ze:" end="$" keepend contains=hlsplaylistValueFloat +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-MEDIA-SEQUENCE\ze:" end="$" keepend contains=hlsplaylistValueInt +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-DISCONTINUITY-SEQUENCE\ze:" end="$" keepend contains=hlsplaylistValueInt +syn match hlsplaylistTagDelimiter "^#EXT-X-ENDLIST$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-PLAYLIST-TYPE\ze:" end="$" keepend contains=hlsplaylistAttributeEnum +syn match hlsplaylistTagStandard "^#EXT-X-I-FRAME-ONLY$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-PART-INF\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagHeader start="^#EXT-X-SERVER-CONTROL\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Media Segment Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXTINF\ze:" end="$" keepend contains=hlsplaylistValueFloat,hlsplaylistExtInfDesc +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-BYTERANGE\ze:" end="$" keepend contains=hlsplaylistValueInt +syn match hlsplaylistTagDelimiter "^#EXT-X-DISCONTINUITY$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-KEY\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-MAP\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-PROGRAM-DATE-TIME\ze:" end="$" keepend contains=hlsplaylistValueDateTime +syn match hlsplaylistTagDelimiter "^#EXT-X-GAP$" +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-BITRATE\ze:" end="$" keepend contains=hlsplaylistValueFloat +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-PART\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Media Metadata Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-DATERANGE\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-SKIP\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-PRELOAD-HINT\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-RENDITION-REPORT\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Multivariant Playlist Tags +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-MEDIA\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-STREAM-INF\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStatement start="^#EXT-X-I-FRAME-STREAM-INF\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-SESSION-DATA\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-SESSION-KEY\ze:" end="$" keepend contains=hlsplaylistAttributeList +syn region hlsplaylistTagLine matchgroup=hlsplaylistTagStandard start="^#EXT-X-CONTENT-STEERING\ze:" end="$" keepend contains=hlsplaylistAttributeList + +" Attributes +syn region hlsplaylistAttributeList start=":" end="$" keepend contained + \ contains=hlsplaylistAttributeName,hlsplaylistAttributeInt,hlsplaylistAttributeHex,hlsplaylistAttributeFloat,hlsplaylistAttributeString,hlsplaylistAttributeEnum,hlsplaylistAttributeResolution,hlsplaylistAttributeUri +" Common attributes +syn match hlsplaylistAttributeName "[A-Za-z-]\+\ze=" contained +syn match hlsplaylistAttributeEnum "=\zs[A-Za-z][A-Za-z0-9-_]*" contained +syn match hlsplaylistAttributeString +=\zs"[^"]*"+ contained +syn match hlsplaylistAttributeInt "=\zs\d\+" contained +syn match hlsplaylistAttributeFloat "=\zs-\?\d*\.\d*" contained +syn match hlsplaylistAttributeHex "=\zs0[xX]\d*" contained +syn match hlsplaylistAttributeResolution "=\zs\d\+x\d\+" contained +" Allow different highligting for URI attributes +syn region hlsplaylistAttributeUri matchgroup=hlsplaylistAttributeName start="\zsURI\ze" end="\(,\|$\)" contained contains=hlsplaylistUriQuotes +syn region hlsplaylistUriQuotes matchgroup=hlsplaylistAttributeString start=+"+ end=+"+ keepend contained contains=hlsplaylistUriValue +syn match hlsplaylistUriValue /[^" ]\+/ contained +" Individual values +syn match hlsplaylistValueInt "[0-9]\+" contained +syn match hlsplaylistValueFloat "\(\d\+\|\d*\.\d*\)" contained +syn match hlsplaylistExtInfDesc ",\zs.*$" contained +syn match hlsplaylistValueDateTime "\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d\(\.\d*\)\?\(Z\|\d\d:\?\d\d\)$" contained + + +" Define default highlighting + +hi def link hlsplaylistComment Comment +hi def link hlsplaylistUrl NONE + +hi def link hlsplaylistTagHeader Special +hi def link hlsplaylistTagStandard Define +hi def link hlsplaylistTagDelimiter Delimiter +hi def link hlsplaylistTagStatement Statement +hi def link hlsplaylistTagUnknown Special + +hi def link hlsplaylistUriQuotes String +hi def link hlsplaylistUriValue Underlined +hi def link hlsplaylistAttributeQuotes String +hi def link hlsplaylistAttributeName Identifier +hi def link hlsplaylistAttributeInt Number +hi def link hlsplaylistAttributeHex Number +hi def link hlsplaylistAttributeFloat Float +hi def link hlsplaylistAttributeString String +hi def link hlsplaylistAttributeEnum Constant +hi def link hlsplaylistAttributeResolution Constant +hi def link hlsplaylistValueInt Number +hi def link hlsplaylistValueFloat Float +hi def link hlsplaylistExtInfDesc String +hi def link hlsplaylistValueDateTime Constant + + +let b:current_syntax = "hlsplaylist" + +let &cpo = s:cpo_save +unlet s:cpo_save + +" vim: sts=2 sw=2 et diff --git a/runtime/syntax/plsql.vim b/runtime/syntax/plsql.vim index 21681d59e4..9b4df09ac7 100644 --- a/runtime/syntax/plsql.vim +++ b/runtime/syntax/plsql.vim @@ -4,8 +4,11 @@ " Previous Maintainer: Jeff Lanzarotta (jefflanzarotta at yahoo dot com) " Previous Maintainer: C. Laurence Gonsalves (clgonsal@kami.com) " URL: https://github.com/lee-lindley/vim_plsql_syntax -" Last Change: Aug 21, 2022 -" History Lee Lindley (lee dot lindley at gmail dot com) +" Last Change: Sep 19, 2022 +" History Carsten Czarski (carsten dot czarski at oracle com) +" add handling for typical SQL*Plus commands (rem, start, host, set, etc) +" add error highlight for non-breaking space +" Lee Lindley (lee dot lindley at gmail dot com) " use get with default 0 instead of exists per Bram suggestion " make procedure folding optional " updated to 19c keywords. refined quoting. @@ -54,8 +57,13 @@ syn case ignore syn match plsqlGarbage "[^ \t()]" syn match plsqlIdentifier "[a-z][a-z0-9$_#]*" +syn match plsqlSqlPlusDefine "&&\?[a-z][a-z0-9$_#]*\.\?" syn match plsqlHostIdentifier ":[a-z][a-z0-9$_#]*" +" The Non-Breaking is often accidentally typed (Mac User: Opt+Space, after typing the "|", Opt+7); +" error highlight for these avoids running into annoying compiler errors. +syn match plsqlIllegalSpace "[\xa0]" + " When wanted, highlight the trailing whitespace. if get(g:,"plsql_space_errors",0) == 1 if get(g:,"plsql_no_trail_space_error",0) == 0 @@ -79,7 +87,6 @@ syn match plsqlOperator "\" " " conditional compilation Preprocessor directives and sqlplus define sigil syn match plsqlPseudo "$[$a-z][a-z0-9$_#]*" -syn match plsqlPseudo "&" syn match plsqlReserved "\<\(CREATE\|THEN\|UPDATE\|INSERT\|SET\)\>" syn match plsqlKeyword "\<\(REPLACE\|PACKAGE\|FUNCTION\|PROCEDURE\|TYPE|BODY\|WHEN\|MATCHED\)\>" @@ -150,7 +157,7 @@ syn keyword plsqlKeyword DATA_SECURITY_REWRITE_LIMIT DATA_VALIDATE DATE_MODE DAY syn keyword plsqlKeyword DBMS_STATS DBSTR2UTF8 DBTIMEZONE DB_ROLE_CHANGE DB_UNIQUE_NAME DB_VERSION syn keyword plsqlKeyword DDL DEALLOCATE DEBUG DEBUGGER DECLARE DECODE DECOMPOSE DECOMPRESS DECORRELATE syn keyword plsqlKeyword DECR DECREMENT DECRYPT DEDUPLICATE DEFAULTS DEFAULT_COLLATION DEFAULT_PDB_HINT -syn keyword plsqlKeyword DEFERRABLE DEFERRED DEFINE DEFINED DEFINER DEFINITION DEGREE DELAY DELEGATE +syn keyword plsqlKeyword DEFERRABLE DEFERRED DEFINED DEFINER DEFINITION DEGREE DELAY DELEGATE syn keyword plsqlKeyword DELETEXML DELETE_ALL DEMAND DENORM_AV DENSE_RANK DENSE_RANKM DEPENDENT DEPTH syn keyword plsqlKeyword DEQUEUE DEREF DEREF_NO_REWRITE DESCENDANT DESCRIPTION DESTROY DETACHED DETERMINED syn keyword plsqlKeyword DETERMINES DETERMINISTIC DG_GATHER_STATS DIAGNOSTICS DICTIONARY DIGEST DIMENSION @@ -189,7 +196,7 @@ syn keyword plsqlKeyword HELP HEXTORAW HEXTOREF HIDDEN HIDE HIERARCHICAL HIERARC syn keyword plsqlKeyword HIER_CAPTION HIER_CHILDREN HIER_CHILD_COUNT HIER_COLUMN HIER_CONDITION HIER_DEPTH syn keyword plsqlKeyword HIER_DESCRIPTION HIER_HAS_CHILDREN HIER_LAG HIER_LEAD HIER_LEVEL HIER_MEMBER_NAME syn keyword plsqlKeyword HIER_MEMBER_UNIQUE_NAME HIER_ORDER HIER_PARENT HIER_WINDOW HIGH HINTSET_BEGIN -syn keyword plsqlKeyword HINTSET_END HOST HOT HOUR HOURS HTTP HWM_BROKERED HYBRID ID IDENTIFIER IDENTITY +syn keyword plsqlKeyword HINTSET_END HOT HOUR HOURS HTTP HWM_BROKERED HYBRID ID IDENTIFIER IDENTITY syn keyword plsqlKeyword IDGENERATORS IDLE IDLE_TIME IGNORE IGNORE_OPTIM_EMBEDDED_HINTS IGNORE_ROW_ON_DUPKEY_INDEX syn keyword plsqlKeyword IGNORE_WHERE_CLAUSE ILM IMMEDIATE IMMUTABLE IMPACT IMPORT INACTIVE INACTIVE_ACCOUNT_TIME syn keyword plsqlKeyword INCLUDE INCLUDES INCLUDE_VERSION INCLUDING INCOMING INCR INCREMENT INCREMENTAL @@ -342,7 +349,7 @@ syn keyword plsqlKeyword SELF SEMIJOIN SEMIJOIN_DRIVER SEMI_TO_INNER SENSITIVE S syn keyword plsqlKeyword SERIAL SERIALIZABLE SERVERERROR SERVICE SERVICES SERVICE_NAME_CONVERT SESSION syn keyword plsqlKeyword SESSIONS_PER_USER SESSIONTIMEZONE SESSIONTZNAME SESSION_CACHED_CURSORS SETS syn keyword plsqlKeyword SETTINGS SET_GBY_PUSHDOWN SET_TO_JOIN SEVERE SHARD SHARDED SHARDS SHARDSPACE -syn keyword plsqlKeyword SHARD_CHUNK_ID SHARED SHARED_POOL SHARE_OF SHARING SHD$COL$MAP SHELFLIFE SHOW +syn keyword plsqlKeyword SHARD_CHUNK_ID SHARED SHARED_POOL SHARE_OF SHARING SHD$COL$MAP SHELFLIFE syn keyword plsqlKeyword SHRINK SHUTDOWN SIBLING SIBLINGS SID SIGN SIGNAL_COMPONENT SIGNAL_FUNCTION syn keyword plsqlKeyword SIGNATURE SIMPLE SIN SINGLE SINGLETASK SINH SITE SKEWNESS_POP SKEWNESS_SAMP syn keyword plsqlKeyword SKIP SKIP_EXT_OPTIMIZER SKIP_PROXY SKIP_UNQ_UNUSABLE_IDX SKIP_UNUSABLE_INDEXES @@ -445,7 +452,7 @@ syn keyword plsqlKeyword VECTOR_READ_TRACE VECTOR_TRANSFORM VECTOR_TRANSFORM_DIM syn keyword plsqlKeyword VERIFIER VERIFY VERSION VERSIONING VERSIONS VERSIONS_ENDSCN VERSIONS_ENDTIME syn keyword plsqlKeyword VERSIONS_OPERATION VERSIONS_STARTSCN VERSIONS_STARTTIME VERSIONS_XID VIEWS syn keyword plsqlKeyword VIOLATION VIRTUAL VISIBILITY VISIBLE VOLUME VSIZE WAIT WALLET WEEK WEEKS WELLFORMED -syn keyword plsqlKeyword WHENEVER WHITESPACE WIDTH_BUCKET WINDOW WITHIN WITHOUT WITH_EXPRESSION +syn keyword plsqlKeyword WHITESPACE WIDTH_BUCKET WINDOW WITHIN WITHOUT WITH_EXPRESSION syn keyword plsqlKeyword WITH_PLSQL WORK WRAPPED WRAPPER WRITE XDB_FASTPATH_INSERT XID XML XML2OBJECT syn keyword plsqlKeyword XMLATTRIBUTES XMLCAST XMLCDATA XMLCOLATTVAL XMLCOMMENT XMLCONCAT XMLDIFF XMLELEMENT syn keyword plsqlKeyword XMLEXISTS XMLEXISTS2 XMLFOREST XMLINDEX_REWRITE XMLINDEX_REWRITE_IN_SELECT @@ -468,13 +475,13 @@ syn keyword plsqlReserved MINUS MODE NOCOMPRESS NOWAIT NUMBER_BASE OCICOLL OCIDA syn keyword plsqlReserved OCIDURATION OCIINTERVAL OCILOBLOCATOR OCINUMBER OCIRAW OCIREF OCIREFCURSOR syn keyword plsqlReserved OCIROWID OCISTRING OCITYPE OF ON OPTION ORACLE ORADATA ORDER ORLANY ORLVARY syn keyword plsqlReserved OUT OVERRIDING PARALLEL_ENABLE PARAMETER PASCAL PCTFREE PIPE PIPELINED POLYMORPHIC -syn keyword plsqlReserved PRAGMA PRIOR PUBLIC RAISE RECORD RELIES_ON REM RENAME RESOURCE RESULT REVOKE ROWID +syn keyword plsqlReserved PRAGMA PRIOR PUBLIC RAISE RECORD RELIES_ON RENAME RESOURCE RESULT REVOKE ROWID syn keyword plsqlReserved SB1 SB2 syn match plsqlReserved "\" syn keyword plsqlReserved SEPARATE SHARE SHORT SIZE SIZE_T SPARSE SQLCODE SQLDATA syn keyword plsqlReserved SQLNAME SQLSTATE STANDARD START STORED STRUCT STYLE SYNONYM TABLE TDO syn keyword plsqlReserved TRANSACTIONAL TRIGGER UB1 UB4 UNION UNIQUE UNSIGNED UNTRUSTED VALIST -syn keyword plsqlReserved VALUES VARIABLE VIEW VOID WHERE WITH +syn keyword plsqlReserved VALUES VIEW VOID WHERE WITH " PL/SQL and SQL functions. syn keyword plsqlFunction ABS ACOS ADD_MONTHS APPROX_COUNT APPROX_COUNT_DISTINCT APPROX_COUNT_DISTINCT_AGG @@ -584,18 +591,18 @@ syn match plsqlEND "\" syn match plsqlISAS "\<\(IS\|AS\)\>" " Various types of comments. -syntax region plsqlCommentL start="--" skip="\\$" end="$" keepend extend contains=@plsqlCommentGroup,plsqlSpaceError +syntax region plsqlCommentL start="--" skip="\\$" end="$" keepend extend contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace,plsqlSqlplusDefine if get(g:,"plsql_fold",0) == 1 syntax region plsqlComment \ start="/\*" end="\*/" \ extend - \ contains=@plsqlCommentGroup,plsqlSpaceError + \ contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace,plsqlSqlplusDefine \ fold else syntax region plsqlComment \ start="/\*" end="\*/" \ extend - \ contains=@plsqlCommentGroup,plsqlSpaceError + \ contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace,plsqlSqlplusDefine endif syn cluster plsqlCommentAll contains=plsqlCommentL,plsqlComment @@ -618,23 +625,23 @@ syn match plsqlFloatLiteral contained "\.\(\d\+\([eE][+-]\?\d\+\)\?\)[fd]\?" " double quoted strings in SQL are database object names. Should be a subgroup of Normal. " We will use Character group as a proxy for that so color can be chosen close to Normal syn region plsqlQuotedIdentifier matchgroup=plsqlOperator start=+n\?"+ end=+"+ keepend extend -syn cluster plsqlIdentifiers contains=plsqlIdentifier,plsqlQuotedIdentifier +syn cluster plsqlIdentifiers contains=plsqlIdentifier,plsqlQuotedIdentifier,plsqlSqlPlusDefine " quoted string literals if get(g:,"plsql_fold",0) == 1 - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ fold keepend extend - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ contains=plsqlSqlplusDefine fold keepend extend + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ contains=plsqlSqlplusDefine fold keepend extend else - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ - syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?'+ skip=+''+ end=+'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\z([^[(<{]\)+ end=+\z1'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'<+ end=+>'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'{+ end=+}'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'(+ end=+)'+ contains=plsqlSqlplusDefine + syn region plsqlStringLiteral matchgroup=plsqlOperator start=+n\?q'\[+ end=+]'+ contains=plsqlSqlplusDefine endif syn keyword plsqlBooleanLiteral TRUE FALSE @@ -682,6 +689,10 @@ syn match plsqlConditional "\\_s\+\" syn match plsqlCase "\\_s\+\" syn match plsqlCase "\" +syn region plsqlSqlPlusCommentL start="^\(REM\)\( \|$\)" skip="\\$" end="$" keepend extend contains=@plsqlCommentGroup,plsqlSpaceError,plsqlIllegalSpace +syn region plsqlSqlPlusCommand start="^\(SET\|DEFINE\|PROMPT\|ACCEPT\|EXEC\|HOST\|SHOW\|VAR\|VARIABLE\|COL\|WHENEVER\|TIMING\)\( \|$\)" skip="\\$" end="$" keepend extend +syn region plsqlSqlPlusRunFile start="^\(@\|@@\)" skip="\\$" end="$" keepend extend + if get(g:,"plsql_fold",0) == 1 setlocal foldmethod=syntax syn sync fromstart @@ -826,6 +837,13 @@ hi def link plsqlComment2String String hi def link plsqlTrigger Function hi def link plsqlTypeAttribute StorageClass hi def link plsqlTodo Todo + +hi def link plsqlIllegalSpace Error +hi def link plsqlSqlPlusDefine PreProc +hi def link plsqlSqlPlusCommand PreProc +hi def link plsqlSqlPlusRunFile Include +hi def link plsqlSqlPlusCommentL Comment + " to be able to change them after loading, need override whether defined or not if get(g:,"plsql_legacy_sql_keywords",0) == 1 hi link plsqlSQLKeyword Function diff --git a/runtime/syntax/solidity.vim b/runtime/syntax/solidity.vim new file mode 100644 index 0000000000..e552446e10 --- /dev/null +++ b/runtime/syntax/solidity.vim @@ -0,0 +1,173 @@ +" Vim syntax file +" Language: Solidity +" Maintainer: Cothi (jiungdev@gmail.com) +" Original Author: tomlion (https://github.com/tomlion/vim-solidity/blob/master/syntax/solidity.vim) +" Last Changed: 2022 Sep 27 +" +" Additional contributors: +" Modified by thesis (https://github.com/thesis/vim-solidity/blob/main/indent/solidity.vim) + +if exists("b:current_syntax") + finish +endif + +" keyword +syn keyword solKeyword abstract anonymous as break calldata case catch constant constructor continue default switch revert require +syn keyword solKeyword ecrecover addmod mulmod keccak256 +syn keyword solKeyword delete do else emit enum external final for function if immutable import in indexed inline +syn keyword solKeyword interface internal is let match memory modifier new of payable pragma private public pure override virtual +syn keyword solKeyword relocatable return returns static storage struct throw try type typeof using +syn keyword solKeyword var view while + +syn keyword solConstant true false wei szabo finney ether seconds minutes hours days weeks years now +syn keyword solConstant abi block blockhash msg tx this super selfdestruct + +syn keyword solBuiltinType mapping address bool +syn keyword solBuiltinType int int8 int16 int24 int32 int40 int48 int56 int64 int72 int80 int88 int96 int104 int112 int120 int128 int136 int144 int152 int160 int168 int178 int184 int192 int200 int208 int216 int224 int232 int240 int248 int256 +syn keyword solBuiltinType uint uint8 uint16 uint24 uint32 uint40 uint48 uint56 uint64 uint72 uint80 uint88 uint96 uint104 uint112 uint120 uint128 uint136 uint144 uint152 uint160 uint168 uint178 uint184 uint192 uint200 uint208 uint216 uint224 uint232 uint240 uint248 uint256 +syn keyword solBuiltinType fixed +syn keyword solBuiltinType fixed0x8 fixed0x16 fixed0x24 fixed0x32 fixed0x40 fixed0x48 fixed0x56 fixed0x64 fixed0x72 fixed0x80 fixed0x88 fixed0x96 fixed0x104 fixed0x112 fixed0x120 fixed0x128 fixed0x136 fixed0x144 fixed0x152 fixed0x160 fixed0x168 fixed0x178 fixed0x184 fixed0x192 fixed0x200 fixed0x208 fixed0x216 fixed0x224 fixed0x232 fixed0x240 fixed0x248 fixed0x256 +syn keyword solBuiltinType fixed8x8 fixed8x16 fixed8x24 fixed8x32 fixed8x40 fixed8x48 fixed8x56 fixed8x64 fixed8x72 fixed8x80 fixed8x88 fixed8x96 fixed8x104 fixed8x112 fixed8x120 fixed8x128 fixed8x136 fixed8x144 fixed8x152 fixed8x160 fixed8x168 fixed8x178 fixed8x184 fixed8x192 fixed8x200 fixed8x208 fixed8x216 fixed8x224 fixed8x232 fixed8x240 fixed8x248 +syn keyword solBuiltinType fixed16x8 fixed16x16 fixed16x24 fixed16x32 fixed16x40 fixed16x48 fixed16x56 fixed16x64 fixed16x72 fixed16x80 fixed16x88 fixed16x96 fixed16x104 fixed16x112 fixed16x120 fixed16x128 fixed16x136 fixed16x144 fixed16x152 fixed16x160 fixed16x168 fixed16x178 fixed16x184 fixed16x192 fixed16x200 fixed16x208 fixed16x216 fixed16x224 fixed16x232 fixed16x240 +syn keyword solBuiltinType fixed24x8 fixed24x16 fixed24x24 fixed24x32 fixed24x40 fixed24x48 fixed24x56 fixed24x64 fixed24x72 fixed24x80 fixed24x88 fixed24x96 fixed24x104 fixed24x112 fixed24x120 fixed24x128 fixed24x136 fixed24x144 fixed24x152 fixed24x160 fixed24x168 fixed24x178 fixed24x184 fixed24x192 fixed24x200 fixed24x208 fixed24x216 fixed24x224 fixed24x232 +syn keyword solBuiltinType fixed32x8 fixed32x16 fixed32x24 fixed32x32 fixed32x40 fixed32x48 fixed32x56 fixed32x64 fixed32x72 fixed32x80 fixed32x88 fixed32x96 fixed32x104 fixed32x112 fixed32x120 fixed32x128 fixed32x136 fixed32x144 fixed32x152 fixed32x160 fixed32x168 fixed32x178 fixed32x184 fixed32x192 fixed32x200 fixed32x208 fixed32x216 fixed32x224 +syn keyword solBuiltinType fixed40x8 fixed40x16 fixed40x24 fixed40x32 fixed40x40 fixed40x48 fixed40x56 fixed40x64 fixed40x72 fixed40x80 fixed40x88 fixed40x96 fixed40x104 fixed40x112 fixed40x120 fixed40x128 fixed40x136 fixed40x144 fixed40x152 fixed40x160 fixed40x168 fixed40x178 fixed40x184 fixed40x192 fixed40x200 fixed40x208 fixed40x216 +syn keyword solBuiltinType fixed48x8 fixed48x16 fixed48x24 fixed48x32 fixed48x40 fixed48x48 fixed48x56 fixed48x64 fixed48x72 fixed48x80 fixed48x88 fixed48x96 fixed48x104 fixed48x112 fixed48x120 fixed48x128 fixed48x136 fixed48x144 fixed48x152 fixed48x160 fixed48x168 fixed48x178 fixed48x184 fixed48x192 fixed48x200 fixed48x208 +syn keyword solBuiltinType fixed56x8 fixed56x16 fixed56x24 fixed56x32 fixed56x40 fixed56x48 fixed56x56 fixed56x64 fixed56x72 fixed56x80 fixed56x88 fixed56x96 fixed56x104 fixed56x112 fixed56x120 fixed56x128 fixed56x136 fixed56x144 fixed56x152 fixed56x160 fixed56x168 fixed56x178 fixed56x184 fixed56x192 fixed56x200 +syn keyword solBuiltinType fixed64x8 fixed64x16 fixed64x24 fixed64x32 fixed64x40 fixed64x48 fixed64x56 fixed64x64 fixed64x72 fixed64x80 fixed64x88 fixed64x96 fixed64x104 fixed64x112 fixed64x120 fixed64x128 fixed64x136 fixed64x144 fixed64x152 fixed64x160 fixed64x168 fixed64x178 fixed64x184 fixed64x192 +syn keyword solBuiltinType fixed72x8 fixed72x16 fixed72x24 fixed72x32 fixed72x40 fixed72x48 fixed72x56 fixed72x64 fixed72x72 fixed72x80 fixed72x88 fixed72x96 fixed72x104 fixed72x112 fixed72x120 fixed72x128 fixed72x136 fixed72x144 fixed72x152 fixed72x160 fixed72x168 fixed72x178 fixed72x184 +syn keyword solBuiltinType fixed80x8 fixed80x16 fixed80x24 fixed80x32 fixed80x40 fixed80x48 fixed80x56 fixed80x64 fixed80x72 fixed80x80 fixed80x88 fixed80x96 fixed80x104 fixed80x112 fixed80x120 fixed80x128 fixed80x136 fixed80x144 fixed80x152 fixed80x160 fixed80x168 fixed80x178 +syn keyword solBuiltinType fixed88x8 fixed88x16 fixed88x24 fixed88x32 fixed88x40 fixed88x48 fixed88x56 fixed88x64 fixed88x72 fixed88x80 fixed88x88 fixed88x96 fixed88x104 fixed88x112 fixed88x120 fixed88x128 fixed88x136 fixed88x144 fixed88x152 fixed88x160 fixed88x168 +syn keyword solBuiltinType fixed96x8 fixed96x16 fixed96x24 fixed96x32 fixed96x40 fixed96x48 fixed96x56 fixed96x64 fixed96x72 fixed96x80 fixed96x88 fixed96x96 fixed96x104 fixed96x112 fixed96x120 fixed96x128 fixed96x136 fixed96x144 fixed96x152 fixed96x160 +syn keyword solBuiltinType fixed104x8 fixed104x16 fixed104x24 fixed104x32 fixed104x40 fixed104x48 fixed104x56 fixed104x64 fixed104x72 fixed104x80 fixed104x88 fixed104x96 fixed104x104 fixed104x112 fixed104x120 fixed104x128 fixed104x136 fixed104x144 fixed104x152 +syn keyword solBuiltinType fixed112x8 fixed112x16 fixed112x24 fixed112x32 fixed112x40 fixed112x48 fixed112x56 fixed112x64 fixed112x72 fixed112x80 fixed112x88 fixed112x96 fixed112x104 fixed112x112 fixed112x120 fixed112x128 fixed112x136 fixed112x144 +syn keyword solBuiltinType fixed120x8 fixed120x16 fixed120x24 fixed120x32 fixed120x40 fixed120x48 fixed120x56 fixed120x64 fixed120x72 fixed120x80 fixed120x88 fixed120x96 fixed120x104 fixed120x112 fixed120x120 fixed120x128 fixed120x136 +syn keyword solBuiltinType fixed128x8 fixed128x16 fixed128x24 fixed128x32 fixed128x40 fixed128x48 fixed128x56 fixed128x64 fixed128x72 fixed128x80 fixed128x88 fixed128x96 fixed128x104 fixed128x112 fixed128x120 fixed128x128 +syn keyword solBuiltinType fixed136x8 fixed136x16 fixed136x24 fixed136x32 fixed136x40 fixed136x48 fixed136x56 fixed136x64 fixed136x72 fixed136x80 fixed136x88 fixed136x96 fixed136x104 fixed136x112 fixed136x120 +syn keyword solBuiltinType fixed144x8 fixed144x16 fixed144x24 fixed144x32 fixed144x40 fixed144x48 fixed144x56 fixed144x64 fixed144x72 fixed144x80 fixed144x88 fixed144x96 fixed144x104 fixed144x112 +syn keyword solBuiltinType fixed152x8 fixed152x16 fixed152x24 fixed152x32 fixed152x40 fixed152x48 fixed152x56 fixed152x64 fixed152x72 fixed152x80 fixed152x88 fixed152x96 fixed152x104 +syn keyword solBuiltinType fixed160x8 fixed160x16 fixed160x24 fixed160x32 fixed160x40 fixed160x48 fixed160x56 fixed160x64 fixed160x72 fixed160x80 fixed160x88 fixed160x96 +syn keyword solBuiltinType fixed168x8 fixed168x16 fixed168x24 fixed168x32 fixed168x40 fixed168x48 fixed168x56 fixed168x64 fixed168x72 fixed168x80 fixed168x88 +syn keyword solBuiltinType fixed176x8 fixed176x16 fixed176x24 fixed176x32 fixed176x40 fixed176x48 fixed176x56 fixed176x64 fixed176x72 fixed176x80 +syn keyword solBuiltinType fixed184x8 fixed184x16 fixed184x24 fixed184x32 fixed184x40 fixed184x48 fixed184x56 fixed184x64 fixed184x72 +syn keyword solBuiltinType fixed192x8 fixed192x16 fixed192x24 fixed192x32 fixed192x40 fixed192x48 fixed192x56 fixed192x64 +syn keyword solBuiltinType fixed200x8 fixed200x16 fixed200x24 fixed200x32 fixed200x40 fixed200x48 fixed200x56 +syn keyword solBuiltinType fixed208x8 fixed208x16 fixed208x24 fixed208x32 fixed208x40 fixed208x48 +syn keyword solBuiltinType fixed216x8 fixed216x16 fixed216x24 fixed216x32 fixed216x40 +syn keyword solBuiltinType fixed224x8 fixed224x16 fixed224x24 fixed224x32 +syn keyword solBuiltinType fixed232x8 fixed232x16 fixed232x24 +syn keyword solBuiltinType fixed240x8 fixed240x16 +syn keyword solBuiltinType fixed248x8 +syn keyword solBuiltinType ufixed +syn keyword solBuiltinType ufixed0x8 ufixed0x16 ufixed0x24 ufixed0x32 ufixed0x40 ufixed0x48 ufixed0x56 ufixed0x64 ufixed0x72 ufixed0x80 ufixed0x88 ufixed0x96 ufixed0x104 ufixed0x112 ufixed0x120 ufixed0x128 ufixed0x136 ufixed0x144 ufixed0x152 ufixed0x160 ufixed0x168 ufixed0x178 ufixed0x184 ufixed0x192 ufixed0x200 ufixed0x208 ufixed0x216 ufixed0x224 ufixed0x232 ufixed0x240 ufixed0x248 ufixed0x256 +syn keyword solBuiltinType ufixed8x8 ufixed8x16 ufixed8x24 ufixed8x32 ufixed8x40 ufixed8x48 ufixed8x56 ufixed8x64 ufixed8x72 ufixed8x80 ufixed8x88 ufixed8x96 ufixed8x104 ufixed8x112 ufixed8x120 ufixed8x128 ufixed8x136 ufixed8x144 ufixed8x152 ufixed8x160 ufixed8x168 ufixed8x178 ufixed8x184 ufixed8x192 ufixed8x200 ufixed8x208 ufixed8x216 ufixed8x224 ufixed8x232 ufixed8x240 ufixed8x248 +syn keyword solBuiltinType ufixed16x8 ufixed16x16 ufixed16x24 ufixed16x32 ufixed16x40 ufixed16x48 ufixed16x56 ufixed16x64 ufixed16x72 ufixed16x80 ufixed16x88 ufixed16x96 ufixed16x104 ufixed16x112 ufixed16x120 ufixed16x128 ufixed16x136 ufixed16x144 ufixed16x152 ufixed16x160 ufixed16x168 ufixed16x178 ufixed16x184 ufixed16x192 ufixed16x200 ufixed16x208 ufixed16x216 ufixed16x224 ufixed16x232 ufixed16x240 +syn keyword solBuiltinType ufixed24x8 ufixed24x16 ufixed24x24 ufixed24x32 ufixed24x40 ufixed24x48 ufixed24x56 ufixed24x64 ufixed24x72 ufixed24x80 ufixed24x88 ufixed24x96 ufixed24x104 ufixed24x112 ufixed24x120 ufixed24x128 ufixed24x136 ufixed24x144 ufixed24x152 ufixed24x160 ufixed24x168 ufixed24x178 ufixed24x184 ufixed24x192 ufixed24x200 ufixed24x208 ufixed24x216 ufixed24x224 ufixed24x232 +syn keyword solBuiltinType ufixed32x8 ufixed32x16 ufixed32x24 ufixed32x32 ufixed32x40 ufixed32x48 ufixed32x56 ufixed32x64 ufixed32x72 ufixed32x80 ufixed32x88 ufixed32x96 ufixed32x104 ufixed32x112 ufixed32x120 ufixed32x128 ufixed32x136 ufixed32x144 ufixed32x152 ufixed32x160 ufixed32x168 ufixed32x178 ufixed32x184 ufixed32x192 ufixed32x200 ufixed32x208 ufixed32x216 ufixed32x224 +syn keyword solBuiltinType ufixed40x8 ufixed40x16 ufixed40x24 ufixed40x32 ufixed40x40 ufixed40x48 ufixed40x56 ufixed40x64 ufixed40x72 ufixed40x80 ufixed40x88 ufixed40x96 ufixed40x104 ufixed40x112 ufixed40x120 ufixed40x128 ufixed40x136 ufixed40x144 ufixed40x152 ufixed40x160 ufixed40x168 ufixed40x178 ufixed40x184 ufixed40x192 ufixed40x200 ufixed40x208 ufixed40x216 +syn keyword solBuiltinType ufixed48x8 ufixed48x16 ufixed48x24 ufixed48x32 ufixed48x40 ufixed48x48 ufixed48x56 ufixed48x64 ufixed48x72 ufixed48x80 ufixed48x88 ufixed48x96 ufixed48x104 ufixed48x112 ufixed48x120 ufixed48x128 ufixed48x136 ufixed48x144 ufixed48x152 ufixed48x160 ufixed48x168 ufixed48x178 ufixed48x184 ufixed48x192 ufixed48x200 ufixed48x208 +syn keyword solBuiltinType ufixed56x8 ufixed56x16 ufixed56x24 ufixed56x32 ufixed56x40 ufixed56x48 ufixed56x56 ufixed56x64 ufixed56x72 ufixed56x80 ufixed56x88 ufixed56x96 ufixed56x104 ufixed56x112 ufixed56x120 ufixed56x128 ufixed56x136 ufixed56x144 ufixed56x152 ufixed56x160 ufixed56x168 ufixed56x178 ufixed56x184 ufixed56x192 ufixed56x200 +syn keyword solBuiltinType ufixed64x8 ufixed64x16 ufixed64x24 ufixed64x32 ufixed64x40 ufixed64x48 ufixed64x56 ufixed64x64 ufixed64x72 ufixed64x80 ufixed64x88 ufixed64x96 ufixed64x104 ufixed64x112 ufixed64x120 ufixed64x128 ufixed64x136 ufixed64x144 ufixed64x152 ufixed64x160 ufixed64x168 ufixed64x178 ufixed64x184 ufixed64x192 +syn keyword solBuiltinType ufixed72x8 ufixed72x16 ufixed72x24 ufixed72x32 ufixed72x40 ufixed72x48 ufixed72x56 ufixed72x64 ufixed72x72 ufixed72x80 ufixed72x88 ufixed72x96 ufixed72x104 ufixed72x112 ufixed72x120 ufixed72x128 ufixed72x136 ufixed72x144 ufixed72x152 ufixed72x160 ufixed72x168 ufixed72x178 ufixed72x184 +syn keyword solBuiltinType ufixed80x8 ufixed80x16 ufixed80x24 ufixed80x32 ufixed80x40 ufixed80x48 ufixed80x56 ufixed80x64 ufixed80x72 ufixed80x80 ufixed80x88 ufixed80x96 ufixed80x104 ufixed80x112 ufixed80x120 ufixed80x128 ufixed80x136 ufixed80x144 ufixed80x152 ufixed80x160 ufixed80x168 ufixed80x178 +syn keyword solBuiltinType ufixed88x8 ufixed88x16 ufixed88x24 ufixed88x32 ufixed88x40 ufixed88x48 ufixed88x56 ufixed88x64 ufixed88x72 ufixed88x80 ufixed88x88 ufixed88x96 ufixed88x104 ufixed88x112 ufixed88x120 ufixed88x128 ufixed88x136 ufixed88x144 ufixed88x152 ufixed88x160 ufixed88x168 +syn keyword solBuiltinType ufixed96x8 ufixed96x16 ufixed96x24 ufixed96x32 ufixed96x40 ufixed96x48 ufixed96x56 ufixed96x64 ufixed96x72 ufixed96x80 ufixed96x88 ufixed96x96 ufixed96x104 ufixed96x112 ufixed96x120 ufixed96x128 ufixed96x136 ufixed96x144 ufixed96x152 ufixed96x160 +syn keyword solBuiltinType ufixed104x8 ufixed104x16 ufixed104x24 ufixed104x32 ufixed104x40 ufixed104x48 ufixed104x56 ufixed104x64 ufixed104x72 ufixed104x80 ufixed104x88 ufixed104x96 ufixed104x104 ufixed104x112 ufixed104x120 ufixed104x128 ufixed104x136 ufixed104x144 ufixed104x152 +syn keyword solBuiltinType ufixed112x8 ufixed112x16 ufixed112x24 ufixed112x32 ufixed112x40 ufixed112x48 ufixed112x56 ufixed112x64 ufixed112x72 ufixed112x80 ufixed112x88 ufixed112x96 ufixed112x104 ufixed112x112 ufixed112x120 ufixed112x128 ufixed112x136 ufixed112x144 +syn keyword solBuiltinType ufixed120x8 ufixed120x16 ufixed120x24 ufixed120x32 ufixed120x40 ufixed120x48 ufixed120x56 ufixed120x64 ufixed120x72 ufixed120x80 ufixed120x88 ufixed120x96 ufixed120x104 ufixed120x112 ufixed120x120 ufixed120x128 ufixed120x136 +syn keyword solBuiltinType ufixed128x8 ufixed128x16 ufixed128x24 ufixed128x32 ufixed128x40 ufixed128x48 ufixed128x56 ufixed128x64 ufixed128x72 ufixed128x80 ufixed128x88 ufixed128x96 ufixed128x104 ufixed128x112 ufixed128x120 ufixed128x128 +syn keyword solBuiltinType ufixed136x8 ufixed136x16 ufixed136x24 ufixed136x32 ufixed136x40 ufixed136x48 ufixed136x56 ufixed136x64 ufixed136x72 ufixed136x80 ufixed136x88 ufixed136x96 ufixed136x104 ufixed136x112 ufixed136x120 +syn keyword solBuiltinType ufixed144x8 ufixed144x16 ufixed144x24 ufixed144x32 ufixed144x40 ufixed144x48 ufixed144x56 ufixed144x64 ufixed144x72 ufixed144x80 ufixed144x88 ufixed144x96 ufixed144x104 ufixed144x112 +syn keyword solBuiltinType ufixed152x8 ufixed152x16 ufixed152x24 ufixed152x32 ufixed152x40 ufixed152x48 ufixed152x56 ufixed152x64 ufixed152x72 ufixed152x80 ufixed152x88 ufixed152x96 ufixed152x104 +syn keyword solBuiltinType ufixed160x8 ufixed160x16 ufixed160x24 ufixed160x32 ufixed160x40 ufixed160x48 ufixed160x56 ufixed160x64 ufixed160x72 ufixed160x80 ufixed160x88 ufixed160x96 +syn keyword solBuiltinType ufixed168x8 ufixed168x16 ufixed168x24 ufixed168x32 ufixed168x40 ufixed168x48 ufixed168x56 ufixed168x64 ufixed168x72 ufixed168x80 ufixed168x88 +syn keyword solBuiltinType ufixed176x8 ufixed176x16 ufixed176x24 ufixed176x32 ufixed176x40 ufixed176x48 ufixed176x56 ufixed176x64 ufixed176x72 ufixed176x80 +syn keyword solBuiltinType ufixed184x8 ufixed184x16 ufixed184x24 ufixed184x32 ufixed184x40 ufixed184x48 ufixed184x56 ufixed184x64 ufixed184x72 +syn keyword solBuiltinType ufixed192x8 ufixed192x16 ufixed192x24 ufixed192x32 ufixed192x40 ufixed192x48 ufixed192x56 ufixed192x64 +syn keyword solBuiltinType ufixed200x8 ufixed200x16 ufixed200x24 ufixed200x32 ufixed200x40 ufixed200x48 ufixed200x56 +syn keyword solBuiltinType ufixed208x8 ufixed208x16 ufixed208x24 ufixed208x32 ufixed208x40 ufixed208x48 +syn keyword solBuiltinType ufixed216x8 ufixed216x16 ufixed216x24 ufixed216x32 ufixed216x40 +syn keyword solBuiltinType ufixed224x8 ufixed224x16 ufixed224x24 ufixed224x32 +syn keyword solBuiltinType ufixed232x8 ufixed232x16 ufixed232x24 +syn keyword solBuiltinType ufixed240x8 ufixed240x16 +syn keyword solBuiltinType ufixed248x8 +syn keyword solBuiltinType string string1 string2 string3 string4 string5 string6 string7 string8 string9 string10 string11 string12 string13 string14 string15 string16 string17 string18 string19 string20 string21 string22 string23 string24 string25 string26 string27 string28 string29 string30 string31 string32 +syn keyword solBuiltinType byte bytes bytes1 bytes2 bytes3 bytes4 bytes5 bytes6 bytes7 bytes8 bytes9 bytes10 bytes11 bytes12 bytes13 bytes14 bytes15 bytes16 bytes17 bytes18 bytes19 bytes20 bytes21 bytes22 bytes23 bytes24 bytes25 bytes26 bytes27 bytes28 bytes29 bytes30 bytes31 bytes32 + +hi def link solKeyword Keyword +hi def link solConstant Constant +hi def link solBuiltinType Type +hi def link solBuiltinFunction Keyword + +syn match solOperator /\(!\||\|&\|+\|-\|<\|>\|=\|%\|\/\|*\|\~\|\^\)/ +syn match solNumber /\<-\=\d\+L\=\>\|\<0[xX]\x\+\>/ +syn match solFloat /\<-\=\%(\d\+\.\d\+\|\d\+\.\|\.\d\+\)\%([eE][+-]\=\d\+\)\=\>/ + +syn region solString start=+"+ skip=+\\\\\|\\$"\|\\"+ end=+"+ +syn region solString start=+'+ skip=+\\\\\|\\$'\|\\'+ end=+'+ + +hi def link solOperator Operator +hi def link solNumber Number +hi def link solFloat Float +hi def link solString String + +" Function +syn match solFunction /\/ nextgroup=solFuncName,solFuncArgs skipwhite +syn match solFuncName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solFuncArgs skipwhite + +syn region solFuncArgs contained matchgroup=solFuncParens start='(' end=')' contains=solFuncArgCommas,solBuiltinType nextgroup=solModifierName,solFuncReturns,solFuncBody keepend skipwhite skipempty +syn match solModifierName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solModifierArgs,solModifierName skipwhite +syn region solModifierArgs contained matchgroup=solFuncParens start='(' end=')' contains=solFuncArgCommas nextgroup=solModifierName,solFuncReturns,solFuncBody skipwhite +syn region solFuncReturns contained matchgroup=solFuncParens nextgroup=solFuncBody start='(' end=')' contains=solFuncArgCommas,solBuiltinType skipwhite + +syn match solFuncArgCommas contained ',' +syn region solFuncBody start="{" end="}" fold transparent + +hi def link solFunction Type +hi def link solFuncName Function +hi def link solModifierName Function + +" Yul blocks +syn match yul /\/ skipwhite skipempty nextgroup=yulBody +syn region yulBody contained start='{' end='}' fold contains=yulAssemblyOp,solNumber,yulVarDeclaration,solLineComment,solComment skipwhite skipempty +syn keyword yulAssemblyOp contained stop add sub mul div sdiv mod smod exp not lt gt slt sgt eq iszero and or xor byte shl shr sar addmod mulmod signextend keccak256 pc pop mload mstore mstore8 sload sstore msize gas address balance selfbalance caller callvalue calldataload calldatasize calldatacopy codesize codecopy extcodesize extcodecopy returndatasize returndatacopy extcodehash create create2 call callcode delegatecall staticcall return revert selfdestruct invalid log0 log1 log2 log3 log4 chainid basefee origin gasprice blockhash coinbase timestamp number difficulty gaslimit +syn keyword yulVarDeclaration contained let + +hi def link yul Keyword +hi def link yulVarDeclaration Keyword +hi def link yulAssemblyOp Keyword + +" Contract +syn match solContract /\<\%(contract\|library\|interface\)\>/ nextgroup=solContractName skipwhite +syn match solContractName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solContractParent skipwhite +syn region solContractParent contained start='is' end='{' contains=solContractName,solContractNoise,solContractCommas skipwhite skipempty +syn match solContractNoise contained 'is' containedin=solContractParent +syn match solContractCommas contained ',' + +hi def link solContract Type +hi def link solContractName Function + +" Event +syn match solEvent /\/ nextgroup=solEventName,solEventArgs skipwhite +syn match solEventName contained /\<[a-zA-Z_$][0-9a-zA-Z_$]*/ nextgroup=solEventArgs skipwhite +syn region solEventArgs contained matchgroup=solFuncParens start='(' end=')' contains=solEventArgCommas,solBuiltinType,solEventArgSpecial skipwhite skipempty +syn match solEventArgCommas contained ',' +syn match solEventArgSpecial contained 'indexed' + +hi def link solEvent Type +hi def link solEventName Function +hi def link solEventArgSpecial Label + +" Comment +syn keyword solCommentTodo TODO FIXME XXX TBD contained +syn match solNatSpec contained /@title\|@author\|@notice\|@dev\|@param\|@inheritdoc\|@return/ +syn region solLineComment start=+\/\/+ end=+$+ contains=solCommentTodo,solNatSpec,@Spell +syn region solLineComment start=+^\s*\/\/+ skip=+\n\s*\/\/+ end=+$+ contains=solCommentTodo,solNatSpec,@Spell fold +syn region solComment start="/\*" end="\*/" contains=solCommentTodo,solNatSpec,@Spell fold + +hi def link solCommentTodo Todo +hi def link solNatSpec Label +hi def link solLineComment Comment +hi def link solComment Comment + +let b:current_syntax = "solidity" diff --git a/runtime/syntax/vim.vim b/runtime/syntax/vim.vim index d5e138dbc3..cbd793fd3c 100644 --- a/runtime/syntax/vim.vim +++ b/runtime/syntax/vim.vim @@ -368,7 +368,7 @@ syn match vimSetMod contained "&vim\=\|[!&?<]\|all&" " Let: {{{2 " === syn keyword vimLet let unl[et] skipwhite nextgroup=vimVar,vimFuncVar,vimLetHereDoc -VimFoldh syn region vimLetHereDoc matchgroup=vimLetHereDocStart start='=<<\s\+\%(trim\|eval\>\)\=\s*\z(\L\S*\)' matchgroup=vimLetHereDocStop end='^\s*\z1\s*$' +VimFoldh syn region vimLetHereDoc matchgroup=vimLetHereDocStart start='=<<\s\+\%(trim\s\+\)\=\%(eval\s\+\)\=\z(\L\S*\)' matchgroup=vimLetHereDocStop end='^\s*\z1\s*$' " Abbreviations: {{{2 " ============= -- cgit From bafeb32b95c61b91220b3090e4293478a74ce31d Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Wed, 28 Sep 2022 21:55:22 +0800 Subject: fix(spell): correct spell move behavior without "noplainbuffer" (#20386) --- src/nvim/spell.c | 12 ++--- test/functional/ui/spell_spec.lua | 94 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 6 deletions(-) diff --git a/src/nvim/spell.c b/src/nvim/spell.c index 53fa920358..7d2b58ff46 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -1344,14 +1344,14 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att : p - buf) > wp->w_cursor.col)) { col = (colnr_T)(p - buf); - bool can_spell = (wp->w_s->b_p_spo_flags & SPO_NPBUFFER) == 0; + bool can_spell = decor_spell_nav_col(wp, lnum, &decor_lnum, col, &decor_error); if (!can_spell) { - can_spell = decor_spell_nav_col(wp, lnum, &decor_lnum, col, &decor_error); - } - - if (!can_spell && has_syntax) { - (void)syn_get_id(wp, lnum, col, false, &can_spell, false); + if (has_syntax) { + (void)syn_get_id(wp, lnum, col, false, &can_spell, false); + } else { + can_spell = (wp->w_s->b_p_spo_flags & SPO_NPBUFFER) == 0; + } } if (!can_spell) { diff --git a/test/functional/ui/spell_spec.lua b/test/functional/ui/spell_spec.lua index de77100cc0..1aa73e7b13 100644 --- a/test/functional/ui/spell_spec.lua +++ b/test/functional/ui/spell_spec.lua @@ -19,6 +19,10 @@ describe("'spell'", function() [0] = {bold=true, foreground=Screen.colors.Blue}, [1] = {special = Screen.colors.Red, undercurl = true}, [2] = {special = Screen.colors.Blue1, undercurl = true}, + [3] = {foreground = tonumber('0x6a0dad')}, + [4] = {foreground = Screen.colors.Magenta}, + [5] = {bold = true, foreground = Screen.colors.SeaGreen}, + [6] = {foreground = Screen.colors.Red}, }) end) @@ -68,4 +72,94 @@ describe("'spell'", function() | ]]) end) + + it('"noplainbuffer" and syntax #20385', function() + command('set filetype=c') + command('syntax on') + command('set spell') + insert([[ + #include + bool func(void);]]) + screen:expect([[ + {3:#include }{4:} | + {5:bool} func({5:void})^; | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + | + ]]) + feed('[s') + screen:expect([[ + {3:#include }{4:} | + {5:bool} func({5:void})^; | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {6:search hit TOP, continuing at BOTTOM} | + ]]) + -- "noplainbuffer" shouldn't change spellchecking behavior with syntax enabled + command('set spelloptions+=noplainbuffer') + screen:expect_unchanged() + feed(']s') + screen:expect([[ + {3:#include }{4:} | + {5:bool} func({5:void})^; | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {6:search hit BOTTOM, continuing at TOP} | + ]]) + -- no spellchecking with "noplainbuffer" and syntax disabled + command('syntax off') + screen:expect([[ + #include | + bool func(void)^; | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {6:search hit BOTTOM, continuing at TOP} | + ]]) + feed('[s') + screen:expect([[ + #include | + bool func(void)^; | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {6:search hit TOP, continuing at BOTTOM} | + ]]) + -- everything is spellchecked without "noplainbuffer" with syntax disabled + command('set spelloptions&') + screen:expect([[ + #include <{1:stdbool}.h> | + {1:bool} {1:func}(void)^; | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {6:search hit TOP, continuing at BOTTOM} | + ]]) + feed(']s') + screen:expect([[ + #include <{1:^stdbool}.h> | + {1:bool} {1:func}(void); | + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {0:~ }| + {6:search hit BOTTOM, continuing at TOP} | + ]]) + end) end) -- cgit From 47b821eccf7bd08f429bb16e9d4ea309d6994896 Mon Sep 17 00:00:00 2001 From: bfredl Date: Wed, 28 Sep 2022 16:16:02 +0200 Subject: docs: mark cmdheight=0 and vim.attach_ui as experimental These will require further work for user experience out of the box during the 0.9 cycle. --- runtime/doc/lua.txt | 6 ++++++ runtime/doc/options.txt | 10 +++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 0c6eb6af78..3026476ab9 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -978,6 +978,12 @@ vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* {callback} receives event name plus additional parameters. See |ui-popupmenu| and the sections below for event format for respective events. + WARNING: This api is considered experimental. Usability will vary for + different screen elements. In particular `ext_messages` behavior is subject + to further changes and usability improvements. This is expected to be + used to handle messages when setting 'cmdheight' to zero (which is + likewise experimental). + Example (stub for a |ui-popupmenu| implementation): > ns = vim.api.nvim_create_namespace('my_fancy_pum') diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index c1a0836f5b..0654265dbe 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -1338,9 +1338,13 @@ A jump table for the options with a short description can be found at |Q_op|. When 'cmdheight' is zero, there is no command-line unless it is being used. The command-line will cover the last line of the screen when - shown. Some informative messages will not be displayed, any other - messages will cause the |hit-enter| prompt. Expect some other - unexpected behavior too. + shown. + + WARNING: `cmdheight=0` is considered experimental. Except some + unwanted behaviour. Some 'shortmess' flags and similar + mechanism might fail to take effect, causing unwanted hit-enter + prompts. Some informative messages, both from Nvim itself and + plugins, will not be displayed. *'cmdwinheight'* *'cwh'* 'cmdwinheight' 'cwh' number (default 7) -- cgit From a5effcedd2888298fda62947410316c080e9a4dc Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Wed, 28 Sep 2022 16:29:35 +0200 Subject: build(deps): bump help parser and queries (#20388) --- cmake.deps/CMakeLists.txt | 4 ++-- runtime/queries/help/highlights.scm | 18 ++++++++++-------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index 897d056860..da95fe31b3 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -210,8 +210,8 @@ set(TREESITTER_LUA_SHA256 564594fe0ffd2f2fb3578a15019b723e1bc94ac82cb6a0103a6b3b set(TREESITTER_VIM_URL https://github.com/vigoux/tree-sitter-viml/archive/v0.2.0.tar.gz) set(TREESITTER_VIM_SHA256 608dcc31a7948cb66ae7f45494620e2e9face1af75598205541f80d782ec4501) -set(TREESITTER_HELP_URL https://github.com/vigoux/tree-sitter-vimdoc/archive/a2c5c01f797eef67634941630442eea66eb7e1b6.tar.gz) -set(TREESITTER_HELP_SHA256 b999c145da02652c235d497cb32e72660175d3b9fa129a7a6ba164b60414e73d) +set(TREESITTER_HELP_URL https://github.com/neovim/tree-sitter-vimdoc/archive/v1.0.tar.gz) +set(TREESITTER_HELP_SHA256 42821a3aa35e7fefcedbe1090f76f997dbdb2de7cbe76ba1507c1426d9a6af19) set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) diff --git a/runtime/queries/help/highlights.scm b/runtime/queries/help/highlights.scm index 41c78a7f1c..6be4e49c81 100644 --- a/runtime/queries/help/highlights.scm +++ b/runtime/queries/help/highlights.scm @@ -1,14 +1,16 @@ -(headline) @text.title +(h1) @text.title +(h2) @text.title +(h3) @text.title (column_heading) @text.title (tag "*" @conceal (#set! conceal "") - name: (_) @label) -(option - name: (_) @text.literal) -(hotlink + text: (_) @label) +(taglink "|" @conceal (#set! conceal "") - destination: (_) @text.reference) -(backtick + text: (_) @text.reference) +(optionlink + text: (_) @text.literal) +(codespan "`" @conceal (#set! conceal "") - content: (_) @string) + text: (_) @string) (argument) @parameter -- cgit From cd96fe06e188bcd6e64f78cb078a307fb45f31f0 Mon Sep 17 00:00:00 2001 From: Christian Clason Date: Wed, 28 Sep 2022 16:39:42 +0200 Subject: build(deps): bump treesitter-vimdoc to v1.0.0 --- cmake.deps/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index da95fe31b3..30587b39e9 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -210,8 +210,8 @@ set(TREESITTER_LUA_SHA256 564594fe0ffd2f2fb3578a15019b723e1bc94ac82cb6a0103a6b3b set(TREESITTER_VIM_URL https://github.com/vigoux/tree-sitter-viml/archive/v0.2.0.tar.gz) set(TREESITTER_VIM_SHA256 608dcc31a7948cb66ae7f45494620e2e9face1af75598205541f80d782ec4501) -set(TREESITTER_HELP_URL https://github.com/neovim/tree-sitter-vimdoc/archive/v1.0.tar.gz) -set(TREESITTER_HELP_SHA256 42821a3aa35e7fefcedbe1090f76f997dbdb2de7cbe76ba1507c1426d9a6af19) +set(TREESITTER_HELP_URL https://github.com/neovim/tree-sitter-vimdoc/archive/v1.0.0.tar.gz) +set(TREESITTER_HELP_SHA256 bb026d479b0a8ac4d05b6c0cc11f698f2476828e7df9ff34c11dc5178a361e5a) set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) -- cgit From d9ed8d1110847e4cd4c49c23eba1f86fff8b29bf Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Wed, 28 Sep 2022 16:19:33 +0200 Subject: feat(treesitter): update :help parser and queries --- cmake.deps/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt index 30587b39e9..941db5fb0a 100644 --- a/cmake.deps/CMakeLists.txt +++ b/cmake.deps/CMakeLists.txt @@ -210,8 +210,8 @@ set(TREESITTER_LUA_SHA256 564594fe0ffd2f2fb3578a15019b723e1bc94ac82cb6a0103a6b3b set(TREESITTER_VIM_URL https://github.com/vigoux/tree-sitter-viml/archive/v0.2.0.tar.gz) set(TREESITTER_VIM_SHA256 608dcc31a7948cb66ae7f45494620e2e9face1af75598205541f80d782ec4501) -set(TREESITTER_HELP_URL https://github.com/neovim/tree-sitter-vimdoc/archive/v1.0.0.tar.gz) -set(TREESITTER_HELP_SHA256 bb026d479b0a8ac4d05b6c0cc11f698f2476828e7df9ff34c11dc5178a361e5a) +set(TREESITTER_HELP_URL https://github.com/neovim/tree-sitter-vimdoc/archive/2ba61cf9e7236d0ae3ce5c526bbd689ace3ff3bd.tar.gz) +set(TREESITTER_HELP_SHA256 ce89e486c2cc52c0d82edf0600d0f67af9ae9e4b438673224633d0c9f47c62be) set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz) set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e) -- cgit From 7b4c49888a97c21f346b8337330fbc8e196b9cf8 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Fri, 23 Sep 2022 14:26:59 +0200 Subject: feat(gen_help_html.lua): put commit-id in footer --- scripts/gen_help_html.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/gen_help_html.lua b/scripts/gen_help_html.lua index d79ece53f3..6e297814b8 100644 --- a/scripts/gen_help_html.lua +++ b/scripts/gen_help_html.lua @@ -16,7 +16,7 @@ -- -- NOTES: -- * gen() and validate() are the primary entrypoints. validate() only exists because gen() is too --- slow (~1 min) to run in per-commit CI. +-- slow (~1 min) to run in per-commit CI. -- * visit_node() is the core function used by gen() to traverse the document tree and produce HTML. -- * visit_validate() is the core function used by validate(). -- * Files in `new_layout` will be generated with a "flow" layout instead of preformatted/fixed-width layout. @@ -50,7 +50,6 @@ local tagmap = nil local helpfiles = nil local invalid_tags = {} -local commit = '?' local api = vim.api local M = {} @@ -477,7 +476,7 @@ end -- @param old boolean Preformat paragraphs (for old :help files which are full of arbitrary whitespace) -- -- @returns html, stats -local function gen_one(fname, to_fname, old) +local function gen_one(fname, to_fname, old, commit) local stats = { noise_lines = {}, parse_errors = {}, @@ -604,7 +603,7 @@ local function gen_one(fname, to_fname, old)
- Generated on %s from {%s} + Generated at %s from %s
parse_errors: %d %s | noise_lines: %d @@ -612,7 +611,7 @@ local function gen_one(fname, to_fname, old)
]]):format( - os.date('%Y-%m-%d %H:%M:%S'), commit, #stats.parse_errors, bug_link, + os.date('%Y-%m-%d %H:%M'), commit, commit:sub(1, 7), #stats.parse_errors, bug_link, html_esc(table.concat(stats.noise_lines, '\n')), #stats.noise_lines) html = ('%s%s%s
\n%s\n\n'):format( @@ -763,11 +762,12 @@ end --- @param include table|nil Process only these filenames. Example: {'api.txt', 'autocmd.txt', 'channel.txt'} --- --- @returns info dict -function M.gen(help_dir, to_dir, include) +function M.gen(help_dir, to_dir, include, commit) vim.validate{ help_dir={help_dir, function(d) return vim.fn.isdirectory(d) == 1 end, 'valid directory'}, to_dir={to_dir, 's'}, include={include, 't', true}, + commit={commit, 's', true}, } local err_count = 0 @@ -781,7 +781,7 @@ function M.gen(help_dir, to_dir, include) for _, f in ipairs(helpfiles) do local helpfile = vim.fs.basename(f) local to_fname = ('%s/%s'):format(to_dir, get_helppage(helpfile)) - local html, stats = gen_one(f, to_fname, not new_layout[helpfile]) + local html, stats = gen_one(f, to_fname, not new_layout[helpfile], commit or '?') tofile(to_fname, html) print(('generated (%-4s errors): %-15s => %s'):format(#stats.parse_errors, helpfile, vim.fs.basename(to_fname))) err_count = err_count + #stats.parse_errors -- cgit From 16336c486ecb5a60e85a870904316308c7d7fc3f Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Sun, 25 Sep 2022 02:20:47 +0200 Subject: feat(gen_help_html.lua): adapt to new parser - adapt to parser changes from https://github.com/vigoux/tree-sitter-vimdoc/pull/16 - numerous other generator improvements --- runtime/doc/api.txt | 53 ++-- runtime/doc/develop.txt | 17 ++ runtime/doc/eval.txt | 2 +- runtime/doc/filetype.txt | 2 +- runtime/doc/helphelp.txt | 7 +- runtime/doc/luaref.txt | 110 +++---- runtime/doc/quickref.txt | 45 ++- runtime/doc/ui.txt | 201 +++++++------ runtime/lua/vim/lsp/util.lua | 4 +- scripts/gen_help_html.lua | 467 +++++++++++++++++++----------- test/functional/core/startup_spec.lua | 4 +- test/functional/helpers.lua | 13 +- test/functional/lua/help_spec.lua | 31 +- test/functional/options/defaults_spec.lua | 58 ++-- 14 files changed, 601 insertions(+), 413 deletions(-) diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index f0145344a4..59d1d36be9 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -83,6 +83,7 @@ and |rpcnotify()|: let nvim = jobstart(['nvim', '--embed'], {'rpc': v:true}) echo rpcrequest(nvim, 'nvim_eval', '"Hello " . "world!"') call jobstop(nvim) +< ============================================================================== API Definitions *api-definitions* @@ -92,7 +93,7 @@ The Nvim C API defines custom types for all function parameters. Some are just typedefs around C99 standard types, others are Nvim-defined data structures. Basic types ~ - +> API Type C type ------------------------------------------------------------------------ Nil @@ -103,7 +104,7 @@ Basic types ~ Array Dictionary (msgpack: map) Object - +< Note: empty Array is accepted as a valid argument for Dictionary parameter. Special types (msgpack EXT) ~ @@ -115,13 +116,13 @@ Special types (msgpack EXT) ~ The EXT object data is the (integer) object handle. The EXT type codes given in the |api-metadata| `types` key are stable: they will not change and are thus forward-compatible. - +> EXT Type C type Data ------------------------------------------------------------------------ Buffer enum value kObjectTypeBuffer |bufnr()| Window enum value kObjectTypeWindow |window-ID| Tabpage enum value kObjectTypeTabpage internal handle - +< *api-indexing* Most of the API uses 0-based indices, and ranges are end-exclusive. For the @@ -130,19 +131,19 @@ end of a range, -1 denotes the last line/column. Exception: the following API functions use "mark-like" indexing (1-based lines, 0-based columns): - |nvim_get_mark()| - |nvim_buf_get_mark()| - |nvim_buf_set_mark()| - |nvim_win_get_cursor()| - |nvim_win_set_cursor()| +- |nvim_get_mark()| +- |nvim_buf_get_mark()| +- |nvim_buf_set_mark()| +- |nvim_win_get_cursor()| +- |nvim_win_set_cursor()| Exception: the following API functions use |extmarks| indexing (0-based indices, end-inclusive): - |nvim_buf_del_extmark()| - |nvim_buf_get_extmark_by_id()| - |nvim_buf_get_extmarks()| - |nvim_buf_set_extmark()| +- |nvim_buf_del_extmark()| +- |nvim_buf_get_extmark_by_id()| +- |nvim_buf_get_extmarks()| +- |nvim_buf_set_extmark()| *api-fast* Most API functions are "deferred": they are queued on the main loop and @@ -162,19 +163,19 @@ and return values. Nvim exposes its API metadata as a Dictionary with these items: -version Nvim version, API level/compatibility -version.api_level API version integer *api-level* -version.api_compatible API is backwards-compatible with this level -version.api_prerelease Declares the API as unstable/unreleased > - (version.api_prerelease && fn.since == version.api_level) -functions API function signatures, containing |api-types| info - describing the return value and parameters. -ui_events |UI| event signatures -ui_options Supported |ui-option|s -{fn}.since API level where function {fn} was introduced -{fn}.deprecated_since API level where function {fn} was deprecated -types Custom handle types defined by Nvim -error_types Possible error types returned by API functions +- version Nvim version, API level/compatibility +- version.api_level API version integer *api-level* +- version.api_compatible API is backwards-compatible with this level +- version.api_prerelease Declares the API as unstable/unreleased + `(version.api_prerelease && fn.since == version.api_level)` +- functions API function signatures, containing |api-types| info + describing the return value and parameters. +- ui_events |UI| event signatures +- ui_options Supported |ui-option|s +- {fn}.since API level where function {fn} was introduced +- {fn}.deprecated_since API level where function {fn} was deprecated +- types Custom handle types defined by Nvim +- error_types Possible error types returned by API functions About the `functions` map: diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt index 4f17e7d34a..ebb0dfeb4e 100644 --- a/runtime/doc/develop.txt +++ b/runtime/doc/develop.txt @@ -151,6 +151,23 @@ DOCUMENTATION *dev-doc* /// @param dirname The path fragment before `pend` < +Documentation format ~ + +For Nvim-owned docs, use the following strict subset of "vimdoc" to ensure +the help doc renders nicely in other formats (such as HTML: +https://neovim.io/doc/user ). + +Strict "vimdoc" subset: + +- Use lists (like this!) prefixed with "-", "*", or "•", for adjacent lines + that you don't want auto-wrapped. Lists are always rendered with "flow" + (soft-wrapped) layout instead of preformatted (hard-wrapped) layout common + in legacy :help docs. +- Separate blocks (paragraphs) of content by a blank line(s). +- Do not use indentation in random places—that prevents the page from using + "flow" layout. If you need a preformatted section, put it in + a |help-codeblock| starting with ">". + C docstrings ~ Nvim API documentation lives in the source code, as docstrings (Doxygen diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt index ae28977556..6a9fb6d03c 100644 --- a/runtime/doc/eval.txt +++ b/runtime/doc/eval.txt @@ -4119,7 +4119,7 @@ This example sorts lines with a specific compare function. > As a one-liner: > :call setline(1, sort(getline(1, '$'), function("Strcmp"))) - +< scanf() replacement ~ *sscanf* diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 9f8ef248f8..ac54a6b6ca 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -178,7 +178,7 @@ If a file type that you want to use is not detected yet, there are a few ways to add it. In any way, it's better not to modify the $VIMRUNTIME/filetype.lua or $VIMRUNTIME/filetype.vim files. They will be overwritten when installing a new version of Nvim. The following explains the legacy Vim mechanism (enabled -if |do_legacy_filetype| is set). For Nvim's default mechanism, see +if |g:do_legacy_filetype| is set). For Nvim's default mechanism, see |vim.filetype.add()|. A. If you want to overrule all default file type checks. diff --git a/runtime/doc/helphelp.txt b/runtime/doc/helphelp.txt index 569995d319..4758cd37c6 100644 --- a/runtime/doc/helphelp.txt +++ b/runtime/doc/helphelp.txt @@ -212,12 +212,6 @@ This is done when viewing the file in Vim, the file itself is not changed. It is done by going through all help files and obtaining the first line of each file. The files in $VIMRUNTIME/doc are skipped. - *help-xterm-window* -If you want to have the help in another xterm window, you could use this -command: > - :!xterm -e vim +help & -< - *:helpt* *:helptags* *E150* *E151* *E152* *E153* *E154* *E670* *E856* :helpt[ags] [++t] {dir} @@ -372,6 +366,7 @@ To separate sections in a help file, place a series of '=' characters in a line starting from the first column. The section separator line is highlighted differently. + *help-codeblock* To quote a block of ex-commands verbatim, place a greater than (>) character at the end of the line before the block and a less than (<) character as the first non-blank on a line following the block. Any line starting in column 1 diff --git a/runtime/doc/luaref.txt b/runtime/doc/luaref.txt index ecb92d4bb6..0b04005e1a 100644 --- a/runtime/doc/luaref.txt +++ b/runtime/doc/luaref.txt @@ -55,7 +55,6 @@ Lua means "moon" in Portuguese and is pronounced LOO-ah. ============================================================================== 2 THE LANGUAGE *luaref-language* -============================================================================== This section describes the lexis, the syntax, and the semantics of Lua. In other words, this section describes which tokens are valid, how they can be @@ -450,21 +449,22 @@ through an arithmetic progression. It has the following syntax: < The `block` is repeated for `name` starting at the value of the first `exp`, until it passes the second `exp` by steps of the third `exp`. More precisely, -a `for` statement like +a `for` statement like > - `for var =` `e1, e2, e3` `do` `block` `end` + for var = e1, e2, e3 do block end -is equivalent to the code: +< is equivalent to the code: > - `do` - `local` `var, limit, step` `= tonumber(e1), tonumber(e2), tonumber(e3)` - `if not (` `var` `and` `limit` `and` `step` `) then error() end` - `while (` `step` `>0 and` `var` `<=` `limit` `)` - `or (` `step` `<=0 and` `var` `>=` `limit` `) do` - `block` - `var` `=` `var` `+` `step` - `end` - `end` + do + local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) + if not ( var and limit and step ) then error() end + while ( step >0 and var <= limit ) + or ( step <=0 and var >= limit ) do + block + var = var + step + end + end +< Note the following: @@ -490,18 +490,18 @@ A `for` statement like `for` `var1, ..., varn` `in` `explist` `do` `block` `end` -is equivalent to the code: - - `do` - `local` `f, s, var` `=` `explist` - `while true do` - `local` `var1, ..., varn` `=` `f(s, var)` - `var` `=` `var1` - `if` `var` `== nil then break end` - `block` - `end` - `end` +is equivalent to the code: > + do + local f, s, var = explist + while true do + local var1, ..., varn = f(s, var) + var = var1 + if var == nil then break end + block + end + end +< Note the following: - `explist` is evaluated only once. Its results are an iterator function, @@ -1871,25 +1871,25 @@ lua_gc *lua_gc()* This function performs several tasks, according to the value of the parameter `what`: - `LUA_GCSTOP` stops the garbage collector. - `LUA_GCRESTART` restarts the garbage collector. - `LUA_GCCOLLECT` performs a full garbage-collection cycle. - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in + - `LUA_GCSTOP` stops the garbage collector. + - `LUA_GCRESTART` restarts the garbage collector. + - `LUA_GCCOLLECT` performs a full garbage-collection cycle. + - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in use by Lua. - `LUA_GCCOUNTB` returns the remainder of dividing the current + - `LUA_GCCOUNTB` returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024. - `LUA_GCSTEP` performs an incremental step of garbage collection. + - `LUA_GCSTEP` performs an incremental step of garbage collection. The step "size" is controlled by `data` (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of `data`. The function returns 1 if the step finished a garbage-collection cycle. - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the + - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the `pause` of the collector (see |luaref-langGC|). The function returns the previous value of the pause. - `LUA_GCSETSTEPMUL` sets `data` /100 as the new value for the + - `LUA_GCSETSTEPMUL`sets `data` /100 as the new value for the `step` `multiplier` of the collector (see |luaref-langGC|). The function returns the previous value of the step multiplier. @@ -2717,20 +2717,22 @@ need "inside information" from the interpreter. lua_Debug *lua_Debug()* - `typedef struct lua_Debug {` - `int event;` - `const char *name; /* (n) */` - `const char *namewhat; /* (n) */` - `const char *what; /* (S) */` - `const char *source; /* (S) */` - `int currentline; /* (l) */` - `int nups; /* (u) number of upvalues */` - `int linedefined; /* (S) */` - `int lastlinedefined; /* (S) */` - `char short_src[LUA_IDSIZE]; /* (S) */` - `/* private part */` - `other fields` - `} lua_Debug;` +> + typedef struct lua_Debug { + int event; + const char *name; /* (n) */ + const char *namewhat; /* (n) */ + const char *what; /* (S) */ + const char *source; /* (S) */ + int currentline; /* (l) */ + int nups; /* (u) number of upvalues */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + other fields + } lua_Debug; +< A structure used to carry different pieces of information about an active function. `lua_getstack` (see |lua_getstack()|) fills only the private part @@ -2739,28 +2741,28 @@ useful information, call `lua_getinfo` (see |lua_getinfo()|). The fields of `lua_Debug` have the following meaning: - `source` If the function was defined in a string, then `source` is +- `source` If the function was defined in a string, then `source` is that string. If the function was defined in a file, then `source` starts with a `@` followed by the file name. - `short_src` a "printable" version of `source`, to be used in error messages. - `linedefined` the line number where the definition of the function starts. - `lastlinedefined` the line number where the definition of the function ends. - `what` the string `"Lua"` if the function is a Lua function, +- `short_src` a "printable" version of `source`, to be used in error messages. +- `linedefined` the line number where the definition of the function starts. +- `lastlinedefined` the line number where the definition of the function ends. +- `what` the string `"Lua"` if the function is a Lua function, `"C"` if it is a C function, `"main"` if it is the main part of a chunk, and `"tail"` if it was a function that did a tail call. In the latter case, Lua has no other information about the function. - `currentline` the current line where the given function is executing. +- `currentline` the current line where the given function is executing. When no line information is available, `currentline` is set to -1. - `name` a reasonable name for the given function. Because +- `name` a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions may be the value of multiple global variables, while others may be stored only in a table field. The `lua_getinfo` function checks how the function was called to find a suitable name. If it cannot find a name, then `name` is set to `NULL`. - `namewhat` explains the `name` field. The value of `namewhat` can be +- `namewhat` explains the `name` field. The value of `namewhat` can be `"global"`, `"local"`, `"method"`, `"field"`, `"upvalue"`, or `""` (the empty string), according to how the function was called. (Lua uses the empty string when diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt index 23ce16a40a..bdb0f7447c 100644 --- a/runtime/doc/quickref.txt +++ b/runtime/doc/quickref.txt @@ -3,7 +3,8 @@ VIM REFERENCE MANUAL by Bram Moolenaar - Quick reference guide +============================================================================== +Quick reference guide *quickref* *Contents* tag subject tag subject ~ @@ -29,11 +30,11 @@ |Q_to| Text objects |Q_gu| GUI commands |Q_fo| Folding ------------------------------------------------------------------------------- -N is used to indicate an optional count that can be given before the command. ------------------------------------------------------------------------------ *Q_lr* Left-right motions +N is used to indicate an optional count that can be given before the command. + |h| N h left (also: CTRL-H, , or key) |l| N l right (also: or key) |0| 0 to first character in the line (also: key) @@ -56,6 +57,7 @@ N is used to indicate an optional count that can be given before the command. |;| N ; repeat the last "f", "F", "t", or "T" N times |,| N , repeat the last "f", "F", "t", or "T" N times in opposite direction + ------------------------------------------------------------------------------ *Q_ud* Up-down motions @@ -73,6 +75,7 @@ N is used to indicate an optional count that can be given before the command. given, otherwise it is the |%| command |gk| N gk up N screen lines (differs from "k" when line wraps) |gj| N gj down N screen lines (differs from "j" when line wraps) + ------------------------------------------------------------------------------ *Q_tm* Text object motions @@ -105,6 +108,7 @@ N is used to indicate an optional count that can be given before the command. |]#| N ]# N times forward to unclosed "#else" or "#endif" |[star| N [* N times back to start of comment "/*" |]star| N ]* N times forward to end of comment "*/" + ------------------------------------------------------------------------------ *Q_pa* Pattern searches @@ -168,6 +172,7 @@ N is used to indicate an optional count that can be given before the command. b[+num] [num] identical to s[+num] above (mnemonic: begin) b[-num] [num] identical to s[-num] above (mnemonic: begin) ;{search-command} execute {search-command} next + ------------------------------------------------------------------------------ *Q_ma* Marks and motions @@ -188,6 +193,7 @@ N is used to indicate an optional count that can be given before the command. |CTRL-O| N CTRL-O go to Nth older position in jump list |CTRL-I| N CTRL-I go to Nth newer position in jump list |:ju| :ju[mps] print the jump list + ------------------------------------------------------------------------------ *Q_vm* Various motions @@ -202,6 +208,7 @@ N is used to indicate an optional count that can be given before the command. |go| N go go to Nth byte in the buffer |:go| :[range]go[to] [off] go to [off] byte in the buffer + ------------------------------------------------------------------------------ *Q_ta* Using tags @@ -229,6 +236,7 @@ N is used to indicate an optional count that can be given before the command. |:ptjump| :ptj[ump] like ":tjump" but show tag in preview window |:pclose| :pc[lose] close tag preview window |CTRL-W_z| CTRL-W z close tag preview window + ------------------------------------------------------------------------------ *Q_sc* Scrolling @@ -247,6 +255,7 @@ These only work when 'wrap' is off: |zl| N zl scroll screen N characters to the left |zH| N zH scroll screen half a screenwidth to the right |zL| N zL scroll screen half a screenwidth to the left + ------------------------------------------------------------------------------ *Q_in* Inserting text @@ -263,6 +272,7 @@ These only work when 'wrap' is off: in Visual block mode: |v_b_I| I insert the same text in front of all the selected lines |v_b_A| A append the same text after all the selected lines + ------------------------------------------------------------------------------ *Q_ai* Insert mode keys @@ -279,6 +289,7 @@ moving around: |i_| shift-up/down one screenful backward/forward |i_| cursor after last character in the line |i_| cursor to first character in the line + ------------------------------------------------------------------------------ *Q_ss* Special keys in Insert mode @@ -313,6 +324,7 @@ moving around: |i_0_CTRL-D| 0 CTRL-D delete all indent in the current line |i_^_CTRL-D| ^ CTRL-D delete all indent in the current line, restore indent in next line + ------------------------------------------------------------------------------ *Q_di* Digraphs @@ -325,12 +337,14 @@ In Insert or Command-line mode: enter digraph |i_digraph| {char1} {char2} enter digraph if 'digraph' option set + ------------------------------------------------------------------------------ *Q_si* Special inserts |:r| :r [file] insert the contents of [file] below the cursor |:r!| :r! {command} insert the standard output of {command} below the cursor + ------------------------------------------------------------------------------ *Q_de* Deleting text @@ -346,6 +360,7 @@ In Insert or Command-line mode: |gJ| N gJ like "J", but without inserting spaces |v_gJ| {visual}gJ like "{visual}J", but without inserting spaces |:d| :[range]d [x] delete [range] lines [into register x] + ------------------------------------------------------------------------------ *Q_cm* Copying and moving text @@ -363,6 +378,7 @@ In Insert or Command-line mode: |[p| N [p like P, but adjust indent to current line |gp| N gp like p, but leave cursor after the new text |gP| N gP like P, but leave cursor after the new text + ------------------------------------------------------------------------------ *Q_ch* Changing text @@ -418,6 +434,7 @@ In Insert or Command-line mode: left-align the lines in [range] (with [indent]) |:ri| :[range]ri[ght] [width] right-align the lines in [range] + ------------------------------------------------------------------------------ *Q_co* Complex changes @@ -444,6 +461,7 @@ In Insert or Command-line mode: |:ret| :[range]ret[ab][!] [tabstop] set 'tabstop' to new value and adjust white space accordingly + ------------------------------------------------------------------------------ *Q_vi* Visual mode @@ -457,6 +475,7 @@ In Insert or Command-line mode: |v_v| v highlight characters or stop highlighting |v_V| V highlight linewise or stop highlighting |v_CTRL-V| CTRL-V highlight blockwise or stop highlighting + ------------------------------------------------------------------------------ *Q_to* Text objects (only in Visual mode or after an operator) @@ -509,6 +528,7 @@ In Insert or Command-line mode: |:sl| :sl[eep] [sec] don't do anything for [sec] seconds |gs| N gs goto Sleep for N seconds + ------------------------------------------------------------------------------ *Q_km* Key mapping @@ -556,6 +576,7 @@ In Insert or Command-line mode: like ":mkvimrc", but store current files, windows, etc. too, to be able to continue this session later + ------------------------------------------------------------------------------ *Q_ab* Abbreviations @@ -570,6 +591,7 @@ In Insert or Command-line mode: |:abclear| :abc[lear] remove all abbreviations |:cabclear| :cabc[lear] remove all abbr's for Cmdline mode |:iabclear| :iabc[lear] remove all abbr's for Insert mode + ------------------------------------------------------------------------------ *Q_op* Options @@ -940,18 +962,21 @@ Short explanation of each option: *option-list* 'writeany' 'wa' write to file with no need for "!" override 'writebackup' 'wb' make a backup before overwriting a file 'writedelay' 'wd' delay this many msec for each char (for debug) + ------------------------------------------------------------------------------ *Q_ur* Undo/Redo commands |u| N u undo last N changes |CTRL-R| N CTRL-R redo last N undone changes |U| U restore last changed line + ------------------------------------------------------------------------------ *Q_et* External commands |:!| :!{command} execute {command} with a shell |K| K lookup keyword under the cursor with 'keywordprg' program (default: "man") + ------------------------------------------------------------------------------ *Q_qf* Quickfix commands @@ -975,6 +1000,7 @@ Short explanation of each option: *option-list* error |:grep| :gr[ep] [args] execute 'grepprg' to find matches and jump to the first one + ------------------------------------------------------------------------------ *Q_vc* Various commands @@ -1000,6 +1026,7 @@ Short explanation of each option: *option-list* unsaved changes or read-only files |:browse| :browse {command} open/read/write file, using a file selection dialog + ------------------------------------------------------------------------------ *Q_ce* Command-line editing @@ -1046,6 +1073,7 @@ Context-sensitive completion on the command-line: to next match |c_CTRL-P| CTRL-P after 'wildchar' with multiple matches: go to previous match + ------------------------------------------------------------------------------ *Q_ra* Ex ranges @@ -1066,6 +1094,7 @@ Context-sensitive completion on the command-line: (default: 1) |:range| -[num] subtract [num] from the preceding line number (default: 1) + ------------------------------------------------------------------------------ *Q_ex* Special Ex characters @@ -1098,6 +1127,7 @@ Context-sensitive completion on the command-line: |::r| :r root (extension removed) |::e| :e extension |::s| :s/{pat}/{repl}/ substitute {pat} with {repl} + ------------------------------------------------------------------------------ *Q_st* Starting Vim @@ -1134,6 +1164,7 @@ Context-sensitive completion on the command-line: |--help| --help show list of arguments and exit |--version| --version show version info and exit |--| - read file from stdin + ------------------------------------------------------------------------------ *Q_ed* Editing a file @@ -1153,6 +1184,7 @@ Context-sensitive completion on the command-line: position |:file| :f[ile] {name} set the current file name to {name} |:files| :files show alternate file names + ------------------------------------------------------------------------------ *Q_fl* Using the argument list |argument-list| @@ -1173,6 +1205,7 @@ Context-sensitive completion on the command-line: |:Next| :N[ext] :sN[ext] edit previous file |:first| :fir[st] :sfir[st] edit first file |:last| :la[st] :sla[st] edit last file + ------------------------------------------------------------------------------ *Q_wq* Writing and quitting @@ -1210,6 +1243,7 @@ Context-sensitive completion on the command-line: |:stop| :st[op][!] suspend Vim or start new shell; if 'aw' option is set and [!] not given write the buffer |CTRL-Z| CTRL-Z same as ":stop" + ------------------------------------------------------------------------------ *Q_ac* Automatic Commands @@ -1241,6 +1275,7 @@ Context-sensitive completion on the command-line: with {pat} |:autocmd| :au! {event} {pat} {cmd} remove all autocommands for {event} with {pat} and enter new one + ------------------------------------------------------------------------------ *Q_wi* Multi-window commands @@ -1286,6 +1321,7 @@ Context-sensitive completion on the command-line: |CTRL-W_>| CTRL-W > increase current window width |CTRL-W_bar| CTRL-W | set current window width (default: widest possible) + ------------------------------------------------------------------------------ *Q_bu* Buffer list commands @@ -1307,6 +1343,7 @@ Context-sensitive completion on the command-line: |:bfirst| :bfirst :sbfirst to first arg/buf |:blast| :blast :sblast to last arg/buf |:bmodified| :[N]bmod [N] :[N]sbmod [N] to Nth modified buf + ------------------------------------------------------------------------------ *Q_sy* Syntax Highlighting @@ -1333,6 +1370,7 @@ Context-sensitive completion on the command-line: |:filetype| :filetype plugin indent on switch on file type detection, with automatic indenting and settings + ------------------------------------------------------------------------------ *Q_gu* GUI commands @@ -1345,6 +1383,7 @@ Context-sensitive completion on the command-line: add toolbar item, giving {rhs} |:tmenu| :tmenu {mpath} {text} add tooltip to menu {mpath} |:unmenu| :unmenu {mpath} remove menu {mpath} + ------------------------------------------------------------------------------ *Q_fo* Folding diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt index 2d0c8d3b75..7ce6cd251f 100644 --- a/runtime/doc/ui.txt +++ b/runtime/doc/ui.txt @@ -23,40 +23,37 @@ screen grid with a size of width × height cells. This is typically done by an embedder at startup (see |ui-startup|), but UIs can also connect to a running Nvim instance and invoke nvim_ui_attach(). The `options` parameter is a map with these (optional) keys: + *ui-rgb* - `rgb` Decides the color format. - true: (default) 24-bit RGB colors - false: Terminal colors (8-bit, max 256) +- `rgb` Decides the color format. + - true: (default) 24-bit RGB colors + - false: Terminal colors (8-bit, max 256) *ui-override* - `override` Decides how UI capabilities are resolved. - true: Enable requested UI capabilities, even - if not supported by all connected UIs - (including |TUI|). - false: (default) Disable UI capabilities not - supported by all connected UIs - (including TUI). +- `override` Decides how UI capabilities are resolved. + - true: Enable requested UI capabilities, even if not + supported by all connected UIs (including |TUI|). + - false: (default) Disable UI capabilities not + supported by all connected UIs (including TUI). *ui-ext-options* - `ext_cmdline` Externalize the cmdline. |ui-cmdline| - `ext_hlstate` Detailed highlight state. |ui-hlstate| - Sets `ext_linegrid` implicitly. - `ext_linegrid` Line-based grid events. |ui-linegrid| - Deactivates |ui-grid-old| implicitly. - `ext_messages` Externalize messages. |ui-messages| - Sets `ext_linegrid` and `ext_cmdline` implicitly. - `ext_multigrid` Per-window grid events. |ui-multigrid| - Sets `ext_linegrid` implicitly. - `ext_popupmenu` Externalize |popupmenu-completion| and - 'wildmenu'. |ui-popupmenu| - `ext_tabline` Externalize the tabline. |ui-tabline| - `ext_termcolors` Use external default colors. - `term_name` Sets the name of the terminal 'term'. - `term_colors` Sets the number of supported colors 't_Co'. - `term_background` Sets the default value of 'background'. - `stdin_fd` Read buffer from `fd` as if it was a stdin pipe - This option can only used by |--embed| ui, - see |ui-startup-stdin|. - - +- `ext_cmdline` Externalize the cmdline. |ui-cmdline| +- `ext_hlstate` Detailed highlight state. |ui-hlstate| + Sets `ext_linegrid` implicitly. +- `ext_linegrid` Line-based grid events. |ui-linegrid| + Deactivates |ui-grid-old| implicitly. +- `ext_messages` Externalize messages. |ui-messages| + Sets `ext_linegrid` and `ext_cmdline` implicitly. +- `ext_multigrid` Per-window grid events. |ui-multigrid| + Sets `ext_linegrid` implicitly. +- `ext_popupmenu` Externalize |popupmenu-completion| and + 'wildmenu'. |ui-popupmenu| +- `ext_tabline` Externalize the tabline. |ui-tabline| +- `ext_termcolors` Use external default colors. +- `term_name` Sets the name of the terminal 'term'. +- `term_colors` Sets the number of supported colors 't_Co'. +- `term_background` Sets the default value of 'background'. +- `stdin_fd` Read buffer from `fd` as if it was a stdin pipe + This option can only used by |--embed| ui, + see |ui-startup-stdin|. Specifying an unknown option is an error; UIs can check the |api-metadata| `ui_options` key for supported options. @@ -164,13 +161,13 @@ Global Events *ui-global* The following UI events are always emitted, and describe global state of the editor. -["set_title", title] -["set_icon", icon] +["set_title", title] ~ +["set_icon", icon] ~ Set the window title, and icon (minimized) window title, respectively. In windowing systems not distinguishing between the two, "set_icon" can be ignored. -["mode_info_set", cursor_style_enabled, mode_info] +["mode_info_set", cursor_style_enabled, mode_info] ~ `cursor_style_enabled` is a boolean indicating if the UI should set the cursor style. `mode_info` is a list of mode property maps. The current mode is given by the `mode_idx` field of the `mode_change` @@ -197,21 +194,21 @@ the editor. `hl_id`: Use `attr_id` instead. `hl_lm`: Use `attr_id_lm` instead. -["option_set", name, value] +["option_set", name, value] ~ UI-related option changed, where `name` is one of: - 'arabicshape' - 'ambiwidth' - 'emoji' - 'guifont' - 'guifontwide' - 'linespace' - 'mousefocus' - 'mousemoveevent' - 'pumblend' - 'showtabline' - 'termguicolors' - "ext_*" (all |ui-ext-options|) + - 'arabicshape' + - 'ambiwidth' + - 'emoji' + - 'guifont' + - 'guifontwide' + - 'linespace' + - 'mousefocus' + - 'mousemoveevent' + - 'pumblend' + - 'showtabline' + - 'termguicolors' + - "ext_*" (all |ui-ext-options|) Triggered when the UI first connects to Nvim, and whenever an option is changed by the user or a plugin. @@ -224,7 +221,7 @@ the editor. however a UI might still use such options when rendering raw text sent from Nvim, like for |ui-cmdline|. -["mode_change", mode, mode_idx] +["mode_change", mode, mode_idx] ~ Editor mode changed. The `mode` parameter is a string representing the current mode. `mode_idx` is an index into the array emitted in the `mode_info_set` event. UIs should change the cursor style @@ -233,30 +230,30 @@ the editor. instance more submodes and temporary states might be represented as separate modes. -["mouse_on"] -["mouse_off"] +["mouse_on"] ~ +["mouse_off"] ~ 'mouse' was enabled/disabled in the current editor mode. Useful for a terminal UI, or embedding into an application where Nvim mouse would conflict with other usages of the mouse. Other UI:s may ignore this event. -["busy_start"] -["busy_stop"] +["busy_start"] ~ +["busy_stop"] ~ Indicates to the UI that it must stop rendering the cursor. This event is misnamed and does not actually have anything to do with busyness. -["suspend"] +["suspend"] ~ |:suspend| command or |CTRL-Z| mapping is used. A terminal client (or another client where it makes sense) could suspend itself. Other clients can safely ignore it. -["update_menu"] +["update_menu"] ~ The menu mappings changed. -["bell"] -["visual_bell"] +["bell"] ~ +["visual_bell"] ~ Notify the user with an audible or visual bell, respectively. -["flush"] +["flush"] ~ Nvim is done redrawing the screen. For an implementation that renders to an internal buffer, this is the time to display the redrawn parts to the user. @@ -279,11 +276,11 @@ be created; to enable per-window grids, activate |ui-multigrid|. Highlight attribute groups are predefined. UIs should maintain a table to map numerical highlight ids to the actual attributes. -["grid_resize", grid, width, height] +["grid_resize", grid, width, height] ~ Resize a `grid`. If `grid` wasn't seen by the client before, a new grid is being created with this size. -["default_colors_set", rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg] +["default_colors_set", rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg] ~ The first three arguments set the default foreground, background and special colors respectively. `cterm_fg` and `cterm_bg` specifies the default color codes to use in a 256-color terminal. @@ -300,7 +297,7 @@ numerical highlight ids to the actual attributes. screen with changed background color itself. *ui-event-hl_attr_define* -["hl_attr_define", id, rgb_attr, cterm_attr, info] +["hl_attr_define", id, rgb_attr, cterm_attr, info] ~ Add a highlight with `id` to the highlight table, with the attributes specified by the `rgb_attr` and `cterm_attr` dicts, with the following (all optional) keys. @@ -346,7 +343,7 @@ numerical highlight ids to the actual attributes. `info` is an empty array by default, and will be used by the |ui-hlstate| extension explained below. -["hl_group_set", name, hl_id] +["hl_group_set", name, hl_id] ~ The bulitin highlight group `name` was set to use the attributes `hl_id` defined by a previous `hl_attr_define` call. This event is not needed to render the grids which use attribute ids directly, but is useful @@ -355,7 +352,7 @@ numerical highlight ids to the actual attributes. use the |hl-Pmenu| family of builtin highlights. *ui-event-grid_line* -["grid_line", grid, row, col_start, cells] +["grid_line", grid, row, col_start, cells] ~ Redraw a continuous part of a `row` on a `grid`, starting at the column `col_start`. `cells` is an array of arrays each with 1 to 3 items: `[text(, hl_id, repeat)]` . `text` is the UTF-8 text that should be put in @@ -374,19 +371,19 @@ numerical highlight ids to the actual attributes. enough to cover the remaining line, will be sent when the rest of the line should be cleared. -["grid_clear", grid] +["grid_clear", grid] ~ Clear a `grid`. -["grid_destroy", grid] +["grid_destroy", grid] ~ `grid` will not be used anymore and the UI can free any data associated with it. -["grid_cursor_goto", grid, row, column] +["grid_cursor_goto", grid, row, column] ~ Makes `grid` the current grid and `row, column` the cursor position on this grid. This event will be sent at most once in a `redraw` batch and indicates the visible cursor position. -["grid_scroll", grid, top, bot, left, right, rows, cols] +["grid_scroll", grid, top, bot, left, right, rows, cols] ~ Scroll a region of `grid`. This is semantically unrelated to editor |scrolling|, rather this is an optimized way to say "copy these screen cells". @@ -439,30 +436,30 @@ Grid Events (cell-based) *ui-grid-old* This is the legacy representation of the screen grid, emitted if |ui-linegrid| is not active. New UIs should implement |ui-linegrid| instead. -["resize", width, height] +["resize", width, height] ~ The grid is resized to `width` and `height` cells. -["clear"] +["clear"] ~ Clear the grid. -["eol_clear"] +["eol_clear"] ~ Clear from the cursor position to the end of the current line. -["cursor_goto", row, col] +["cursor_goto", row, col] ~ Move the cursor to position (row, col). Currently, the same cursor is used to define the position for text insertion and the visible cursor. However, only the last cursor position, after processing the entire array in the "redraw" event, is intended to be a visible cursor position. -["update_fg", color] -["update_bg", color] -["update_sp", color] +["update_fg", color] ~ +["update_bg", color] ~ +["update_sp", color] ~ Set the default foreground, background and special colors respectively. *ui-event-highlight_set* -["highlight_set", attrs] +["highlight_set", attrs] ~ Set the attributes that the next text put on the grid will have. `attrs` is a dict with the keys below. Any absent key is reset to its default value. Color defaults are set by the `update_fg` etc @@ -482,18 +479,18 @@ is not active. New UIs should implement |ui-linegrid| instead. `underdotted`: underdotted text. The dots have `special` color. `underdashed`: underdashed text. The dashes have `special` color. -["put", text] +["put", text] ~ The (utf-8 encoded) string `text` is put at the cursor position (and the cursor is advanced), with the highlights as set by the last `highlight_set` update. -["set_scroll_region", top, bot, left, right] +["set_scroll_region", top, bot, left, right] ~ Define the scroll region used by `scroll` below. Note: ranges are end-inclusive, which is inconsistent with API conventions. -["scroll", count] +["scroll", count] ~ Scroll the text in the scroll region. The diagrams below illustrate what will happen, depending on the scroll direction. "=" is used to represent the SR(scroll region) boundaries and "-" the moved rectangles. @@ -588,29 +585,29 @@ A window can be hidden and redisplayed without its grid being deallocated. This can happen multiple times for the same window, for instance when switching tabs. -["win_pos", grid, win, start_row, start_col, width, height] +["win_pos", grid, win, start_row, start_col, width, height] ~ Set the position and size of the grid in Nvim (i.e. the outer grid size). If the window was previously hidden, it should now be shown again. -["win_float_pos", grid, win, anchor, anchor_grid, anchor_row, anchor_col, focusable] +["win_float_pos", grid, win, anchor, anchor_grid, anchor_row, anchor_col, focusable] ~ Display or reconfigure floating window `win`. The window should be displayed above another grid `anchor_grid` at the specified position `anchor_row` and `anchor_col`. For the meaning of `anchor` and more details of positioning, see |nvim_open_win()|. -["win_external_pos", grid, win] +["win_external_pos", grid, win] ~ Display or reconfigure external window `win`. The window should be displayed as a separate top-level window in the desktop environment, or something similar. -["win_hide", grid] +["win_hide", grid] ~ Stop displaying the window. The window can be shown again later. -["win_close", grid] +["win_close", grid] ~ Close the window. -["msg_set_pos", grid, row, scrolled, sep_char] +["msg_set_pos", grid, row, scrolled, sep_char] ~ Display messages on `grid`. The grid will be displayed at `row` on the default grid (grid=1), covering the full column width. `scrolled` indicates whether the message area has been scrolled to cover other @@ -621,13 +618,13 @@ tabs. When |ui-messages| is active, no message grid is used, and this event will not be sent. -["win_viewport", grid, win, topline, botline, curline, curcol] +["win_viewport", grid, win, topline, botline, curline, curcol] ~ Indicates the range of buffer text displayed in the window, as well as the cursor position in the buffer. All positions are zero-based. `botline` is set to one more than the line count of the buffer, if there are filler lines past the end. -["win_extmark", grid, win, ns_id, mark_id, row, col] +["win_extmark", grid, win, ns_id, mark_id, row, col] ~ Updates the position of an extmark which is currently visible in a window. Only emitted if the mark has the `ui_watched` attribute. @@ -639,7 +636,7 @@ Activated by the `ext_popupmenu` |ui-option|. This UI extension delegates presentation of the |popupmenu-completion| and command-line 'wildmenu'. -["popupmenu_show", items, selected, row, col, grid] +["popupmenu_show", items, selected, row, col, grid] ~ Show |popupmenu-completion|. `items` is an array of completion items to show; each item is an array of the form [word, kind, menu, info] as defined at |complete-items|, except that `word` is replaced by `abbr` @@ -651,12 +648,12 @@ command-line 'wildmenu'. set to -1 to indicate the popupmenu should be anchored to the external cmdline. Then `col` will be a byte position in the cmdline text. -["popupmenu_select", selected] +["popupmenu_select", selected] ~ Select an item in the current popupmenu. `selected` is a zero-based index into the array of items from the last popupmenu_show event, or -1 if no item is selected. -["popupmenu_hide"] +["popupmenu_hide"] ~ Hide the popupmenu. ============================================================================== @@ -664,7 +661,7 @@ Tabline Events *ui-tabline* Activated by the `ext_tabline` |ui-option|. -["tabline_update", curtab, tabs, curbuf, buffers] +["tabline_update", curtab, tabs, curbuf, buffers] ~ Tabline was updated. UIs should present this data in a custom tabline widget. Note: options `curbuf` + `buffers` were added in API7. curtab: Current Tabpage @@ -680,7 +677,7 @@ Activated by the `ext_cmdline` |ui-option|. This UI extension delegates presentation of the |cmdline| (except 'wildmenu'). For command-line 'wildmenu' UI events, activate |ui-popupmenu|. -["cmdline_show", content, pos, firstc, prompt, indent, level] +["cmdline_show", content, pos, firstc, prompt, indent, level] ~ content: List of [attrs, string] [[{}, "t"], [attrs, "est"], ...] @@ -703,10 +700,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. prompt has level 2. A command line invoked from the |cmdline-window| has a higher level than than the edited command line. -["cmdline_pos", pos, level] +["cmdline_pos", pos, level] ~ Change the cursor position in the cmdline. -["cmdline_special_char", c, shift, level] +["cmdline_special_char", c, shift, level] ~ Display a special char in the cmdline at the cursor position. This is typically used to indicate a pending state, e.g. after |c_CTRL-V|. If `shift` is true the text after the cursor should be shifted, otherwise @@ -714,10 +711,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. Should be hidden at next cmdline_show. -["cmdline_hide"] +["cmdline_hide"] ~ Hide the cmdline. -["cmdline_block_show", lines] +["cmdline_block_show", lines] ~ Show a block of context to the current command line. For example if the user defines a |:function| interactively: > :function Foo() @@ -727,10 +724,10 @@ For command-line 'wildmenu' UI events, activate |ui-popupmenu|. `lines` is a list of lines of highlighted chunks, in the same form as the "cmdline_show" `contents` parameter. -["cmdline_block_append", line] +["cmdline_block_append", line] ~ Append a line at the end of the currently shown block. -["cmdline_block_hide"] +["cmdline_block_hide"] ~ Hide the block. ============================================================================== @@ -747,7 +744,7 @@ Nvim will not allocate screen space for the cmdline or messages, and 'cmdheight' will be forced zero. Cmdline state is emitted as |ui-cmdline| events, which the UI must handle. -["msg_show", kind, content, replace_last] +["msg_show", kind, content, replace_last] ~ Display a message to the user. kind @@ -781,25 +778,25 @@ events, which the UI must handle. true: Replace the message in the most-recent `msg_show` call, but any other visible message should still remain. -["msg_clear"] +["msg_clear"] ~ Clear all messages currently displayed by "msg_show". (Messages sent by other "msg_" events below will not be affected). -["msg_showmode", content] +["msg_showmode", content] ~ Shows 'showmode' and |recording| messages. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_showcmd", content] +["msg_showcmd", content] ~ Shows 'showcmd' messages. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_ruler", content] +["msg_ruler", content] ~ Used to display 'ruler' when there is no space for the ruler in a statusline. `content` has the same format as in "msg_show". This event is sent with empty `content` to hide the last message. -["msg_history_show", entries] +["msg_history_show", entries] ~ Sent when |:messages| command is invoked. History is sent as a list of entries, where each entry is a `[kind, content]` tuple. diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index dbc18963f9..aea2a27f9e 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -907,8 +907,8 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers return end --The active signature. If omitted or the value lies outside the range of - --`signatures` the value defaults to zero or is ignored if `signatures.length - --=== 0`. Whenever possible implementors should make an active decision about + --`signatures` the value defaults to zero or is ignored if `signatures.length == 0`. + --Whenever possible implementors should make an active decision about --the active signature and shouldn't rely on a default value. local contents = {} local active_hl diff --git a/scripts/gen_help_html.lua b/scripts/gen_help_html.lua index 6e297814b8..fdbf5f605a 100644 --- a/scripts/gen_help_html.lua +++ b/scripts/gen_help_html.lua @@ -1,5 +1,7 @@ -- Converts Vim :help files to HTML. Validates |tag| links and document syntax (parser errors). -- +-- NOTE: :helptags checks for duplicate tags, whereas this script checks _links_ (to tags). +-- -- USAGE (GENERATE HTML): -- 1. Run `make helptags` first; this script depends on vim.fn.taglist(). -- 2. nvim -V1 -es --clean +"lua require('scripts.gen_help_html').gen('./build/runtime/doc/', 'target/dir/')" @@ -20,37 +22,19 @@ -- * visit_node() is the core function used by gen() to traverse the document tree and produce HTML. -- * visit_validate() is the core function used by validate(). -- * Files in `new_layout` will be generated with a "flow" layout instead of preformatted/fixed-width layout. --- --- parser bugs: --- * Should NOT be code_block: --- tab:xy The 'x' is always used, then 'y' as many times as will --- fit. Thus "tab:>-" displays: --- > --- >- --- >-- --- etc. --- --- tab:xyz The 'z' is always used, then 'x' is prepended, and --- then 'y' is used as many times as will fit. Thus --- "tab:<->" displays: --- > --- <> --- <-> --- <--> --- etc. --- * Should NOT be a "headline". Perhaps a "table" (or just "line"). --- expr5 and expr6 *expr5* *expr6* --- --------------- --- expr6 + expr6 Number addition, |List| or |Blob| concatenation *expr-+* --- expr6 - expr6 Number subtraction *expr--* --- expr6 . expr6 String concatenation *expr-.* --- expr6 .. expr6 String concatenation *expr-..* local tagmap = nil local helpfiles = nil -local invalid_tags = {} +local invalid_links = {} +local invalid_urls = {} +local invalid_spelling = {} +local spell_dict = { + Neovim = 'Nvim', + NeoVim = 'Nvim', + neovim = 'Nvim', + lua = 'Lua', +} -local api = vim.api local M = {} -- These files are generated with "flow" layout (non fixed-width, wrapped text paragraphs). @@ -59,16 +43,31 @@ local new_layout = { ['api.txt'] = true, ['channel.txt'] = true, ['develop.txt'] = true, + ['luaref.txt'] = true, ['nvim.txt'] = true, ['pi_health.txt'] = true, ['provider.txt'] = true, ['ui.txt'] = true, } --- TODO: treesitter gets stuck on these files... -local exclude = { - ['filetype.txt'] = true, - ['usr_24.txt'] = true, +-- TODO: These known invalid |links| require an update to the relevant docs. +local exclude_invalid = { + ["'previewpopup'"] = "quickref.txt", + ["'pvp'"] = "quickref.txt", + ["'string'"] = "eval.txt", + Query = "treesitter.txt", + ["eq?"] = "treesitter.txt", + ["lsp-request"] = "lsp.txt", + matchit = "vim_diff.txt", + ["matchit.txt"] = "help.txt", + ["set!"] = "treesitter.txt", + ["v:_null_blob"] = "builtin.txt", + ["v:_null_dict"] = "builtin.txt", + ["v:_null_list"] = "builtin.txt", + ["v:_null_string"] = "builtin.txt", + ["vim.lsp.buf_request()"] = "lsp.txt", + ["vim.lsp.util.get_progress_messages()"] = "lsp.txt", + ["vim.treesitter.start()"] = "treesitter.txt" } local function tofile(fname, text) @@ -82,10 +81,6 @@ local function tofile(fname, text) end local function html_esc(s) - if s:find(']local%-additions[*<]') + ) then + -- table.insert(stats.noise_lines, getbuflinestr(root, opt.buf, 0)) + table.insert(noise_lines or {}, line) + return true + end + return false end --- Checks if a given line is a "noise" line that doesn't look good in HTML form. -local function is_noise(line) - return ( - line:find('Type .*gO.* to see the table of contents') - -- Title line of traditional :help pages. - -- Example: "NVIM REFERENCE MANUAL by ..." - or line:find('^%s*N?VIM REFERENCE MANUAL') - -- First line of traditional :help pages. - -- Example: "*api.txt* Nvim" - or line:find('%s*%*?[a-zA-Z]+%.txt%*?%s+N?[vV]im%s*$') - -- modeline - -- Example: "vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:" - or line:find('^%s*vi[m]%:.*ft=help') - or line:find('^%s*vi[m]%:.*filetype=help') - ) -end - --- Creates a github issue URL at vigoux/tree-sitter-vimdoc with prefilled content. +-- Creates a github issue URL at neovim/tree-sitter-vimdoc with prefilled content. local function get_bug_url_vimdoc(fname, to_fname, sample_text) local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname)) - local bug_url = ('https://github.com/vigoux/tree-sitter-vimdoc/issues/new?labels=bug&title=parse+error%3A+' + local bug_url = ('https://github.com/neovim/tree-sitter-vimdoc/issues/new?labels=bug&title=parse+error%3A+' ..vim.fs.basename(fname) ..'+&body=Found+%60tree-sitter-vimdoc%60+parse+error+at%3A+' ..this_url @@ -237,31 +236,57 @@ local function getbuflinestr(node, bufnr, offset) return table.concat(lines, '\n') end --- Gets the whitespace just before `node` from the raw buffer text. --- Needed for preformatted `old` lines. -local function getws(node, bufnr) - local line1, c1, line2, _ = node:range() - local raw = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)[1] - local text_before = raw:sub(1, c1) - local leading_ws = text_before:match('%s+$') or '' - return leading_ws -end - -local function get_tagname(node, bufnr, link) - local node_name = (node.named and node:named()) and node:type() or nil +local function get_tagname(node, bufnr) local node_text = vim.treesitter.get_node_text(node, bufnr) - local tag = ((node_name == 'option' and node_text) - or (link and node_text:gsub('^|', ''):gsub('|$', '') or node_text:gsub('^%*', ''):gsub('%*$', ''))) - local helpfile = tag and vim.fs.basename(tagmap[tag]) or nil -- "api.txt" - local helppage = get_helppage(helpfile) -- "api.html" + local tag = (node:type() == 'optionlink' or node:parent():type() == 'optionlink') and ("'%s'"):format(node_text) or node_text + local helpfile = vim.fs.basename(tagmap[tag]) or nil -- "api.txt" + local helppage = get_helppage(helpfile) -- "api.html" return helppage, tag end +-- Returns true if the given invalid tagname is a false positive. +local function ignore_invalid(s) + -- Strings like |~/====| appear in various places and the parser thinks they are links, but they + -- are just table borders. + return not not (s:find('===') or exclude_invalid[s]) +end + +local function ignore_parse_error(s) + -- Ignore parse errors for unclosed codespan/optionlink/tag. + -- This is common in vimdocs and is treated as plaintext by :help. + return s:find("^[`'|*]") +end + +local function has_ancestor(node, ancestor_name) + local p = node + while true do + p = p:parent() + if not p or p:type() == 'help_file' then + break + elseif p:type() == ancestor_name then + return true + end + end + return false +end + +local function validate_link(node, bufnr, fname) + local helppage, tagname = get_tagname(node:child(1), bufnr, true) + if not has_ancestor(node, 'column_heading') and not node:has_error() and not tagmap[tagname] and not ignore_invalid(tagname) then + invalid_links[tagname] = vim.fs.basename(fname) + end + return helppage, tagname +end + -- Traverses the tree at `root` and checks that |tag| links point to valid helptags. local function visit_validate(root, level, lang_tree, opt, stats) level = level or 0 local node_name = (root.named and root:named()) and root:type() or nil local toplevel = level < 1 + local function node_text(node) + return vim.treesitter.get_node_text(node or root, opt.buf) + end + local text = trim(node_text()) if root:child_count() > 0 then for node, _ in root:iter_children() do @@ -272,14 +297,26 @@ local function visit_validate(root, level, lang_tree, opt, stats) end if node_name == 'ERROR' then + if ignore_parse_error(text) then + return + end -- Store the raw text to give context to the bug report. local sample_text = not toplevel and getbuflinestr(root, opt.buf, 3) or '[top level!]' table.insert(stats.parse_errors, sample_text) - elseif node_name == 'hotlink' or node_name == 'option' then - local _, tagname = get_tagname(root, opt.buf, true) - if not root:has_error() and not tagmap[tagname] then - invalid_tags[tagname] = vim.fs.basename(opt.fname) + elseif node_name == 'word' or node_name == 'uppercase_name' then + if spell_dict[text] then + if not invalid_spelling[text] then + invalid_spelling[text] = { vim.fs.basename(opt.fname) } + else + table.insert(invalid_spelling[text], vim.fs.basename(opt.fname)) + end end + elseif node_name == 'url' then + if text:find('http%:') then + invalid_urls[text] = vim.fs.basename(opt.fname) + end + elseif node_name == 'taglink' or node_name == 'optionlink' then + local _, _ = validate_link(root, opt.buf, opt.fname) end end @@ -296,19 +333,18 @@ local function visit_node(root, level, lang_tree, headings, opt, stats) local parent = root:parent() and root:parent():type() or nil local text = '' local toplevel = level < 1 - local function node_text() - return vim.treesitter.get_node_text(root, opt.buf) + local function node_text(node) + return vim.treesitter.get_node_text(node or root, opt.buf) end - if root:child_count() == 0 then + if root:child_count() == 0 or node_name == 'ERROR' then text = node_text() else -- Process children and join them with whitespace. for node, _ in root:iter_children() do if node:named() then local r = visit_node(node, level + 1, lang_tree, headings, opt, stats) - local ws = r == '' and '' or ((opt.old and (node:type() == 'word' or not node:named())) and getws(node, opt.buf) or ' ') - text = string.format('%s%s%s', text, ws, r) + text = string.format('%s%s', text, r) end end end @@ -316,82 +352,112 @@ local function visit_node(root, level, lang_tree, headings, opt, stats) if node_name == 'help_file' then -- root node return text + elseif node_name == 'url' then + return ('%s'):format(trimmed, trimmed) elseif node_name == 'word' or node_name == 'uppercase_name' then - if parent == 'headline' then - -- Start a new heading item, or update the current one. - local n = (prev == nil or #headings == 0) and #headings + 1 or #headings - headings[n] = string.format('%s%s', headings[n] and headings[n]..' ' or '', text) - end - return html_esc(text) - elseif node_name == 'headline' then - return ('

%s

\n'):format(to_heading_tag(headings[#headings]), text) + elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then + if is_noise(text, stats.noise_lines) then + return '' -- Discard common "noise" lines. + end + -- Remove "===" and tags from ToC text. + local hname = (node_text():gsub('%-%-%-%-+', ''):gsub('%=%=%=%=+', ''):gsub('%*.*%*', '')) + if node_name == 'h1' or #headings == 0 then + table.insert(headings, { name = hname, subheadings = {}, }) + else + table.insert(headings[#headings].subheadings, { name = hname, subheadings = {}, }) + end + local el = node_name == 'h1' and 'h2' or 'h3' + return ('<%s class="help-heading">%s\n'):format(to_heading_tag(hname), el, text, el) elseif node_name == 'column_heading' or node_name == 'column_name' then - return ('

%s

\n'):format(trimmed) - elseif node_name == 'line' then - -- TODO: remove these "sibling inspection" hacks once the parser provides structured info - -- about paragraphs and listitems: https://github.com/vigoux/tree-sitter-vimdoc/issues/12 - local next_text = root:next_sibling() and vim.treesitter.get_node_text(root:next_sibling(), opt.buf) or '' - local li = startswith_bullet(text) -- Listitem? - local next_li = startswith_bullet(next_text) -- Next is listitem? - -- Close the paragraph/listitem if the next sibling is not a line. - local close = (next_ ~= 'line' or next_li or is_blank(next_text)) and '\n' or '' - - -- HACK: discard common "noise" lines. - if is_noise(text) then - table.insert(stats.noise_lines, getbuflinestr(root, opt.buf, 0)) - return (opt.old or prev ~= 'line') and '' or close + if root:has_error() then + return text + end + return ('
%s
'):format(trimmed) + elseif node_name == 'block' then + if is_blank(text) then + return '' end - if opt.old then - -- XXX: Treat old docs as preformatted. Until those docs are "fixed" or we get better info - -- from tree-sitter-vimdoc, this avoids broken layout for legacy docs. - return ('
%s
\n'):format(text) + -- XXX: Treat old docs as preformatted; random indentation is used for layout there. + return ('
%s
\n'):format(text) end - - if li then - return string.format('
%s%s', trim_bullet(expandtabs(text)), close) + return string.format('
\n%s\n
\n', text) + elseif node_name == 'line' then + local sib = root:prev_sibling() + local sib_last = sib and sib:named_child(sib:named_child_count() - 1) + local in_li = false + + -- XXX: parser bug: (codeblock) without terminating "<" consumes first char of the next (line). Recover it here. + local recovered = (sib_last and sib_last:type() == 'codeblock') and node_text(root:prev_sibling()):sub(-1) or '' + recovered = recovered == '<' and '' or html_esc(recovered) + + -- XXX: see if we are currently "in" a listitem. + while sib ~= nil and not in_li do + in_li = (sib:type() == 'line_li') + sib = sib:prev_sibling() end - if prev ~= 'line' then -- Start a new paragraph. - return string.format('
%s%s', expandtabs(text), close) + + -- Close the current listitem. + local close = (in_li and next_ ~= 'line') and '
' or '' + + if is_blank(text) or is_noise(text, stats.noise_lines) then + return close -- Discard common "noise" lines. end - -- Continue in the current paragraph/listitem. - return string.format('%s%s', expandtabs(text), close) - elseif node_name == 'hotlink' or node_name == 'option' then - local helppage, tagname = get_tagname(root, opt.buf, true) - if not root:has_error() and not tagmap[tagname] then - invalid_tags[tagname] = vim.fs.basename(opt.fname) + local div = (root:child(0) and root:child(0):type() == 'column_heading') or close ~= '' + return string.format('%s%s%s%s', recovered, div and trim(text) or text, div and '' or '\n', close) + elseif node_name == 'line_li' then + -- Close the listitem immediately if the next sibling is not a line. + local close = (next_ ~= 'line') and '
' or '' + return string.format('
%s %s', trim_bullet(text), close) + elseif node_name == 'taglink' or node_name == 'optionlink' then + if root:has_error() then + return text + end + local helppage, tagname = validate_link(root, opt.buf, opt.fname) + return (' %s'):format(helppage, url_encode(tagname), html_esc(tagname)) + elseif node_name == 'codespan' then + if root:has_error() then + return text end - return ('%s'):format(helppage, url_encode(tagname), html_esc(tagname)) - elseif node_name == 'backtick' then - return ('%s'):format(html_esc(text)) + return (' %s'):format(text) elseif node_name == 'argument' then - return ('{%s}'):format(html_esc(trimmed)) - elseif node_name == 'code_block' then - return ('
\n%s
\n'):format(html_esc(trim_indent(trim_gt_lt(text)))) + return (' {%s}'):format(trimmed) + elseif node_name == 'codeblock' then + return ('
%s
'):format(html_esc(trim_indent(trim_gt_lt(text)))) elseif node_name == 'tag' then -- anchor - local _, tagname = get_tagname(root, opt.buf, false) - local s = ('%s'):format(url_encode(tagname), trimmed) - if parent == 'headline' and prev ~= 'tag' then + if root:has_error() then + return text + end + local in_heading = (parent == 'h1' or parent == 'h2') + local cssclass = (not in_heading and get_indent(node_text()) > 8) and 'help-tag-right' or 'help-tag' + local tagname = node_text(root:child(1)) + if vim.tbl_count(stats.first_tags) < 2 then + -- First 2 tags in the doc will be anchored at the main heading. + table.insert(stats.first_tags, tagname) + return '' + end + local s = (' %s'):format(url_encode(tagname), cssclass, trimmed) + if in_heading and prev ~= 'tag' then -- Start the container for tags in a heading. -- This makes "justify-content:space-between" right-align the tags. --

foo bartag1 tag2

return string.format('%s', s) - elseif parent == 'headline' and next_ == nil then + elseif in_heading and next_ == nil then -- End the container for tags in a heading. return string.format('%s', s) end return s elseif node_name == 'ERROR' then + if ignore_parse_error(trimmed) then + return text + end + -- Store the raw text to give context to the bug report. local sample_text = not toplevel and getbuflinestr(root, opt.buf, 3) or '[top level!]' table.insert(stats.parse_errors, sample_text) - if prev == 'ERROR' then - -- Avoid trashing the text with cascading errors. - return trimmed, ('parse-error:"%s"'):format(node_text()) - end - return ('%s'):format( + return ('%s'):format( get_bug_url_vimdoc(opt.fname, opt.to_fname, sample_text), trimmed) else -- Unknown token. local sample_text = not toplevel and getbuflinestr(root, opt.buf, 3) or '[top level!]' @@ -406,8 +472,7 @@ local function get_helpfiles(include) for f, type in vim.fs.dir(dir) do if (vim.endswith(f, '.txt') and type == 'file' - and (not include or vim.tbl_contains(include, f)) - and (not exclude[f])) then + and (not include or vim.tbl_contains(include, f))) then local fullpath = vim.fn.fnamemodify(('%s/%s'):format(dir, f), ':p') table.insert(rv, fullpath) end @@ -430,6 +495,13 @@ local function get_helptags(help_dir) return m end +-- Use the help.so parser defined in the build, not whatever happens to be installed on the system. +local function ensure_runtimepath() + if not vim.o.runtimepath:find('build/lib/nvim/') then + vim.cmd[[set runtimepath^=./build/lib/nvim/]] + end +end + -- Opens `fname` in a buffer and gets a treesitter parser for the buffer contents. -- -- @returns lang_tree, bufnr @@ -437,7 +509,7 @@ local function parse_buf(fname) local buf if type(fname) == 'string' then vim.cmd('split '..vim.fn.fnameescape(fname)) -- Filename. - buf = api.nvim_get_current_buf() + buf = vim.api.nvim_get_current_buf() else buf = fname vim.cmd('sbuffer '..tostring(fname)) -- Buffer number. @@ -451,10 +523,9 @@ end -- - checks that |tag| links point to valid helptags. -- - recursively counts parse errors ("ERROR" nodes) -- --- @returns { invalid_tags: number, parse_errors: number } +-- @returns { invalid_links: number, parse_errors: number } local function validate_one(fname) local stats = { - invalid_tags = {}, parse_errors = {}, } local lang_tree, buf = parse_buf(fname) @@ -463,10 +534,7 @@ local function validate_one(fname) end lang_tree:destroy() vim.cmd.close() - return { - invalid_tags = invalid_tags, - parse_errors = stats.parse_errors, - } + return stats end -- Generates HTML from one :help file `fname` and writes the result to `to_fname`. @@ -480,9 +548,10 @@ local function gen_one(fname, to_fname, old, commit) local stats = { noise_lines = {}, parse_errors = {}, + first_tags = {}, -- Track the first few tags in doc. } local lang_tree, buf = parse_buf(fname) - local headings = {} -- Headings (for ToC). + local headings = {} -- Headings (for ToC). 2-dimensional: h1 contains h2/h3. local title = to_titlecase(basename_noext(fname)) local html = ([[ @@ -555,7 +624,12 @@ local function gen_one(fname, to_fname, old, commit) ]] - local main = ([[ + local main = '' + for _, tree in ipairs(lang_tree:trees()) do + main = main .. (visit_node(tree:root(), 0, tree, headings, { buf = buf, old = old, fname = fname, to_fname = to_fname }, stats)) + end + + main = ([[