diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/mpack/LICENSE-MIT | 22 | ||||
| -rw-r--r-- | src/mpack/conv.c | 375 | ||||
| -rw-r--r-- | src/mpack/conv.h | 55 | ||||
| -rw-r--r-- | src/mpack/lmpack.c | 1215 | ||||
| -rw-r--r-- | src/mpack/lmpack.h | 3 | ||||
| -rw-r--r-- | src/mpack/mpack_core.c | 575 | ||||
| -rw-r--r-- | src/mpack/mpack_core.h | 87 | ||||
| -rw-r--r-- | src/mpack/object.c | 195 | ||||
| -rw-r--r-- | src/mpack/object.h | 86 | ||||
| -rw-r--r-- | src/mpack/rpc.c | 331 | ||||
| -rw-r--r-- | src/mpack/rpc.h | 83 | ||||
| -rw-r--r-- | src/nvim/CMakeLists.txt | 14 | ||||
| -rw-r--r-- | src/nvim/api/buffer.c | 17 | ||||
| -rw-r--r-- | src/nvim/api/ui_events.in.h | 3 | ||||
| -rw-r--r-- | src/nvim/api/vim.c | 41 | ||||
| -rw-r--r-- | src/nvim/ascii.h | 8 | ||||
| -rw-r--r-- | src/nvim/aucmd.c | 24 | ||||
| -rw-r--r-- | src/nvim/buffer_defs.h | 2 | ||||
| -rw-r--r-- | src/nvim/channel.c | 17 | ||||
| -rw-r--r-- | src/nvim/charset.c | 77 | ||||
| -rw-r--r-- | src/nvim/charset.h | 11 | ||||
| -rw-r--r-- | src/nvim/diff.c | 2 | ||||
| -rw-r--r-- | src/nvim/edit.c | 1469 | ||||
| -rw-r--r-- | src/nvim/eval.c | 35 | ||||
| -rw-r--r-- | src/nvim/eval.lua | 2 | ||||
| -rw-r--r-- | src/nvim/eval/decode.c | 6 | ||||
| -rw-r--r-- | src/nvim/eval/funcs.c | 17 | ||||
| -rw-r--r-- | src/nvim/eval/typval.c | 3 | ||||
| -rw-r--r-- | src/nvim/event/process.c | 20 | ||||
| -rw-r--r-- | src/nvim/event/process.h | 1 | ||||
| -rw-r--r-- | src/nvim/ex_cmds.c | 1496 | ||||
| -rw-r--r-- | src/nvim/ex_docmd.c | 3387 | ||||
| -rw-r--r-- | src/nvim/ex_getln.c | 4 | ||||
| -rw-r--r-- | src/nvim/fileio.c | 1498 | ||||
| -rw-r--r-- | src/nvim/fold.c | 1114 | ||||
| -rw-r--r-- | src/nvim/fold.h | 2 | ||||
| -rw-r--r-- | src/nvim/getchar.c | 4 | ||||
| -rw-r--r-- | src/nvim/keymap.c | 12 | ||||
| -rw-r--r-- | src/nvim/lua/executor.c | 30 | ||||
| -rw-r--r-- | src/nvim/lua/vim.lua | 51 | ||||
| -rw-r--r-- | src/nvim/lua/xdiff.c | 4 | ||||
| -rw-r--r-- | src/nvim/main.c | 29 | ||||
| -rw-r--r-- | src/nvim/math.c | 38 | ||||
| -rw-r--r-- | src/nvim/mbyte.c | 808 | ||||
| -rw-r--r-- | src/nvim/mouse.c | 16 | ||||
| -rw-r--r-- | src/nvim/move.c | 11 | ||||
| -rw-r--r-- | src/nvim/normal.c | 2414 | ||||
| -rw-r--r-- | src/nvim/ops.c | 1449 | ||||
| -rw-r--r-- | src/nvim/option.c | 44 | ||||
| -rw-r--r-- | src/nvim/option_defs.h | 1 | ||||
| -rw-r--r-- | src/nvim/options.lua | 2 | ||||
| -rw-r--r-- | src/nvim/plines.c | 20 | ||||
| -rw-r--r-- | src/nvim/po/sr.po | 52 | ||||
| -rw-r--r-- | src/nvim/po/tr.po | 759 | ||||
| -rw-r--r-- | src/nvim/screen.c | 470 | ||||
| -rw-r--r-- | src/nvim/search.c | 2157 | ||||
| -rw-r--r-- | src/nvim/syntax.c | 2169 | ||||
| -rw-r--r-- | src/nvim/testdir/test_breakindent.vim | 25 | ||||
| -rw-r--r-- | src/nvim/testdir/test_display.vim | 18 | ||||
| -rw-r--r-- | src/nvim/testdir/test_eval_stuff.vim | 36 | ||||
| -rw-r--r-- | src/nvim/testdir/test_expr.vim | 11 | ||||
| -rw-r--r-- | src/nvim/testdir/test_filetype.vim | 94 | ||||
| -rw-r--r-- | src/nvim/testdir/test_functions.vim | 12 | ||||
| -rw-r--r-- | src/nvim/testdir/test_highlight.vim | 2 | ||||
| -rw-r--r-- | src/nvim/testdir/test_ins_complete.vim | 127 | ||||
| -rw-r--r-- | src/nvim/testdir/test_syntax.vim | 2 | ||||
| -rw-r--r-- | src/nvim/viml/parser/expressions.c | 4 | ||||
| -rw-r--r-- | src/nvim/window.c | 1640 | ||||
| -rw-r--r-- | src/xdiff/COPYING (renamed from src/nvim/xdiff/COPYING) | 0 | ||||
| -rw-r--r-- | src/xdiff/README.txt (renamed from src/nvim/xdiff/README.txt) | 2 | ||||
| -rw-r--r-- | src/xdiff/xdiff.h (renamed from src/nvim/xdiff/xdiff.h) | 39 | ||||
| -rw-r--r-- | src/xdiff/xdiffi.c (renamed from src/nvim/xdiff/xdiffi.c) | 176 | ||||
| -rw-r--r-- | src/xdiff/xdiffi.h (renamed from src/nvim/xdiff/xdiffi.h) | 2 | ||||
| -rw-r--r-- | src/xdiff/xemit.c (renamed from src/nvim/xdiff/xemit.c) | 36 | ||||
| -rw-r--r-- | src/xdiff/xemit.h (renamed from src/nvim/xdiff/xemit.h) | 2 | ||||
| -rw-r--r-- | src/xdiff/xhistogram.c (renamed from src/nvim/xdiff/xhistogram.c) | 16 | ||||
| -rw-r--r-- | src/xdiff/xinclude.h (renamed from src/nvim/xdiff/xinclude.h) | 8 | ||||
| -rw-r--r-- | src/xdiff/xmacros.h (renamed from src/nvim/xdiff/xmacros.h) | 2 | ||||
| -rw-r--r-- | src/xdiff/xpatience.c (renamed from src/nvim/xdiff/xpatience.c) | 53 | ||||
| -rw-r--r-- | src/xdiff/xprepare.c (renamed from src/nvim/xdiff/xprepare.c) | 0 | ||||
| -rw-r--r-- | src/xdiff/xprepare.h (renamed from src/nvim/xdiff/xprepare.h) | 2 | ||||
| -rw-r--r-- | src/xdiff/xtypes.h (renamed from src/nvim/xdiff/xtypes.h) | 2 | ||||
| -rw-r--r-- | src/xdiff/xutils.c (renamed from src/nvim/xdiff/xutils.c) | 37 | ||||
| -rw-r--r-- | src/xdiff/xutils.h (renamed from src/nvim/xdiff/xutils.h) | 2 |
84 files changed, 15271 insertions, 9916 deletions
diff --git a/src/mpack/LICENSE-MIT b/src/mpack/LICENSE-MIT new file mode 100644 index 0000000000..030ba872c5 --- /dev/null +++ b/src/mpack/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2016 Thiago de Arruda + +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. diff --git a/src/mpack/conv.c b/src/mpack/conv.c new file mode 100644 index 0000000000..203b13fadb --- /dev/null +++ b/src/mpack/conv.c @@ -0,0 +1,375 @@ +#include "conv.h" + +static int mpack_fits_single(double v); +static mpack_value_t mpack_pack_ieee754(double v, unsigned m, unsigned e); +static int mpack_is_be(void) FPURE; +static double mpack_fmod_pow2_32(double a); + + +#define POW2(n) \ + ((double)(1 << (n / 2)) * (double)(1 << (n / 2)) * (double)(1 << (n % 2))) + +#define MPACK_SWAP_VALUE(val) \ + do { \ + mpack_uint32_t lo = val.lo; \ + val.lo = val.hi; \ + val.hi = lo; \ + } while (0) + +MPACK_API mpack_token_t mpack_pack_nil(void) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_NIL; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_boolean(unsigned v) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_BOOLEAN; + rv.data.value.lo = v ? 1 : 0; + rv.data.value.hi = 0; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_uint(mpack_uintmax_t v) +{ + mpack_token_t rv; + rv.data.value.lo = v & 0xffffffff; + rv.data.value.hi = (mpack_uint32_t)((v >> 31) >> 1); + rv.type = MPACK_TOKEN_UINT; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_sint(mpack_sintmax_t v) +{ + if (v < 0) { + mpack_token_t rv; + mpack_uintmax_t tc = -((mpack_uintmax_t)(v + 1)) + 1; + tc = ~tc + 1; + rv = mpack_pack_uint(tc); + rv.type = MPACK_TOKEN_SINT; + return rv; + } + + return mpack_pack_uint((mpack_uintmax_t)v); +} + +MPACK_API mpack_token_t mpack_pack_float_compat(double v) +{ + /* ieee754 single-precision limits to determine if "v" can be fully + * represented in 4 bytes */ + mpack_token_t rv; + + if (mpack_fits_single(v)) { + rv.length = 4; + rv.data.value = mpack_pack_ieee754(v, 23, 8); + } else { + rv.length = 8; + rv.data.value = mpack_pack_ieee754(v, 52, 11); + } + + rv.type = MPACK_TOKEN_FLOAT; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_float_fast(double v) +{ + /* ieee754 single-precision limits to determine if "v" can be fully + * represented in 4 bytes */ + mpack_token_t rv; + + if (mpack_fits_single(v)) { + union { + float f; + mpack_uint32_t m; + } conv; + conv.f = (float)v; + rv.length = 4; + rv.data.value.lo = conv.m; + rv.data.value.hi = 0; + } else { + union { + double d; + mpack_value_t m; + } conv; + conv.d = v; + rv.length = 8; + rv.data.value = conv.m; + if (mpack_is_be()) { + MPACK_SWAP_VALUE(rv.data.value); + } + } + + rv.type = MPACK_TOKEN_FLOAT; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_number(double v) +{ + mpack_token_t tok; + double vabs; + vabs = v < 0 ? -v : v; + assert(v <= 9007199254740991. && v >= -9007199254740991.); + tok.data.value.hi = (mpack_uint32_t)(vabs / POW2(32)); + tok.data.value.lo = (mpack_uint32_t)mpack_fmod_pow2_32(vabs); + + if (v < 0) { + /* Compute the two's complement */ + tok.type = MPACK_TOKEN_SINT; + tok.data.value.hi = ~tok.data.value.hi; + tok.data.value.lo = ~tok.data.value.lo + 1; + if (!tok.data.value.lo) tok.data.value.hi++; + if (tok.data.value.lo == 0 && tok.data.value.hi == 0) tok.length = 1; + else if (tok.data.value.lo < 0x80000000) tok.length = 8; + else if (tok.data.value.lo < 0xffff7fff) tok.length = 4; + else if (tok.data.value.lo < 0xffffff7f) tok.length = 2; + else tok.length = 1; + } else { + tok.type = MPACK_TOKEN_UINT; + if (tok.data.value.hi) tok.length = 8; + else if (tok.data.value.lo > 0xffff) tok.length = 4; + else if (tok.data.value.lo > 0xff) tok.length = 2; + else tok.length = 1; + } + + if (mpack_unpack_number(tok) != v) { + return mpack_pack_float(v); + } + + return tok; +} + +MPACK_API mpack_token_t mpack_pack_chunk(const char *p, mpack_uint32_t l) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_CHUNK; + rv.data.chunk_ptr = p; + rv.length = l; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_str(mpack_uint32_t l) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_STR; + rv.length = l; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_bin(mpack_uint32_t l) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_BIN; + rv.length = l; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_ext(int t, mpack_uint32_t l) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_EXT; + rv.length = l; + rv.data.ext_type = t; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_array(mpack_uint32_t l) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_ARRAY; + rv.length = l; + return rv; +} + +MPACK_API mpack_token_t mpack_pack_map(mpack_uint32_t l) +{ + mpack_token_t rv; + rv.type = MPACK_TOKEN_MAP; + rv.length = l; + return rv; +} + +MPACK_API bool mpack_unpack_boolean(mpack_token_t t) +{ + return t.data.value.lo || t.data.value.hi; +} + +MPACK_API mpack_uintmax_t mpack_unpack_uint(mpack_token_t t) +{ + return (((mpack_uintmax_t)t.data.value.hi << 31) << 1) | t.data.value.lo; +} + +/* unpack signed integer without relying on two's complement as internal + * representation */ +MPACK_API mpack_sintmax_t mpack_unpack_sint(mpack_token_t t) +{ + mpack_uint32_t hi = t.data.value.hi; + mpack_uint32_t lo = t.data.value.lo; + mpack_uintmax_t rv = lo; + assert(t.length <= sizeof(mpack_sintmax_t)); + + if (t.length == 8) { + rv |= (((mpack_uintmax_t)hi) << 31) << 1; + } + /* reverse the two's complement so that lo/hi contain the absolute value. + * note that we have to mask ~rv so that it reflects the two's complement + * of the appropriate byte length */ + rv = (~rv & (((mpack_uintmax_t)1 << ((t.length * 8) - 1)) - 1)) + 1; + /* negate and return the absolute value, making sure mpack_sintmax_t can + * represent the positive cast. */ + return -((mpack_sintmax_t)(rv - 1)) - 1; +} + +MPACK_API double mpack_unpack_float_compat(mpack_token_t t) +{ + mpack_uint32_t sign; + mpack_sint32_t exponent, bias; + unsigned mantbits; + unsigned expbits; + double mant; + + if (t.data.value.lo == 0 && t.data.value.hi == 0) + /* nothing to do */ + return 0; + + if (t.length == 4) mantbits = 23, expbits = 8; + else mantbits = 52, expbits = 11; + bias = (1 << (expbits - 1)) - 1; + + /* restore sign/exponent/mantissa */ + if (mantbits == 52) { + sign = t.data.value.hi >> 31; + exponent = (t.data.value.hi >> 20) & ((1 << 11) - 1); + mant = (t.data.value.hi & ((1 << 20) - 1)) * POW2(32); + mant += t.data.value.lo; + } else { + sign = t.data.value.lo >> 31; + exponent = (t.data.value.lo >> 23) & ((1 << 8) - 1); + mant = t.data.value.lo & ((1 << 23) - 1); + } + + mant /= POW2(mantbits); + if (exponent) mant += 1.0; /* restore leading 1 */ + else exponent = 1; /* subnormal */ + exponent -= bias; + + /* restore original value */ + while (exponent > 0) mant *= 2.0, exponent--; + while (exponent < 0) mant /= 2.0, exponent++; + return mant * (sign ? -1 : 1); +} + +MPACK_API double mpack_unpack_float_fast(mpack_token_t t) +{ + if (t.length == 4) { + union { + float f; + mpack_uint32_t m; + } conv; + conv.m = t.data.value.lo; + return conv.f; + } else { + union { + double d; + mpack_value_t m; + } conv; + conv.m = t.data.value; + + if (mpack_is_be()) { + MPACK_SWAP_VALUE(conv.m); + } + + return conv.d; + } +} + +MPACK_API double mpack_unpack_number(mpack_token_t t) +{ + double rv; + mpack_uint32_t hi, lo; + if (t.type == MPACK_TOKEN_FLOAT) return mpack_unpack_float(t); + assert(t.type == MPACK_TOKEN_UINT || t.type == MPACK_TOKEN_SINT); + hi = t.data.value.hi; + lo = t.data.value.lo; + if (t.type == MPACK_TOKEN_SINT) { + /* same idea as mpack_unpack_sint, except here we shouldn't rely on + * mpack_uintmax_t having 64-bits, operating on the 32-bit words separately. + */ + if (!hi) { + assert(t.length <= 4); + hi = 0; + lo = (~lo & (((mpack_uint32_t)1 << ((t.length * 8) - 1)) - 1)); + } else { + hi = ~hi; + lo = ~lo; + } + lo++; + if (!lo) hi++; + } + rv = (double)lo + POW2(32) * hi; + return t.type == MPACK_TOKEN_SINT ? -rv : rv; +} + +static int mpack_fits_single(double v) +{ + return (float)v == v; +} + +static mpack_value_t mpack_pack_ieee754(double v, unsigned mantbits, + unsigned expbits) +{ + mpack_value_t rv = {0, 0}; + mpack_sint32_t exponent, bias = (1 << (expbits - 1)) - 1; + mpack_uint32_t sign; + double mant; + + if (v == 0) { + rv.lo = 0; + rv.hi = 0; + goto end; + } + + if (v < 0) sign = 1, mant = -v; + else sign = 0, mant = v; + + exponent = 0; + while (mant >= 2.0) mant /= 2.0, exponent++; + while (mant < 1.0 && exponent > -(bias - 1)) mant *= 2.0, exponent--; + + if (mant < 1.0) exponent = -bias; /* subnormal value */ + else mant = mant - 1.0; /* remove leading 1 */ + exponent += bias; + mant *= POW2(mantbits); + + if (mantbits == 52) { + rv.hi = (mpack_uint32_t)(mant / POW2(32)); + rv.lo = (mpack_uint32_t)(mant - rv.hi * POW2(32)); + rv.hi |= ((mpack_uint32_t)exponent << 20) | (sign << 31); + } else if (mantbits == 23) { + rv.hi = 0; + rv.lo = (mpack_uint32_t)mant; + rv.lo |= ((mpack_uint32_t)exponent << 23) | (sign << 31); + } + +end: + return rv; +} + +static int mpack_is_be(void) +{ + union { + mpack_uint32_t i; + char c[sizeof(mpack_uint32_t)]; + } test; + + test.i = 1; + return test.c[0] == 0; +} + +/* this simplified version of `fmod` that returns the remainder of double + * division by 0xffffffff, which is enough for our purposes */ +static double mpack_fmod_pow2_32(double a) +{ + return a - ((double)(mpack_uint32_t)(a / POW2(32)) * POW2(32)); +} diff --git a/src/mpack/conv.h b/src/mpack/conv.h new file mode 100644 index 0000000000..71f14a067e --- /dev/null +++ b/src/mpack/conv.h @@ -0,0 +1,55 @@ +#ifndef MPACK_CONV_H +#define MPACK_CONV_H + +#include "mpack_core.h" + +#if ULLONG_MAX == 0xffffffffffffffff +typedef long long mpack_sintmax_t; +typedef unsigned long long mpack_uintmax_t; +#elif UINT64_MAX == 0xffffffffffffffff +typedef int64_t mpack_sintmax_t; +typedef uint64_t mpack_uintmax_t; +#else +typedef mpack_sint32_t mpack_sintmax_t; +typedef mpack_uint32_t mpack_uintmax_t; +#endif + +#ifndef bool +# define bool unsigned +#endif + +MPACK_API mpack_token_t mpack_pack_nil(void) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_boolean(unsigned v) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_uint(mpack_uintmax_t v) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_sint(mpack_sintmax_t v) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_float_compat(double v) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_float_fast(double v) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_number(double v) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_chunk(const char *p, mpack_uint32_t l) + FUNUSED FPURE FNONULL; +MPACK_API mpack_token_t mpack_pack_str(mpack_uint32_t l) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_bin(mpack_uint32_t l) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_ext(int type, mpack_uint32_t l) + FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_array(mpack_uint32_t l) FUNUSED FPURE; +MPACK_API mpack_token_t mpack_pack_map(mpack_uint32_t l) FUNUSED FPURE; +MPACK_API bool mpack_unpack_boolean(mpack_token_t t) FUNUSED FPURE; +MPACK_API mpack_uintmax_t mpack_unpack_uint(mpack_token_t t) FUNUSED FPURE; +MPACK_API mpack_sintmax_t mpack_unpack_sint(mpack_token_t t) FUNUSED FPURE; +MPACK_API double mpack_unpack_float_fast(mpack_token_t t) FUNUSED FPURE; +MPACK_API double mpack_unpack_float_compat(mpack_token_t t) FUNUSED FPURE; +MPACK_API double mpack_unpack_number(mpack_token_t t) FUNUSED FPURE; + +/* The mpack_{pack,unpack}_float_fast functions should work in 99% of the + * platforms. When compiling for a platform where floats don't use ieee754 as + * the internal format, pass + * -Dmpack_{pack,unpack}_float=mpack_{pack,unpack}_float_compat to the + * compiler.*/ +#ifndef mpack_pack_float +# define mpack_pack_float mpack_pack_float_fast +#endif +#ifndef mpack_unpack_float +# define mpack_unpack_float mpack_unpack_float_fast +#endif + +#endif /* MPACK_CONV_H */ diff --git a/src/mpack/lmpack.c b/src/mpack/lmpack.c new file mode 100644 index 0000000000..99207246c8 --- /dev/null +++ b/src/mpack/lmpack.c @@ -0,0 +1,1215 @@ +/* + * This module exports three classes, and each instance of those classes has its + * own private registry for temporary reference storage(keeping state between + * calls). A private registry makes managing memory much easier since all we + * have to do is call luaL_unref passing the registry reference when the + * instance is collected by the __gc metamethod. + * + * This private registry is manipulated with `lmpack_ref` / `lmpack_unref` / + * `lmpack_geti`, which are analogous to `luaL_ref` / `luaL_unref` / + * `lua_rawgeti` but operate on the private registry passed as argument. + * + * In order to simplify debug registry leaks during normal operation(with the + * leak_test.lua script), these `lmpack_*` registry functions will target the + * normal lua registry when MPACK_DEBUG_REGISTRY_LEAK is defined during + * compilation. + */ +#define LUA_LIB +#include <limits.h> +#include <stdlib.h> +#include <string.h> +#include <stdio.h> + +#include <lauxlib.h> +#include <lua.h> +#include <luaconf.h> + +#include "nvim/macros.h" + +#include "lmpack.h" + +#include "rpc.h" + +#define UNPACKER_META_NAME "mpack.Unpacker" +#define PACKER_META_NAME "mpack.Packer" +#define SESSION_META_NAME "mpack.Session" +#define NIL_NAME "mpack.NIL" +#define EMPTY_DICT_NAME "mpack.empty_dict" + +/* + * TODO(tarruda): When targeting lua 5.3 and being compiled with `long long` + * support(not -ansi), we should make use of lua 64 bit integers for + * representing msgpack integers, since `double` can't represent the full range. + */ + +#ifndef luaL_reg +/* Taken from Lua5.1's lauxlib.h */ +#define luaL_reg luaL_Reg +#endif + +#if LUA_VERSION_NUM > 501 +#ifndef luaL_register +#define luaL_register(L,n,f) luaL_setfuncs(L,f,0) +#endif +#endif + +typedef struct { + lua_State *L; + mpack_parser_t *parser; + int reg, ext, unpacking, mtdict; + char *string_buffer; +} Unpacker; + +typedef struct { + lua_State *L; + mpack_parser_t *parser; + int reg, ext, root, packing, mtdict; + int is_bin, is_bin_fn; +} Packer; + +typedef struct { + lua_State *L; + int reg; + mpack_rpc_session_t *session; + struct { + int type; + mpack_rpc_message_t msg; + int method_or_error; + int args_or_result; + } unpacked; + int unpacker; +} Session; + +static int lmpack_ref(lua_State *L, int reg) +{ +#ifdef MPACK_DEBUG_REGISTRY_LEAK + return luaL_ref(L, LUA_REGISTRYINDEX); +#else + int rv; + lua_rawgeti(L, LUA_REGISTRYINDEX, reg); + lua_pushvalue(L, -2); + rv = luaL_ref(L, -2); + lua_pop(L, 2); + return rv; +#endif +} + +static void lmpack_unref(lua_State *L, int reg, int ref) +{ +#ifdef MPACK_DEBUG_REGISTRY_LEAK + luaL_unref(L, LUA_REGISTRYINDEX, ref); +#else + lua_rawgeti(L, LUA_REGISTRYINDEX, reg); + luaL_unref(L, -1, ref); + lua_pop(L, 1); +#endif +} + +static void lmpack_geti(lua_State *L, int reg, int ref) +{ +#ifdef MPACK_DEBUG_REGISTRY_LEAK + lua_rawgeti(L, LUA_REGISTRYINDEX, ref); +#else + lua_rawgeti(L, LUA_REGISTRYINDEX, reg); + lua_rawgeti(L, -1, ref); + lua_replace(L, -2); +#endif +} + +/* make a shallow copy of the table on stack and remove it after the copy is + * done */ +static void lmpack_shallow_copy(lua_State *L) +{ + lua_newtable(L); + lua_pushnil(L); + while (lua_next(L, -3)) { + lua_pushvalue(L, -2); + lua_insert(L, -2); + lua_settable(L, -4); + } + lua_remove(L, -2); +} + +static mpack_parser_t *lmpack_grow_parser(mpack_parser_t *parser) +{ + mpack_parser_t *old = parser; + mpack_uint32_t new_capacity = old->capacity * 2; + parser = malloc(MPACK_PARSER_STRUCT_SIZE(new_capacity)); + if (!parser) goto end; + mpack_parser_init(parser, new_capacity); + mpack_parser_copy(parser, old); + free(old); +end: + return parser; +} + +static mpack_rpc_session_t *lmpack_grow_session(mpack_rpc_session_t *session) +{ + mpack_rpc_session_t *old = session; + mpack_uint32_t new_capacity = old->capacity * 2; + session = malloc(MPACK_RPC_SESSION_STRUCT_SIZE(new_capacity)); + if (!session) goto end; + mpack_rpc_session_init(session, new_capacity); + mpack_rpc_session_copy(session, old); + free(old); +end: + return session; +} + +static Unpacker *lmpack_check_unpacker(lua_State *L, int index) +{ + return luaL_checkudata(L, index, UNPACKER_META_NAME); +} + +static Packer *lmpack_check_packer(lua_State *L, int index) +{ + return luaL_checkudata(L, index, PACKER_META_NAME); +} + +static Session *lmpack_check_session(lua_State *L, int index) +{ + return luaL_checkudata(L, index, SESSION_META_NAME); +} + +static int lmpack_isnil(lua_State *L, int index) +{ + int rv; + if (!lua_isuserdata(L, index)) return 0; + lua_getfield(L, LUA_REGISTRYINDEX, NIL_NAME); + rv = lua_rawequal(L, -1, -2); + lua_pop(L, 1); + return rv; +} + +static int lmpack_isunpacker(lua_State *L, int index) +{ + int rv; + if (!lua_isuserdata(L, index) || !lua_getmetatable(L, index)) return 0; + luaL_getmetatable(L, UNPACKER_META_NAME); + rv = lua_rawequal(L, -1, -2); + lua_pop(L, 2); + return rv; +} + +static void lmpack_pushnil(lua_State *L) +{ + lua_getfield(L, LUA_REGISTRYINDEX, NIL_NAME); +} + +/* adapted from + * https://github.com/antirez/lua-cmsgpack/blob/master/lua_cmsgpack.c */ +static mpack_uint32_t lmpack_objlen(lua_State *L, int *is_array) +{ + size_t len, max; + int isarr, type; + lua_Number n; +#ifndef NDEBUG + int top = lua_gettop(L); + assert(top); +#endif + + if ((type = lua_type(L, -1)) != LUA_TTABLE) { +#if LUA_VERSION_NUM >= 502 + len = lua_rawlen(L, -1); +#elif LUA_VERSION_NUM == 501 + len = lua_objlen(L, -1); +#else + #error You have either broken or too old Lua installation. This library requires Lua>=5.1 +#endif + goto end; + } + + /* count the number of keys and determine if it is an array */ + len = 0; + max = 0; + isarr = 1; + lua_pushnil(L); + + while (lua_next(L, -2)) { + lua_pop(L, 1); /* pop value */ + isarr = isarr + && lua_isnumber(L, -1) /* lua number */ + && (n = lua_tonumber(L, -1)) > 0 /* greater than 0 */ + && (size_t)n == n; /* and integer */ + max = isarr && (size_t)n > max ? (size_t)n : max; + len++; + } + + // when len==0, the caller should guess the type! + if (len > 0) { + *is_array = isarr && max == len; + } + +end: + if ((size_t)-1 > (mpack_uint32_t)-1 && len > (mpack_uint32_t)-1) + /* msgpack spec doesn't allow lengths > 32 bits */ + len = (mpack_uint32_t)-1; + assert(top == lua_gettop(L)); + return (mpack_uint32_t)len; +} + +static int lmpack_unpacker_new(lua_State *L) +{ + Unpacker *rv; + + if (lua_gettop(L) > 1) + return luaL_error(L, "expecting at most 1 table argument"); + + rv = lua_newuserdata(L, sizeof(*rv)); + rv->parser = malloc(sizeof(*rv->parser)); + if (!rv->parser) return luaL_error(L, "Failed to allocate memory"); + mpack_parser_init(rv->parser, 0); + rv->parser->data.p = rv; + rv->string_buffer = NULL; + rv->L = L; + rv->unpacking = 0; + luaL_getmetatable(L, UNPACKER_META_NAME); + lua_setmetatable(L, -2); + +#ifndef MPACK_DEBUG_REGISTRY_LEAK + lua_newtable(L); + rv->reg = luaL_ref(L, LUA_REGISTRYINDEX); +#endif + rv->ext = LUA_NOREF; + + lua_getfield(L, LUA_REGISTRYINDEX, EMPTY_DICT_NAME); + rv->mtdict = lmpack_ref(L, rv->reg); + + if (lua_istable(L, 1)) { + /* parse options */ + lua_getfield(L, 1, "ext"); + if (!lua_isnil(L, -1)) { + if (!lua_istable(L, -1)) + return luaL_error(L, "\"ext\" option must be a table"); + lmpack_shallow_copy(L); + } + rv->ext = lmpack_ref(L, rv->reg); + } + + return 1; +} + +static int lmpack_unpacker_delete(lua_State *L) +{ + Unpacker *unpacker = lmpack_check_unpacker(L, 1); + if (unpacker->ext != LUA_NOREF) + lmpack_unref(L, unpacker->reg, unpacker->ext); +#ifndef MPACK_DEBUG_REGISTRY_LEAK + luaL_unref(L, LUA_REGISTRYINDEX, unpacker->reg); +#endif + free(unpacker->parser); + return 0; +} + +static void lmpack_parse_enter(mpack_parser_t *parser, mpack_node_t *node) +{ + Unpacker *unpacker = parser->data.p; + lua_State *L = unpacker->L; + + switch (node->tok.type) { + case MPACK_TOKEN_NIL: + lmpack_pushnil(L); break; + case MPACK_TOKEN_BOOLEAN: + lua_pushboolean(L, (int)mpack_unpack_boolean(node->tok)); break; + case MPACK_TOKEN_UINT: + case MPACK_TOKEN_SINT: + case MPACK_TOKEN_FLOAT: + lua_pushnumber(L, mpack_unpack_number(node->tok)); break; + case MPACK_TOKEN_CHUNK: + assert(unpacker->string_buffer); + memcpy(unpacker->string_buffer + MPACK_PARENT_NODE(node)->pos, + node->tok.data.chunk_ptr, node->tok.length); + break; + case MPACK_TOKEN_BIN: + case MPACK_TOKEN_STR: + case MPACK_TOKEN_EXT: + unpacker->string_buffer = malloc(node->tok.length); + if (!unpacker->string_buffer) luaL_error(L, "Failed to allocate memory"); + break; + case MPACK_TOKEN_ARRAY: + case MPACK_TOKEN_MAP: + lua_newtable(L); + node->data[0].i = lmpack_ref(L, unpacker->reg); + break; + } +} + +static void lmpack_parse_exit(mpack_parser_t *parser, mpack_node_t *node) +{ + Unpacker *unpacker = parser->data.p; + lua_State *L = unpacker->L; + mpack_node_t *parent = MPACK_PARENT_NODE(node); + + switch (node->tok.type) { + case MPACK_TOKEN_BIN: + case MPACK_TOKEN_STR: + case MPACK_TOKEN_EXT: + lua_pushlstring(L, unpacker->string_buffer, node->tok.length); + free(unpacker->string_buffer); + unpacker->string_buffer = NULL; + if (node->tok.type == MPACK_TOKEN_EXT && unpacker->ext != LUA_NOREF) { + /* check if there's a handler for this type */ + lmpack_geti(L, unpacker->reg, unpacker->ext); + lua_rawgeti(L, -1, node->tok.data.ext_type); + if (lua_isfunction(L, -1)) { + /* stack: + * + * -1: ext unpacker function + * -2: ext unpackers table + * -3: ext string + * + * We want to call the ext unpacker function with the type and string + * as arguments, so push those now + */ + lua_pushinteger(L, node->tok.data.ext_type); + lua_pushvalue(L, -4); + lua_call(L, 2, 1); + /* stack: + * + * -1: returned object + * -2: ext unpackers table + * -3: ext string + */ + lua_replace(L, -3); + } else { + /* the last lua_rawgeti should have pushed nil on the stack, + * remove it */ + lua_pop(L, 1); + } + /* pop the ext unpackers table */ + lua_pop(L, 1); + } + break; + case MPACK_TOKEN_ARRAY: + case MPACK_TOKEN_MAP: + lmpack_geti(L, unpacker->reg, (int)node->data[0].i); + lmpack_unref(L, unpacker->reg, (int)node->data[0].i); + if (node->key_visited == 0 && node->tok.type == MPACK_TOKEN_MAP) { + lmpack_geti(L, unpacker->reg, unpacker->mtdict); // [table, mtdict] + lua_setmetatable(L, -2); // [table] + } + + break; + default: + break; + } + + if (parent && parent->tok.type < MPACK_TOKEN_BIN) { + /* At this point the parsed object is on the stack. Add it to the parent + * container. First put the container on the stack. */ + lmpack_geti(L, unpacker->reg, (int)parent->data[0].i); + + if (parent->tok.type == MPACK_TOKEN_ARRAY) { + /* Array, save the value on key equal to `parent->pos` */ + lua_pushnumber(L, (lua_Number)parent->pos); + lua_pushvalue(L, -3); + lua_settable(L, -3); + } else { + assert(parent->tok.type == MPACK_TOKEN_MAP); + if (parent->key_visited) { + /* save the key on the registry */ + lua_pushvalue(L, -2); + parent->data[1].i = lmpack_ref(L, unpacker->reg); + } else { + /* set the key/value pair */ + lmpack_geti(L, unpacker->reg, (int)parent->data[1].i); + lmpack_unref(L, unpacker->reg, (int)parent->data[1].i); + lua_pushvalue(L, -3); + lua_settable(L, -3); + } + } + lua_pop(L, 2); /* pop the container/object */ + } +} + +static int lmpack_unpacker_unpack_str(lua_State *L, Unpacker *unpacker, + const char **str, size_t *len) +{ + int rv; + + if (unpacker->unpacking) { + return luaL_error(L, "Unpacker instance already working. Use another " + "Unpacker or the module's \"unpack\" function if you " + "need to unpack from the ext handler"); + } + + do { + unpacker->unpacking = 1; + rv = mpack_parse(unpacker->parser, str, len, lmpack_parse_enter, + lmpack_parse_exit); + unpacker->unpacking = 0; + + if (rv == MPACK_NOMEM) { + unpacker->parser = lmpack_grow_parser(unpacker->parser); + if (!unpacker->parser) { + unpacker->unpacking = 0; + return luaL_error(L, "failed to grow Unpacker capacity"); + } + } + } while (rv == MPACK_NOMEM); + + if (rv == MPACK_ERROR) + return luaL_error(L, "invalid msgpack string"); + + return rv; +} + +static int lmpack_unpacker_unpack(lua_State *L) +{ + int result, argc; + lua_Number startpos; + size_t len, offset; + const char *str, *str_init; + Unpacker *unpacker; + + if ((argc = lua_gettop(L)) > 3 || argc < 2) + return luaL_error(L, "expecting between 2 and 3 arguments"); + + unpacker = lmpack_check_unpacker(L, 1); + unpacker->L = L; + + str_init = str = luaL_checklstring(L, 2, &len); + startpos = lua_gettop(L) == 3 ? luaL_checknumber(L, 3) : 1; + + luaL_argcheck(L, startpos > 0, 3, + "start position must be greater than zero"); + luaL_argcheck(L, (size_t)startpos == startpos, 3, + "start position must be an integer"); + luaL_argcheck(L, (size_t)startpos <= len, 3, + "start position must be less than or equal to the input string length"); + + offset = (size_t)startpos - 1 ; + str += offset; + len -= offset; + result = lmpack_unpacker_unpack_str(L, unpacker, &str, &len); + + if (result == MPACK_EOF) + /* if we hit EOF, return nil as the object */ + lua_pushnil(L); + + /* also return the new position in the input string */ + lua_pushinteger(L, str - str_init + 1); + assert(lua_gettop(L) == argc + 2); + return 2; +} + +static int lmpack_packer_new(lua_State *L) +{ + Packer *rv; + + if (lua_gettop(L) > 1) + return luaL_error(L, "expecting at most 1 table argument"); + + rv = lua_newuserdata(L, sizeof(*rv)); + rv->parser = malloc(sizeof(*rv->parser)); + if (!rv->parser) return luaL_error(L, "failed to allocate parser memory"); + mpack_parser_init(rv->parser, 0); + rv->parser->data.p = rv; + rv->L = L; + rv->packing = 0; + rv->is_bin = 0; + rv->is_bin_fn = LUA_NOREF; + luaL_getmetatable(L, PACKER_META_NAME); + lua_setmetatable(L, -2); + +#ifndef MPACK_DEBUG_REGISTRY_LEAK + lua_newtable(L); + rv->reg = luaL_ref(L, LUA_REGISTRYINDEX); +#endif + rv->ext = LUA_NOREF; + + lua_getfield(L, LUA_REGISTRYINDEX, EMPTY_DICT_NAME); + rv->mtdict = lmpack_ref(L, rv->reg); + + if (lua_istable(L, 1)) { + /* parse options */ + lua_getfield(L, 1, "ext"); + if (!lua_isnil(L, -1)) { + if (!lua_istable(L, -1)) + return luaL_error(L, "\"ext\" option must be a table"); + lmpack_shallow_copy(L); + } + rv->ext = lmpack_ref(L, rv->reg); + lua_getfield(L, 1, "is_bin"); + if (!lua_isnil(L, -1)) { + if (!lua_isboolean(L, -1) && !lua_isfunction(L, -1)) + return luaL_error(L, + "\"is_bin\" option must be a boolean or function"); + rv->is_bin = lua_toboolean(L, -1); + if (lua_isfunction(L, -1)) rv->is_bin_fn = lmpack_ref(L, rv->reg); + else lua_pop(L, 1); + } else { + lua_pop(L, 1); + } + + } + + return 1; +} + +static int lmpack_packer_delete(lua_State *L) +{ + Packer *packer = lmpack_check_packer(L, 1); + if (packer->ext != LUA_NOREF) + lmpack_unref(L, packer->reg, packer->ext); +#ifndef MPACK_DEBUG_REGISTRY_LEAK + luaL_unref(L, LUA_REGISTRYINDEX, packer->reg); +#endif + free(packer->parser); + return 0; +} + +static void lmpack_unparse_enter(mpack_parser_t *parser, mpack_node_t *node) +{ + int type; + Packer *packer = parser->data.p; + lua_State *L = packer->L; + mpack_node_t *parent = MPACK_PARENT_NODE(node); + + if (parent) { + /* get the parent */ + lmpack_geti(L, packer->reg, (int)parent->data[0].i); + + if (parent->tok.type > MPACK_TOKEN_MAP) { + /* strings are a special case, they are packed as single child chunk + * node */ + const char *str = lua_tolstring(L, -1, NULL); + node->tok = mpack_pack_chunk(str, parent->tok.length); + lua_pop(L, 1); + return; + } + + if (parent->tok.type == MPACK_TOKEN_ARRAY) { + /* push the next index */ + lua_pushnumber(L, (lua_Number)(parent->pos + 1)); + /* push the element */ + lua_gettable(L, -2); + } else if (parent->tok.type == MPACK_TOKEN_MAP) { + int result; + /* push the previous key */ + lmpack_geti(L, packer->reg, (int)parent->data[1].i); + /* push the pair */ + result = lua_next(L, -2); + assert(result); /* should not be here if the map was fully processed */ + if (parent->key_visited) { + /* release the current key */ + lmpack_unref(L, packer->reg, (int)parent->data[1].i); + /* push key to the top */ + lua_pushvalue(L, -2); + /* set the key for the next iteration, leaving value on top */ + parent->data[1].i = lmpack_ref(L, packer->reg); + /* replace key by the value */ + lua_replace(L, -2); + } else { + /* pop value */ + lua_pop(L, 1); + } + } + /* remove parent, leaving only the object which will be serialized */ + lua_remove(L, -2); + } else { + /* root object */ + lmpack_geti(L, packer->reg, packer->root); + } + + type = lua_type(L, -1); + + switch (type) { + case LUA_TBOOLEAN: + node->tok = mpack_pack_boolean((unsigned)lua_toboolean(L, -1)); + break; + case LUA_TNUMBER: + node->tok = mpack_pack_number(lua_tonumber(L, -1)); + break; + case LUA_TSTRING: { + int is_bin = packer->is_bin; + if (is_bin && packer->is_bin_fn != LUA_NOREF) { + lmpack_geti(L, packer->reg, packer->is_bin_fn); + lua_pushvalue(L, -2); + lua_call(L, 1, 1); + is_bin = lua_toboolean(L, -1); + lua_pop(L, 1); + } + if (is_bin) node->tok = mpack_pack_bin(lmpack_objlen(L, NULL)); + else node->tok = mpack_pack_str(lmpack_objlen(L, NULL)); + break; + } + case LUA_TTABLE: { + mpack_uint32_t len; + mpack_node_t *n; + + int has_meta = lua_getmetatable(L, -1); + if (packer->ext != LUA_NOREF && has_meta) { + /* check if there's a handler for this metatable */ + lmpack_geti(L, packer->reg, packer->ext); + lua_pushvalue(L, -2); + lua_gettable(L, -2); + if (lua_isfunction(L, -1)) { + lua_Number ext = -1; + /* stack: + * + * -1: ext packer function + * -2: ext packers table + * -3: metatable + * -4: original object + * + * We want to call the ext packer function with the original object as + * argument, so push it on the top + */ + lua_pushvalue(L, -4); + /* handler should return type code and string */ + lua_call(L, 1, 2); + if (!lua_isnumber(L, -2) || (ext = lua_tonumber(L, -2)) < 0 + || ext > 127 || (int)ext != ext) + luaL_error(L, + "the first result from ext packer must be an integer " + "between 0 and 127"); + if (!lua_isstring(L, -1)) + luaL_error(L, + "the second result from ext packer must be a string"); + node->tok = mpack_pack_ext((int)ext, lmpack_objlen(L, NULL)); + /* stack: + * + * -1: ext string + * -2: ext type + * -3: ext packers table + * -4: metatable + * -5: original table + * + * We want to leave only the returned ext string, so + * replace -5 with the string and pop 3 + */ + lua_replace(L, -5); + lua_pop(L, 3); + break; /* done */ + } else { + /* stack: + * + * -1: ext packers table + * -2: metatable + * -3: original table + * + * We want to leave only the original table and metatable since they + * will be handled below, so pop 1 + */ + lua_pop(L, 1); + } + } + + int is_array = 1; + if (has_meta) { + // stack: [table, metatable] + if (packer->mtdict != LUA_NOREF) { + lmpack_geti(L, packer->reg, packer->mtdict); // [table, metatable, mtdict] + is_array = !lua_rawequal(L, -1, -2); + lua_pop(L, 1); // [table, metatable]; + } + lua_pop(L, 1); // [table] + } + + /* check for cycles */ + n = node; + while ((n = MPACK_PARENT_NODE(n))) { + lmpack_geti(L, packer->reg, (int)n->data[0].i); + if (lua_rawequal(L, -1, -2)) { + /* break out of cycles with NIL */ + node->tok = mpack_pack_nil(); + lua_pop(L, 2); + lmpack_pushnil(L); + goto end; + } + lua_pop(L, 1); + } + + len = lmpack_objlen(L, &is_array); + if (is_array) { + node->tok = mpack_pack_array(len); + } else { + node->tok = mpack_pack_map(len); + /* save nil as the previous key to start iteration */ + node->data[1].i = LUA_REFNIL; + } + break; + } + case LUA_TUSERDATA: + if (lmpack_isnil(L, -1)) { + node->tok = mpack_pack_nil(); + break; + } + FALLTHROUGH; + default: + { + /* #define FMT */ + char errmsg[50]; + snprintf(errmsg, 50, "can't serialize object of type %d", type); + luaL_error(L, errmsg); + } + } + +end: + node->data[0].i = lmpack_ref(L, packer->reg); +} + +static void lmpack_unparse_exit(mpack_parser_t *parser, mpack_node_t *node) +{ + Packer *packer = parser->data.p; + lua_State *L = packer->L; + if (node->tok.type != MPACK_TOKEN_CHUNK) { + /* release the object */ + lmpack_unref(L, packer->reg, (int)node->data[0].i); + if (node->tok.type == MPACK_TOKEN_MAP) + lmpack_unref(L, packer->reg, (int)node->data[1].i); + } +} + +static int lmpack_packer_pack(lua_State *L) +{ + char *b; + size_t bl; + int result, argc; + Packer *packer; + luaL_Buffer buffer; + + if ((argc = lua_gettop(L)) != 2) + return luaL_error(L, "expecting exactly 2 arguments"); + + packer = lmpack_check_packer(L, 1); + packer->L = L; + packer->root = lmpack_ref(L, packer->reg); + luaL_buffinit(L, &buffer); + b = luaL_prepbuffer(&buffer); + bl = LUAL_BUFFERSIZE; + + if (packer->packing) { + return luaL_error(L, "Packer instance already working. Use another Packer " + "or the module's \"pack\" function if you need to " + "pack from the ext handler"); + } + + do { + size_t bl_init = bl; + packer->packing = 1; + result = mpack_unparse(packer->parser, &b, &bl, lmpack_unparse_enter, + lmpack_unparse_exit); + packer->packing = 0; + + if (result == MPACK_NOMEM) { + packer->parser = lmpack_grow_parser(packer->parser); + if (!packer->parser) { + packer->packing = 0; + return luaL_error(L, "Failed to grow Packer capacity"); + } + } + + luaL_addsize(&buffer, bl_init - bl); + + if (!bl) { + /* buffer empty, resize */ + b = luaL_prepbuffer(&buffer); + bl = LUAL_BUFFERSIZE; + } + } while (result == MPACK_EOF || result == MPACK_NOMEM); + + lmpack_unref(L, packer->reg, packer->root); + luaL_pushresult(&buffer); + assert(lua_gettop(L) == argc); + return 1; +} + +static int lmpack_session_new(lua_State *L) +{ + Session *rv = lua_newuserdata(L, sizeof(*rv)); + rv->session = malloc(sizeof(*rv->session)); + if (!rv->session) return luaL_error(L, "Failed to allocate memory"); + mpack_rpc_session_init(rv->session, 0); + rv->L = L; + luaL_getmetatable(L, SESSION_META_NAME); + lua_setmetatable(L, -2); +#ifndef MPACK_DEBUG_REGISTRY_LEAK + lua_newtable(L); + rv->reg = luaL_ref(L, LUA_REGISTRYINDEX); +#endif + rv->unpacker = LUA_REFNIL; + rv->unpacked.args_or_result = LUA_NOREF; + rv->unpacked.method_or_error = LUA_NOREF; + rv->unpacked.type = MPACK_EOF; + + if (lua_istable(L, 1)) { + /* parse options */ + lua_getfield(L, 1, "unpack"); + if (!lmpack_isunpacker(L, -1)) { + return luaL_error(L, + "\"unpack\" option must be a " UNPACKER_META_NAME " instance"); + } + rv->unpacker = lmpack_ref(L, rv->reg); + } + + return 1; +} + +static int lmpack_session_delete(lua_State *L) +{ + Session *session = lmpack_check_session(L, 1); + lmpack_unref(L, session->reg, session->unpacker); +#ifndef MPACK_DEBUG_REGISTRY_LEAK + luaL_unref(L, LUA_REGISTRYINDEX, session->reg); +#endif + free(session->session); + return 0; +} + +static int lmpack_session_receive(lua_State *L) +{ + int argc, done, rcount = 3; + lua_Number startpos; + size_t len; + const char *str, *str_init; + Session *session; + Unpacker *unpacker = NULL; + + if ((argc = lua_gettop(L)) > 3 || argc < 2) + return luaL_error(L, "expecting between 2 and 3 arguments"); + + session = lmpack_check_session(L, 1); + str_init = str = luaL_checklstring(L, 2, &len); + startpos = lua_gettop(L) == 3 ? luaL_checknumber(L, 3) : 1; + + luaL_argcheck(L, startpos > 0, 3, + "start position must be greater than zero"); + luaL_argcheck(L, (size_t)startpos == startpos, 3, + "start position must be an integer"); + luaL_argcheck(L, (size_t)startpos <= len, 3, + "start position must be less than or equal to the input string length"); + + str += (size_t)startpos - 1; + + if (session->unpacker != LUA_REFNIL) { + lmpack_geti(L, session->reg, session->unpacker); + unpacker = lmpack_check_unpacker(L, -1); + unpacker->L = L; + rcount += 2; + lua_pop(L, 1); + } + + for (;;) { + int result; + + if (session->unpacked.type == MPACK_EOF) { + session->unpacked.type = + mpack_rpc_receive(session->session, &str, &len, &session->unpacked.msg); + + if (!unpacker || session->unpacked.type == MPACK_EOF) + break; + } + + result = lmpack_unpacker_unpack_str(L, unpacker, &str, &len); + + if (result == MPACK_EOF) break; + + if (session->unpacked.method_or_error == LUA_NOREF) { + session->unpacked.method_or_error = lmpack_ref(L, session->reg); + } else { + session->unpacked.args_or_result = lmpack_ref(L, session->reg); + break; + } + } + + done = session->unpacked.type != MPACK_EOF + && (session->unpacked.args_or_result != LUA_NOREF || !unpacker); + + if (!done) { + lua_pushnil(L); + lua_pushnil(L); + if (unpacker) { + lua_pushnil(L); + lua_pushnil(L); + } + goto end; + } + + switch (session->unpacked.type) { + case MPACK_RPC_REQUEST: + lua_pushstring(L, "request"); + lua_pushnumber(L, session->unpacked.msg.id); + break; + case MPACK_RPC_RESPONSE: + lua_pushstring(L, "response"); + lmpack_geti(L, session->reg, (int)session->unpacked.msg.data.i); + break; + case MPACK_RPC_NOTIFICATION: + lua_pushstring(L, "notification"); + lua_pushnil(L); + break; + default: + /* In most cases the only sane thing to do when receiving invalid + * msgpack-rpc is to close the connection, so handle all errors with + * this generic message. Later may add more detailed information. */ + return luaL_error(L, "invalid msgpack-rpc string"); + } + + session->unpacked.type = MPACK_EOF; + + if (unpacker) { + lmpack_geti(L, session->reg, session->unpacked.method_or_error); + lmpack_geti(L, session->reg, session->unpacked.args_or_result); + lmpack_unref(L, session->reg, session->unpacked.method_or_error); + lmpack_unref(L, session->reg, session->unpacked.args_or_result); + session->unpacked.method_or_error = LUA_NOREF; + session->unpacked.args_or_result = LUA_NOREF; + } + +end: + lua_pushinteger(L, str - str_init + 1); + return rcount; +} + +static int lmpack_session_request(lua_State *L) +{ + int result; + char buf[16], *b = buf; + size_t bl = sizeof(buf); + Session *session; + mpack_data_t data; + + if (lua_gettop(L) > 2 || lua_gettop(L) < 1) + return luaL_error(L, "expecting 1 or 2 arguments"); + + session = lmpack_check_session(L, 1); + data.i = lua_isnoneornil(L, 2) ? LUA_NOREF : lmpack_ref(L, session->reg); + do { + result = mpack_rpc_request(session->session, &b, &bl, data); + if (result == MPACK_NOMEM) { + session->session = lmpack_grow_session(session->session); + if (!session->session) + return luaL_error(L, "Failed to grow Session capacity"); + } + } while (result == MPACK_NOMEM); + + assert(result == MPACK_OK); + lua_pushlstring(L, buf, sizeof(buf) - bl); + return 1; +} + +static int lmpack_session_reply(lua_State *L) +{ + int result; + char buf[16], *b = buf; + size_t bl = sizeof(buf); + Session *session; + lua_Number id; + + if (lua_gettop(L) != 2) + return luaL_error(L, "expecting exactly 2 arguments"); + + session = lmpack_check_session(L, 1); + id = lua_tonumber(L, 2); + luaL_argcheck(L, ((size_t)id == id && id >= 0 && id <= 0xffffffff), 2, + "invalid request id"); + result = mpack_rpc_reply(session->session, &b, &bl, (mpack_uint32_t)id); + assert(result == MPACK_OK); + lua_pushlstring(L, buf, sizeof(buf) - bl); + return 1; +} + +static int lmpack_session_notify(lua_State *L) +{ + int result; + char buf[16], *b = buf; + size_t bl = sizeof(buf); + Session *session; + + if (lua_gettop(L) != 1) + return luaL_error(L, "expecting exactly 1 argument"); + + session = lmpack_check_session(L, 1); + result = mpack_rpc_notify(session->session, &b, &bl); + assert(result == MPACK_OK); + lua_pushlstring(L, buf, sizeof(buf) - bl); + return 1; +} + +static int lmpack_nil_tostring(lua_State* L) +{ + lua_pushfstring(L, NIL_NAME, lua_topointer(L, 1)); + return 1; +} + +static int lmpack_unpack(lua_State *L) +{ + int result; + size_t len; + const char *str; + Unpacker unpacker; + mpack_parser_t parser; + + if (lua_gettop(L) != 1) + return luaL_error(L, "expecting exactly 1 argument"); + + str = luaL_checklstring(L, 1, &len); + + /* initialize unpacker */ + lua_newtable(L); + unpacker.reg = luaL_ref(L, LUA_REGISTRYINDEX); + unpacker.ext = LUA_NOREF; + unpacker.parser = &parser; + mpack_parser_init(unpacker.parser, 0); + unpacker.parser->data.p = &unpacker; + unpacker.string_buffer = NULL; + unpacker.L = L; + + lua_getfield(L, LUA_REGISTRYINDEX, EMPTY_DICT_NAME); + unpacker.mtdict = lmpack_ref(L, unpacker.reg); + + result = mpack_parse(&parser, &str, &len, lmpack_parse_enter, + lmpack_parse_exit); + + luaL_unref(L, LUA_REGISTRYINDEX, unpacker.reg); + + if (result == MPACK_NOMEM) + return luaL_error(L, "object was too deep to unpack"); + else if (result == MPACK_EOF) + return luaL_error(L, "incomplete msgpack string"); + else if (result == MPACK_ERROR) + return luaL_error(L, "invalid msgpack string"); + else if (result == MPACK_OK && len) + return luaL_error(L, "trailing data in msgpack string"); + + assert(result == MPACK_OK); + return 1; +} + +static int lmpack_pack(lua_State *L) +{ + char *b; + size_t bl; + int result; + Packer packer; + mpack_parser_t parser; + luaL_Buffer buffer; + + if (lua_gettop(L) != 1) + return luaL_error(L, "expecting exactly 1 argument"); + + /* initialize packer */ + lua_newtable(L); + packer.reg = luaL_ref(L, LUA_REGISTRYINDEX); + packer.ext = LUA_NOREF; + packer.parser = &parser; + mpack_parser_init(packer.parser, 0); + packer.parser->data.p = &packer; + packer.is_bin = 0; + packer.L = L; + packer.root = lmpack_ref(L, packer.reg); + + lua_getfield(L, LUA_REGISTRYINDEX, EMPTY_DICT_NAME); + packer.mtdict = lmpack_ref(L, packer.reg); + + + luaL_buffinit(L, &buffer); + b = luaL_prepbuffer(&buffer); + bl = LUAL_BUFFERSIZE; + + do { + size_t bl_init = bl; + result = mpack_unparse(packer.parser, &b, &bl, lmpack_unparse_enter, + lmpack_unparse_exit); + + if (result == MPACK_NOMEM) { + lmpack_unref(L, packer.reg, packer.root); + luaL_unref(L, LUA_REGISTRYINDEX, packer.reg); + return luaL_error(L, "object was too deep to pack"); + } + + luaL_addsize(&buffer, bl_init - bl); + + if (!bl) { + /* buffer empty, resize */ + b = luaL_prepbuffer(&buffer); + bl = LUAL_BUFFERSIZE; + } + } while (result == MPACK_EOF); + + lmpack_unref(L, packer.reg, packer.root); + luaL_unref(L, LUA_REGISTRYINDEX, packer.reg); + luaL_pushresult(&buffer); + return 1; +} + +static const luaL_reg unpacker_methods[] = { + {"__call", lmpack_unpacker_unpack}, + {"__gc", lmpack_unpacker_delete}, + {NULL, NULL} +}; + +static const luaL_reg packer_methods[] = { + {"__call", lmpack_packer_pack}, + {"__gc", lmpack_packer_delete}, + {NULL, NULL} +}; + +static const luaL_reg session_methods[] = { + {"receive", lmpack_session_receive}, + {"request", lmpack_session_request}, + {"reply", lmpack_session_reply}, + {"notify", lmpack_session_notify}, + {"__gc", lmpack_session_delete}, + {NULL, NULL} +}; + +static const luaL_reg mpack_functions[] = { + {"Unpacker", lmpack_unpacker_new}, + {"Packer", lmpack_packer_new}, + {"Session", lmpack_session_new}, + {"unpack", lmpack_unpack}, + {"pack", lmpack_pack}, + {NULL, NULL} +}; + +int luaopen_mpack(lua_State *L) +{ + /* Unpacker */ + luaL_newmetatable(L, UNPACKER_META_NAME); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_register(L, NULL, unpacker_methods); + lua_pop(L, 1); + /* Packer */ + luaL_newmetatable(L, PACKER_META_NAME); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_register(L, NULL, packer_methods); + lua_pop(L, 1); + /* Session */ + luaL_newmetatable(L, SESSION_META_NAME); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_register(L, NULL, session_methods); + lua_pop(L, 1); + /* NIL */ + /* Check if NIL is already stored in the registry */ + lua_getfield(L, LUA_REGISTRYINDEX, NIL_NAME); + /* If it isn't, create it */ + if (lua_isnil(L, -1)) { + /* Use a constant userdata to represent NIL */ + (void)lua_newuserdata(L, sizeof(void *)); + /* Create a metatable for NIL userdata */ + lua_createtable(L, 0, 1); + lua_pushstring(L, "__tostring"); + lua_pushcfunction(L, lmpack_nil_tostring); + lua_settable(L, -3); + /* Assign the metatable to the userdata object */ + lua_setmetatable(L, -2); + /* Save NIL on the registry so we can access it easily from other functions */ + lua_setfield(L, LUA_REGISTRYINDEX, NIL_NAME); + } + + lua_pop(L, 1); + + /* module */ + lua_newtable(L); + luaL_register(L, NULL, mpack_functions); + /* save NIL on the module */ + lua_getfield(L, LUA_REGISTRYINDEX, NIL_NAME); + lua_setfield(L, -2, "NIL"); + return 1; +} diff --git a/src/mpack/lmpack.h b/src/mpack/lmpack.h new file mode 100644 index 0000000000..e35f40fab6 --- /dev/null +++ b/src/mpack/lmpack.h @@ -0,0 +1,3 @@ +#include <lua.h> + +int luaopen_mpack(lua_State *L); diff --git a/src/mpack/mpack_core.c b/src/mpack/mpack_core.c new file mode 100644 index 0000000000..0ad09bd46a --- /dev/null +++ b/src/mpack/mpack_core.c @@ -0,0 +1,575 @@ +#include <string.h> + +#include "mpack_core.h" + +#define UNUSED(p) (void)p; +#define ADVANCE(buf, buflen) ((*buflen)--, (unsigned char)*((*buf)++)) +#define TLEN(val, range_start) ((mpack_uint32_t)(1 << (val - range_start))) +#ifndef MIN +# define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) +#endif + +static int mpack_rtoken(const char **buf, size_t *buflen, + mpack_token_t *tok); +static int mpack_rpending(const char **b, size_t *nl, mpack_tokbuf_t *tb); +static int mpack_rvalue(mpack_token_type_t t, mpack_uint32_t l, + const char **b, size_t *bl, mpack_token_t *tok); +static int mpack_rblob(mpack_token_type_t t, mpack_uint32_t l, + const char **b, size_t *bl, mpack_token_t *tok); +static int mpack_wtoken(const mpack_token_t *tok, char **b, size_t *bl); +static int mpack_wpending(char **b, size_t *bl, mpack_tokbuf_t *tb); +static int mpack_wpint(char **b, size_t *bl, mpack_value_t v); +static int mpack_wnint(char **b, size_t *bl, mpack_value_t v); +static int mpack_wfloat(char **b, size_t *bl, const mpack_token_t *v); +static int mpack_wstr(char **buf, size_t *buflen, mpack_uint32_t len); +static int mpack_wbin(char **buf, size_t *buflen, mpack_uint32_t len); +static int mpack_wext(char **buf, size_t *buflen, int type, + mpack_uint32_t len); +static int mpack_warray(char **buf, size_t *buflen, mpack_uint32_t len); +static int mpack_wmap(char **buf, size_t *buflen, mpack_uint32_t len); +static int mpack_w1(char **b, size_t *bl, mpack_uint32_t v); +static int mpack_w2(char **b, size_t *bl, mpack_uint32_t v); +static int mpack_w4(char **b, size_t *bl, mpack_uint32_t v); +static mpack_value_t mpack_byte(unsigned char b); +static int mpack_value(mpack_token_type_t t, mpack_uint32_t l, + mpack_value_t v, mpack_token_t *tok); +static int mpack_blob(mpack_token_type_t t, mpack_uint32_t l, int et, + mpack_token_t *tok); + +MPACK_API void mpack_tokbuf_init(mpack_tokbuf_t *tokbuf) +{ + tokbuf->ppos = 0; + tokbuf->plen = 0; + tokbuf->passthrough = 0; +} + +MPACK_API int mpack_read(mpack_tokbuf_t *tokbuf, const char **buf, + size_t *buflen, mpack_token_t *tok) +{ + int status; + size_t initial_ppos, ptrlen, advanced; + const char *ptr, *ptr_save; + assert(*buf && *buflen); + + if (tokbuf->passthrough) { + /* pass data from str/bin/ext directly as a MPACK_TOKEN_CHUNK, adjusting + * *buf and *buflen */ + tok->type = MPACK_TOKEN_CHUNK; + tok->data.chunk_ptr = *buf; + tok->length = MIN((mpack_uint32_t)*buflen, tokbuf->passthrough); + tokbuf->passthrough -= tok->length; + *buf += tok->length; + *buflen -= tok->length; + goto done; + } + + initial_ppos = tokbuf->ppos; + + if (tokbuf->plen) { + if (!mpack_rpending(buf, buflen, tokbuf)) { + return MPACK_EOF; + } + ptr = tokbuf->pending; + ptrlen = tokbuf->ppos; + } else { + ptr = *buf; + ptrlen = *buflen; + } + + ptr_save = ptr; + + if ((status = mpack_rtoken(&ptr, &ptrlen, tok))) { + if (status != MPACK_EOF) return MPACK_ERROR; + /* need more data */ + assert(!tokbuf->plen); + /* read the remainder of *buf to tokbuf->pending so it can be parsed + * later with more data. only required when tokbuf->plen == 0 or else + * it would have been done already. */ + tokbuf->plen = tok->length + 1; + assert(tokbuf->plen <= sizeof(tokbuf->pending)); + tokbuf->ppos = 0; + status = mpack_rpending(buf, buflen, tokbuf); + assert(!status); + return MPACK_EOF; + } + + advanced = (size_t)(ptr - ptr_save) - initial_ppos; + tokbuf->plen = tokbuf->ppos = 0; + *buflen -= advanced; + *buf += advanced; + + if (tok->type > MPACK_TOKEN_MAP) { + tokbuf->passthrough = tok->length; + } + +done: + return MPACK_OK; +} + +MPACK_API int mpack_write(mpack_tokbuf_t *tokbuf, char **buf, size_t *buflen, + const mpack_token_t *t) +{ + int status; + char *ptr; + size_t ptrlen; + mpack_token_t tok = tokbuf->plen ? tokbuf->pending_tok : *t; + assert(*buf && *buflen); + + if (tok.type == MPACK_TOKEN_CHUNK) { + size_t written, pending, count; + if (!tokbuf->plen) tokbuf->ppos = 0; + written = tokbuf->ppos; + pending = tok.length - written; + count = MIN(pending, *buflen); + memcpy(*buf, tok.data.chunk_ptr + written, count); + *buf += count; + *buflen -= count; + tokbuf->ppos += count; + tokbuf->plen = count == pending ? 0 : tok.length; + if (count == pending) { + return MPACK_OK; + } else { + tokbuf->pending_tok = tok; + return MPACK_EOF; + } + } + + if (tokbuf->plen) return mpack_wpending(buf, buflen, tokbuf); + + if (*buflen < MPACK_MAX_TOKEN_LEN) { + ptr = tokbuf->pending; + ptrlen = sizeof(tokbuf->pending); + } else { + ptr = *buf; + ptrlen = *buflen; + } + + if ((status = mpack_wtoken(&tok, &ptr, &ptrlen))) return status; + + if (*buflen < MPACK_MAX_TOKEN_LEN) { + size_t toklen = sizeof(tokbuf->pending) - ptrlen; + size_t write_cnt = MIN(toklen, *buflen); + memcpy(*buf, tokbuf->pending, write_cnt); + *buf += write_cnt; + *buflen -= write_cnt; + if (write_cnt < toklen) { + assert(!*buflen); + tokbuf->plen = toklen; + tokbuf->ppos = write_cnt; + tokbuf->pending_tok = tok; + return MPACK_EOF; + } + } else { + *buflen -= (size_t)(ptr - *buf); + *buf = ptr; + } + + return MPACK_OK; +} + +static int mpack_rtoken(const char **buf, size_t *buflen, + mpack_token_t *tok) +{ + unsigned char t = ADVANCE(buf, buflen); + if (t < 0x80) { + /* positive fixint */ + return mpack_value(MPACK_TOKEN_UINT, 1, mpack_byte(t), tok); + } else if (t < 0x90) { + /* fixmap */ + return mpack_blob(MPACK_TOKEN_MAP, t & 0xf, 0, tok); + } else if (t < 0xa0) { + /* fixarray */ + return mpack_blob(MPACK_TOKEN_ARRAY, t & 0xf, 0, tok); + } else if (t < 0xc0) { + /* fixstr */ + return mpack_blob(MPACK_TOKEN_STR, t & 0x1f, 0, tok); + } else if (t < 0xe0) { + switch (t) { + case 0xc0: /* nil */ + return mpack_value(MPACK_TOKEN_NIL, 0, mpack_byte(0), tok); + case 0xc2: /* false */ + return mpack_value(MPACK_TOKEN_BOOLEAN, 1, mpack_byte(0), tok); + case 0xc3: /* true */ + return mpack_value(MPACK_TOKEN_BOOLEAN, 1, mpack_byte(1), tok); + case 0xc4: /* bin 8 */ + case 0xc5: /* bin 16 */ + case 0xc6: /* bin 32 */ + return mpack_rblob(MPACK_TOKEN_BIN, TLEN(t, 0xc4), buf, buflen, tok); + case 0xc7: /* ext 8 */ + case 0xc8: /* ext 16 */ + case 0xc9: /* ext 32 */ + return mpack_rblob(MPACK_TOKEN_EXT, TLEN(t, 0xc7), buf, buflen, tok); + case 0xca: /* float 32 */ + case 0xcb: /* float 64 */ + return mpack_rvalue(MPACK_TOKEN_FLOAT, TLEN(t, 0xc8), buf, buflen, tok); + case 0xcc: /* uint 8 */ + case 0xcd: /* uint 16 */ + case 0xce: /* uint 32 */ + case 0xcf: /* uint 64 */ + return mpack_rvalue(MPACK_TOKEN_UINT, TLEN(t, 0xcc), buf, buflen, tok); + case 0xd0: /* int 8 */ + case 0xd1: /* int 16 */ + case 0xd2: /* int 32 */ + case 0xd3: /* int 64 */ + return mpack_rvalue(MPACK_TOKEN_SINT, TLEN(t, 0xd0), buf, buflen, tok); + case 0xd4: /* fixext 1 */ + case 0xd5: /* fixext 2 */ + case 0xd6: /* fixext 4 */ + case 0xd7: /* fixext 8 */ + case 0xd8: /* fixext 16 */ + if (*buflen == 0) { + /* require only one extra byte for the type code */ + tok->length = 1; + return MPACK_EOF; + } + tok->length = TLEN(t, 0xd4); + tok->type = MPACK_TOKEN_EXT; + tok->data.ext_type = ADVANCE(buf, buflen); + return MPACK_OK; + case 0xd9: /* str 8 */ + case 0xda: /* str 16 */ + case 0xdb: /* str 32 */ + return mpack_rblob(MPACK_TOKEN_STR, TLEN(t, 0xd9), buf, buflen, tok); + case 0xdc: /* array 16 */ + case 0xdd: /* array 32 */ + return mpack_rblob(MPACK_TOKEN_ARRAY, TLEN(t, 0xdb), buf, buflen, tok); + case 0xde: /* map 16 */ + case 0xdf: /* map 32 */ + return mpack_rblob(MPACK_TOKEN_MAP, TLEN(t, 0xdd), buf, buflen, tok); + default: + return MPACK_ERROR; + } + } else { + /* negative fixint */ + return mpack_value(MPACK_TOKEN_SINT, 1, mpack_byte(t), tok); + } +} + +static int mpack_rpending(const char **buf, size_t *buflen, + mpack_tokbuf_t *state) +{ + size_t count; + assert(state->ppos < state->plen); + count = MIN(state->plen - state->ppos, *buflen); + memcpy(state->pending + state->ppos, *buf, count); + state->ppos += count; + if (state->ppos < state->plen) { + /* consume buffer since no token will be parsed yet. */ + *buf += *buflen; + *buflen = 0; + return 0; + } + return 1; +} + +static int mpack_rvalue(mpack_token_type_t type, mpack_uint32_t remaining, + const char **buf, size_t *buflen, mpack_token_t *tok) +{ + if (*buflen < remaining) { + tok->length = remaining; + return MPACK_EOF; + } + + mpack_value(type, remaining, mpack_byte(0), tok); + + while (remaining) { + mpack_uint32_t byte = ADVANCE(buf, buflen), byte_idx, byte_shift; + byte_idx = (mpack_uint32_t)--remaining; + byte_shift = (byte_idx % 4) * 8; + tok->data.value.lo |= byte << byte_shift; + if (remaining == 4) { + /* unpacked the first half of a 8-byte value, shift what was parsed to the + * "hi" field and reset "lo" for the trailing 4 bytes. */ + tok->data.value.hi = tok->data.value.lo; + tok->data.value.lo = 0; + } + } + + if (type == MPACK_TOKEN_SINT) { + mpack_uint32_t hi = tok->data.value.hi; + mpack_uint32_t lo = tok->data.value.lo; + mpack_uint32_t msb = (tok->length == 8 && hi >> 31) || + (tok->length == 4 && lo >> 31) || + (tok->length == 2 && lo >> 15) || + (tok->length == 1 && lo >> 7); + if (!msb) { + tok->type = MPACK_TOKEN_UINT; + } + } + + return MPACK_OK; +} + +static int mpack_rblob(mpack_token_type_t type, mpack_uint32_t tlen, + const char **buf, size_t *buflen, mpack_token_t *tok) +{ + mpack_token_t l; + mpack_uint32_t required = tlen + (type == MPACK_TOKEN_EXT ? 1 : 0); + + if (*buflen < required) { + tok->length = required; + return MPACK_EOF; + } + + l.data.value.lo = 0; + mpack_rvalue(MPACK_TOKEN_UINT, tlen, buf, buflen, &l); + tok->type = type; + tok->length = l.data.value.lo; + + if (type == MPACK_TOKEN_EXT) { + tok->data.ext_type = ADVANCE(buf, buflen); + } + + return MPACK_OK; +} + +static int mpack_wtoken(const mpack_token_t *tok, char **buf, + size_t *buflen) +{ + switch (tok->type) { + case MPACK_TOKEN_NIL: + return mpack_w1(buf, buflen, 0xc0); + case MPACK_TOKEN_BOOLEAN: + return mpack_w1(buf, buflen, tok->data.value.lo ? 0xc3 : 0xc2); + case MPACK_TOKEN_UINT: + return mpack_wpint(buf, buflen, tok->data.value); + case MPACK_TOKEN_SINT: + return mpack_wnint(buf, buflen, tok->data.value); + case MPACK_TOKEN_FLOAT: + return mpack_wfloat(buf, buflen, tok); + case MPACK_TOKEN_BIN: + return mpack_wbin(buf, buflen, tok->length); + case MPACK_TOKEN_STR: + return mpack_wstr(buf, buflen, tok->length); + case MPACK_TOKEN_EXT: + return mpack_wext(buf, buflen, tok->data.ext_type, tok->length); + case MPACK_TOKEN_ARRAY: + return mpack_warray(buf, buflen, tok->length); + case MPACK_TOKEN_MAP: + return mpack_wmap(buf, buflen, tok->length); + default: + return MPACK_ERROR; + } +} + +static int mpack_wpending(char **buf, size_t *buflen, mpack_tokbuf_t *state) +{ + size_t count; + assert(state->ppos < state->plen); + count = MIN(state->plen - state->ppos, *buflen); + memcpy(*buf, state->pending + state->ppos, count); + state->ppos += count; + *buf += count; + *buflen -= count; + if (state->ppos == state->plen) { + state->plen = 0; + return MPACK_OK; + } + return MPACK_EOF; +} + +static int mpack_wpint(char **buf, size_t *buflen, mpack_value_t val) +{ + mpack_uint32_t hi = val.hi; + mpack_uint32_t lo = val.lo; + + if (hi) { + /* uint 64 */ + return mpack_w1(buf, buflen, 0xcf) || + mpack_w4(buf, buflen, hi) || + mpack_w4(buf, buflen, lo); + } else if (lo > 0xffff) { + /* uint 32 */ + return mpack_w1(buf, buflen, 0xce) || + mpack_w4(buf, buflen, lo); + } else if (lo > 0xff) { + /* uint 16 */ + return mpack_w1(buf, buflen, 0xcd) || + mpack_w2(buf, buflen, lo); + } else if (lo > 0x7f) { + /* uint 8 */ + return mpack_w1(buf, buflen, 0xcc) || + mpack_w1(buf, buflen, lo); + } else { + return mpack_w1(buf, buflen, lo); + } +} + +static int mpack_wnint(char **buf, size_t *buflen, mpack_value_t val) +{ + mpack_uint32_t hi = val.hi; + mpack_uint32_t lo = val.lo; + + if (lo < 0x80000000) { + /* int 64 */ + return mpack_w1(buf, buflen, 0xd3) || + mpack_w4(buf, buflen, hi) || + mpack_w4(buf, buflen, lo); + } else if (lo < 0xffff7fff) { + /* int 32 */ + return mpack_w1(buf, buflen, 0xd2) || + mpack_w4(buf, buflen, lo); + } else if (lo < 0xffffff7f) { + /* int 16 */ + return mpack_w1(buf, buflen, 0xd1) || + mpack_w2(buf, buflen, lo); + } else if (lo < 0xffffffe0) { + /* int 8 */ + return mpack_w1(buf, buflen, 0xd0) || + mpack_w1(buf, buflen, lo); + } else { + /* negative fixint */ + return mpack_w1(buf, buflen, (mpack_uint32_t)(0x100 + lo)); + } +} + +static int mpack_wfloat(char **buf, size_t *buflen, + const mpack_token_t *tok) +{ + if (tok->length == 4) { + return mpack_w1(buf, buflen, 0xca) || + mpack_w4(buf, buflen, tok->data.value.lo); + } else if (tok->length == 8) { + return mpack_w1(buf, buflen, 0xcb) || + mpack_w4(buf, buflen, tok->data.value.hi) || + mpack_w4(buf, buflen, tok->data.value.lo); + } else { + return MPACK_ERROR; + } +} + +static int mpack_wstr(char **buf, size_t *buflen, mpack_uint32_t len) +{ + if (len < 0x20) { + return mpack_w1(buf, buflen, 0xa0 | len); + } else if (len < 0x100) { + return mpack_w1(buf, buflen, 0xd9) || + mpack_w1(buf, buflen, len); + } else if (len < 0x10000) { + return mpack_w1(buf, buflen, 0xda) || + mpack_w2(buf, buflen, len); + } else { + return mpack_w1(buf, buflen, 0xdb) || + mpack_w4(buf, buflen, len); + } +} + +static int mpack_wbin(char **buf, size_t *buflen, mpack_uint32_t len) +{ + if (len < 0x100) { + return mpack_w1(buf, buflen, 0xc4) || + mpack_w1(buf, buflen, len); + } else if (len < 0x10000) { + return mpack_w1(buf, buflen, 0xc5) || + mpack_w2(buf, buflen, len); + } else { + return mpack_w1(buf, buflen, 0xc6) || + mpack_w4(buf, buflen, len); + } +} + +static int mpack_wext(char **buf, size_t *buflen, int type, + mpack_uint32_t len) +{ + mpack_uint32_t t; + assert(type >= 0 && type < 0x80); + t = (mpack_uint32_t)type; + switch (len) { + case 1: mpack_w1(buf, buflen, 0xd4); return mpack_w1(buf, buflen, t); + case 2: mpack_w1(buf, buflen, 0xd5); return mpack_w1(buf, buflen, t); + case 4: mpack_w1(buf, buflen, 0xd6); return mpack_w1(buf, buflen, t); + case 8: mpack_w1(buf, buflen, 0xd7); return mpack_w1(buf, buflen, t); + case 16: mpack_w1(buf, buflen, 0xd8); return mpack_w1(buf, buflen, t); + default: + if (len < 0x100) { + return mpack_w1(buf, buflen, 0xc7) || + mpack_w1(buf, buflen, len) || + mpack_w1(buf, buflen, t); + } else if (len < 0x10000) { + return mpack_w1(buf, buflen, 0xc8) || + mpack_w2(buf, buflen, len) || + mpack_w1(buf, buflen, t); + } else { + return mpack_w1(buf, buflen, 0xc9) || + mpack_w4(buf, buflen, len) || + mpack_w1(buf, buflen, t); + } + } +} + +static int mpack_warray(char **buf, size_t *buflen, mpack_uint32_t len) +{ + if (len < 0x10) { + return mpack_w1(buf, buflen, 0x90 | len); + } else if (len < 0x10000) { + return mpack_w1(buf, buflen, 0xdc) || + mpack_w2(buf, buflen, len); + } else { + return mpack_w1(buf, buflen, 0xdd) || + mpack_w4(buf, buflen, len); + } +} + +static int mpack_wmap(char **buf, size_t *buflen, mpack_uint32_t len) +{ + if (len < 0x10) { + return mpack_w1(buf, buflen, 0x80 | len); + } else if (len < 0x10000) { + return mpack_w1(buf, buflen, 0xde) || + mpack_w2(buf, buflen, len); + } else { + return mpack_w1(buf, buflen, 0xdf) || + mpack_w4(buf, buflen, len); + } +} + +static int mpack_w1(char **b, size_t *bl, mpack_uint32_t v) +{ + (*bl)--; + *(*b)++ = (char)(v & 0xff); + return MPACK_OK; +} + +static int mpack_w2(char **b, size_t *bl, mpack_uint32_t v) +{ + *bl -= 2; + *(*b)++ = (char)((v >> 8) & 0xff); + *(*b)++ = (char)(v & 0xff); + return MPACK_OK; +} + +static int mpack_w4(char **b, size_t *bl, mpack_uint32_t v) +{ + *bl -= 4; + *(*b)++ = (char)((v >> 24) & 0xff); + *(*b)++ = (char)((v >> 16) & 0xff); + *(*b)++ = (char)((v >> 8) & 0xff); + *(*b)++ = (char)(v & 0xff); + return MPACK_OK; +} + +static int mpack_value(mpack_token_type_t type, mpack_uint32_t length, + mpack_value_t value, mpack_token_t *tok) +{ + tok->type = type; + tok->length = length; + tok->data.value = value; + return MPACK_OK; +} + +static int mpack_blob(mpack_token_type_t type, mpack_uint32_t length, + int ext_type, mpack_token_t *tok) +{ + tok->type = type; + tok->length = length; + tok->data.ext_type = ext_type; + return MPACK_OK; +} + +static mpack_value_t mpack_byte(unsigned char byte) +{ + mpack_value_t rv; + rv.lo = byte; + rv.hi = 0; + return rv; +} diff --git a/src/mpack/mpack_core.h b/src/mpack/mpack_core.h new file mode 100644 index 0000000000..9edd13c41e --- /dev/null +++ b/src/mpack/mpack_core.h @@ -0,0 +1,87 @@ +#ifndef MPACK_CORE_H +#define MPACK_CORE_H + +#ifndef MPACK_API +# define MPACK_API extern +#endif + +#include <assert.h> +#include <limits.h> +#include <stddef.h> + +#ifdef __GNUC__ +# define FPURE __attribute__((const)) +# define FNONULL __attribute__((nonnull)) +# define FNONULL_ARG(x) __attribute__((nonnull x)) +# define FUNUSED __attribute__((unused)) +#else +# define FPURE +# define FNONULL +# define FNONULL_ARG(x) +# define FUNUSED +#endif + +#if UINT_MAX == 0xffffffff +typedef int mpack_sint32_t; +typedef unsigned int mpack_uint32_t; +#elif ULONG_MAX == 0xffffffff +typedef long mpack_sint32_t; +typedef unsigned long mpack_uint32_t; +#else +# error "can't find unsigned 32-bit integer type" +#endif + +typedef struct mpack_value_s { + mpack_uint32_t lo, hi; +} mpack_value_t; + + +enum { + MPACK_OK = 0, + MPACK_EOF = 1, + MPACK_ERROR = 2 +}; + +#define MPACK_MAX_TOKEN_LEN 9 /* 64-bit ints/floats plus type code */ + +typedef enum { + MPACK_TOKEN_NIL = 1, + MPACK_TOKEN_BOOLEAN = 2, + MPACK_TOKEN_UINT = 3, + MPACK_TOKEN_SINT = 4, + MPACK_TOKEN_FLOAT = 5, + MPACK_TOKEN_CHUNK = 6, + MPACK_TOKEN_ARRAY = 7, + MPACK_TOKEN_MAP = 8, + MPACK_TOKEN_BIN = 9, + MPACK_TOKEN_STR = 10, + MPACK_TOKEN_EXT = 11 +} mpack_token_type_t; + +typedef struct mpack_token_s { + mpack_token_type_t type; /* Type of token */ + mpack_uint32_t length; /* Byte length for str/bin/ext/chunk/float/int/uint. + Item count for array/map. */ + union { + mpack_value_t value; /* 32-bit parts of primitives (bool,int,float) */ + const char *chunk_ptr; /* Chunk of data from str/bin/ext */ + int ext_type; /* Type field for ext tokens */ + } data; +} mpack_token_t; + +typedef struct mpack_tokbuf_s { + char pending[MPACK_MAX_TOKEN_LEN]; + mpack_token_t pending_tok; + size_t ppos, plen; + mpack_uint32_t passthrough; +} mpack_tokbuf_t; + +#define MPACK_TOKBUF_INITIAL_VALUE { { 0 }, { 0, 0, { { 0, 0 } } }, 0, 0, 0 } + +MPACK_API void mpack_tokbuf_init(mpack_tokbuf_t *tb) FUNUSED FNONULL; +MPACK_API int mpack_read(mpack_tokbuf_t *tb, const char **b, size_t *bl, + mpack_token_t *tok) FUNUSED FNONULL; +MPACK_API int mpack_write(mpack_tokbuf_t *tb, char **b, size_t *bl, + const mpack_token_t *tok) FUNUSED FNONULL; + +#endif /* MPACK_CORE_H */ diff --git a/src/mpack/object.c b/src/mpack/object.c new file mode 100644 index 0000000000..0c7759ee51 --- /dev/null +++ b/src/mpack/object.c @@ -0,0 +1,195 @@ +#include <string.h> + +#include "object.h" + +static int mpack_parser_full(mpack_parser_t *w); +static mpack_node_t *mpack_parser_push(mpack_parser_t *w); +static mpack_node_t *mpack_parser_pop(mpack_parser_t *w); + +MPACK_API void mpack_parser_init(mpack_parser_t *parser, + mpack_uint32_t capacity) +{ + mpack_tokbuf_init(&parser->tokbuf); + parser->data.p = NULL; + parser->capacity = capacity ? capacity : MPACK_MAX_OBJECT_DEPTH; + parser->size = 0; + parser->exiting = 0; + memset(parser->items, 0, sizeof(mpack_node_t) * (parser->capacity + 1)); + parser->items[0].pos = (size_t)-1; + parser->status = 0; +} + +#define MPACK_EXCEPTION_CHECK(parser) \ + do { \ + if (parser->status == MPACK_EXCEPTION) { \ + return MPACK_EXCEPTION; \ + } \ + } while (0) + +#define MPACK_WALK(action) \ + do { \ + mpack_node_t *n; \ + \ + if (parser->exiting) goto exit; \ + if (mpack_parser_full(parser)) return MPACK_NOMEM; \ + n = mpack_parser_push(parser); \ + action; \ + MPACK_EXCEPTION_CHECK(parser); \ + parser->exiting = 1; \ + return MPACK_EOF; \ + \ +exit: \ + parser->exiting = 0; \ + while ((n = mpack_parser_pop(parser))) { \ + exit_cb(parser, n); \ + MPACK_EXCEPTION_CHECK(parser); \ + if (!parser->size) return MPACK_OK; \ + } \ + \ + return MPACK_EOF; \ + } while (0) + +MPACK_API int mpack_parse_tok(mpack_parser_t *parser, mpack_token_t tok, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) +{ + MPACK_EXCEPTION_CHECK(parser); + MPACK_WALK({n->tok = tok; enter_cb(parser, n);}); +} + +MPACK_API int mpack_unparse_tok(mpack_parser_t *parser, mpack_token_t *tok, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) +{ + MPACK_EXCEPTION_CHECK(parser); + MPACK_WALK({enter_cb(parser, n); *tok = n->tok;}); +} + +MPACK_API int mpack_parse(mpack_parser_t *parser, const char **buf, + size_t *buflen, mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) +{ + int status = MPACK_EOF; + MPACK_EXCEPTION_CHECK(parser); + + while (*buflen && status) { + mpack_token_t tok; + mpack_tokbuf_t *tb = &parser->tokbuf; + const char *buf_save = *buf; + size_t buflen_save = *buflen; + + if ((status = mpack_read(tb, buf, buflen, &tok)) == MPACK_EOF) continue; + else if (status == MPACK_ERROR) goto rollback; + + do { + status = mpack_parse_tok(parser, tok, enter_cb, exit_cb); + MPACK_EXCEPTION_CHECK(parser); + } while (parser->exiting); + + if (status != MPACK_NOMEM) continue; + +rollback: + /* restore buf/buflen so the next call will try to read the same token */ + *buf = buf_save; + *buflen = buflen_save; + break; + } + + return status; +} + +MPACK_API int mpack_unparse(mpack_parser_t *parser, char **buf, size_t *buflen, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) +{ + int status = MPACK_EOF; + MPACK_EXCEPTION_CHECK(parser); + + while (*buflen && status) { + int write_status; + mpack_token_t tok; + mpack_tokbuf_t *tb = &parser->tokbuf; + + if (!tb->plen) + parser->status = mpack_unparse_tok(parser, &tok, enter_cb, exit_cb); + + MPACK_EXCEPTION_CHECK(parser); + + status = parser->status; + + if (status == MPACK_NOMEM) + break; + + if (parser->exiting) { + write_status = mpack_write(tb, buf, buflen, &tok); + status = write_status ? write_status : status; + } + } + + return status; +} + +MPACK_API void mpack_parser_copy(mpack_parser_t *dst, mpack_parser_t *src) +{ + mpack_uint32_t i; + mpack_uint32_t dst_capacity = dst->capacity; + assert(src->capacity <= dst_capacity); + /* copy all fields except the stack */ + memcpy(dst, src, sizeof(mpack_one_parser_t) - sizeof(mpack_node_t)); + /* reset capacity */ + dst->capacity = dst_capacity; + /* copy the stack */ + for (i = 0; i <= src->capacity; i++) { + dst->items[i] = src->items[i]; + } +} + +static int mpack_parser_full(mpack_parser_t *parser) +{ + return parser->size == parser->capacity; +} + +static mpack_node_t *mpack_parser_push(mpack_parser_t *parser) +{ + mpack_node_t *top; + assert(parser->size < parser->capacity); + top = parser->items + parser->size + 1; + top->data[0].p = NULL; + top->data[1].p = NULL; + top->pos = 0; + top->key_visited = 0; + /* increase size and invoke callback, passing parent node if any */ + parser->size++; + return top; +} + +static mpack_node_t *mpack_parser_pop(mpack_parser_t *parser) +{ + mpack_node_t *top, *parent; + assert(parser->size); + top = parser->items + parser->size; + + if (top->tok.type > MPACK_TOKEN_CHUNK && top->pos < top->tok.length) { + /* continue processing children */ + return NULL; + } + + parent = MPACK_PARENT_NODE(top); + if (parent) { + /* we use parent->tok.length to keep track of how many children remain. + * update it to reflect the processed node. */ + if (top->tok.type == MPACK_TOKEN_CHUNK) { + parent->pos += top->tok.length; + } else if (parent->tok.type == MPACK_TOKEN_MAP) { + /* maps allow up to 2^32 - 1 pairs, so to allow this many items in a + * 32-bit length variable we use an additional flag to determine if the + * key of a certain position was visited */ + if (parent->key_visited) { + parent->pos++; + } + parent->key_visited = !parent->key_visited; + } else { + parent->pos++; + } + } + + parser->size--; + return top; +} + diff --git a/src/mpack/object.h b/src/mpack/object.h new file mode 100644 index 0000000000..5327e56e18 --- /dev/null +++ b/src/mpack/object.h @@ -0,0 +1,86 @@ +#ifndef MPACK_OBJECT_H +#define MPACK_OBJECT_H + +#include "mpack_core.h" +#include "conv.h" + +#ifndef MPACK_MAX_OBJECT_DEPTH +# define MPACK_MAX_OBJECT_DEPTH 32 +#endif + +#define MPACK_PARENT_NODE(n) (((n) - 1)->pos == (size_t)-1 ? NULL : (n) - 1) + +#define MPACK_THROW(parser) \ + do { \ + parser->status = MPACK_EXCEPTION; \ + return; \ + } while (0) + +enum { + MPACK_EXCEPTION = -1, + MPACK_NOMEM = MPACK_ERROR + 1 +}; + +/* Storing integer in pointers in undefined behavior according to the C + * standard. Define a union type to accomodate arbitrary user data associated + * with nodes(and with requests in rpc.h). */ +typedef union { + void *p; + mpack_uintmax_t u; + mpack_sintmax_t i; + double d; +} mpack_data_t; + +typedef struct mpack_node_s { + mpack_token_t tok; + size_t pos; + /* flag to determine if the key was visited when traversing a map */ + int key_visited; + /* allow 2 instances mpack_data_t per node. the reason is that when + * serializing, the user may need to keep track of traversal state besides the + * parent node reference */ + mpack_data_t data[2]; +} mpack_node_t; + +#define MPACK_PARSER_STRUCT(c) \ + struct { \ + mpack_data_t data; \ + mpack_uint32_t size, capacity; \ + int status; \ + int exiting; \ + mpack_tokbuf_t tokbuf; \ + mpack_node_t items[c + 1]; \ + } + +/* Some compilers warn against anonymous structs: + * https://github.com/libmpack/libmpack/issues/6 */ +typedef MPACK_PARSER_STRUCT(0) mpack_one_parser_t; + +#define MPACK_PARSER_STRUCT_SIZE(c) \ + (sizeof(mpack_node_t) * c + \ + sizeof(mpack_one_parser_t)) + +typedef MPACK_PARSER_STRUCT(MPACK_MAX_OBJECT_DEPTH) mpack_parser_t; +typedef void(*mpack_walk_cb)(mpack_parser_t *w, mpack_node_t *n); + +MPACK_API void mpack_parser_init(mpack_parser_t *p, mpack_uint32_t c) + FUNUSED FNONULL; + +MPACK_API int mpack_parse_tok(mpack_parser_t *walker, mpack_token_t tok, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) + FUNUSED FNONULL_ARG((1,3,4)); +MPACK_API int mpack_unparse_tok(mpack_parser_t *walker, mpack_token_t *tok, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) + FUNUSED FNONULL_ARG((1,2,3,4)); + +MPACK_API int mpack_parse(mpack_parser_t *parser, const char **b, size_t *bl, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) + FUNUSED FNONULL_ARG((1,2,3,4,5)); +MPACK_API int mpack_unparse(mpack_parser_t *parser, char **b, size_t *bl, + mpack_walk_cb enter_cb, mpack_walk_cb exit_cb) + FUNUSED FNONULL_ARG((1,2,3,4,5)); + +MPACK_API void mpack_parser_copy(mpack_parser_t *d, mpack_parser_t *s) + FUNUSED FNONULL; + +#endif /* MPACK_OBJECT_H */ diff --git a/src/mpack/rpc.c b/src/mpack/rpc.c new file mode 100644 index 0000000000..3b2b328065 --- /dev/null +++ b/src/mpack/rpc.c @@ -0,0 +1,331 @@ +#include <string.h> + +#include "rpc.h" + +enum { + MPACK_RPC_RECEIVE_ARRAY = 1, + MPACK_RPC_RECEIVE_TYPE, + MPACK_RPC_RECEIVE_ID +}; + +static mpack_rpc_header_t mpack_rpc_request_hdr(void); +static mpack_rpc_header_t mpack_rpc_reply_hdr(void); +static mpack_rpc_header_t mpack_rpc_notify_hdr(void); +static int mpack_rpc_put(mpack_rpc_session_t *s, mpack_rpc_message_t m); +static int mpack_rpc_pop(mpack_rpc_session_t *s, mpack_rpc_message_t *m); +static void mpack_rpc_reset_hdr(mpack_rpc_header_t *hdr); + +MPACK_API void mpack_rpc_session_init(mpack_rpc_session_t *session, + mpack_uint32_t capacity) +{ + session->capacity = capacity ? capacity : MPACK_RPC_MAX_REQUESTS; + session->request_id = 0; + mpack_tokbuf_init(&session->reader); + mpack_tokbuf_init(&session->writer); + mpack_rpc_reset_hdr(&session->receive); + mpack_rpc_reset_hdr(&session->send); + memset(session->slots, 0, + sizeof(struct mpack_rpc_slot_s) * session->capacity); +} + +MPACK_API int mpack_rpc_receive_tok(mpack_rpc_session_t *session, + mpack_token_t tok, mpack_rpc_message_t *msg) +{ + int type; + + if (session->receive.index == 0) { + if (tok.type != MPACK_TOKEN_ARRAY) + /* not an array */ + return MPACK_RPC_EARRAY; + + if (tok.length < 3 || tok.length > 4) + /* invalid array length */ + return MPACK_RPC_EARRAYL; + + session->receive.toks[0] = tok; + session->receive.index++; + return MPACK_EOF; /* get the type */ + } + + if (session->receive.index == 1) { + + if (tok.type != MPACK_TOKEN_UINT || tok.length > 1 || tok.data.value.lo > 2) + /* invalid type */ + return MPACK_RPC_ETYPE; + + if (tok.data.value.lo < 2 && session->receive.toks[0].length != 4) + /* request or response with array length != 4 */ + return MPACK_RPC_EARRAYL; + + if (tok.data.value.lo == 2 && session->receive.toks[0].length != 3) + /* notification with array length != 3 */ + return MPACK_RPC_EARRAYL; + + session->receive.toks[1] = tok; + session->receive.index++; + + if (tok.data.value.lo < 2) return MPACK_EOF; + + type = MPACK_RPC_NOTIFICATION; + goto end; + } + + assert(session->receive.index == 2); + + if (tok.type != MPACK_TOKEN_UINT || tok.length > 4) + /* invalid request/response id */ + return MPACK_RPC_EMSGID; + + msg->id = tok.data.value.lo; + msg->data.p = NULL; + type = (int)session->receive.toks[1].data.value.lo + MPACK_RPC_REQUEST; + + if (type == MPACK_RPC_RESPONSE && !mpack_rpc_pop(session, msg)) + /* response with invalid id */ + return MPACK_RPC_ERESPID; + +end: + mpack_rpc_reset_hdr(&session->receive); + return type; +} + +MPACK_API int mpack_rpc_request_tok(mpack_rpc_session_t *session, + mpack_token_t *tok, mpack_data_t data) +{ + if (session->send.index == 0) { + int status; + mpack_rpc_message_t msg; + do { + msg.id = session->request_id; + msg.data = data; + session->send = mpack_rpc_request_hdr(); + session->send.toks[2].type = MPACK_TOKEN_UINT; + session->send.toks[2].data.value.lo = msg.id; + session->send.toks[2].data.value.hi = 0; + *tok = session->send.toks[0]; + status = mpack_rpc_put(session, msg); + if (status == -1) return MPACK_NOMEM; + session->request_id = (session->request_id + 1) % 0xffffffff; + } while (!status); + session->send.index++; + return MPACK_EOF; + } + + if (session->send.index == 1) { + *tok = session->send.toks[1]; + session->send.index++; + return MPACK_EOF; + } + + assert(session->send.index == 2); + *tok = session->send.toks[2]; + mpack_rpc_reset_hdr(&session->send); + return MPACK_OK; +} + +MPACK_API int mpack_rpc_reply_tok(mpack_rpc_session_t *session, + mpack_token_t *tok, mpack_uint32_t id) +{ + if (session->send.index == 0) { + session->send = mpack_rpc_reply_hdr(); + session->send.toks[2].type = MPACK_TOKEN_UINT; + session->send.toks[2].data.value.lo = id; + session->send.toks[2].data.value.hi = 0; + *tok = session->send.toks[0]; + session->send.index++; + return MPACK_EOF; + } + + if (session->send.index == 1) { + *tok = session->send.toks[1]; + session->send.index++; + return MPACK_EOF; + } + + assert(session->send.index == 2); + *tok = session->send.toks[2]; + mpack_rpc_reset_hdr(&session->send); + return MPACK_OK; +} + +MPACK_API int mpack_rpc_notify_tok(mpack_rpc_session_t *session, + mpack_token_t *tok) +{ + if (session->send.index == 0) { + session->send = mpack_rpc_notify_hdr(); + *tok = session->send.toks[0]; + session->send.index++; + return MPACK_EOF; + } + + assert(session->send.index == 1); + *tok = session->send.toks[1]; + mpack_rpc_reset_hdr(&session->send); + return MPACK_OK; +} + +MPACK_API int mpack_rpc_receive(mpack_rpc_session_t *session, const char **buf, + size_t *buflen, mpack_rpc_message_t *msg) +{ + int status; + + do { + mpack_token_t tok; + status = mpack_read(&session->reader, buf, buflen, &tok); + if (status) break; + status = mpack_rpc_receive_tok(session, tok, msg); + if (status >= MPACK_RPC_REQUEST) break; + } while (*buflen); + + return status; +} + +MPACK_API int mpack_rpc_request(mpack_rpc_session_t *session, char **buf, + size_t *buflen, mpack_data_t data) +{ + int status = MPACK_EOF; + + while (status && *buflen) { + int write_status; + mpack_token_t tok; + if (!session->writer.plen) { + status = mpack_rpc_request_tok(session, &tok, data); + } + if (status == MPACK_NOMEM) break; + write_status = mpack_write(&session->writer, buf, buflen, &tok); + status = write_status ? write_status : status; + } + + return status; +} + +MPACK_API int mpack_rpc_reply(mpack_rpc_session_t *session, char **buf, + size_t *buflen, mpack_uint32_t id) +{ + int status = MPACK_EOF; + + while (status && *buflen) { + int write_status; + mpack_token_t tok; + if (!session->writer.plen) { + status = mpack_rpc_reply_tok(session, &tok, id); + } + write_status = mpack_write(&session->writer, buf, buflen, &tok); + status = write_status ? write_status : status; + } + + return status; +} + +MPACK_API int mpack_rpc_notify(mpack_rpc_session_t *session, char **buf, + size_t *buflen) +{ + int status = MPACK_EOF; + + while (status && *buflen) { + int write_status; + mpack_token_t tok; + if (!session->writer.plen) { + status = mpack_rpc_notify_tok(session, &tok); + } + write_status = mpack_write(&session->writer, buf, buflen, &tok); + status = write_status ? write_status : status; + } + + return status; +} + +MPACK_API void mpack_rpc_session_copy(mpack_rpc_session_t *dst, + mpack_rpc_session_t *src) +{ + mpack_uint32_t i; + mpack_uint32_t dst_capacity = dst->capacity; + assert(src->capacity <= dst_capacity); + /* copy all fields except slots */ + memcpy(dst, src, sizeof(mpack_rpc_one_session_t) - + sizeof(struct mpack_rpc_slot_s)); + /* reset capacity */ + dst->capacity = dst_capacity; + /* reinsert requests */ + memset(dst->slots, 0, sizeof(struct mpack_rpc_slot_s) * dst->capacity); + for (i = 0; i < src->capacity; i++) { + if (src->slots[i].used) mpack_rpc_put(dst, src->slots[i].msg); + } +} + +static mpack_rpc_header_t mpack_rpc_request_hdr(void) +{ + mpack_rpc_header_t hdr; + hdr.index = 0; + hdr.toks[0].type = MPACK_TOKEN_ARRAY; + hdr.toks[0].length = 4; + hdr.toks[1].type = MPACK_TOKEN_UINT; + hdr.toks[1].data.value.lo = 0; + hdr.toks[1].data.value.hi = 0; + return hdr; +} + +static mpack_rpc_header_t mpack_rpc_reply_hdr(void) +{ + mpack_rpc_header_t hdr = mpack_rpc_request_hdr(); + hdr.toks[1].data.value.lo = 1; + hdr.toks[1].data.value.hi = 0; + return hdr; +} + +static mpack_rpc_header_t mpack_rpc_notify_hdr(void) +{ + mpack_rpc_header_t hdr = mpack_rpc_request_hdr(); + hdr.toks[0].length = 3; + hdr.toks[1].data.value.lo = 2; + hdr.toks[1].data.value.hi = 0; + return hdr; +} + +static int mpack_rpc_put(mpack_rpc_session_t *session, mpack_rpc_message_t msg) +{ + struct mpack_rpc_slot_s *slot = NULL; + mpack_uint32_t i; + mpack_uint32_t hash = msg.id % session->capacity; + + for (i = 0; i < session->capacity; i++) { + if (!session->slots[hash].used || session->slots[hash].msg.id == msg.id) { + slot = session->slots + hash; + break; + } + hash = hash > 0 ? hash - 1 : session->capacity - 1; + } + + if (!slot) return -1; /* no space */ + if (slot->msg.id == msg.id && slot->used) return 0; /* duplicate key */ + slot->msg = msg; + slot->used = 1; + return 1; +} + +static int mpack_rpc_pop(mpack_rpc_session_t *session, mpack_rpc_message_t *msg) +{ + struct mpack_rpc_slot_s *slot = NULL; + mpack_uint32_t i; + mpack_uint32_t hash = msg->id % session->capacity; + + for (i = 0; i < session->capacity; i++) { + if (session->slots[hash].used && session->slots[hash].msg.id == msg->id) { + slot = session->slots + hash; + break; + } + hash = hash > 0 ? hash - 1 : session->capacity - 1; + } + + if (!slot) return 0; + + *msg = slot->msg; + slot->used = 0; + + return 1; +} + +static void mpack_rpc_reset_hdr(mpack_rpc_header_t *hdr) +{ + hdr->index = 0; +} diff --git a/src/mpack/rpc.h b/src/mpack/rpc.h new file mode 100644 index 0000000000..c1e8d656b5 --- /dev/null +++ b/src/mpack/rpc.h @@ -0,0 +1,83 @@ +#ifndef MPACK_RPC_H +#define MPACK_RPC_H + +#include "mpack_core.h" +#include "object.h" + +#ifndef MPACK_RPC_MAX_REQUESTS +# define MPACK_RPC_MAX_REQUESTS 32 +#endif + +enum { + MPACK_RPC_REQUEST = MPACK_NOMEM + 1, + MPACK_RPC_RESPONSE, + MPACK_RPC_NOTIFICATION, + MPACK_RPC_ERROR +}; + +enum { + MPACK_RPC_EARRAY = MPACK_RPC_ERROR, + MPACK_RPC_EARRAYL, + MPACK_RPC_ETYPE, + MPACK_RPC_EMSGID, + MPACK_RPC_ERESPID +}; + +typedef struct mpack_rpc_header_s { + mpack_token_t toks[3]; + int index; +} mpack_rpc_header_t; + +typedef struct mpack_rpc_message_s { + mpack_uint32_t id; + mpack_data_t data; +} mpack_rpc_message_t; + +struct mpack_rpc_slot_s { + int used; + mpack_rpc_message_t msg; +}; + +#define MPACK_RPC_SESSION_STRUCT(c) \ + struct { \ + mpack_tokbuf_t reader, writer; \ + mpack_rpc_header_t receive, send; \ + mpack_uint32_t request_id, capacity; \ + struct mpack_rpc_slot_s slots[c]; \ + } + +/* Some compilers warn against anonymous structs: + * https://github.com/libmpack/libmpack/issues/6 */ +typedef MPACK_RPC_SESSION_STRUCT(1) mpack_rpc_one_session_t; + +#define MPACK_RPC_SESSION_STRUCT_SIZE(c) \ + (sizeof(struct mpack_rpc_slot_s) * (c - 1) + \ + sizeof(mpack_rpc_one_session_t)) + +typedef MPACK_RPC_SESSION_STRUCT(MPACK_RPC_MAX_REQUESTS) mpack_rpc_session_t; + +MPACK_API void mpack_rpc_session_init(mpack_rpc_session_t *s, mpack_uint32_t c) + FUNUSED FNONULL; + +MPACK_API int mpack_rpc_receive_tok(mpack_rpc_session_t *s, mpack_token_t t, + mpack_rpc_message_t *msg) FUNUSED FNONULL; +MPACK_API int mpack_rpc_request_tok(mpack_rpc_session_t *s, mpack_token_t *t, + mpack_data_t d) FUNUSED FNONULL_ARG((1,2)); +MPACK_API int mpack_rpc_reply_tok(mpack_rpc_session_t *s, mpack_token_t *t, + mpack_uint32_t i) FUNUSED FNONULL; +MPACK_API int mpack_rpc_notify_tok(mpack_rpc_session_t *s, mpack_token_t *t) + FUNUSED FNONULL; + +MPACK_API int mpack_rpc_receive(mpack_rpc_session_t *s, const char **b, + size_t *bl, mpack_rpc_message_t *m) FUNUSED FNONULL; +MPACK_API int mpack_rpc_request(mpack_rpc_session_t *s, char **b, size_t *bl, + mpack_data_t d) FUNUSED FNONULL_ARG((1,2,3)); +MPACK_API int mpack_rpc_reply(mpack_rpc_session_t *s, char **b, size_t *bl, + mpack_uint32_t i) FNONULL FUNUSED; +MPACK_API int mpack_rpc_notify(mpack_rpc_session_t *s, char **b, size_t *bl) + FNONULL FUNUSED; + +MPACK_API void mpack_rpc_session_copy(mpack_rpc_session_t *d, + mpack_rpc_session_t *s) FUNUSED FNONULL; + +#endif /* MPACK_RPC_H */ diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt index 3b2207f80b..331ab16dd7 100644 --- a/src/nvim/CMakeLists.txt +++ b/src/nvim/CMakeLists.txt @@ -87,8 +87,8 @@ file(MAKE_DIRECTORY ${LINT_SUPPRESSES_ROOT}/src) file(GLOB NVIM_SOURCES *.c) file(GLOB NVIM_HEADERS *.h) -file(GLOB XDIFF_SOURCES xdiff/*.c) -file(GLOB XDIFF_HEADERS xdiff/*.h) +file(GLOB EXTERNAL_SOURCES ../xdiff/*.c ../mpack/*.c) +file(GLOB EXTERNAL_HEADERS ../xdiff/*.h ../mpack/*.h) foreach(subdir os @@ -171,8 +171,8 @@ foreach(sfile ${CONV_SOURCES}) message(FATAL_ERROR "${sfile} doesn't exist (it was added to CONV_SOURCES)") endif() endforeach() -# xdiff: inlined external project, we don't maintain it. #9306 -list(APPEND CONV_SOURCES ${XDIFF_SOURCES}) +# xdiff, mpack: inlined external project, we don't maintain it. #9306 +list(APPEND CONV_SOURCES ${EXTERNAL_SOURCES}) if(NOT MSVC) set_source_files_properties( @@ -471,7 +471,7 @@ endif() add_executable(nvim ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} ${NVIM_GENERATED_SOURCES} ${NVIM_SOURCES} ${NVIM_HEADERS} - ${XDIFF_SOURCES} ${XDIFF_HEADERS}) + ${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS}) target_link_libraries(nvim ${NVIM_EXEC_LINK_LIBRARIES}) install_helper(TARGETS nvim) @@ -602,7 +602,7 @@ add_library( EXCLUDE_FROM_ALL ${NVIM_SOURCES} ${NVIM_GENERATED_SOURCES} ${NVIM_HEADERS} ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} - ${XDIFF_SOURCES} ${XDIFF_HEADERS} + ${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS} ) set_property(TARGET libnvim APPEND PROPERTY INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS}) @@ -632,7 +632,7 @@ else() EXCLUDE_FROM_ALL ${NVIM_SOURCES} ${NVIM_GENERATED_SOURCES} ${NVIM_HEADERS} ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS} - ${XDIFF_SOURCES} ${XDIFF_HEADERS} + ${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS} ${UNIT_TEST_FIXTURES} ) target_link_libraries(nvim-test ${NVIM_TEST_LINK_LIBRARIES}) diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c index 878ffdf06f..3808f601d9 100644 --- a/src/nvim/api/buffer.c +++ b/src/nvim/api/buffer.c @@ -1232,7 +1232,7 @@ static Array extmark_to_array(ExtmarkInfo extmark, bool id, bool add_dict) return rv; } -/// Returns position for a given extmark id +/// Gets the position (0-indexed) of an extmark. /// /// @param buffer Buffer handle, or 0 for current buffer /// @param ns_id Namespace id from |nvim_create_namespace()| @@ -1240,7 +1240,8 @@ static Array extmark_to_array(ExtmarkInfo extmark, bool id, bool add_dict) /// @param opts Optional parameters. Keys: /// - details: Whether to include the details dict /// @param[out] err Error details, if any -/// @return (row, col) tuple or empty list () if extmark id was absent +/// @return 0-indexed (row, col) tuple or empty list () if extmark id was +/// absent ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id, Integer id, Dictionary opts, Error *err) @@ -1320,10 +1321,10 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id, /// /// @param buffer Buffer handle, or 0 for current buffer /// @param ns_id Namespace id from |nvim_create_namespace()| -/// @param start Start of range, given as (row, col) or valid extmark id -/// (whose position defines the bound) -/// @param end End of range, given as (row, col) or valid extmark id -/// (whose position defines the bound) +/// @param start Start of range: a 0-indexed (row, col) or valid extmark id +/// (whose position defines the bound). |api-indexing| +/// @param end End of range (inclusive): a 0-indexed (row, col) or valid +/// extmark id (whose position defines the bound). |api-indexing| /// @param opts Optional parameters. Keys: /// - limit: Maximum number of marks to return /// - details Whether to include the details dict @@ -1424,8 +1425,8 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, /// /// @param buffer Buffer handle, or 0 for current buffer /// @param ns_id Namespace id from |nvim_create_namespace()| -/// @param line Line where to place the mark, 0-based -/// @param col Column where to place the mark, 0-based +/// @param line Line where to place the mark, 0-based. |api-indexing| +/// @param col Column where to place the mark, 0-based. |api-indexing| /// @param opts Optional parameters. /// - id : id of the extmark to edit. /// - end_line : ending line of the mark, 0-based inclusive. diff --git a/src/nvim/api/ui_events.in.h b/src/nvim/api/ui_events.in.h index 35d39a34d7..03fe5c5058 100644 --- a/src/nvim/api/ui_events.in.h +++ b/src/nvim/api/ui_events.in.h @@ -119,7 +119,8 @@ void msg_set_pos(Integer grid, Integer row, Boolean scrolled, String sep_char) FUNC_API_SINCE(6) FUNC_API_BRIDGE_IMPL FUNC_API_COMPOSITOR_IMPL; void win_viewport(Integer grid, Window win, Integer topline, - Integer botline, Integer curline, Integer curcol) + Integer botline, Integer curline, Integer curcol, + Integer line_count) FUNC_API_SINCE(7) FUNC_API_REMOTE_ONLY; void popupmenu_show(Array items, Integer selected, diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index 2536249de5..f65d5cc185 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -275,9 +275,9 @@ static void on_redraw_event(void **argv) /// /// On execution error: does not fail, but updates v:errmsg. /// -/// If you need to input sequences like <C-o> use |nvim_replace_termcodes| to -/// replace the termcodes and then pass the resulting string to nvim_feedkeys. -/// You'll also want to enable escape_csi. +/// To input sequences like <C-o> use |nvim_replace_termcodes()| (typically +/// with escape_csi=true) to replace |keycodes|, then pass the result to +/// nvim_feedkeys(). /// /// Example: /// <pre> @@ -1551,7 +1551,7 @@ void nvim_set_current_tabpage(Tabpage tabpage, Error *err) } } -/// Creates a new namespace, or gets an existing one. +/// Creates a new *namespace*, or gets an existing one. /// /// Namespaces are used for buffer highlights and virtual text, see /// |nvim_buf_add_highlight()| and |nvim_buf_set_extmark()|. @@ -2057,27 +2057,28 @@ void nvim_set_client_info(uint64_t channel_id, String name, rpc_set_client_info(channel_id, info); } -/// Get information about a channel. +/// Gets information about a channel. /// /// @returns Dictionary describing a channel, with these keys: -/// - "stream" the stream underlying the channel +/// - "id" Channel id. +/// - "argv" (optional) Job arguments list. +/// - "stream" Stream underlying the channel. /// - "stdio" stdin and stdout of this Nvim instance /// - "stderr" stderr of this Nvim instance /// - "socket" TCP/IP socket or named pipe -/// - "job" job with communication over its stdio -/// - "mode" how data received on the channel is interpreted -/// - "bytes" send and receive raw bytes -/// - "terminal" a |terminal| instance interprets ASCII sequences -/// - "rpc" |RPC| communication on the channel is active -/// - "pty" Name of pseudoterminal, if one is used (optional). -/// On a POSIX system, this will be a device path like -/// /dev/pts/1. Even if the name is unknown, the key will -/// still be present to indicate a pty is used. This is -/// currently the case when using winpty on windows. -/// - "buffer" buffer with connected |terminal| instance (optional) -/// - "client" information about the client on the other end of the -/// RPC channel, if it has added it using -/// |nvim_set_client_info()|. (optional) +/// - "job" Job with communication over its stdio. +/// - "mode" How data received on the channel is interpreted. +/// - "bytes" Send and receive raw bytes. +/// - "terminal" |terminal| instance interprets ASCII sequences. +/// - "rpc" |RPC| communication on the channel is active. +/// - "pty" (optional) Name of pseudoterminal. On a POSIX system this +/// is a device path like "/dev/pts/1". If the name is unknown, +/// the key will still be present if a pty is used (e.g. for +/// winpty on Windows). +/// - "buffer" (optional) Buffer with connected |terminal| instance. +/// - "client" (optional) Info about the peer (client on the other end of +/// the RPC channel), if provided by it via +/// |nvim_set_client_info()|. /// Dictionary nvim_get_chan_info(Integer chan, Error *err) FUNC_API_SINCE(4) diff --git a/src/nvim/ascii.h b/src/nvim/ascii.h index f41068ea70..7b5e82cd3f 100644 --- a/src/nvim/ascii.h +++ b/src/nvim/ascii.h @@ -169,6 +169,14 @@ static inline bool ascii_isbdigit(int c) return (c == '0' || c == '1'); } +/// Checks if `c` is an octal digit, that is, 0-7. +/// +/// @see {ascii_isdigit} +static inline bool ascii_isodigit(int c) +{ + return (c >= '0' && c <= '7'); +} + /// Checks if `c` is a white-space character, that is, /// one of \f, \n, \r, \t, \v. /// diff --git a/src/nvim/aucmd.c b/src/nvim/aucmd.c index 32c77fa288..802fc9de57 100644 --- a/src/nvim/aucmd.c +++ b/src/nvim/aucmd.c @@ -8,6 +8,7 @@ #include "nvim/ui.h" #include "nvim/aucmd.h" #include "nvim/eval.h" +#include "nvim/ex_docmd.h" #include "nvim/ex_getln.h" #include "nvim/buffer.h" @@ -35,6 +36,29 @@ void do_autocmd_uienter(uint64_t chanid, bool attached) recursive = false; } +void init_default_autocmds(void) +{ + // open terminals when opening files that start with term:// +#define PROTO "term://" + do_cmdline_cmd("augroup nvim_terminal"); + do_cmdline_cmd("autocmd BufReadCmd " PROTO "* ++nested " + "if !exists('b:term_title')|call termopen(" + // Capture the command string + "matchstr(expand(\"<amatch>\"), " + "'\\c\\m" PROTO "\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), " + // capture the working directory + "{'cwd': expand(get(matchlist(expand(\"<amatch>\"), " + "'\\c\\m" PROTO "\\(.\\{-}\\)//'), 1, ''))})" + "|endif"); + do_cmdline_cmd("augroup END"); +#undef PROTO + + // limit syntax synchronization in the command window + do_cmdline_cmd("augroup nvim_cmdwin"); + do_cmdline_cmd("autocmd! CmdwinEnter [:>] syntax sync minlines=1 maxlines=1"); + do_cmdline_cmd("augroup END"); +} + static void focusgained_event(void **argv) { bool *gainedp = argv[0]; diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index 0ae8dd3664..89f7448188 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -230,6 +230,8 @@ typedef struct { # define w_p_culopt w_onebuf_opt.wo_culopt // 'cursorlineopt' char_u *wo_cc; # define w_p_cc w_onebuf_opt.wo_cc // 'colorcolumn' + char_u *wo_sbr; +# define w_p_sbr w_onebuf_opt.wo_sbr // 'showbreak' char_u *wo_stl; #define w_p_stl w_onebuf_opt.wo_stl // 'statusline' int wo_scb; diff --git a/src/nvim/channel.c b/src/nvim/channel.c index 6f12d2eab8..94db7fb3b9 100644 --- a/src/nvim/channel.c +++ b/src/nvim/channel.c @@ -240,6 +240,10 @@ static void free_channel_event(void **argv) rpc_free(chan); } + if (chan->streamtype == kChannelStreamProc) { + process_free(&chan->stream.proc); + } + callback_reader_free(&chan->on_data); callback_reader_free(&chan->on_stderr); callback_free(&chan->on_exit); @@ -847,13 +851,24 @@ Dictionary channel_info(uint64_t id) const char *stream_desc, *mode_desc; switch (chan->streamtype) { - case kChannelStreamProc: + case kChannelStreamProc: { stream_desc = "job"; if (chan->stream.proc.type == kProcessTypePty) { const char *name = pty_process_tty_name(&chan->stream.pty); PUT(info, "pty", STRING_OBJ(cstr_to_string(name))); } + + char **p = chan->stream.proc.argv; + Array argv = ARRAY_DICT_INIT; + if (p != NULL) { + while (*p != NULL) { + ADD(argv, STRING_OBJ(cstr_to_string(*p))); + p++; + } + } + PUT(info, "argv", ARRAY_OBJ(argv)); break; + } case kChannelStreamStdio: stream_desc = "stdio"; diff --git a/src/nvim/charset.c b/src/nvim/charset.c index 0252ef4e9c..ab4e4ad4bd 100644 --- a/src/nvim/charset.c +++ b/src/nvim/charset.c @@ -941,7 +941,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, // 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 - && (*p_sbr == NUL) + && *get_showbreak_value(wp) == NUL && !wp->w_p_bri ) { for (;;) { head = 0; @@ -1385,6 +1385,8 @@ bool vim_isblankline(char_u *lbuf) /// If "prep" is not NULL, returns a flag to indicate the type of the number: /// 0 decimal /// '0' octal +/// 'O' octal +/// 'o' octal /// 'B' bin /// 'b' bin /// 'X' hex @@ -1396,20 +1398,25 @@ bool vim_isblankline(char_u *lbuf) /// If "what" contains STR2NR_OCT recognize octal numbers. /// If "what" contains STR2NR_HEX recognize hex numbers. /// If "what" contains STR2NR_FORCE always assume bin/oct/hex. +/// If "what" contains STR2NR_QUOTE ignore embedded single quotes /// If maxlen > 0, check at a maximum maxlen chars. +/// If strict is true, check the number strictly. return *len = 0 if fail. /// /// @param start /// @param prep Returns guessed type of number 0 = decimal, 'x' or 'X' is -/// hexadecimal, '0' = octal, 'b' or 'B' is binary. When using -/// STR2NR_FORCE is always zero. +/// hexadecimal, '0', 'o' or 'O' is octal, 'b' or 'B' is binary. +/// When using STR2NR_FORCE is always zero. /// @param len Returns the detected length of number. /// @param what Recognizes what number passed, @see ChStr2NrFlags. /// @param nptr Returns the signed result. /// @param unptr Returns the unsigned result. /// @param maxlen Max length of string to check. +/// @param strict If true, fail if the number has unexpected trailing +/// alpha-numeric 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, varnumber_T *const nptr, - uvarnumber_T *const unptr, const int maxlen) + uvarnumber_T *const unptr, const int maxlen, const bool strict) FUNC_ATTR_NONNULL_ARG(1) { const char *ptr = (const char *)start; @@ -1419,14 +1426,18 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, const bool negative = (ptr[0] == '-'); uvarnumber_T un = 0; + if (len != NULL) { + *len = 0; + } + if (negative) { ptr++; } if (what & STR2NR_FORCE) { - // When forcing main consideration is skipping the prefix. Octal and decimal - // numbers have no prefixes to skip. pre is not set. - switch ((unsigned)what & (~(unsigned)STR2NR_FORCE)) { + // When forcing main consideration is skipping the prefix. Decimal numbers + // have no prefixes to skip. pre is not set. + switch (what & ~(STR2NR_FORCE | STR2NR_QUOTE)) { case STR2NR_HEX: { if (!STRING_ENDED(ptr + 2) && ptr[0] == '0' @@ -1445,7 +1456,16 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, } goto vim_str2nr_bin; } - case STR2NR_OCT: { + // Make STR2NR_OOCT work the same as STR2NR_OCT when forcing. + case STR2NR_OCT: + case STR2NR_OOCT: + case STR2NR_OCT | STR2NR_OOCT: { + if (!STRING_ENDED(ptr + 2) + && ptr[0] == '0' + && (ptr[1] == 'o' || ptr[1] == 'O') + && ascii_isodigit(ptr[2])) { + ptr += 2; + } goto vim_str2nr_oct; } case 0: { @@ -1455,9 +1475,9 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, abort(); } } - } else if ((what & (STR2NR_HEX|STR2NR_OCT|STR2NR_BIN)) - && !STRING_ENDED(ptr + 1) - && ptr[0] == '0' && ptr[1] != '8' && ptr[1] != '9') { + } 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 = ptr[1]; // Detect hexadecimal: 0x or 0X followed by hex digit. if ((what & STR2NR_HEX) @@ -1475,10 +1495,18 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, ptr += 2; goto vim_str2nr_bin; } - // Detect octal number: zero followed by octal digits without '8' or '9'. + // Detect octal: 0o or 0O followed by octal digits (without '8' or '9'). + if ((what & STR2NR_OOCT) + && !STRING_ENDED(ptr + 2) + && (pre == 'O' || pre == 'o') + && ascii_isodigit(ptr[2])) { + ptr += 2; + goto vim_str2nr_oct; + } + // Detect old octal format: 0 followed by octal digits. pre = 0; if (!(what & STR2NR_OCT) - || !('0' <= ptr[1] && ptr[1] <= '7')) { + || !ascii_isodigit(ptr[1])) { goto vim_str2nr_dec; } for (int i = 2; !STRING_ENDED(ptr + i) && ascii_isdigit(ptr[i]); i++) { @@ -1492,11 +1520,22 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, goto vim_str2nr_dec; } - // Do the string-to-numeric conversion "manually" to avoid sscanf quirks. + // Do the conversion manually to avoid sscanf() quirks. abort(); // Should’ve used goto earlier. #define PARSE_NUMBER(base, cond, conv) \ do { \ - while (!STRING_ENDED(ptr) && (cond)) { \ + const char *const after_prefix = ptr; \ + while (!STRING_ENDED(ptr)) { \ + if ((what & STR2NR_QUOTE) && ptr > after_prefix && *ptr == '\'') { \ + ptr++; \ + if (!STRING_ENDED(ptr) && (cond)) { \ + continue; \ + } \ + ptr--; \ + } \ + if (!(cond)) { \ + break; \ + } \ const uvarnumber_T digit = (uvarnumber_T)(conv); \ /* avoid ubsan error for overflow */ \ if (un < UVARNUMBER_MAX / base \ @@ -1513,7 +1552,7 @@ vim_str2nr_bin: PARSE_NUMBER(2, (*ptr == '0' || *ptr == '1'), (*ptr - '0')); goto vim_str2nr_proceed; vim_str2nr_oct: - PARSE_NUMBER(8, ('0' <= *ptr && *ptr <= '7'), (*ptr - '0')); + PARSE_NUMBER(8, (ascii_isodigit(*ptr)), (*ptr - '0')); goto vim_str2nr_proceed; vim_str2nr_dec: PARSE_NUMBER(10, (ascii_isdigit(*ptr)), (*ptr - '0')); @@ -1524,6 +1563,12 @@ vim_str2nr_hex: #undef PARSE_NUMBER vim_str2nr_proceed: + // Check for an alpha-numeric character immediately following, that is + // most likely a typo. + if (strict && ptr - (const char *)start != maxlen && ASCII_ISALNUM(*ptr)) { + return; + } + if (prep != NULL) { *prep = pre; } diff --git a/src/nvim/charset.h b/src/nvim/charset.h index e657ce19b6..2fef4d78a2 100644 --- a/src/nvim/charset.h +++ b/src/nvim/charset.h @@ -23,13 +23,20 @@ typedef enum { STR2NR_BIN = (1 << 0), ///< Allow binary numbers. STR2NR_OCT = (1 << 1), ///< Allow octal numbers. STR2NR_HEX = (1 << 2), ///< Allow hexadecimal numbers. + STR2NR_OOCT = (1 << 3), ///< Octal with prefix "0o": 0o777 /// Force one of the above variants. /// /// STR2NR_FORCE|STR2NR_DEC is actually not different from supplying zero /// as flags, but still present for completeness. - STR2NR_FORCE = (1 << 3), + /// + /// STR2NR_FORCE|STR2NR_OCT|STR2NR_OOCT is the same as STR2NR_FORCE|STR2NR_OCT + /// or STR2NR_FORCE|STR2NR_OOCT. + STR2NR_FORCE = (1 << 7), /// Recognize all formats vim_str2nr() can recognize. - STR2NR_ALL = STR2NR_BIN | STR2NR_OCT | STR2NR_HEX, + STR2NR_ALL = STR2NR_BIN | STR2NR_OCT | STR2NR_HEX | STR2NR_OOCT, + /// Disallow octals numbers without the 0o prefix. + STR2NR_NO_OCT = STR2NR_BIN | STR2NR_HEX | STR2NR_OOCT, + STR2NR_QUOTE = (1 << 4), ///< Ignore embedded single quotes. } ChStr2NrFlags; #ifdef INCLUDE_GENERATED_DECLARATIONS diff --git a/src/nvim/diff.c b/src/nvim/diff.c index 299175b28c..26269a44d2 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -1059,7 +1059,7 @@ static int diff_file_internal(diffio_T *diffio) emit_cfg.ctxlen = 0; // don't need any diff_context here emit_cb.priv = &diffio->dio_diff; - emit_cb.outf = xdiff_out; + emit_cb.out_line = xdiff_out; if (xdl_diff(&diffio->dio_orig.din_mmfile, &diffio->dio_new.din_mmfile, ¶m, &emit_cfg, &emit_cb) < 0) { diff --git a/src/nvim/edit.c b/src/nvim/edit.c index ffe60ab043..f39a6a281b 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -6,60 +6,60 @@ */ #include <assert.h> -#include <string.h> #include <inttypes.h> #include <stdbool.h> +#include <string.h> -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/edit.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" #include "nvim/digraph.h" +#include "nvim/edit.h" #include "nvim/eval.h" #include "nvim/eval/typval.h" +#include "nvim/event/loop.h" #include "nvim/ex_docmd.h" #include "nvim/ex_getln.h" +#include "nvim/extmark.h" #include "nvim/fileio.h" #include "nvim/fold.h" #include "nvim/getchar.h" #include "nvim/indent.h" #include "nvim/indent_c.h" +#include "nvim/keymap.h" #include "nvim/main.h" -#include "nvim/extmark.h" +#include "nvim/mark.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/keymap.h" +#include "nvim/mouse.h" #include "nvim/move.h" #include "nvim/normal.h" #include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/time.h" #include "nvim/path.h" -#include "nvim/popupmnu.h" #include "nvim/plines.h" +#include "nvim/popupmnu.h" #include "nvim/quickfix.h" #include "nvim/regexp.h" #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/spell.h" -#include "nvim/strings.h" #include "nvim/state.h" +#include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/tag.h" -#include "nvim/ui.h" -#include "nvim/mouse.h" #include "nvim/terminal.h" +#include "nvim/ui.h" #include "nvim/undo.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/event/loop.h" -#include "nvim/mark.h" -#include "nvim/os/input.h" -#include "nvim/os/time.h" // Definitions used for CTRL-X submode. // Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] @@ -84,6 +84,7 @@ #define CTRL_X_SPELL 14 #define CTRL_X_LOCAL_MSG 15 ///< only used in "ctrl_x_msgs" #define CTRL_X_EVAL 16 ///< for builtin function complete() +#define CTRL_X_CMDLINE_CTRL_X 17 ///< CTRL-X typed in CTRL_X_CMDLINE #define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT] #define CTRL_X_MODE_LINE_OR_EVAL(m) \ @@ -109,6 +110,7 @@ static char *ctrl_x_msgs[] = N_(" Spelling suggestion (s^N^P)"), N_(" Keyword Local completion (^N^P)"), NULL, // CTRL_X_EVAL doesn't use msg. + N_(" Command-line completion (^V^N^P)"), }; static char *ctrl_x_mode_names[] = { @@ -128,7 +130,8 @@ static char *ctrl_x_mode_names[] = { "omni", "spell", NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs" - "eval" + "eval", + "cmdline", }; static char e_hitend[] = N_("Hit end of paragraph"); @@ -140,13 +143,13 @@ static char e_compldel[] = N_("E840: Completion function deleted text"); */ typedef struct compl_S compl_T; struct compl_S { - compl_T *cp_next; - compl_T *cp_prev; - char_u *cp_str; // matched text - char_u *(cp_text[CPT_COUNT]); // text for the menu + compl_T *cp_next; + compl_T *cp_prev; + char_u *cp_str; // matched text + char_u *(cp_text[CPT_COUNT]); // text for the menu typval_T cp_user_data; - char_u *cp_fname; // file containing the match, allocated when - // cp_flags has CP_FREE_FNAME + char_u *cp_fname; // file containing the match, allocated when + // cp_flags has CP_FREE_FNAME int cp_flags; // CP_ values int cp_number; // sequence number }; @@ -158,10 +161,10 @@ struct compl_S { * "compl_shown_match" is different from compl_curr_match during * ins_compl_get_exp(). */ -static compl_T *compl_first_match = NULL; -static compl_T *compl_curr_match = NULL; -static compl_T *compl_shown_match = NULL; -static compl_T *compl_old_match = NULL; +static compl_T *compl_first_match = NULL; +static compl_T *compl_curr_match = NULL; +static compl_T *compl_shown_match = NULL; +static compl_T *compl_old_match = NULL; /* After using a cursor key <Enter> selects a match in the popup menu, * otherwise it inserts a line break. */ @@ -169,7 +172,7 @@ static int compl_enter_selects = FALSE; /* When "compl_leader" is not NULL only matches that start with this string * are used. */ -static char_u *compl_leader = NULL; +static char_u *compl_leader = NULL; static int compl_get_longest = FALSE; /* put longest common string in compl_leader */ @@ -196,15 +199,15 @@ static bool compl_started = false; static int ctrl_x_mode = CTRL_X_NORMAL; static int compl_matches = 0; -static char_u *compl_pattern = NULL; +static char_u *compl_pattern = NULL; static Direction compl_direction = FORWARD; static Direction compl_shows_dir = FORWARD; static int compl_pending = 0; // > 1 for postponed CTRL-N static pos_T compl_startpos; 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 - * completion started */ +static char_u *compl_orig_text = NULL; /* text as it was before + * completion started */ static int compl_cont_mode = 0; static expand_T compl_xp; @@ -257,8 +260,8 @@ static colnr_T Insstart_textlen; // length of line when insert started static colnr_T Insstart_blank_vcol; // vcol for first inserted blank static bool update_Insstart_orig = true; // set Insstart_orig to Insstart -static char_u *last_insert = NULL; // the text of the previous insert, - // K_SPECIAL and CSI are escaped +static char_u *last_insert = NULL; // the text of the previous insert, + // K_SPECIAL and CSI are escaped static int last_insert_skip; // nr of chars in front of previous insert static int new_insert_skip; // nr of chars in front of current insert static int did_restart_edit; // "restart_edit" when calling edit() @@ -310,7 +313,7 @@ static void insert_enter(InsertState *s) s->ptr = (char_u *)"i"; } - set_vim_var_string(VV_INSERTMODE, (char *) s->ptr, 1); + set_vim_var_string(VV_INSERTMODE, (char *)s->ptr, 1); set_vim_var_string(VV_CHAR, NULL, -1); ins_apply_autocmds(EVENT_INSERTENTER); @@ -762,7 +765,8 @@ static int insert_execute(VimState *state, int key) s->c = do_digraph(s->c); - if ((s->c == Ctrl_V || s->c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE) { + if ((s->c == Ctrl_V || s->c == Ctrl_Q) + && (ctrl_x_mode == CTRL_X_CMDLINE || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X)) { insert_do_complete(s); return 1; } @@ -791,15 +795,22 @@ static int insert_execute(VimState *state, int key) } } - if (curwin->w_p_rl) + if (curwin->w_p_rl) { switch (s->c) { - case K_LEFT: s->c = K_RIGHT; break; - case K_S_LEFT: s->c = K_S_RIGHT; break; - case K_C_LEFT: s->c = K_C_RIGHT; break; - case K_RIGHT: s->c = K_LEFT; break; - case K_S_RIGHT: s->c = K_S_LEFT; break; - case K_C_RIGHT: s->c = K_C_LEFT; break; + case K_LEFT: + s->c = K_RIGHT; break; + case K_S_LEFT: + s->c = K_S_RIGHT; break; + case K_C_LEFT: + s->c = K_C_RIGHT; break; + case K_RIGHT: + s->c = K_LEFT; break; + case K_S_RIGHT: + s->c = K_S_LEFT; break; + case K_C_RIGHT: + s->c = K_C_LEFT; break; } + } // If 'keymodel' contains "startsel", may start selection. If it // does, a CTRL-O and c will be stuffed, we need to get these @@ -1288,8 +1299,9 @@ normalchar: // If the new value is already inserted or an empty string // then don't insert any character. - if (s->c == NUL) + if (s->c == NUL) { break; + } } // Try to perform smart-indenting. ins_try_si(s->c); @@ -1309,8 +1321,8 @@ normalchar: // special character. Let CTRL-] expand abbreviations without // inserting it. if (vim_iswordc(s->c) - // Add ABBR_OFF for characters above 0x100, this is - // what check_abbr() expects. + // Add ABBR_OFF for characters above 0x100, this is + // what check_abbr() expects. || (!echeck_abbr((s->c >= 0x100) ? (s->c + ABBR_OFF) : s->c) && s->c != Ctrl_RSB)) { insert_special(s->c, false, false); @@ -1415,21 +1427,20 @@ bool edit(int cmdchar, bool startln, long count) return s->c == Ctrl_O; } -/* - * Redraw for Insert mode. - * This is postponed until getting the next character to make '$' in the 'cpo' - * option work correctly. - * Only redraw when there are no characters available. This speeds up - * inserting sequences of characters (e.g., for CTRL-R). - */ -static void ins_redraw( - bool ready // not busy with something -) +/// Redraw for Insert mode. +/// This is postponed until getting the next character to make '$' in the 'cpo' +/// option work correctly. +/// Only redraw when there are no characters available. This speeds up +/// inserting sequences of characters (e.g., for CTRL-R). +/// +/// @param ready not busy with something +static void ins_redraw(bool ready) { bool conceal_cursor_moved = false; - if (char_avail()) + if (char_avail()) { return; + } // Trigger CursorMoved if the cursor moved. Not when the popup menu is // visible, the command might delete it. @@ -1655,8 +1666,8 @@ static void init_prompt(int cmdchar_todo) /// @return true if the cursor is in the editable position of the prompt line. bool prompt_curpos_editable(void) { - return curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count - && curwin->w_cursor.col >= (int)STRLEN(prompt_text()); + return curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count + && curwin->w_cursor.col >= (int)STRLEN(prompt_text()); } /* @@ -1685,8 +1696,9 @@ void display_dollar(colnr_T col) { colnr_T save_col; - if (!redrawing()) + if (!redrawing()) { return; + } save_col = curwin->w_cursor.col; curwin->w_cursor.col = col; @@ -1714,34 +1726,28 @@ static void undisplay_dollar(void) } } -/* - * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D). - * Keep the cursor on the same character. - * type == INDENT_INC increase indent (for CTRL-T or <Tab>) - * type == INDENT_DEC decrease indent (for CTRL-D) - * type == INDENT_SET set indent to "amount" - * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec). - */ -void -change_indent ( - int type, - int amount, - int round, - int replaced, // replaced character, put on replace stack - int call_changed_bytes // call changed_bytes() -) +/// Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D). +/// Keep the cursor on the same character. +/// type == INDENT_INC increase indent (for CTRL-T or <Tab>) +/// type == INDENT_DEC decrease indent (for CTRL-D) +/// type == INDENT_SET set indent to "amount" +/// +/// @param round if TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec). +/// @param replaced replaced character, put on replace stack +/// @param call_changed_bytes call changed_bytes() +void change_indent(int type, int amount, int round, int replaced, int call_changed_bytes) { int vcol; int last_vcol; int insstart_less; // reduction for Insstart.col int new_cursor_col; int i; - char_u *ptr; + char_u *ptr; int save_p_list; int start_col; colnr_T vc; colnr_T orig_col = 0; // init for GCC - char_u *new_line, *orig_line = NULL; // init for GCC + char_u *new_line, *orig_line = NULL; // init for GCC // VREPLACE mode needs to know what the line was like before changing if (State & VREPLACE_FLAG) { @@ -1773,8 +1779,9 @@ change_indent ( * 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) + if (new_cursor_col < 0) { vcol = get_indent() - vcol; + } if (new_cursor_col > 0) { // can't fix replace stack start_col = -1; @@ -1783,9 +1790,9 @@ change_indent ( /* * Set the new indent. The cursor will be put on the first non-blank. */ - if (type == INDENT_SET) + if (type == INDENT_SET) { (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); - else { + } else { int save_State = State; // Avoid being called recursively. @@ -1811,12 +1818,13 @@ change_indent ( * When changing the indent while the cursor is touching it, reset * Insstart_col to 0. */ - if (new_cursor_col == 0) + if (new_cursor_col == 0) { insstart_less = MAXCOL; + } new_cursor_col += curwin->w_cursor.col; - } else if (!(State & INSERT)) + } else if (!(State & INSERT)) { new_cursor_col = curwin->w_cursor.col; - else { + } else { /* * Compute the screen column where the cursor should be. */ @@ -1863,10 +1871,11 @@ change_indent ( curwin->w_p_list = save_p_list; - if (new_cursor_col <= 0) + if (new_cursor_col <= 0) { curwin->w_cursor.col = 0; - else + } else { curwin->w_cursor.col = (colnr_T)new_cursor_col; + } curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); @@ -1875,15 +1884,17 @@ change_indent ( */ if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { - if ((int)Insstart.col <= insstart_less) + if ((int)Insstart.col <= insstart_less) { Insstart.col = 0; - else + } else { Insstart.col -= insstart_less; + } } - if ((int)ai_col <= insstart_less) + if ((int)ai_col <= insstart_less) { ai_col = 0; - else + } else { ai_col -= insstart_less; + } } /* @@ -1975,10 +1986,11 @@ void backspace_until_column(int col) { while ((int)curwin->w_cursor.col > col) { curwin->w_cursor.col--; - if (State & REPLACE_FLAG) + if (State & REPLACE_FLAG) { replace_do_bs(col); - else if (!del_char_after_col(col)) + } else if (!del_char_after_col(col)) { break; + } } } @@ -2020,20 +2032,22 @@ static bool del_char_after_col(int limit_col) */ static void ins_ctrl_x(void) { - /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X - * CTRL-V works like CTRL-N */ - if (ctrl_x_mode != CTRL_X_CMDLINE) { - /* if the next ^X<> won't ADD nothing, then reset - * compl_cont_status */ - if (compl_cont_status & CONT_N_ADDS) + if (ctrl_x_mode != CTRL_X_CMDLINE && ctrl_x_mode != CTRL_X_CMDLINE_CTRL_X) { + // if the next ^X<> won't ADD nothing, then reset compl_cont_status + if (compl_cont_status & CONT_N_ADDS) { compl_cont_status |= CONT_INTRPT; - else + } else { compl_cont_status = 0; + } // 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_pre = NULL; showmode(); + } else { + // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X + // CTRL-V look like CTRL-N + ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X; } } @@ -2043,7 +2057,8 @@ bool ctrl_x_mode_not_default(void) return ctrl_x_mode != CTRL_X_NORMAL; } -// Whether CTRL-X was typed without a following character. +// Whether CTRL-X was typed without a following character, +// not including when in CTRL-X CTRL-V mode. bool ctrl_x_mode_not_defined_yet(void) { return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET; @@ -2095,12 +2110,14 @@ bool vim_is_ctrl_x_key(int c) case 0: // Not in any CTRL-X mode return c == Ctrl_N || c == Ctrl_P || c == Ctrl_X; case CTRL_X_NOT_DEFINED_YET: + case CTRL_X_CMDLINE_CTRL_X: return c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O - || c == Ctrl_S || c == Ctrl_K || c == 's'; + || c == Ctrl_S || c == Ctrl_K || c == 's' + || c == Ctrl_Z; case CTRL_X_SCROLL: return c == Ctrl_Y || c == Ctrl_E; case CTRL_X_WHOLE_LINE: @@ -2154,6 +2171,7 @@ static bool ins_compl_accept_char(int c) return vim_isfilec(c) && !vim_ispathsep(c); case CTRL_X_CMDLINE: + case CTRL_X_CMDLINE_CTRL_X: case CTRL_X_OMNI: // Command line and Omni completion can work with just about any // printable character, but do stop at white space. @@ -2172,8 +2190,8 @@ static bool ins_compl_accept_char(int c) /// the rest of the word to be in -- webb /// /// @param[in] cont_s_ipos next ^X<> will set initial_pos -int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, - Direction dir, bool cont_s_ipos) +int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname, Direction dir, + bool cont_s_ipos) FUNC_ATTR_NONNULL_ARG(1) { char_u *str = str_arg; @@ -2316,15 +2334,12 @@ 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_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) FUNC_ATTR_NONNULL_ARG(1) { - compl_T *match; + compl_T *match; const Direction dir = (cdir == kDirectionNotSet ? compl_direction : cdir); int flags = flags_arg; @@ -2420,9 +2435,9 @@ static int ins_compl_add(char_u *const str, int len, /* * Link the new match structure in the list of matches. */ - if (compl_first_match == NULL) + if (compl_first_match == NULL) { match->cp_next = match->cp_prev = NULL; - else if (dir == FORWARD) { + } else if (dir == FORWARD) { match->cp_next = compl_curr_match->cp_next; match->cp_prev = compl_curr_match; } else { // BACKWARD @@ -2472,7 +2487,7 @@ static bool ins_compl_equal(compl_T *match, char_u *str, size_t len) */ static void ins_compl_longest_match(compl_T *match) { - char_u *p, *s; + char_u *p, *s; int c1, c2; int had_match; @@ -2486,8 +2501,9 @@ static void ins_compl_longest_match(compl_T *match) /* When the match isn't there (to avoid matching itself) remove it * again after redrawing. */ - if (!had_match) + if (!had_match) { ins_compl_delete(); + } compl_used_match = false; } else { // Reduce the text if this match differs from compl_leader. @@ -2516,8 +2532,9 @@ static void ins_compl_longest_match(compl_T *match) /* When the match isn't there (to avoid matching itself) remove it * again after redrawing. */ - if (!had_match) + if (!had_match) { ins_compl_delete(); + } } compl_used_match = false; @@ -2601,8 +2618,9 @@ void set_completion(colnr_T startcol, list_T *list) ins_compl_free(); compl_direction = FORWARD; - if (startcol > curwin->w_cursor.col) + if (startcol > curwin->w_cursor.col) { startcol = curwin->w_cursor.col; + } compl_col = startcol; compl_length = (int)curwin->w_cursor.col - (int)startcol; // compl_pattern doesn't need to be set @@ -2725,8 +2743,8 @@ static void trigger_complete_changed_event(int cur) /// Also adjusts "compl_shown_match" to an entry that is actually displayed. void ins_compl_show_pum(void) { - compl_T *compl; - compl_T *shown_compl = NULL; + compl_T *compl; + compl_T *shown_compl = NULL; bool did_find_shown_match = false; bool shown_match_ok = false; int i; @@ -2735,8 +2753,9 @@ void ins_compl_show_pum(void) int lead_len = 0; bool array_changed = false; - if (!pum_wanted() || !pum_enough_matches()) + if (!pum_wanted() || !pum_enough_matches()) { return; + } // Dirty hard-coded hack: remove any matchparen highlighting. do_cmdline_cmd("if exists('g:loaded_matchparen')|3match none|endif"); @@ -2767,8 +2786,9 @@ void ins_compl_show_pum(void) } compl = compl->cp_next; } while (compl != NULL && compl != compl_first_match); - if (compl_match_arraysize == 0) + if (compl_match_arraysize == 0) { return; + } assert(compl_match_arraysize >= 0); compl_match_array = xcalloc(compl_match_arraysize, sizeof(pumitem_T)); @@ -2799,18 +2819,20 @@ void ins_compl_show_pum(void) cur = i; } - if (compl->cp_text[CPT_ABBR] != NULL) + if (compl->cp_text[CPT_ABBR] != NULL) { compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR]; - else + } else { compl_match_array[i].pum_text = compl->cp_str; + } compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND]; compl_match_array[i].pum_info = compl->cp_text[CPT_INFO]; - if (compl->cp_text[CPT_MENU] != NULL) + if (compl->cp_text[CPT_MENU] != NULL) { compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU]; - else + } else { compl_match_array[i++].pum_extra = compl->cp_fname; + } } if (compl == compl_shown_match) { @@ -2867,23 +2889,18 @@ void ins_compl_show_pum(void) #define DICT_FIRST (1) // use just first element in "dict" #define DICT_EXACT (2) // "dict" is the exact name of a file -/* - * Add any identifiers that match the given pattern in the list of dictionary - * files "dict_start" to the list of completions. - */ -static void -ins_compl_dictionaries ( - char_u *dict_start, - char_u *pat, - int flags, // DICT_FIRST and/or DICT_EXACT - int thesaurus // Thesaurus completion -) -{ - char_u *dict = dict_start; - char_u *ptr; - char_u *buf; +/// Add any identifiers that match the given pattern in the list of dictionary +/// files "dict_start" to the list of completions. +/// +/// @param flags DICT_FIRST and/or DICT_EXACT +/// @param thesaurus Thesaurus completion +static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, int thesaurus) +{ + char_u *dict = dict_start; + char_u *ptr; + char_u *buf; regmatch_T regmatch; - char_u **files; + char_u **files; int count; int save_p_scs; Direction dir = compl_direction; @@ -2891,10 +2908,11 @@ ins_compl_dictionaries ( if (*dict == NUL) { /* When 'dictionary' is empty and spell checking is enabled use * "spell". */ - if (!thesaurus && curwin->w_p_spell) + if (!thesaurus && curwin->w_p_spell) { dict = (char_u *)"spell"; - else + } else { return; + } } buf = xmalloc(LSIZE); @@ -2902,8 +2920,9 @@ ins_compl_dictionaries ( // If 'infercase' is set, don't use 'smartcase' here save_p_scs = p_scs; - if (curbuf->b_p_inf) + if (curbuf->b_p_inf) { p_scs = FALSE; + } /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern * to only match at the start of a line. Otherwise just match the @@ -2919,8 +2938,9 @@ ins_compl_dictionaries ( xfree(ptr); } else { regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); - if (regmatch.regprog == NULL) + if (regmatch.regprog == NULL) { goto theend; + } } // ignore case depends on 'ignorecase', 'smartcase' and "pat" @@ -2935,30 +2955,34 @@ ins_compl_dictionaries ( * backticks (for security, the 'dict' option may have been set in * a modeline). */ copy_option_part(&dict, buf, LSIZE, ","); - if (!thesaurus && STRCMP(buf, "spell") == 0) + if (!thesaurus && STRCMP(buf, "spell") == 0) { count = -1; - else if (vim_strchr(buf, '`') != NULL - || expand_wildcards(1, &buf, &count, &files, - EW_FILE|EW_SILENT) != OK) + } else if (vim_strchr(buf, '`') != NULL + || expand_wildcards(1, &buf, &count, &files, + EW_FILE|EW_SILENT) != OK) { count = 0; + } } if (count == -1) { /* Complete from active spelling. Skip "\<" in the pattern, we * don't use it as a RE. */ - if (pat[0] == '\\' && pat[1] == '<') + if (pat[0] == '\\' && pat[1] == '<') { ptr = pat + 2; - else + } else { ptr = pat; + } spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0); } else if (count > 0) { // avoid warning for using "files" uninit ins_compl_files(count, files, thesaurus, flags, - ®match, buf, &dir); - if (flags != DICT_EXACT) + ®match, buf, &dir); + if (flags != DICT_EXACT) { FreeWild(count, files); + } } - if (flags != 0) + if (flags != 0) { break; + } } theend: @@ -2967,14 +2991,13 @@ theend: xfree(buf); } -static void ins_compl_files(int count, char_u **files, int thesaurus, - int flags, regmatch_T *regmatch, char_u *buf, - Direction *dir) +static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, + regmatch_T *regmatch, char_u *buf, Direction *dir) FUNC_ATTR_NONNULL_ARG(2, 7) { - char_u *ptr; + char_u *ptr; int i; - FILE *fp; + FILE *fp; int add_r; for (i = 0; i < count && !got_int && !compl_interrupted; i++) { @@ -3017,8 +3040,9 @@ static void ins_compl_files(int count, char_u **files, int thesaurus, /* Find start of the next word. Skip white * space and punctuation. */ ptr = find_word_start(ptr); - if (*ptr == NUL || *ptr == NL) + if (*ptr == NUL || *ptr == NL) { break; + } wstart = ptr; // Find end of the word. @@ -3096,11 +3120,12 @@ char_u *find_word_end(char_u *ptr) */ static char_u *find_line_end(char_u *ptr) { - char_u *s; + char_u *s; s = ptr + STRLEN(ptr); - while (s > ptr && (s[-1] == CAR || s[-1] == NL)) + while (s > ptr && (s[-1] == CAR || s[-1] == NL)) { --s; + } return s; } @@ -3114,8 +3139,9 @@ static void ins_compl_free(void) XFREE_CLEAR(compl_pattern); XFREE_CLEAR(compl_leader); - if (compl_first_match == NULL) + if (compl_first_match == NULL) { return; + } ins_compl_del_pum(); pum_clear(); @@ -3277,9 +3303,9 @@ void get_complete_info(list_T *what_list, dict_T *retdict) tv_dict_add_str(di, S_LEN("info"), (char *)EMPTY_IF_NULL(match->cp_text[CPT_INFO])); if (match->cp_user_data.v_type == VAR_UNKNOWN) { - tv_dict_add_str(di, S_LEN("user_data"), ""); + tv_dict_add_str(di, S_LEN("user_data"), ""); } else { - tv_dict_add_tv(di, S_LEN("user_data"), &match->cp_user_data); + tv_dict_add_tv(di, S_LEN("user_data"), &match->cp_user_data); } } match = match->cp_next; @@ -3319,8 +3345,8 @@ static char_u * ins_compl_mode(void) */ static int ins_compl_bs(void) { - char_u *line; - char_u *p; + char_u *line; + char_u *p; line = get_cursor_line_ptr(); p = line + curwin->w_cursor.col; @@ -3340,8 +3366,9 @@ static int ins_compl_bs(void) /* Deleted more than what was used to find matches or didn't finish * finding all matches: need to look for matches all over again. */ if (curwin->w_cursor.col <= compl_col + compl_length - || ins_compl_need_restart()) + || ins_compl_need_restart()) { ins_compl_restart(); + } xfree(compl_leader); compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col); @@ -3398,8 +3425,9 @@ static void ins_compl_new_leader(void) /* Don't let Enter select the original text when there is no popup menu. * Don't let Enter select when use user function and refresh_always is set */ - if (compl_match_array == NULL || ins_compl_need_restart()) + if (compl_match_array == NULL || ins_compl_need_restart()) { compl_enter_selects = FALSE; + } } /* @@ -3410,8 +3438,9 @@ static int ins_compl_len(void) { int off = (int)curwin->w_cursor.col - (int)compl_col; - if (off < 0) + if (off < 0) { return 0; + } return off; } @@ -3424,7 +3453,7 @@ static void ins_compl_addleader(int c) int cc; if (stop_arrow() == FAIL) { - return; + return; } if ((cc = utf_char2len(c)) > 1) { char_u buf[MB_MAXBYTES + 1]; @@ -3489,10 +3518,10 @@ static void ins_compl_set_original_text(char_u *str) */ static void ins_compl_addfrommatch(void) { - char_u *p; + char_u *p; int len = (int)curwin->w_cursor.col - (int)compl_col; int c; - compl_T *cp; + compl_T *cp; assert(compl_shown_match != NULL); p = compl_shown_match->cp_str; if ((int)STRLEN(p) <= len) { // the match is too short @@ -3504,15 +3533,17 @@ static void ins_compl_addfrommatch(void) && cp != compl_first_match; cp = cp->cp_next) { if (compl_leader == NULL || ins_compl_equal(cp, compl_leader, - (int)STRLEN(compl_leader))) { + (int)STRLEN(compl_leader))) { p = cp->cp_str; break; } } - if (p == NULL || (int)STRLEN(p) <= len) + if (p == NULL || (int)STRLEN(p) <= len) { return; - } else + } + } else { return; + } } p += len; c = PTR2CHAR(p); @@ -3534,8 +3565,9 @@ static bool ins_compl_prep(int c) /* Forget any previous 'special' messages if this is actually * a ^X mode key - bar ^R, in which case we wait to see what it gives us. */ - if (c != Ctrl_R && vim_is_ctrl_x_key(c)) + if (c != Ctrl_R && vim_is_ctrl_x_key(c)) { edit_submode_extra = NULL; + } // Ignore end of Select mode mapping and mouse scroll buttons. if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP @@ -3544,6 +3576,26 @@ static bool ins_compl_prep(int c) return retval; } + if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X) { + if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c) + || !vim_is_ctrl_x_key(c)) { + // Not starting another completion mode. + ctrl_x_mode = CTRL_X_CMDLINE; + + // CTRL-X CTRL-Z should stop completion without inserting anything + if (c == Ctrl_Z) { + retval = true; + } + } else { + ctrl_x_mode = CTRL_X_CMDLINE; + + // Other CTRL-X keys first stop completion, then start another + // completion mode. + ins_compl_prep(' '); + ctrl_x_mode = CTRL_X_NOT_DEFINED_YET; + } + } + // Set "compl_get_longest" when finding the first matches. if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || (ctrl_x_mode == CTRL_X_NORMAL && !compl_started)) { @@ -3560,10 +3612,11 @@ static bool ins_compl_prep(int c) case Ctrl_E: case Ctrl_Y: ctrl_x_mode = CTRL_X_SCROLL; - if (!(State & REPLACE_FLAG)) + if (!(State & REPLACE_FLAG)) { edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)"); - else + } else { edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)"); + } edit_submode_pre = NULL; showmode(); break; @@ -3609,6 +3662,12 @@ static bool ins_compl_prep(int c) case Ctrl_Q: ctrl_x_mode = CTRL_X_CMDLINE; break; + case Ctrl_Z: + ctrl_x_mode = CTRL_X_NORMAL; + edit_submode = NULL; + showmode(); + retval = true; + break; case Ctrl_P: case Ctrl_N: /* ^X^P means LOCAL expansion if nothing interrupted (eg we @@ -3618,10 +3677,11 @@ static bool ins_compl_prep(int c) * ^X^F^X^P or ^P^X^X^P, see below) * nothing changes if interrupting mode 0, (eg, the flag * doesn't change when going to ADDING mode -- Acevedo */ - if (!(compl_cont_status & CONT_INTRPT)) + if (!(compl_cont_status & CONT_INTRPT)) { compl_cont_status |= CONT_LOCAL; - else if (compl_cont_mode != 0) + } else if (compl_cont_mode != 0) { compl_cont_status &= ~CONT_LOCAL; + } FALLTHROUGH; default: /* If we have typed at least 2 ^X's... for modes != 0, we set @@ -3635,10 +3695,11 @@ static bool ins_compl_prep(int c) * In mode 0 an extra ^X is needed since ^X^P goes to ADDING * mode -- Acevedo */ if (c == Ctrl_X) { - if (compl_cont_mode != 0) + if (compl_cont_mode != 0) { compl_cont_status = 0; - else + } else { compl_cont_mode = CTRL_X_NOT_DEFINED_YET; + } } ctrl_x_mode = CTRL_X_NORMAL; edit_submode = NULL; @@ -3681,10 +3742,11 @@ static bool ins_compl_prep(int c) * When using the longest match, edited the match or used * CTRL-E then don't use the current match. */ - if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) + if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) { ptr = compl_curr_match->cp_str; - else + } else { ptr = NULL; + } ins_compl_fixRedoBufForLeader(ptr); } @@ -3766,16 +3828,18 @@ static bool ins_compl_prep(int c) /* * Indent now if a key was typed that is in 'cinkeys'. */ - if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0))) + if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0))) { do_c_expr_indent(); + } // Trigger the CompleteDone event to give scripts a chance to act // upon the end of completion. ins_apply_autocmds(EVENT_COMPLETEDONE); } - } else if (ctrl_x_mode == CTRL_X_LOCAL_MSG) + } else if (ctrl_x_mode == CTRL_X_LOCAL_MSG) { /* Trigger the CompleteDone event to give scripts a chance to act * upon the (possibly failed) completion. */ ins_apply_autocmds(EVENT_COMPLETEDONE); + } /* reset continue_* if we left expansion-mode, if we stay they'll be * (re)set properly in ins_complete() */ @@ -3795,8 +3859,8 @@ static bool ins_compl_prep(int c) static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) { int len; - char_u *p; - char_u *ptr = ptr_arg; + char_u *p; + char_u *ptr = ptr_arg; if (ptr == NULL) { if (compl_leader != NULL) { @@ -3823,7 +3887,7 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg) /* * Loops through the list of windows, loaded-buffers or non-loaded-buffers * (depending on flag) starting from buf and looking for a non-scanned - * buffer (other than curbuf). curbuf is special, if it is called with + * buffer (other than curbuf). curbuf is special, if it is called with * buf=curbuf then it has to be the first call for a given flag/expansion. * * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo @@ -3838,10 +3902,11 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) } assert(wp); while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin - && wp->w_buffer->b_scanned) + && wp->w_buffer->b_scanned) { ; + } buf = wp->w_buffer; - } else + } else { /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U' * (unlisted buffers) * When completing whole lines skip unloaded buffers. */ @@ -3850,19 +3915,19 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) ? buf->b_p_bl : (!buf->b_p_bl || (buf->b_ml.ml_mfp == NULL) != (flag == 'u'))) - || buf->b_scanned)) + || buf->b_scanned)) { ; + } + } return buf; } -// Execute user defined complete function 'completefunc' or 'omnifunc', and -// get matches in "matches". -static void -expand_by_function( - int type, // CTRL_X_OMNI or CTRL_X_FUNCTION - char_u *base -) +/// Execute user defined complete function 'completefunc' or 'omnifunc', and +/// get matches in "matches". +/// +/// @param type CTRL_X_OMNI or CTRL_X_FUNCTION +static void expand_by_function(int type, char_u *base) { list_T *matchlist = NULL; dict_T *matchdict = NULL; @@ -3920,10 +3985,11 @@ expand_by_function( goto theend; } - if (matchlist != NULL) + if (matchlist != NULL) { ins_compl_add_list(matchlist); - else if (matchdict != NULL) + } else if (matchdict != NULL) { ins_compl_add_dict(matchdict); + } theend: // Restore State, it might have been changed. @@ -3960,8 +4026,8 @@ static void ins_compl_add_list(list_T *const list) */ static void ins_compl_add_dict(dict_T *dict) { - dictitem_T *di_refresh; - dictitem_T *di_words; + dictitem_T *di_refresh; + dictitem_T *di_words; // Check for optional "refresh" item. compl_opt_refresh_always = false; @@ -4096,8 +4162,9 @@ static int ins_compl_get_exp(pos_T *ini) || CTRL_X_MODE_LINE_OR_EVAL(l_ctrl_x_mode)) && (!compl_started || found_all)) { found_all = FALSE; - while (*e_cpt == ',' || *e_cpt == ' ') + while (*e_cpt == ',' || *e_cpt == ' ') { e_cpt++; + } if (*e_cpt == '.' && !curbuf->b_scanned) { ins_buf = curbuf; first_match_pos = *ini; @@ -4118,7 +4185,7 @@ static int ins_compl_get_exp(pos_T *ini) set_match_pos = true; } else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL && (ins_buf = - ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf) { + ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf) { // Scan a buffer, but not the current one. if (ins_buf->b_ml.ml_mfp != NULL) { // loaded buffer compl_started = true; @@ -4149,10 +4216,11 @@ static int ins_compl_get_exp(pos_T *ini) if (CTRL_X_MODE_LINE_OR_EVAL(l_ctrl_x_mode)) { type = -1; } else if (*e_cpt == 'k' || *e_cpt == 's') { - if (*e_cpt == 'k') + if (*e_cpt == 'k') { type = CTRL_X_DICTIONARY; - else + } else { type = CTRL_X_THESAURUS; + } if (*++e_cpt != ',' && *e_cpt != NUL) { dict = e_cpt; dict_f = DICT_FIRST; @@ -4174,8 +4242,9 @@ static int ins_compl_get_exp(pos_T *ini) (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ","); found_all = TRUE; - if (type == -1) + if (type == -1) { continue; + } } } @@ -4201,18 +4270,17 @@ static int ins_compl_get_exp(pos_T *ini) case CTRL_X_DICTIONARY: case CTRL_X_THESAURUS: - ins_compl_dictionaries( - dict != NULL ? dict - : (type == CTRL_X_THESAURUS + ins_compl_dictionaries(dict != NULL ? dict + : (type == CTRL_X_THESAURUS ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr) - : (*curbuf->b_p_dict == NUL + : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)), - compl_pattern, - dict != NULL ? dict_f - : 0, type == CTRL_X_THESAURUS); + compl_pattern, + dict != NULL ? dict_f + : 0, type == CTRL_X_THESAURUS); dict = NULL; break; @@ -4242,7 +4310,7 @@ static int ins_compl_get_exp(pos_T *ini) #ifdef BACKSLASH_IN_FILENAME if (curbuf->b_p_csl[0] != NUL) { for (int i = 0; i < num_matches; i++) { - char_u *ptr = matches[i]; + char_u *ptr = matches[i]; while (*ptr != NUL) { if (curbuf->b_p_csl[0] == 's' && *ptr == '\\') { *ptr = '/'; @@ -4259,10 +4327,12 @@ static int ins_compl_get_exp(pos_T *ini) break; case CTRL_X_CMDLINE: + case CTRL_X_CMDLINE_CTRL_X: if (expand_cmdline(&compl_xp, compl_pattern, - (int)STRLEN(compl_pattern), - &num_matches, &matches) == EXPAND_OK) - ins_compl_add_matches(num_matches, matches, FALSE); + (int)STRLEN(compl_pattern), + &num_matches, &matches) == EXPAND_OK) { + ins_compl_add_matches(num_matches, matches, false); + } break; case CTRL_X_FUNCTION: @@ -4272,27 +4342,30 @@ static int ins_compl_get_exp(pos_T *ini) case CTRL_X_SPELL: num_matches = expand_spelling(first_match_pos.lnum, - compl_pattern, &matches); - if (num_matches > 0) + compl_pattern, &matches); + if (num_matches > 0) { ins_compl_add_matches(num_matches, matches, p_ic); + } break; default: // normal ^P/^N and ^X^L // If 'infercase' is set, don't use 'smartcase' here save_p_scs = p_scs; assert(ins_buf); - if (ins_buf->b_p_inf) + if (ins_buf->b_p_inf) { p_scs = FALSE; + } // Buffers other than curbuf are scanned from the beginning or the // end but never from the middle, thus setting nowrapscan in this // buffers is a good idea, on the other hand, we always set // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb save_p_ws = p_ws; - if (ins_buf != curbuf) + if (ins_buf != curbuf) { p_ws = false; - else if (*e_cpt == '.') + } else if (*e_cpt == '.') { p_ws = true; + } for (;; ) { bool cont_s_ipos = false; @@ -4323,8 +4396,9 @@ static int ins_compl_get_exp(pos_T *ini) found_new_match = FAIL; } if (found_new_match == FAIL) { - if (ins_buf == curbuf) + if (ins_buf == curbuf) { found_all = TRUE; + } break; } @@ -4399,13 +4473,13 @@ static int ins_compl_get_exp(pos_T *ini) IObuff[len] = NUL; ptr = IObuff; } - if (len == compl_length) + if (len == compl_length) { continue; + } } } - if (ins_compl_add_infercase( - ptr, len, p_ic, ins_buf == curbuf ? NULL : ins_buf->b_sfname, - 0, cont_s_ipos) != NOTDONE) { + if (ins_compl_add_infercase(ptr, len, p_ic, ins_buf == curbuf ? NULL : ins_buf->b_sfname, + 0, cont_s_ipos) != NOTDONE) { found_new_match = OK; break; } @@ -4425,8 +4499,9 @@ static int ins_compl_get_exp(pos_T *ini) if ((l_ctrl_x_mode != CTRL_X_NORMAL && !CTRL_X_MODE_LINE_OR_EVAL(l_ctrl_x_mode)) || found_new_match != FAIL) { - if (got_int) + if (got_int) { break; + } // Fill the popup menu as soon as possible. if (type != -1) { ins_compl_check_keys(0, false); @@ -4518,21 +4593,16 @@ static dict_T *ins_compl_dict_alloc(compl_T *match) { // { word, abbr, menu, kind, info } dict_T *dict = tv_dict_alloc_lock(VAR_FIXED); - tv_dict_add_str( - dict, S_LEN("word"), - (const char *)EMPTY_IF_NULL(match->cp_str)); - tv_dict_add_str( - dict, S_LEN("abbr"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_ABBR])); - tv_dict_add_str( - dict, S_LEN("menu"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_MENU])); - tv_dict_add_str( - dict, S_LEN("kind"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_KIND])); - tv_dict_add_str( - dict, S_LEN("info"), - (const char *)EMPTY_IF_NULL(match->cp_text[CPT_INFO])); + tv_dict_add_str(dict, S_LEN("word"), + (const char *)EMPTY_IF_NULL(match->cp_str)); + tv_dict_add_str(dict, S_LEN("abbr"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_ABBR])); + tv_dict_add_str(dict, S_LEN("menu"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_MENU])); + tv_dict_add_str(dict, S_LEN("kind"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_KIND])); + tv_dict_add_str(dict, S_LEN("info"), + (const char *)EMPTY_IF_NULL(match->cp_text[CPT_INFO])); if (match->cp_user_data.v_type == VAR_UNKNOWN) { tv_dict_add_str(dict, S_LEN("user_data"), ""); } else { @@ -4541,30 +4611,25 @@ static dict_T *ins_compl_dict_alloc(compl_T *match) return dict; } -/* - * Fill in the next completion in the current direction. - * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to - * get more completions. If it is FALSE, then we just do nothing when there - * are no more completions in a given direction. The latter case is used when - * we are still in the middle of finding completions, to allow browsing - * through the ones found so far. - * Return the total number of matches, or -1 if still unknown -- webb. - * - * compl_curr_match is currently being used by ins_compl_get_exp(), so we use - * compl_shown_match here. - * - * Note that this function may be called recursively once only. First with - * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn - * calls this function with "allow_get_expansion" FALSE. - */ -static int -ins_compl_next ( - int allow_get_expansion, - int count, // Repeat completion this many times; should - // be at least 1 - int insert_match, // Insert the newly selected match - int in_compl_func // Called from complete_check() -) +/// Fill in the next completion in the current direction. +/// If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to +/// get more completions. If it is FALSE, then we just do nothing when there +/// are no more completions in a given direction. The latter case is used when +/// we are still in the middle of finding completions, to allow browsing +/// through the ones found so far. +/// @return the total number of matches, or -1 if still unknown -- webb. +/// +/// compl_curr_match is currently being used by ins_compl_get_exp(), so we use +/// compl_shown_match here. +/// +/// Note that this function may be called recursively once only. First with +/// "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn +/// calls this function with "allow_get_expansion" FALSE. +/// +/// @param count Repeat completion this many times; should be at least 1 +/// @param insert_match Insert the newly selected match +/// @param in_compl_func Called from complete_check() +static int ins_compl_next(int allow_get_expansion, int count, int insert_match, int in_compl_func) { int num_matches = -1; int todo = count; @@ -4574,8 +4639,9 @@ ins_compl_next ( /* When user complete function return -1 for findstart which is next * time of 'always', compl_shown_match become NULL. */ - if (compl_shown_match == NULL) + if (compl_shown_match == NULL) { return -1; + } if (compl_leader != NULL && (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0) { @@ -4592,21 +4658,23 @@ ins_compl_next ( * backward, find the last match. */ if (compl_shows_dir == BACKWARD && !ins_compl_equal(compl_shown_match, - compl_leader, (int)STRLEN(compl_leader)) + compl_leader, (int)STRLEN(compl_leader)) && (compl_shown_match->cp_next == NULL || compl_shown_match->cp_next == compl_first_match)) { while (!ins_compl_equal(compl_shown_match, - compl_leader, (int)STRLEN(compl_leader)) + compl_leader, (int)STRLEN(compl_leader)) && compl_shown_match->cp_prev != NULL - && compl_shown_match->cp_prev != compl_first_match) + && compl_shown_match->cp_prev != compl_first_match) { compl_shown_match = compl_shown_match->cp_prev; + } } } if (allow_get_expansion && insert_match - && (!(compl_get_longest || compl_restarting) || compl_used_match)) + && (!(compl_get_longest || compl_restarting) || compl_used_match)) { // Delete old text to be replaced ins_compl_delete(); + } // When finding the longest common text we stick at the original text, // don't let CTRL-N or CTRL-P move to the first match. @@ -4634,19 +4702,21 @@ ins_compl_next ( } else { if (!allow_get_expansion) { if (advance) { - if (compl_shows_dir == BACKWARD) + if (compl_shows_dir == BACKWARD) { compl_pending -= todo + 1; - else + } else { compl_pending += todo + 1; + } } return -1; } if (!compl_no_select && advance) { - if (compl_shows_dir == BACKWARD) + if (compl_shows_dir == BACKWARD) { --compl_pending; - else + } else { ++compl_pending; + } } // Find matches. @@ -4662,8 +4732,9 @@ ins_compl_next ( if (compl_pending < 0 && compl_shown_match->cp_prev != NULL) { compl_shown_match = compl_shown_match->cp_prev; ++compl_pending; - } else + } else { break; + } } found_end = false; } @@ -4728,8 +4799,8 @@ ins_compl_next ( if (compl_shown_match->cp_fname != NULL) { char *lead = _("match in file"); int space = sc_col - vim_strsize((char_u *)lead) - 2; - char_u *s; - char_u *e; + char_u *s; + char_u *e; if (space > 0) { // We need the tail that fits. With double-byte encoding going @@ -4797,7 +4868,7 @@ void ins_compl_check_keys(int frequency, int in_compl_func) c = safe_vgetc(); // Eat the character compl_shows_dir = ins_compl_key2dir(c); (void)ins_compl_next(false, ins_compl_key2count(c), - c != K_UP && c != K_DOWN, in_compl_func); + c != K_UP && c != K_DOWN, in_compl_func); } else { /* Need to get the character to have KeyTyped set. We'll put it * back with vungetc() below. But skip K_IGNORE. */ @@ -4805,8 +4876,9 @@ void ins_compl_check_keys(int frequency, int in_compl_func) if (c != K_IGNORE) { /* Don't interrupt completion when the character wasn't typed, * e.g., when doing @q to replay keys. */ - if (c != Ctrl_R && KeyTyped) + if (c != Ctrl_R && KeyTyped) { compl_interrupted = TRUE; + } vungetc(c); } @@ -4902,7 +4974,7 @@ static bool ins_compl_use_match(int c) */ static int ins_complete(int c, bool enable_pum) { - char_u *line; + char_u *line; int startcol = 0; // column where searched text starts colnr_T curs_col; // cursor column int n; @@ -4961,9 +5033,8 @@ static int ins_complete(int c, bool enable_pum) * mode but first we need to redefine compl_startpos */ if (compl_cont_status & CONT_S_IPOS) { compl_cont_status |= CONT_SOL; - compl_startpos.col = (colnr_T)(skipwhite( - line + compl_length - + compl_startpos.col) - line); + compl_startpos.col = (colnr_T)(skipwhite(line + compl_length + + compl_startpos.col) - line); } compl_col = compl_startpos.col; } @@ -4977,14 +5048,17 @@ static int ins_complete(int c, bool enable_pum) compl_col = curwin->w_cursor.col - compl_length; } compl_cont_status |= CONT_ADDING | CONT_N_ADDS; - if (compl_length < 1) + if (compl_length < 1) { compl_cont_status &= CONT_LOCAL; + } } else if (CTRL_X_MODE_LINE_OR_EVAL(ctrl_x_mode)) { compl_cont_status = CONT_ADDING | CONT_N_ADDS; - } else + } else { compl_cont_status = 0; - } else + } + } else { compl_cont_status &= CONT_LOCAL; + } if (!(compl_cont_status & CONT_ADDING)) { // normal expansion compl_cont_mode = ctrl_x_mode; @@ -5003,27 +5077,30 @@ static int ins_complete(int c, bool enable_pum) if ((compl_cont_status & CONT_SOL) || ctrl_x_mode == CTRL_X_PATH_DEFINES) { if (!(compl_cont_status & CONT_ADDING)) { - while (--startcol >= 0 && vim_isIDc(line[startcol])) + while (--startcol >= 0 && vim_isIDc(line[startcol])) { ; + } compl_col += ++startcol; compl_length = curs_col - startcol; } - if (p_ic) + if (p_ic) { compl_pattern = str_foldcase(line + compl_col, compl_length, NULL, 0); - else + } else { compl_pattern = vim_strnsave(line + compl_col, compl_length); + } } else if (compl_cont_status & CONT_ADDING) { - char_u *prefix = (char_u *)"\\<"; + 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); + compl_length) + 2); if (!vim_iswordp(line + compl_col) || (compl_col > 0 && ( - vim_iswordp(mb_prevptr(line, line + compl_col)) - ))) + vim_iswordp(mb_prevptr(line, line + compl_col)) + ))) { prefix = (char_u *)""; + } STRCPY((char *)compl_pattern, prefix); (void)quote_meta(compl_pattern + STRLEN(prefix), line + compl_col, compl_length); @@ -5058,10 +5135,10 @@ static int ins_complete(int c, bool enable_pum) STRCAT((char *)compl_pattern, "\\k"); } else { compl_pattern = xmalloc(quote_meta(NULL, line + compl_col, - compl_length) + 2); + compl_length) + 2); STRCPY((char *)compl_pattern, "\\<"); (void)quote_meta(compl_pattern + 2, line + compl_col, - compl_length); + compl_length); } } } else if (CTRL_X_MODE_LINE_OR_EVAL(ctrl_x_mode)) { @@ -5078,7 +5155,7 @@ static int ins_complete(int c, bool enable_pum) } else if (ctrl_x_mode == CTRL_X_FILES) { // Go back to just before the first filename character. if (startcol > 0) { - char_u *p = line + startcol; + char_u *p = line + startcol; MB_PTR_BACK(line, p); while (p > line && vim_isfilec(PTR2CHAR(p))) { @@ -5094,7 +5171,7 @@ static int ins_complete(int c, bool enable_pum) compl_col += startcol; compl_length = (int)curs_col - startcol; compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES); - } else if (ctrl_x_mode == CTRL_X_CMDLINE) { + } else if (ctrl_x_mode == CTRL_X_CMDLINE || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X) { compl_pattern = vim_strnsave(line, curs_col); set_cmd_context(&compl_xp, compl_pattern, (int)STRLEN(compl_pattern), curs_col, false); @@ -5113,10 +5190,10 @@ static int ins_complete(int c, bool enable_pum) * Call user defined function 'completefunc' with "a:findstart" * set to 1 to obtain the length of text to use for completion. */ - char_u *funcname; + char_u *funcname; pos_T pos; - win_T *curwin_save; - buf_T *curbuf_save; + win_T *curwin_save; + buf_T *curbuf_save; const int save_State = State; /* Call 'completefunc' or 'omnifunc' and get pattern length as a @@ -5158,8 +5235,9 @@ static int ins_complete(int c, bool enable_pum) /* Return value -2 means the user complete function wants to * cancel the complete without an error. * Return value -3 does the same as -2 and leaves CTRL-X mode.*/ - if (col == -2) + if (col == -2) { return FAIL; + } if (col == -3) { ctrl_x_mode = CTRL_X_NORMAL; edit_submode = NULL; @@ -5175,11 +5253,13 @@ static int ins_complete(int c, bool enable_pum) */ compl_opt_refresh_always = FALSE; - if (col < 0) + if (col < 0) { col = curs_col; + } compl_col = col; - if (compl_col > curs_col) + if (compl_col > curs_col) { compl_col = curs_col; + } /* Setup variables for completion. Need to obtain "line" again, * it may have become invalid. */ @@ -5190,9 +5270,9 @@ static int ins_complete(int c, bool enable_pum) if (spell_bad_len > 0) { assert(spell_bad_len <= INT_MAX); compl_col = curs_col - (int)spell_bad_len; - } - else + } else { compl_col = spell_word_start(startcol); + } if (compl_col >= (colnr_T)startcol) { compl_length = 0; compl_col = curs_col; @@ -5227,10 +5307,11 @@ static int ins_complete(int c, bool enable_pum) compl_startpos.col = compl_col; } - if (compl_cont_status & CONT_LOCAL) + if (compl_cont_status & CONT_LOCAL) { edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]); - else + } else { edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); + } /* If any of the original typed text has been changed we need to fix * the redo buffer. */ @@ -5335,14 +5416,15 @@ static int ins_complete(int c, bool enable_pum) * Translations may need more than twice that. */ static char_u match_ref[81]; - if (compl_matches > 0) + if (compl_matches > 0) { vim_snprintf((char *)match_ref, sizeof(match_ref), - _("match %d of %d"), - compl_curr_match->cp_number, compl_matches); - else + _("match %d of %d"), + compl_curr_match->cp_number, compl_matches); + } else { vim_snprintf((char *)match_ref, sizeof(match_ref), - _("match %d"), - compl_curr_match->cp_number); + _("match %d"), + compl_curr_match->cp_number); + } edit_submode_extra = match_ref; edit_submode_highl = HLF_R; if (dollar_vcol >= 0) { @@ -5394,8 +5476,9 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) case '*': case '[': if (ctrl_x_mode == CTRL_X_DICTIONARY - || ctrl_x_mode == CTRL_X_THESAURUS) + || ctrl_x_mode == CTRL_X_THESAURUS) { break; + } FALLTHROUGH; case '~': if (!p_magic) { // quote these only if magic is set @@ -5404,8 +5487,9 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) FALLTHROUGH; case '\\': if (ctrl_x_mode == CTRL_X_DICTIONARY - || ctrl_x_mode == CTRL_X_THESAURUS) + || ctrl_x_mode == CTRL_X_THESAURUS) { break; + } FALLTHROUGH; case '^': // currently it's not needed. case '$': @@ -5430,8 +5514,9 @@ static unsigned quote_meta(char_u *dest, char_u *src, int len) } } } - if (dest != NULL) + if (dest != NULL) { *dest = NUL; + } return m; } @@ -5451,8 +5536,9 @@ int get_literal(void) int octal = FALSE; int unicode = 0; - if (got_int) + if (got_int) { return Ctrl_C; + } no_mapping++; // don't map the next key hits cc = 0; @@ -5460,29 +5546,31 @@ int get_literal(void) for (;; ) { nc = plain_vgetc(); if (!(State & CMDLINE) - && MB_BYTE2LEN_CHECK(nc) == 1 - ) + && MB_BYTE2LEN_CHECK(nc) == 1) { add_to_showcmd(nc); - if (nc == 'x' || nc == 'X') + } + if (nc == 'x' || nc == 'X') { hex = TRUE; - else if (nc == 'o' || nc == 'O') + } else if (nc == 'o' || nc == 'O') { octal = TRUE; - else if (nc == 'u' || nc == 'U') + } else if (nc == 'u' || nc == 'U') { unicode = nc; - else { + } else { if (hex - || unicode != 0 - ) { - if (!ascii_isxdigit(nc)) + || unicode != 0) { + if (!ascii_isxdigit(nc)) { break; + } cc = cc * 16 + hex2nr(nc); } else if (octal) { - if (nc < '0' || nc > '7') + if (nc < '0' || nc > '7') { break; + } cc = cc * 8 + nc - '0'; } else { - if (!ascii_isdigit(nc)) + if (!ascii_isdigit(nc)) { break; + } cc = cc * 10 + nc - '0'; } @@ -5490,9 +5578,9 @@ int get_literal(void) } if (cc > 255 - && unicode == 0 - ) + && unicode == 0) { cc = 255; // limit range to 0-255 + } nc = 0; if (hex) { // hex: up to two chars @@ -5522,8 +5610,9 @@ int get_literal(void) } --no_mapping; - if (nc) + if (nc) { vungetc(nc); + } got_int = false; // CTRL-C typed after CTRL-V is not an interrupt return cc; } @@ -5533,7 +5622,7 @@ int get_literal(void) /// @param ctrlv `c` was typed after CTRL-V static void insert_special(int c, int allow_modmask, int ctrlv) { - char_u *p; + char_u *p; int len; // Special function key, translate into "<Key>". Up to the last '>' is @@ -5549,16 +5638,18 @@ static void insert_special(int c, int allow_modmask, int ctrlv) len = (int)STRLEN(p); c = p[len - 1]; if (len > 2) { - if (stop_arrow() == FAIL) + if (stop_arrow() == FAIL) { return; + } p[len - 1] = NUL; ins_str(p); AppendToRedobuffLit(p, -1); ctrlv = FALSE; } } - if (stop_arrow() == OK) + if (stop_arrow() == OK) { insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1); + } } /* @@ -5573,26 +5664,25 @@ static void insert_special(int c, int allow_modmask, int ctrlv) # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^') #define WHITECHAR(cc) ( \ - ascii_iswhite(cc) \ - && !utf_iscomposing(utf_ptr2char(get_cursor_pos_ptr() + 1))) + ascii_iswhite(cc) \ + && !utf_iscomposing(utf_ptr2char(get_cursor_pos_ptr() + 1))) -/* - * "flags": INSCHAR_FORMAT - force formatting - * INSCHAR_CTRLV - char typed just after CTRL-V - * INSCHAR_NO_FEX - don't use 'formatexpr' - * - * NOTE: passes the flags value straight through to internal_format() which, - * beside INSCHAR_FORMAT (above), is also looking for these: - * INSCHAR_DO_COM - format comments - * INSCHAR_COM_LIST - format comments with num list or 2nd line indent - */ -void insertchar( - int c, // character to insert or NUL - int flags, // INSCHAR_FORMAT, etc. - int second_indent // indent for second line if >= 0 -) +/// +/// "flags": INSCHAR_FORMAT - force formatting +/// INSCHAR_CTRLV - char typed just after CTRL-V +/// INSCHAR_NO_FEX - don't use 'formatexpr' +/// +/// NOTE: passes the flags value straight through to internal_format() which, +/// beside INSCHAR_FORMAT (above), is also looking for these: +/// INSCHAR_DO_COM - format comments +/// INSCHAR_COM_LIST - format comments with num list or 2nd line indent +/// +/// @param c character to insert or NUL +/// @param flags INSCHAR_FORMAT, etc. +/// @param second_indent indent for second line if >= 0 +void insertchar(int c, int flags, int second_indent) { - char_u *p; + char_u *p; int force_format = flags & INSCHAR_FORMAT; const int textwidth = comp_textwidth(force_format); @@ -5604,14 +5694,14 @@ void insertchar( * - Always do this when 'formatoptions' has the 'a' flag and the line * ends in white space. * - Otherwise: - * - Don't do this if inserting a blank - * - Don't do this if an existing character is being replaced, unless - * we're in VREPLACE mode. - * - Do this if the cursor is not on the line where insert started - * or - 'formatoptions' doesn't have 'l' or the line was not too long - * before the insert. - * - 'formatoptions' doesn't have 'b' or a blank was inserted at or - * before 'textwidth' + * - Don't do this if inserting a blank + * - Don't do this if an existing character is being replaced, unless + * we're in VREPLACE mode. + * - Do this if the cursor is not on the line where insert started + * or - 'formatoptions' doesn't have 'l' or the line was not too long + * before the insert. + * - 'formatoptions' doesn't have 'b' or a blank was inserted at or + * before 'textwidth' */ if (textwidth > 0 && (force_format @@ -5628,7 +5718,7 @@ void insertchar( // when 'formatexpr' isn't set or it returns non-zero. bool do_internal = true; colnr_T virtcol = get_nolist_virtcol() - + char2cells(c != NUL ? c : gchar_cursor()); + + char2cells(c != NUL ? c : gchar_cursor()); if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0 && (force_format || virtcol > (colnr_T)textwidth)) { @@ -5637,8 +5727,9 @@ void insertchar( // was called. ins_need_undo = true; } - if (do_internal) + if (do_internal) { internal_format(textwidth, second_indent, flags, c == NUL, c); + } } if (c == NUL) { // only formatting was wanted @@ -5647,7 +5738,7 @@ void insertchar( // Check whether this character should end a comment. if (did_ai && c == end_comment_pending) { - char_u *line; + char_u *line; char_u lead_end[COM_MAX_LEN]; // end-comment string int middle_len, end_len; int i; @@ -5676,8 +5767,9 @@ void insertchar( // Skip white space before the cursor i = curwin->w_cursor.col; - while (--i >= 0 && ascii_iswhite(line[i])) + while (--i >= 0 && ascii_iswhite(line[i])) { ; + } i++; // Skip to before the middle leader @@ -5754,10 +5846,12 @@ void insertchar( if (flags & INSCHAR_CTRLV) { redo_literal(*buf); i = 1; - } else + } else { i = 0; - if (buf[i] != NUL) + } + if (buf[i] != NUL) { AppendToRedobuffLit(buf + i, -1); + } } else { int cc; @@ -5779,20 +5873,13 @@ void insertchar( } } -/* - * Format text at the current insert position. - * - * If the INSCHAR_COM_LIST flag is present, then the value of second_indent - * will be the comment leader length sent to open_line(). - */ -static void -internal_format ( - int textwidth, - int second_indent, - int flags, - int format_only, - int c // character to be inserted (can be NUL) -) +/// Format text at the current insert position. +/// +/// If the INSCHAR_COM_LIST flag is present, then the value of second_indent +/// will be the comment leader length sent to open_line(). +/// +/// @param c character to be inserted (can be NUL) +static void internal_format(int textwidth, int second_indent, int flags, int format_only, int c) { int cc; int save_char = NUL; @@ -5815,8 +5902,7 @@ internal_format ( * deleted. Replace it with an 'x' temporarily. */ if (!curbuf->b_p_ai - && !(State & VREPLACE_FLAG) - ) { + && !(State & VREPLACE_FLAG)) { cc = gchar_cursor(); if (ascii_iswhite(cc)) { save_char = cc; @@ -5835,14 +5921,15 @@ internal_format ( colnr_T len; colnr_T virtcol; int orig_col = 0; - char_u *saved_text = NULL; + char_u *saved_text = NULL; colnr_T col; colnr_T end_col; virtcol = get_nolist_virtcol() + char2cells(c != NUL ? c : gchar_cursor()); - if (virtcol <= (colnr_T)textwidth) + if (virtcol <= (colnr_T)textwidth) { break; + } if (no_leader) { do_comments = false; @@ -5890,10 +5977,11 @@ internal_format ( || (flags & INSCHAR_FORMAT) || curwin->w_cursor.lnum != Insstart.lnum || curwin->w_cursor.col >= Insstart.col) { - if (curwin->w_cursor.col == startcol && c != NUL) + if (curwin->w_cursor.col == startcol && c != NUL) { cc = c; - else + } else { cc = gchar_cursor(); + } if (WHITECHAR(cc)) { // remember position of blank just before text end_col = curwin->w_cursor.col; @@ -5948,8 +6036,9 @@ internal_format ( end_foundcol = end_col + 1; foundcol = curwin->w_cursor.col; - if (curwin->w_cursor.col <= (colnr_T)wantcol) + if (curwin->w_cursor.col <= (colnr_T)wantcol) { break; + } } else if ((cc >= 0x100 || !utf_allow_break_before(cc)) && fo_multibyte) { int ncc; @@ -5970,14 +6059,16 @@ internal_format ( if (curwin->w_cursor.col != skip_pos && allow_break) { foundcol = curwin->w_cursor.col; end_foundcol = foundcol; - if (curwin->w_cursor.col <= (colnr_T)wantcol) + if (curwin->w_cursor.col <= (colnr_T)wantcol) { break; + } } curwin->w_cursor.col = col; } - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { break; + } ncc = cc; col = curwin->w_cursor.col; @@ -6039,8 +6130,9 @@ internal_format ( } } } - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { break; + } dec_cursor(); } @@ -6069,11 +6161,13 @@ internal_format ( */ curwin->w_cursor.col = foundcol; while ((cc = gchar_cursor(), WHITECHAR(cc)) - && (!fo_white_par || curwin->w_cursor.col < startcol)) + && (!fo_white_par || curwin->w_cursor.col < startcol)) { inc_cursor(); + } startcol -= curwin->w_cursor.col; - if (startcol < 0) + if (startcol < 0) { startcol = 0; + } if (State & VREPLACE_FLAG) { /* @@ -6100,12 +6194,13 @@ internal_format ( * Only insert/delete lines, but don't really redraw the window. */ open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX - + (fo_white_par ? OPENLINE_KEEPTRAIL : 0) - + (do_comments ? OPENLINE_DO_COM : 0) - + ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0) - , ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent)); - if (!(flags & INSCHAR_COM_LIST)) + + (fo_white_par ? OPENLINE_KEEPTRAIL : 0) + + (do_comments ? OPENLINE_DO_COM : 0) + + ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0) + , ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent)); + if (!(flags & INSCHAR_COM_LIST)) { old_indent = 0; + } replace_offset = 0; if (first_line) { @@ -6156,8 +6251,9 @@ internal_format ( */ curwin->w_cursor.col += startcol; len = (colnr_T)STRLEN(get_cursor_line_ptr()); - if (curwin->w_cursor.col > len) + if (curwin->w_cursor.col > len) { curwin->w_cursor.col = len; + } } haveto_redraw = true; @@ -6182,27 +6278,26 @@ internal_format ( } } -/* - * Called after inserting or deleting text: When 'formatoptions' includes the - * 'a' flag format from the current line until the end of the paragraph. - * Keep the cursor at the same position relative to the text. - * The caller must have saved the cursor line for undo, following ones will be - * saved here. - */ -void auto_format( - bool trailblank, // when true also format with trailing blank - bool prev_line // may start in previous line -) +/// Called after inserting or deleting text: When 'formatoptions' includes the +/// 'a' flag format from the current line until the end of the paragraph. +/// Keep the cursor at the same position relative to the text. +/// The caller must have saved the cursor line for undo, following ones will be +/// saved here. +/// +/// @param trailblank when true also format with trailing blank +/// @param prev_line may start in previous line +void auto_format(bool trailblank, bool prev_line) { pos_T pos; colnr_T len; - char_u *old; - char_u *new, *pnew; + char_u *old; + char_u *new, *pnew; int wasatend; int cc; - if (!has_format_option(FO_AUTO)) + if (!has_format_option(FO_AUTO)) { return; + } pos = curwin->w_cursor; old = get_cursor_line_ptr(); @@ -6220,8 +6315,9 @@ void auto_format( dec_cursor(); cc = gchar_cursor(); if (!WHITECHAR(cc) && curwin->w_cursor.col > 0 - && has_format_option(FO_ONE_LETTER)) + && has_format_option(FO_ONE_LETTER)) { dec_cursor(); + } cc = gchar_cursor(); if (WHITECHAR(cc)) { curwin->w_cursor = pos; @@ -6233,8 +6329,9 @@ void auto_format( /* 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(old, NULL, FALSE, TRUE) == 0) + && get_leader_len(old, NULL, FALSE, TRUE) == 0) { return; + } /* * May start formatting in a previous line, so that after "x" a word is @@ -6243,8 +6340,9 @@ void auto_format( */ if (prev_line && !paragraph_start(curwin->w_cursor.lnum)) { --curwin->w_cursor.lnum; - if (u_save_cursor() == FAIL) + if (u_save_cursor() == FAIL) { return; + } } /* @@ -6287,14 +6385,12 @@ void auto_format( check_cursor(); } -/* - * When an extra space was added to continue a paragraph for auto-formatting, - * delete it now. The space must be under the cursor, just after the insert - * position. - */ -static void check_auto_format( - bool end_insert // true when ending Insert mode -) +/// When an extra space was added to continue a paragraph for auto-formatting, +/// delete it now. The space must be under the cursor, just after the insert +/// position. +/// +/// @param end_insert true when ending Insert mode +static void check_auto_format(bool end_insert) { int c = ' '; int cc; @@ -6319,16 +6415,14 @@ static void check_auto_format( } } -/* - * Find out textwidth to be used for formatting: - * if 'textwidth' option is set, use it - * else if 'wrapmargin' option is set, use curwin->w_width_inner-'wrapmargin' - * if invalid value, use 0. - * Set default to window width (maximum 79) for "gq" operator. - */ -int comp_textwidth( - bool ff // force formatting (for "gq" command) -) +/// Find out textwidth to be used for formatting: +/// if 'textwidth' option is set, use it +/// else if 'wrapmargin' option is set, use curwin->w_width_inner-'wrapmargin' +/// if invalid value, use 0. +/// Set default to window width (maximum 79) for "gq" operator. +/// +/// @param ff force formatting (for "gq" command) +int comp_textwidth(bool ff) { int textwidth = curbuf->b_p_tw; if (textwidth == 0 && curbuf->b_p_wm) { @@ -6341,11 +6435,13 @@ int comp_textwidth( textwidth -= win_fdccol_count(curwin); textwidth -= win_signcol_count(curwin); - if (curwin->w_p_nu || curwin->w_p_rnu) + if (curwin->w_p_nu || curwin->w_p_rnu) { textwidth -= 8; + } } - if (textwidth < 0) + if (textwidth < 0) { textwidth = 0; + } if (ff && textwidth == 0) { textwidth = curwin->w_width_inner - 1; if (textwidth > 79) { @@ -6372,11 +6468,11 @@ static void redo_literal(int c) } } -// start_arrow() is called when an arrow key is used in insert mode. -// For undo/redo it resembles hitting the <ESC> key. -static void start_arrow( - pos_T *end_insert_pos // can be NULL -) +/// start_arrow() is called when an arrow key is used in insert mode. +/// For undo/redo it resembles hitting the <ESC> key. +/// +/// @param end_insert_pos can be NULL +static void start_arrow(pos_T *end_insert_pos) { start_arrow_common(end_insert_pos, true); } @@ -6428,8 +6524,9 @@ static void spell_back_to_badword(void) { pos_T tpos = curwin->w_cursor; spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL); - if (curwin->w_cursor.col != tpos.col) + if (curwin->w_cursor.col != tpos.col) { start_arrow(&tpos); + } } /* @@ -6472,20 +6569,16 @@ int stop_arrow(void) return arrow_used || ins_need_undo ? FAIL : OK; } -/* - * Do a few things to stop inserting. - * "end_insert_pos" is where insert ended. It is NULL when we already jumped - * to another window/buffer. - */ -static void -stop_insert ( - pos_T *end_insert_pos, - int esc, // called by ins_esc() - int nomove // <c-\><c-o>, don't move cursor -) +/// Do a few things to stop inserting. +/// "end_insert_pos" is where insert ended. It is NULL when we already jumped +/// to another window/buffer. +/// +/// @param esc called by ins_esc() +/// @param nomove <c-\><c-o>, don't move cursor +static void stop_insert(pos_T *end_insert_pos, int esc, int nomove) { int cc; - char_u *ptr; + char_u *ptr; stop_redo_ins(); replace_flush(); // abandon replace stack @@ -6501,8 +6594,9 @@ stop_insert ( xfree(last_insert); last_insert = ptr; last_insert_skip = new_insert_skip; - } else + } else { xfree(ptr); + } if (!arrow_used && end_insert_pos != NULL) { // Auto-format now. It may seem strange to do this when stopping an @@ -6519,21 +6613,24 @@ stop_insert ( if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL) { dec_cursor(); cc = gchar_cursor(); - if (!ascii_iswhite(cc)) + if (!ascii_iswhite(cc)) { curwin->w_cursor = tpos; + } } auto_format(true, false); if (ascii_iswhite(cc)) { - if (gchar_cursor() != NUL) + if (gchar_cursor() != NUL) { inc_cursor(); + } /* If the cursor is still at the same character, also keep * the "coladd". */ if (gchar_cursor() == NUL && curwin->w_cursor.lnum == tpos.lnum - && curwin->w_cursor.col == tpos.col) + && curwin->w_cursor.col == tpos.col) { curwin->w_cursor.coladd = tpos.coladd; + } } } @@ -6554,8 +6651,9 @@ stop_insert ( curwin->w_cursor = *end_insert_pos; check_cursor_col(); // make sure it is not past the line for (;; ) { - if (gchar_cursor() == NUL && curwin->w_cursor.col > 0) + if (gchar_cursor() == NUL && curwin->w_cursor.col > 0) { --curwin->w_cursor.col; + } cc = gchar_cursor(); if (!ascii_iswhite(cc)) { break; @@ -6607,7 +6705,7 @@ stop_insert ( */ void set_last_insert(int c) { - char_u *s; + char_u *s; xfree(last_insert); last_insert = xmalloc(MB_MAXBYTES * 3 + 5); @@ -6661,25 +6759,26 @@ char_u *add_char2buf(int c, char_u *s) /* * 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. + * 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) + if ((flags & BL_SOL) && !p_sol) { coladvance(curwin->w_curswant); - else { + } else { curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; if (flags & (BL_WHITE | BL_SOL)) { - char_u *ptr; + char_u *ptr; for (ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr) - && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr) + && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr) { ++curwin->w_cursor.col; + } } curwin->w_set_curswant = TRUE; } @@ -6695,7 +6794,7 @@ void beginline(int flags) int oneright(void) { - char_u *ptr; + char_u *ptr; int l; if (virtual_active()) { @@ -6736,8 +6835,9 @@ int oneleft(void) int width; int v = getviscol(); - if (v == 0) + if (v == 0) { return FAIL; + } // We might get stuck on 'showbreak', skip over it. width = 1; @@ -6767,8 +6867,9 @@ int oneleft(void) return OK; } - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { return FAIL; + } curwin->w_set_curswant = TRUE; --curwin->w_cursor.col; @@ -6779,11 +6880,8 @@ int oneleft(void) return OK; } -int -cursor_up ( - long n, - int upd_topline // When TRUE: update topline -) +/// @oaram upd_topline When TRUE: update topline +int cursor_up(long n, int upd_topline) { linenr_T lnum; @@ -6794,9 +6892,9 @@ cursor_up ( if (lnum <= 1) { return FAIL; } - if (n >= lnum) + if (n >= lnum) { lnum = 1; - else if (hasAnyFolding(curwin)) { + } else if (hasAnyFolding(curwin)) { /* * Count each sequence of folded lines as one logical line. */ @@ -6816,10 +6914,12 @@ cursor_up ( (void)hasFolding(lnum, &lnum, NULL); } } - if (lnum < 1) + if (lnum < 1) { lnum = 1; - } else + } + } else { lnum -= n; + } curwin->w_cursor.lnum = lnum; } @@ -6833,14 +6933,10 @@ cursor_up ( return OK; } -/* - * Cursor down a number of logical lines. - */ -int -cursor_down ( - long n, - int upd_topline // When TRUE: update topline -) +/// Cursor down a number of logical lines. +/// +/// @param upd_topline When TRUE: update topline +int cursor_down(long n, int upd_topline) { linenr_T lnum; @@ -6853,24 +6949,28 @@ cursor_down ( if (lnum >= curbuf->b_ml.ml_line_count) { return FAIL; } - if (lnum + n >= curbuf->b_ml.ml_line_count) + if (lnum + n >= curbuf->b_ml.ml_line_count) { lnum = curbuf->b_ml.ml_line_count; - else if (hasAnyFolding(curwin)) { + } else if (hasAnyFolding(curwin)) { linenr_T last; // count each sequence of folded lines as one logical line while (n--) { - if (hasFolding(lnum, NULL, &last)) + if (hasFolding(lnum, NULL, &last)) { lnum = last + 1; - else + } else { ++lnum; - if (lnum >= curbuf->b_ml.ml_line_count) + } + if (lnum >= curbuf->b_ml.ml_line_count) { break; + } } - if (lnum > curbuf->b_ml.ml_line_count) + if (lnum > curbuf->b_ml.ml_line_count) { lnum = curbuf->b_ml.ml_line_count; - } else + } + } else { lnum += n; + } curwin->w_cursor.lnum = lnum; } @@ -6884,20 +6984,18 @@ cursor_down ( return OK; } -/* - * Stuff the last inserted text in the read buffer. - * Last_insert actually is a copy of the redo buffer, so we - * first have to remove the command. - */ -int stuff_inserted( - int c, // Command character to be inserted - long count, // Repeat this many times - int no_esc // Don't add an ESC at the end -) -{ - char_u *esc_ptr; - char_u *ptr; - char_u *last_ptr; +/// Stuff the last inserted text in the read buffer. +/// Last_insert actually is a copy of the redo buffer, so we +/// first have to remove the command. +/// +/// @param c Command character to be inserted +/// @param count Repeat this many times +/// @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; ptr = get_last_insert(); @@ -6935,8 +7033,9 @@ int stuff_inserted( } } while (--count > 0); - if (last) + if (last) { *last_ptr = last; + } if (esc_ptr != NULL) { *esc_ptr = ESC; // put the ESC back @@ -6952,8 +7051,9 @@ int stuff_inserted( char_u *get_last_insert(void) { - if (last_insert == NULL) + if (last_insert == NULL) { return NULL; + } return last_insert + last_insert_skip; } @@ -6963,11 +7063,12 @@ char_u *get_last_insert(void) */ char_u *get_last_insert_save(void) { - char_u *s; + char_u *s; int len; - if (last_insert == NULL) + if (last_insert == NULL) { return NULL; + } s = vim_strsave(last_insert + last_insert_skip); len = (int)STRLEN(s); if (len > 0 && s[len - 1] == ESC) { // remove trailing ESC @@ -6995,7 +7096,7 @@ static bool echeck_abbr(int c) } return check_abbr(c, get_cursor_line_ptr(), curwin->w_cursor.col, - curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); + curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); } /* @@ -7013,7 +7114,7 @@ static bool echeck_abbr(int c) * that were deleted (always white space). */ -static char_u *replace_stack = NULL; +static char_u *replace_stack = NULL; static ssize_t replace_stack_nr = 0; // next entry in replace stack static ssize_t replace_stack_len = 0; // max. number of entries @@ -7052,8 +7153,9 @@ int replace_push_mb(char_u *p) int l = (*mb_ptr2len)(p); int j; - for (j = l - 1; j >= 0; --j) + for (j = l - 1; j >= 0; --j) { replace_push(p[j]); + } return l; } @@ -7065,23 +7167,22 @@ static int replace_pop(void) return (replace_stack_nr == 0) ? -1 : (int)replace_stack[--replace_stack_nr]; } -/* - * Join the top two items on the replace stack. This removes to "off"'th NUL - * encountered. - */ -static void replace_join( - int off // offset for which NUL to remove -) +/// Join the top two items on the replace stack. This removes to "off"'th NUL +/// encountered. +/// +/// @param off offset for which NUL to remove +static void replace_join(int off) { int i; - for (i = replace_stack_nr; --i >= 0; ) + for (i = replace_stack_nr; --i >= 0; ) { if (replace_stack[i] == NUL && off-- <= 0) { --replace_stack_nr; memmove(replace_stack + i, replace_stack + i + 1, - (size_t)(replace_stack_nr - i)); + (size_t)(replace_stack_nr - i)); return; } + } } /* @@ -7114,8 +7215,9 @@ static void mb_replace_pop_ins(int cc) if ((n = MB_BYTE2LEN(cc)) > 1) { buf[0] = cc; - for (i = 1; i < n; ++i) + for (i = 1; i < n; ++i) { buf[i] = replace_pop(); + } ins_bytes_len(buf, n); } else { ins_char(cc); @@ -7177,7 +7279,7 @@ static void replace_do_bs(int limit_col) int ins_len; int orig_vcols = 0; colnr_T start_vcol; - char_u *p; + char_u *p; int i; int vcol; const int l_State = State; @@ -7220,8 +7322,9 @@ static void replace_do_bs(int limit_col) // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col); - } else if (cc == 0) + } else if (cc == 0) { (void)del_char_after_col(limit_col); + } } /// Check that C-indenting is on. @@ -7239,23 +7342,25 @@ static bool cindent_on(void) */ void fixthisline(IndentGetter get_the_indent) { - int amount = get_the_indent(); + int amount = get_the_indent(); - if (amount >= 0) { - change_indent(INDENT_SET, amount, false, 0, true); - if (linewhite(curwin->w_cursor.lnum)) { - did_ai = true; // delete the indent if the line stays empty - } + if (amount >= 0) { + change_indent(INDENT_SET, amount, false, 0, true); + if (linewhite(curwin->w_cursor.lnum)) { + did_ai = true; // delete the indent if the line stays empty } + } } void fix_indent(void) { - if (p_paste) + if (p_paste) { return; - if (curbuf->b_p_lisp && curbuf->b_p_ai) + } + if (curbuf->b_p_lisp && curbuf->b_p_ai) { fixthisline(get_lisp_indent); - else if (cindent_on()) + } else if (cindent_on()) { do_c_expr_indent(); + } } /// Check that "cinkeys" contains the key "keytyped", @@ -7296,9 +7401,12 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) * 'when' and a '*' or '!' before the key. */ switch (when) { - case '*': try_match = (*look == '*'); break; - case '!': try_match = (*look == '!'); break; - default: try_match = (*look != '*'); break; + case '*': + try_match = (*look == '*'); break; + case '!': + try_match = (*look == '!'); break; + default: + try_match = (*look != '*'); break; } if (*look == '*' || *look == '!') { look++; @@ -7323,8 +7431,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look += 2; - // 'o' means "o" command, open forward. - // 'O' means "O" command, open backward. + // 'o' means "o" command, open forward. + // 'O' means "O" command, open backward. } else if (*look == 'o') { if (try_match && keytyped == KEY_OPEN_FORW) { return true; @@ -7336,8 +7444,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look++; - // 'e' means to check for "else" at start of line and just before the - // cursor. + // 'e' means to check for "else" at start of line and just before the + // cursor. } else if (*look == 'e') { if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4) { p = get_cursor_line_ptr(); @@ -7348,9 +7456,9 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look++; - // ':' only causes an indent if it is at the end of a label or case - // statement, or when it was before typing the ':' (to fix - // class::method for C++). + // ':' only causes an indent if it is at the end of a label or case + // statement, or when it was before typing the ':' (to fix + // class::method for C++). } else if (*look == ':') { if (try_match && keytyped == ':') { p = get_cursor_line_ptr(); @@ -7364,8 +7472,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) && p[curwin->w_cursor.col - 2] == ':') { p[curwin->w_cursor.col - 1] = ' '; const bool i = cin_iscase(p, false) - || cin_isscopedecl(p) - || cin_islabel(); + || cin_isscopedecl(p) + || cin_islabel(); p = get_cursor_line_ptr(); p[curwin->w_cursor.col - 1] = ':'; if (i) { @@ -7375,7 +7483,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look++; - // Is it a key in <>, maybe? + // Is it a key in <>, maybe? } else if (*look == '<') { if (try_match) { // make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>, @@ -7390,10 +7498,12 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) return true; } } - while (*look && *look != '>') + while (*look && *look != '>') { look++; - while (*look == '>') + } + while (*look == '>') { look++; + } } /* * Is it a word: "=word"? @@ -7403,11 +7513,13 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) if (*look == '~') { icase = TRUE; ++look; - } else + } else { icase = FALSE; + } p = vim_strchr(look, ','); - if (p == NULL) + if (p == NULL) { p = look + STRLEN(look); + } if ((try_match || try_match_word) && curwin->w_cursor.col >= (colnr_T)(p - look)) { bool match = false; @@ -7428,8 +7540,9 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) if (s + (p - look) <= line + curwin->w_cursor.col && (icase ? mb_strnicmp(s, look, (size_t)(p - look)) - : STRNCMP(s, look, p - look)) == 0) + : STRNCMP(s, look, p - look)) == 0) { match = true; + } } else { // TODO(@brammool): multi-byte if (keytyped == (int)p[-1] @@ -7460,7 +7573,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty) } look = p; - // Ok, it's a boring generic character. + // Ok, it's a boring generic character. } else { if (try_match && *look == keytyped) { return true; @@ -7490,15 +7603,15 @@ int hkmap(int c) PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV }; static char_u map[26] = - {(char_u)hALEF /*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/, - (char_u)DALET /*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit /*f*/, - (char_u)GIMEL /*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/, - (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/, - (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/, - (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/, - (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/, - (char_u)VAV /*v*/, (char_u)hSHIN /*w*/, (char_u)-1 /*x*/, - (char_u)AIN /*y*/, (char_u)ZADI /*z*/}; + { (char_u)hALEF /*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/, + (char_u)DALET /*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit /*f*/, + (char_u)GIMEL /*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/, + (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/, + (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/, + (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/, + (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/, + (char_u)VAV /*v*/, (char_u)hSHIN /*w*/, (char_u)-1 /*x*/, + (char_u)AIN /*y*/, (char_u)ZADI /*z*/ }; if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z') { return (int)(map[CharOrd(c)] - 1 + p_aleph); @@ -7523,24 +7636,33 @@ int hkmap(int c) } } else { switch (c) { - case '`': return ';'; - case '/': return '.'; - case '\'': return ','; - case 'q': return '/'; - case 'w': return '\''; + case '`': + return ';'; + case '/': + return '.'; + case '\'': + return ','; + case 'q': + return '/'; + case 'w': + return '\''; // Hebrew letters - set offset from 'a' - case ',': c = '{'; break; - case '.': c = 'v'; break; - case ';': c = 't'; break; + case ',': + c = '{'; break; + case '.': + c = 'v'; break; + case ';': + c = 't'; break; default: { - static char str[] = "zqbcxlsjphmkwonu ydafe rig"; + static char str[] = "zqbcxlsjphmkwonu ydafe rig"; - if (c < 'a' || c > 'z') - return c; - c = str[CharOrdLow(c)]; - break; - } + if (c < 'a' || c > 'z') { + return c; + } + c = str[CharOrdLow(c)]; + break; + } } return (int)(CharOrdLow(c) + p_aleph); @@ -7660,13 +7782,15 @@ static void ins_ctrl_g(void) // CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col case K_UP: case Ctrl_K: - case 'k': ins_up(TRUE); + case 'k': + ins_up(TRUE); break; // CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col case K_DOWN: case Ctrl_J: - case 'j': ins_down(TRUE); + case 'j': + ins_down(TRUE); break; // CTRL-G u: start new undoable edit @@ -7688,7 +7812,8 @@ static void ins_ctrl_g(void) break; // Unknown CTRL-G command, reserved for future expansion. - default: vim_beep(BO_CTRLG); + default: + vim_beep(BO_CTRLG); } } @@ -7746,8 +7871,9 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) */ if (*count > 0) { line_breakcheck(); - if (got_int) + if (got_int) { *count = 0; + } } if (--*count > 0) { // repeat what was typed @@ -7796,8 +7922,7 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) || (gchar_cursor() == NUL && !VIsual_active )) - && !revins_on - ) { + && !revins_on) { if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL) { oneleft(); if (restart_edit != NUL) { @@ -7836,8 +7961,9 @@ static bool ins_esc(long *count, int cmdchar, bool nomove) static void ins_ctrl_(void) { if (revins_on && revins_chars && revins_scol >= 0) { - while (gchar_cursor() != NUL && revins_chars--) + while (gchar_cursor() != NUL && revins_chars--) { ++curwin->w_cursor.col; + } } p_ri = !p_ri; revins_on = (State == INSERT && p_ri); @@ -7846,8 +7972,9 @@ static void ins_ctrl_(void) revins_legal++; revins_chars = 0; undisplay_dollar(); - } else + } else { revins_scol = -1; + } p_hkmap = curwin->w_p_rl ^ p_ri; // be consistent! showmode(); } @@ -7870,8 +7997,9 @@ static bool ins_start_select(int c) case K_KPAGEUP: case K_PAGEDOWN: case K_KPAGEDOWN: - if (!(mod_mask & MOD_MASK_SHIFT)) + if (!(mod_mask & MOD_MASK_SHIFT)) { break; + } FALLTHROUGH; case K_S_LEFT: case K_S_RIGHT: @@ -7920,12 +8048,13 @@ static void ins_insert(int replaceState) */ static void ins_ctrl_o(void) { - if (State & VREPLACE_FLAG) + if (State & VREPLACE_FLAG) { restart_edit = 'V'; - else if (State & REPLACE_FLAG) + } else if (State & REPLACE_FLAG) { restart_edit = 'R'; - else + } else { restart_edit = 'I'; + } if (virtual_active()) { ins_at_eol = false; // cursor always keeps its column } else { @@ -7935,15 +8064,16 @@ 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 ">>". + * 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) + if (stop_arrow() == FAIL) { return; + } AppendCharToRedobuff(c); /* @@ -7961,8 +8091,9 @@ static void ins_shift(int c, int lastc) old_indent = get_indent(); // remember curr. indent } change_indent(INDENT_SET, 0, TRUE, 0, TRUE); - } else + } else { change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE); + } if (did_ai && *skipwhite(get_cursor_line_ptr()) != NUL) { did_ai = false; @@ -8124,19 +8255,22 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) // again when auto-formatting. if (has_format_option(FO_AUTO) && has_format_option(FO_WHITE_PAR)) { - char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, true); + char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, true); int len; len = (int)STRLEN(ptr); - if (len > 0 && ptr[len - 1] == ' ') + if (len > 0 && ptr[len - 1] == ' ') { ptr[len - 1] = NUL; + } } do_join(2, FALSE, FALSE, FALSE, false); - if (temp == NUL && gchar_cursor() != NUL) + if (temp == NUL && gchar_cursor() != NUL) { inc_cursor(); - } else + } + } else { dec_cursor(); + } /* * In REPLACE mode we have to put back the text that was replaced @@ -8178,12 +8312,12 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) && (curbuf->b_p_ai || cindent_on() ) - && !revins_on - ) { + && !revins_on) { save_col = curwin->w_cursor.col; beginline(BL_WHITE); - if (curwin->w_cursor.col < save_col) + if (curwin->w_cursor.col < save_col) { mincol = curwin->w_cursor.col; + } curwin->w_cursor.col = save_col; } @@ -8239,8 +8373,9 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) ins_char(' '); } else { ins_str((char_u *)" "); - if ((State & REPLACE_FLAG)) + if ((State & REPLACE_FLAG)) { replace_push(NUL); + } } getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL); } @@ -8294,8 +8429,9 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) revins_chars--; revins_legal++; } - if (revins_on && gchar_cursor() == NUL) + if (revins_on && gchar_cursor() == NUL) { break; + } } // Just a single backspace?: if (mode == BACKSPACE_CHAR) { @@ -8349,12 +8485,12 @@ static bool ins_bs(int c, int mode, int *inserted_space_p) static void ins_mouse(int c) { pos_T tpos; - win_T *old_curwin = curwin; + win_T *old_curwin = curwin; undisplay_dollar(); tpos = curwin->w_cursor; if (do_mouse(NULL, c, BACKWARD, 1, 0)) { - win_T *new_curwin = curwin; + win_T *new_curwin = curwin; if (curwin != old_curwin && win_valid(old_curwin)) { // Mouse took us to another window. We need to go back to the @@ -8394,21 +8530,22 @@ static void ins_mousescroll(int dir) curwin = wp; curbuf = curwin->w_buffer; } - if (curwin == old_curwin) + if (curwin == old_curwin) { undisplay_dollar(); + } // Don't scroll the window in which completion is being done. if (!pum_visible() - || curwin != old_curwin - ) { + || curwin != old_curwin) { if (dir == MSCR_DOWN || dir == MSCR_UP) { - if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) + if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { scroll_redraw(dir, - (long)(curwin->w_botline - curwin->w_topline)); - else + (long)(curwin->w_botline - curwin->w_topline)); + } else { scroll_redraw(dir, 3L); + } } else { - mouse_scroll_horiz(dir); + mouse_scroll_horiz(dir); } } @@ -8430,8 +8567,9 @@ static void ins_left(void) pos_T tpos; const bool end_change = dont_sync_undo == kFalse; // end undoable change - if ((fdo_flags & FDO_HOR) && KeyTyped) + if ((fdo_flags & FDO_HOR) && KeyTyped) { foldOpenCursor(); + } undisplay_dollar(); tpos = curwin->w_cursor; if (oneleft() == OK) { @@ -8461,12 +8599,14 @@ static void ins_home(int c) { pos_T tpos; - if ((fdo_flags & FDO_HOR) && KeyTyped) + if ((fdo_flags & FDO_HOR) && KeyTyped) { foldOpenCursor(); + } undisplay_dollar(); tpos = curwin->w_cursor; - if (c == K_C_HOME) + if (c == K_C_HOME) { curwin->w_cursor.lnum = 1; + } curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; curwin->w_curswant = 0; @@ -8477,12 +8617,14 @@ static void ins_end(int c) { pos_T tpos; - if ((fdo_flags & FDO_HOR) && KeyTyped) + if ((fdo_flags & FDO_HOR) && KeyTyped) { foldOpenCursor(); + } undisplay_dollar(); tpos = curwin->w_cursor; - if (c == K_C_END) + if (c == K_C_END) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; + } coladvance(MAXCOL); curwin->w_curswant = MAXCOL; @@ -8530,8 +8672,9 @@ static void ins_right(void) } revins_legal++; - if (revins_chars) + if (revins_chars) { revins_chars--; + } } else if (vim_strchr(p_ww, ']') != NULL && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { // if 'whichwrap' set for cursor in insert mode, may move the @@ -8567,9 +8710,8 @@ static void ins_s_right(void) dont_sync_undo = kFalse; } -static void ins_up( - bool startcol // when true move to Insstart.col -) +/// @param startcol when true move to Insstart.col +static void ins_up(bool startcol) { pos_T tpos; linenr_T old_topline = curwin->w_topline; @@ -8578,12 +8720,13 @@ static void ins_up( undisplay_dollar(); tpos = curwin->w_cursor; if (cursor_up(1L, TRUE) == OK) { - if (startcol) + if (startcol) { coladvance(getvcol_nolist(&Insstart)); + } if (old_topline != curwin->w_topline - || old_topfill != curwin->w_topfill - ) + || old_topfill != curwin->w_topfill) { redraw_later(curwin, VALID); + } start_arrow(&tpos); can_cindent = true; } else { @@ -8615,9 +8758,8 @@ static void ins_pageup(void) } } -static void ins_down( - bool startcol // when true move to Insstart.col -) +/// @param startcol when true move to Insstart.col +static void ins_down(bool startcol) { pos_T tpos; linenr_T old_topline = curwin->w_topline; @@ -8626,12 +8768,13 @@ static void ins_down( undisplay_dollar(); tpos = curwin->w_cursor; if (cursor_down(1L, TRUE) == OK) { - if (startcol) + if (startcol) { coladvance(getvcol_nolist(&Insstart)); + } if (old_topline != curwin->w_topline - || old_topfill != curwin->w_topfill - ) + || old_topfill != curwin->w_topfill) { redraw_later(curwin, VALID); + } start_arrow(&tpos); can_cindent = true; } else { @@ -8687,15 +8830,15 @@ static bool ins_tab(void) // When nothing special, insert TAB like a normal character. if (!curbuf->b_p_et && !( - p_sta - && ind - // These five lines mean 'tabstop' != 'shiftwidth' - && ((tabstop_count(curbuf->b_p_vts_array) > 1) - || (tabstop_count(curbuf->b_p_vts_array) == 1 - && tabstop_first(curbuf->b_p_vts_array) - != get_sw_value(curbuf)) - || (tabstop_count(curbuf->b_p_vts_array) == 0 - && curbuf->b_p_ts != get_sw_value(curbuf)))) + p_sta + && ind + // These five lines mean 'tabstop' != 'shiftwidth' + && ((tabstop_count(curbuf->b_p_vts_array) > 1) + || (tabstop_count(curbuf->b_p_vts_array) == 1 + && tabstop_first(curbuf->b_p_vts_array) + != get_sw_value(curbuf)) + || (tabstop_count(curbuf->b_p_vts_array) == 0 + && curbuf->b_p_ts != get_sw_value(curbuf)))) && tabstop_count(curbuf->b_p_vsts_array) == 0 && get_sts_value() == 0) { return true; } @@ -8727,7 +8870,7 @@ static bool ins_tab(void) } /* - * Insert the first space with ins_char(). It will delete one char in + * Insert the first space with ins_char(). It will delete one char in * replace mode. Insert the rest with ins_str(); it will not delete any * chars. For VREPLACE mode, we use ins_char() for all characters. */ @@ -8749,11 +8892,11 @@ static bool ins_tab(void) if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_array) > 0 || get_sts_value() > 0 || (p_sta && ind))) { - char_u *ptr; - char_u *saved_line = NULL; // init for GCC + char_u *ptr; + char_u *saved_line = NULL; // init for GCC pos_T pos; pos_T fpos; - pos_T *cursor; + pos_T *cursor; colnr_T want_vcol, vcol; int change_col = -1; int save_list = curwin->w_p_list; @@ -8800,8 +8943,9 @@ static bool ins_tab(void) // and 'linebreak' adding extra virtual columns. while (ascii_iswhite(*ptr)) { i = lbr_chartabsize(NULL, (char_u *)"\t", vcol); - if (vcol + i > want_vcol) + if (vcol + i > want_vcol) { break; + } if (*ptr != TAB) { *ptr = TAB; if (change_col < 0) { @@ -8865,12 +9009,13 @@ static bool ins_tab(void) // Insert each char in saved_line from changed_col to // ptr-cursor ins_bytes_len(saved_line + change_col, - cursor->col - change_col); + cursor->col - change_col); } } - if (State & VREPLACE_FLAG) + if (State & VREPLACE_FLAG) { xfree(saved_line); + } curwin->w_p_list = save_list; } @@ -8896,9 +9041,9 @@ static bool ins_eol(int c) * nothing to put back when the NL is deleted. */ if ((State & REPLACE_FLAG) - && !(State & VREPLACE_FLAG) - ) + && !(State & VREPLACE_FLAG)) { replace_push(NUL); + } /* * In VREPLACE mode, a NL replaces the rest of the line, and starts @@ -9008,8 +9153,8 @@ int ins_copychar(linenr_T lnum) { int c; int temp; - char_u *ptr, *prev_ptr; - char_u *line; + char_u *ptr, *prev_ptr; + char_u *line; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) { vim_beep(BO_COPY); @@ -9025,8 +9170,9 @@ int ins_copychar(linenr_T lnum) prev_ptr = ptr; temp += lbr_chartabsize_adv(line, &ptr, (colnr_T)temp); } - if ((colnr_T)temp > curwin->w_virtcol) + if ((colnr_T)temp > curwin->w_virtcol) { ptr = prev_ptr; + } c = utf_ptr2char(ptr); if (c == NUL) { @@ -9043,10 +9189,11 @@ static int ins_ctrl_ey(int tc) int c = tc; if (ctrl_x_mode == CTRL_X_SCROLL) { - if (c == Ctrl_Y) + if (c == Ctrl_Y) { scrolldown_clamp(); - else + } else { scrollup_clamp(); + } redraw_later(curwin, VALID); } else { c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1)); @@ -9079,8 +9226,8 @@ static int ins_ctrl_ey(int tc) */ static void ins_try_si(int c) { - pos_T *pos, old_pos; - char_u *ptr; + pos_T *pos, old_pos; + char_u *ptr; int i; int temp; @@ -9108,14 +9255,16 @@ static void ins_try_si(int c) } curwin->w_cursor.lnum = pos->lnum; curwin->w_cursor.col = i; - if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL) + if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL) { curwin->w_cursor = *pos; + } i = get_indent(); curwin->w_cursor = old_pos; - if (State & VREPLACE_FLAG) + if (State & VREPLACE_FLAG) { change_indent(INDENT_SET, i, FALSE, NUL, TRUE); - else + } else { (void)set_indent(i, SIN_CHANGED); + } } else if (curwin->w_cursor.col > 0) { /* * when inserting '{' after "O" reduce indent, but not @@ -9133,12 +9282,14 @@ static void ins_try_si(int c) break; } } - if (get_indent() >= i) + if (get_indent() >= i) { temp = FALSE; + } curwin->w_cursor = old_pos; } - if (temp) + if (temp) { shift_line(TRUE, FALSE, 1, TRUE); + } } } diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 5603fbb082..dfbb187b5b 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -1456,21 +1456,18 @@ static void ex_let_const(exarg_T *eap, const bool is_const) /* * Assign the typevalue "tv" to the variable or variables at "arg_start". * Handles both "var" with any type and "[var, var; var]" with a list type. - * When "nextchars" is not NULL it points to a string with characters that + * When "op" is not NULL it points to a string with characters that * must appear after the variable(s). Use "+", "-" or "." for add, subtract * or concatenate. * Returns OK or FAIL; */ -static int -ex_let_vars( - char_u *arg_start, - typval_T *tv, - int copy, // copy values from "tv", don't move - int semicolon, // from skip_var_list() - int var_count, // from skip_var_list() - int is_const, // lock variables for :const - char_u *nextchars -) +static int ex_let_vars(char_u *arg_start, + typval_T *tv, + int copy, // copy values from "tv", don't move + int semicolon, // from skip_var_list() + int var_count, // from skip_var_list() + int is_const, // lock variables for :const + char_u *op) { char_u *arg = arg_start; typval_T ltv; @@ -1479,7 +1476,7 @@ ex_let_vars( /* * ":let var = expr" or ":for var in list" */ - if (ex_let_one(arg, tv, copy, is_const, nextchars, nextchars) == NULL) { + if (ex_let_one(arg, tv, copy, is_const, op, op) == NULL) { return FAIL; } return OK; @@ -1510,7 +1507,7 @@ ex_let_vars( while (*arg != ']') { arg = skipwhite(arg + 1); arg = ex_let_one(arg, TV_LIST_ITEM_TV(item), true, is_const, - (const char_u *)",;]", nextchars); + (const char_u *)",;]", op); if (arg == NULL) { return FAIL; } @@ -1532,8 +1529,8 @@ ex_let_vars( ltv.vval.v_list = rest_list; tv_list_ref(rest_list); - arg = ex_let_one(skipwhite(arg + 1), <v, false, is_const, - (char_u *)"]", nextchars); + arg = ex_let_one(skipwhite(arg + 1), <v, false, is_const, (char_u *)"]", + op); tv_clear(<v); if (arg == NULL) { return FAIL; @@ -3950,7 +3947,12 @@ static int eval7( rettv->vval.v_float = f; } } else { - vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0); + vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0, true); + if (len == 0) { + EMSG2(_(e_invexpr2), *arg); + ret = FAIL; + break; + } *arg += len; if (evaluate) { rettv->v_type = VAR_NUMBER; @@ -8670,6 +8672,7 @@ handle_subscript( } } + // "." is ".name" lookup when we found a dict. while (ret == OK && (((**arg == '[' || (**arg == '.' && rettv->v_type == VAR_DICT) || (**arg == '(' && (!evaluate || tv_is_func(*rettv)))) diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index faff29b268..a7242ba73a 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -344,7 +344,7 @@ return { stdpath={args=1}, str2float={args=1, base=1}, str2list={args={1, 2}, base=1}, - str2nr={args={1, 2}}, + str2nr={args={1, 3}}, strcharpart={args={2, 3}}, strchars={args={1,2}}, strdisplaywidth={args={1, 2}}, diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c index bd4dc87d31..89e1f04bfd 100644 --- a/src/nvim/eval/decode.c +++ b/src/nvim/eval/decode.c @@ -437,7 +437,7 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len, t += 4; uvarnumber_T ch; vim_str2nr((char_u *)ubuf, NULL, NULL, - STR2NR_HEX | STR2NR_FORCE, NULL, &ch, 4); + STR2NR_HEX | STR2NR_FORCE, NULL, &ch, 4, true); if (ch == 0) { hasnul = true; } @@ -611,8 +611,8 @@ 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)); - if ((int) exp_num_len != num_len) { + vim_str2nr((char_u *)s, NULL, &num_len, 0, &nr, NULL, (int)(p - s), true); + if ((int)exp_num_len != num_len) { emsgf(_("E685: internal error: while converting number \"%.*s\" " "to integer vim_str2nr consumed %i bytes in place of %zu"), (int) exp_num_len, s, num_len, exp_num_len); diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 99f9f17e0a..801b0f9d1c 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -9998,7 +9998,7 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int base = 10; varnumber_T n; - int what; + int what = 0; if (argvars[1].v_type != VAR_UNKNOWN) { base = tv_get_number(&argvars[1]); @@ -10006,6 +10006,9 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) EMSG(_(e_invarg)); return; } + if (argvars[2].v_type != VAR_UNKNOWN && tv_get_number(&argvars[2])) { + what |= STR2NR_QUOTE; + } } char_u *p = skipwhite((const char_u *)tv_get_string(&argvars[0])); @@ -10015,22 +10018,20 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) } switch (base) { case 2: { - what = STR2NR_BIN | STR2NR_FORCE; + what |= STR2NR_BIN | STR2NR_FORCE; break; } case 8: { - what = STR2NR_OCT | STR2NR_FORCE; + what |= STR2NR_OCT | STR2NR_OOCT | STR2NR_FORCE; break; } case 16: { - what = STR2NR_HEX | STR2NR_FORCE; + what |= STR2NR_HEX | STR2NR_FORCE; break; } - default: { - what = 0; - } } - vim_str2nr(p, NULL, NULL, what, &n, NULL, 0); + vim_str2nr(p, NULL, NULL, what, &n, NULL, 0, false); + // Text after the number is silently ignored. if (isneg) { rettv->vval.v_number = -n; } else { diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c index 5cb0058ec6..22b3bf026b 100644 --- a/src/nvim/eval/typval.c +++ b/src/nvim/eval/typval.c @@ -2990,7 +2990,8 @@ 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(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0); + vim_str2nr(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0, + false); } return n; } diff --git a/src/nvim/event/process.c b/src/nvim/event/process.c index a2aafc94c8..8b366d0f3c 100644 --- a/src/nvim/event/process.c +++ b/src/nvim/event/process.c @@ -88,7 +88,7 @@ int process_spawn(Process *proc, bool in, bool out, bool err) } else { process_close(proc); } - shell_free_argv(proc->argv); + process_free(proc); proc->status = -1; return status; } @@ -201,7 +201,7 @@ int process_wait(Process *proc, int ms, MultiQueue *events) // Job exited, free its resources. decref(proc); if (proc->events) { - // the decref call created an exit event, process it now + // decref() created an exit event, process it now. multiqueue_process_events(proc->events); } } else { @@ -239,6 +239,15 @@ void process_stop(Process *proc) FUNC_ATTR_NONNULL_ALL KILL_TIMEOUT_MS, 0); } +// Frees process-owned resources. +void process_free(Process *proc) FUNC_ATTR_NONNULL_ALL +{ + if (proc->argv != NULL) { + shell_free_argv(proc->argv); + proc->argv = NULL; + } +} + /// Sends SIGKILL (or SIGTERM..SIGKILL for PTY jobs) to processes that did /// not terminate after process_stop(). static void children_kill_cb(uv_timer_t *handle) @@ -269,9 +278,12 @@ static void children_kill_cb(uv_timer_t *handle) static void process_close_event(void **argv) { Process *proc = argv[0]; - shell_free_argv(proc->argv); - if (proc->cb) { // "on_exit" for jobstart(). See channel_job_start(). + if (proc->cb) { + // User (hint: channel_job_start) is responsible for calling + // process_free(). proc->cb(proc, proc->status, proc->data); + } else { + process_free(proc); } } diff --git a/src/nvim/event/process.h b/src/nvim/event/process.h index 24debdb276..20c02e4900 100644 --- a/src/nvim/event/process.h +++ b/src/nvim/event/process.h @@ -26,6 +26,7 @@ struct process { char **argv; dict_T *env; Stream in, out, err; + /// Exit handler. If set, user must call process_free(). process_exit_cb cb; internal_process_cb internal_exit_cb, internal_close_cb; bool closed, detach, overlapped; diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index f7a1327c87..2ea16f0d50 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -7,52 +7,55 @@ #include <assert.h> #include <float.h> -#include <stdbool.h> -#include <string.h> -#include <stdlib.h> #include <inttypes.h> #include <math.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include "nvim/api/buffer.h" #include "nvim/api/private/defs.h" #include "nvim/api/vim.h" -#include "nvim/api/buffer.h" -#include "nvim/log.h" -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/ex_cmds.h" #include "nvim/buffer.h" +#include "nvim/buffer_updates.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" +#include "nvim/decoration.h" #include "nvim/diff.h" #include "nvim/digraph.h" #include "nvim/edit.h" #include "nvim/eval.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" #include "nvim/ex_getln.h" +#include "nvim/extmark.h" #include "nvim/fileio.h" #include "nvim/fold.h" +#include "nvim/garray.h" #include "nvim/getchar.h" #include "nvim/highlight.h" #include "nvim/indent.h" -#include "nvim/buffer_updates.h" +#include "nvim/log.h" #include "nvim/main.h" #include "nvim/mark.h" -#include "nvim/extmark.h" -#include "nvim/decoration.h" #include "nvim/mbyte.h" #include "nvim/memline.h" +#include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/garray.h" -#include "nvim/memory.h" -#include "nvim/move.h" #include "nvim/mouse.h" +#include "nvim/move.h" #include "nvim/normal.h" #include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/os.h" +#include "nvim/os/shell.h" +#include "nvim/os/time.h" #include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/plines.h" @@ -66,11 +69,8 @@ #include "nvim/tag.h" #include "nvim/ui.h" #include "nvim/undo.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/os/os.h" -#include "nvim/os/shell.h" -#include "nvim/os/input.h" -#include "nvim/os/time.h" /// Case matching style to use for :substitute @@ -147,17 +147,17 @@ void do_ascii(const exarg_T *const eap) dig = get_digraph_for_char(cval); if (dig != NULL) { - iobuff_len += ( - vim_snprintf((char *)IObuff + iobuff_len, - sizeof(IObuff) - iobuff_len, - _("<%s>%s%s %d, Hex %02x, Oct %03o, Digr %s"), - transchar(c), buf1, buf2, cval, cval, cval, dig)); + iobuff_len += ( + vim_snprintf((char *)IObuff + iobuff_len, + sizeof(IObuff) - iobuff_len, + _("<%s>%s%s %d, Hex %02x, Oct %03o, Digr %s"), + transchar(c), buf1, buf2, cval, cval, cval, dig)); } else { - iobuff_len += ( - vim_snprintf((char *)IObuff + iobuff_len, - sizeof(IObuff) - iobuff_len, - _("<%s>%s%s %d, Hex %02x, Octal %03o"), - transchar(c), buf1, buf2, cval, cval, cval)); + iobuff_len += ( + vim_snprintf((char *)IObuff + iobuff_len, + sizeof(IObuff) - iobuff_len, + _("<%s>%s%s %d, Hex %02x, Octal %03o"), + transchar(c), buf1, buf2, cval, cval, cval)); } c = cc[ci++]; @@ -197,21 +197,21 @@ void do_ascii(const exarg_T *const eap) dig = get_digraph_for_char(c); if (dig != NULL) { - iobuff_len += ( - vim_snprintf((char *)IObuff + iobuff_len, - sizeof(IObuff) - iobuff_len, - (c < 0x10000 + iobuff_len += ( + vim_snprintf((char *)IObuff + iobuff_len, + sizeof(IObuff) - iobuff_len, + (c < 0x10000 ? _("> %d, Hex %04x, Oct %o, Digr %s") : _("> %d, Hex %08x, Oct %o, Digr %s")), - c, c, c, dig)); + c, c, c, dig)); } else { - iobuff_len += ( - vim_snprintf((char *)IObuff + iobuff_len, - sizeof(IObuff) - iobuff_len, - (c < 0x10000 + iobuff_len += ( + vim_snprintf((char *)IObuff + iobuff_len, + sizeof(IObuff) - iobuff_len, + (c < 0x10000 ? _("> %d, Hex %04x, Octal %o") : _("> %d, Hex %08x, Octal %o")), - c, c, c)); + c, c, c)); } if (ci == MAX_MCO) { break; @@ -238,26 +238,29 @@ void ex_align(exarg_T *eap) int width; if (curwin->w_p_rl) { - /* switch left and right aligning */ - if (eap->cmdidx == CMD_right) + // switch left and right aligning + if (eap->cmdidx == CMD_right) { eap->cmdidx = CMD_left; - else if (eap->cmdidx == CMD_left) + } else if (eap->cmdidx == CMD_left) { eap->cmdidx = CMD_right; + } } width = atoi((char *)eap->arg); save_curpos = curwin->w_cursor; - if (eap->cmdidx == CMD_left) { /* width is used for new indent */ - if (width >= 0) + if (eap->cmdidx == CMD_left) { // width is used for new indent + if (width >= 0) { indent = width; + } } else { /* * if 'textwidth' set, use it * else if 'wrapmargin' set, use it * if invalid value, use 80 */ - if (width <= 0) + if (width <= 0) { width = curbuf->b_p_tw; + } if (width == 0 && curbuf->b_p_wm > 0) { width = curwin->w_width_inner - curbuf->b_p_wm; } @@ -266,31 +269,33 @@ void ex_align(exarg_T *eap) } } - if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL) + if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL) { return; + } for (curwin->w_cursor.lnum = eap->line1; curwin->w_cursor.lnum <= eap->line2; ++curwin->w_cursor.lnum) { - if (eap->cmdidx == CMD_left) /* left align */ + if (eap->cmdidx == CMD_left) { // left align new_indent = indent; - else { - has_tab = FALSE; /* avoid uninit warnings */ + } else { + has_tab = FALSE; // avoid uninit warnings len = linelen(eap->cmdidx == CMD_right ? &has_tab - : NULL) - get_indent(); + : NULL) - get_indent(); - if (len <= 0) /* skip blank lines */ + if (len <= 0) { // skip blank lines continue; + } - if (eap->cmdidx == CMD_center) + if (eap->cmdidx == CMD_center) { new_indent = (width - len) / 2; - else { - new_indent = width - len; /* right align */ + } else { + new_indent = width - len; // right align /* * Make sure that embedded TABs don't make the text go too far * to the right. */ - if (has_tab) + if (has_tab) { while (new_indent > 0) { (void)set_indent(new_indent, 0); if (linelen(NULL) <= width) { @@ -306,11 +311,13 @@ void ex_align(exarg_T *eap) } --new_indent; } + } } } - if (new_indent < 0) + if (new_indent < 0) { new_indent = 0; - (void)set_indent(new_indent, 0); /* set indent */ + } + (void)set_indent(new_indent, 0); // set indent } changed_lines(eap->line1, 0, eap->line2 + 1, 0L, true); curwin->w_cursor = save_curpos; @@ -322,9 +329,9 @@ void ex_align(exarg_T *eap) */ static int linelen(int *has_tab) { - char_u *line; - char_u *first; - char_u *last; + char_u *line; + char_u *first; + char_u *last; int save; int len; @@ -356,8 +363,8 @@ static int linelen(int *has_tab) /* Buffer for two lines used during sorting. They are allocated to * contain the longest line being sorted. */ -static char_u *sortbuf1; -static char_u *sortbuf2; +static char_u *sortbuf1; +static char_u *sortbuf2; static int sort_lc; ///< sort using locale static int sort_ic; ///< ignore case @@ -400,11 +407,13 @@ static int sort_compare(const void *s1, const void *s2) /* If the user interrupts, there's no way to stop qsort() immediately, but * if we return 0 every time, qsort will assume it's done sorting and * exit. */ - if (sort_abort) + if (sort_abort) { return 0; + } fast_breakcheck(); - if (got_int) + if (got_int) { sort_abort = TRUE; + } // When sorting numbers "start_col_nr" is the number, not the column // number. @@ -436,9 +445,10 @@ static int sort_compare(const void *s1, const void *s2) result = string_compare(sortbuf1, sortbuf2); } - /* If two lines have the same value, preserve the original line order. */ - if (result == 0) + // If two lines have the same value, preserve the original line order. + if (result == 0) { return (int)(l1.lnum - l2.lnum); + } return result; } @@ -451,9 +461,9 @@ void ex_sort(exarg_T *eap) long maxlen = 0; size_t count = (size_t)(eap->line2 - eap->line1 + 1); size_t i; - char_u *p; - char_u *s; - char_u *s2; + char_u *p; + char_u *s; + char_u *s2; char_u c; // temporary character storage bool unique = false; long deleted; @@ -599,7 +609,7 @@ void ex_sort(exarg_T *eap) } else { nrs[lnum - eap->line1].st_u.num.is_number = true; vim_str2nr(s, NULL, NULL, sort_what, - &nrs[lnum - eap->line1].st_u.num.value, NULL, 0); + &nrs[lnum - eap->line1].st_u.num.value, NULL, 0, false); } } else { s = skipwhite(p); @@ -623,10 +633,12 @@ void ex_sort(exarg_T *eap) nrs[lnum - eap->line1].lnum = lnum; - if (regmatch.regprog != NULL) + if (regmatch.regprog != NULL) { fast_breakcheck(); - if (got_int) + } + if (got_int) { goto sortend; + } } // Allocate a buffer that can hold the longest line. @@ -636,8 +648,9 @@ void ex_sort(exarg_T *eap) // Sort the array of line numbers. Note: can't be interrupted! qsort((void *)nrs, count, sizeof(sorti_T), sort_compare); - if (sort_abort) + if (sort_abort) { goto sortend; + } bcount_t old_count = 0, new_count = 0; @@ -665,8 +678,9 @@ void ex_sort(exarg_T *eap) new_count += bytelen; } fast_breakcheck(); - if (got_int) + if (got_int) { goto sortend; + } } // delete the original lines if appending worked @@ -724,18 +738,18 @@ void ex_retab(exarg_T *eap) long start_col = 0; // For start of white-space string long start_vcol = 0; // For start of white-space string long old_len; - char_u *ptr; - char_u *new_line = (char_u *)1; // init to non-NULL + char_u *ptr; + char_u *new_line = (char_u *)1; // init to non-NULL int did_undo; // called u_save for current line long *new_vts_array = NULL; char_u *new_ts_str; // string value of tab argument int save_list; - linenr_T first_line = 0; /* first changed line */ - linenr_T last_line = 0; /* last changed line */ + linenr_T first_line = 0; // first changed line + linenr_T last_line = 0; // last changed line save_list = curwin->w_p_list; - curwin->w_p_list = 0; /* don't want list mode here */ + curwin->w_p_list = 0; // don't want list mode here new_ts_str = eap->arg; if (!tabstop_set(eap->arg, &new_vts_array)) { @@ -762,7 +776,7 @@ void ex_retab(exarg_T *eap) for (;; ) { if (ascii_iswhite(ptr[col])) { if (!got_tab && num_spaces == 0) { - /* First consecutive white-space */ + // First consecutive white-space start_vcol = vcol; start_col = col; } @@ -773,9 +787,9 @@ void ex_retab(exarg_T *eap) } } else { if (got_tab || (eap->forceit && num_spaces > 1)) { - /* Retabulate this string of white-space */ + // Retabulate this string of white-space - /* len is virtual length of white string */ + // len is virtual length of white string len = num_spaces = vcol - start_vcol; num_tabs = 0; if (!curbuf->b_p_et) { @@ -797,16 +811,17 @@ void ex_retab(exarg_T *eap) } } - /* len is actual number of white characters used */ + // len is actual number of white characters used len = num_spaces + num_tabs; old_len = (long)STRLEN(ptr); long new_len = old_len - col + start_col + len + 1; new_line = xmalloc(new_len); - if (start_col > 0) + if (start_col > 0) { memmove(new_line, ptr, (size_t)start_col); + } memmove(new_line + start_col + len, - ptr + col, (size_t)(old_len - col + 1)); + ptr + col, (size_t)(old_len - col + 1)); ptr = new_line + start_col; for (col = 0; col < len; col++) { ptr[col] = (col < num_tabs) ? '\t' : ' '; @@ -828,17 +843,20 @@ void ex_retab(exarg_T *eap) got_tab = false; num_spaces = 0; } - if (ptr[col] == NUL) + if (ptr[col] == NUL) { break; + } vcol += win_chartabsize(curwin, ptr + col, (colnr_T)vcol); col += utfc_ptr2len(ptr + col); } - if (new_line == NULL) /* out of memory */ + if (new_line == NULL) { // out of memory break; + } line_breakcheck(); } - if (got_int) + if (got_int) { EMSG(_(e_interr)); + } // If a single value was given then it can be considered equal to // either the value of 'tabstop' or the value of 'vartabstop'. @@ -856,7 +874,7 @@ void ex_retab(exarg_T *eap) changed_lines(first_line, 0, last_line + 1, 0L, true); } - curwin->w_p_list = save_list; /* restore 'list' */ + curwin->w_p_list = save_list; // restore 'list' if (new_ts_str != NULL) { // set the new tabstop // If 'vartabstop' is in use or if the value given to retab has more @@ -888,7 +906,7 @@ void ex_retab(exarg_T *eap) */ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) { - char_u *str; + char_u *str; linenr_T l; linenr_T extra; // Num lines added before line1 linenr_T num_lines; // Num lines moved @@ -923,14 +941,16 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) * 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) + if (u_save(dest, dest + 1) == FAIL) { return FAIL; + } for (extra = 0, l = line1; l <= line2; l++) { str = vim_strsave(ml_get(l + extra)); ml_append(dest + l - line1, str, (colnr_T)0, false); xfree(str); - if (dest < line1) + if (dest < line1) { extra++; + } } /* @@ -986,17 +1006,19 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) /* * Now we delete the original text -- webb */ - if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL) + if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL) { return FAIL; + } for (l = line1; l <= line2; l++) { ml_delete(line1 + extra, true); } if (!global_busy && num_lines > p_report) { - if (num_lines == 1) + if (num_lines == 1) { MSG(_("1 line moved")); - else + } else { smsg(_("%" PRId64 " lines moved"), (int64_t)num_lines); + } } extmark_move_region(curbuf, line1-1, 0, start_byte, @@ -1007,16 +1029,18 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) /* * Leave the cursor on the last of the moved lines. */ - if (dest >= line1) + if (dest >= line1) { curwin->w_cursor.lnum = dest; - else + } else { curwin->w_cursor.lnum = dest + (line2 - line1) + 1; + } if (line1 < dest) { dest += num_lines + 1; last_line = curbuf->b_ml.ml_line_count; - if (dest > last_line + 1) + if (dest > last_line + 1) { dest = last_line + 1; + } changed_lines(line1, 0, dest, 0L, false); } else { changed_lines(dest + 1, 0, line1 + num_lines, 0L, false); @@ -1034,7 +1058,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest) void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) { linenr_T count; - char_u *p; + char_u *p; count = line2 - line1 + 1; curbuf->b_op_start.lnum = n + 1; @@ -1052,8 +1076,9 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) * line1 = start of source (while copying) * line2 = end of source (while copying) */ - if (u_save(n, n + 1) == FAIL) + if (u_save(n, n + 1) == FAIL) { return; + } curwin->w_cursor.lnum = n; while (line1 <= line2) { @@ -1063,14 +1088,17 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, false); xfree(p); - /* situation 2: skip already copied lines */ - if (line1 == n) + // situation 2: skip already copied lines + if (line1 == n) { line1 = curwin->w_cursor.lnum; + } ++line1; - if (curwin->w_cursor.lnum < line1) + if (curwin->w_cursor.lnum < line1) { ++line1; - if (curwin->w_cursor.lnum < line2) + } + if (curwin->w_cursor.lnum < line2) { ++line2; + } ++curwin->w_cursor.lnum; } @@ -1079,7 +1107,7 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n) msgmore((long)count); } -static char_u *prevcmd = NULL; /* the previous command */ +static char_u *prevcmd = NULL; // the previous command #if defined(EXITFREE) void free_prev_shellcmd(void) @@ -1090,12 +1118,11 @@ void free_prev_shellcmd(void) #endif /* - * Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd" + * Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd" * Bangs in the argument are replaced with the previously entered command. * Remember the argument. */ -void do_bang(int addr_count, exarg_T *eap, bool forceit, - bool do_in, bool do_out) +void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out) FUNC_ATTR_NONNULL_ALL { char_u *arg = eap->arg; // command @@ -1103,9 +1130,9 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, linenr_T line2 = eap->line2; // end of range char_u *newcmd = NULL; // the new command bool free_newcmd = false; // need to free() newcmd - char_u *t; - char_u *p; - char_u *trailarg; + char_u *t; + char_u *p; + char_u *trailarg; int len; int scroll_save = msg_scroll; @@ -1117,8 +1144,8 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, return; } - if (addr_count == 0) { /* :! */ - msg_scroll = FALSE; /* don't scroll here */ + if (addr_count == 0) { // :! + msg_scroll = FALSE; // don't scroll here autowrite_all(); msg_scroll = scroll_save; } @@ -1131,8 +1158,9 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, trailarg = arg; do { len = (int)STRLEN(trailarg) + 1; - if (newcmd != NULL) + if (newcmd != NULL) { len += (int)STRLEN(newcmd); + } if (ins_prevcmd) { if (prevcmd == NULL) { EMSG(_(e_noprev)); @@ -1143,10 +1171,12 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, } t = xmalloc(len); *t = NUL; - if (newcmd != NULL) + if (newcmd != NULL) { STRCAT(t, newcmd); - if (ins_prevcmd) + } + if (ins_prevcmd) { STRCAT(t, prevcmd); + } p = t + STRLEN(t); STRCAT(t, trailarg); xfree(newcmd); @@ -1159,9 +1189,9 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, trailarg = NULL; while (*p) { if (*p == '!') { - if (p > newcmd && p[-1] == '\\') + if (p > newcmd && p[-1] == '\\') { STRMOVE(p - 1, p); - else { + } else { trailarg = p; *trailarg++ = NUL; ins_prevcmd = true; @@ -1175,7 +1205,7 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, xfree(prevcmd); prevcmd = newcmd; - if (bangredo) { /* put cmd in redo buffer for ! command */ + if (bangredo) { // put cmd in redo buffer for ! command /* If % or # appears in the command, it must have been escaped. * Reescape them, so that redoing them does not substitute them by the * buffername. */ @@ -1196,8 +1226,8 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, STRCAT(newcmd, p_shq); free_newcmd = true; } - if (addr_count == 0) { /* :! */ - /* echo the command */ + if (addr_count == 0) { // :! + // echo the command msg_start(); msg_putchar(':'); msg_putchar('!'); @@ -1206,49 +1236,48 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, ui_cursor_goto(msg_row, msg_col); do_shell(newcmd, 0); - } else { /* :range! */ + } else { // :range! /* Careful: This may recursively call do_bang() again! (because of * autocommands) */ do_filter(line1, line2, eap, newcmd, do_in, do_out); apply_autocmds(EVENT_SHELLFILTERPOST, NULL, NULL, FALSE, curbuf); } - if (free_newcmd) + if (free_newcmd) { xfree(newcmd); + } } -// do_filter: filter lines through a command given by the user -// -// We mostly use temp files and the call_shell() routine here. This would -// normally be done using pipes on a Unix system, but this is more portable -// to non-Unix systems. The call_shell() routine needs to be able -// to deal with redirection somehow, and should handle things like looking -// at the PATH env. variable, and adding reasonable extensions to the -// command name given by the user. All reasonable versions of call_shell() -// do this. -// Alternatively, if on Unix and redirecting input or output, but not both, -// and the 'shelltemp' option isn't set, use pipes. -// We use input redirection if do_in is true. -// We use output redirection if do_out is true. -static void do_filter( - linenr_T line1, - linenr_T line2, - exarg_T *eap, /* for forced 'ff' and 'fenc' */ - char_u *cmd, - bool do_in, - bool do_out) +/// do_filter: filter lines through a command given by the user +/// +/// We mostly use temp files and the call_shell() routine here. This would +/// normally be done using pipes on a Unix system, but this is more portable +/// to non-Unix systems. The call_shell() routine needs to be able +/// to deal with redirection somehow, and should handle things like looking +/// at the PATH env. variable, and adding reasonable extensions to the +/// command name given by the user. All reasonable versions of call_shell() +/// do this. +/// Alternatively, if on Unix and redirecting input or output, but not both, +/// and the 'shelltemp' option isn't set, use pipes. +/// We use input redirection if do_in is true. +/// We use output redirection if do_out is true. +/// +/// @param eap for forced 'ff' and 'fenc' +static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, bool do_in, + bool do_out) { - char_u *itmp = NULL; - char_u *otmp = NULL; + char_u *itmp = NULL; + char_u *otmp = NULL; linenr_T linecount; linenr_T read_linecount; pos_T cursor_save; - char_u *cmd_buf; - buf_T *old_curbuf = curbuf; + char_u *cmd_buf; + buf_T *old_curbuf = curbuf; int shell_flags = 0; const int stmp = p_stmp; - if (*cmd == NUL) /* no filter command */ + if (*cmd == NUL) { // no filter command return; + } cursor_save = curwin->w_cursor; @@ -1271,8 +1300,9 @@ static void do_filter( * pipe only need to do 3. */ - if (do_out) + if (do_out) { shell_flags |= kShellOptDoOut; + } if (!do_in && do_out && !stmp) { // Use a pipe to fetch stdout of the command, do not use a temp file. @@ -1291,7 +1321,7 @@ static void do_filter( curbuf->b_op_end.lnum = line2; curwin->w_cursor.lnum = line2; } else if ((do_in && (itmp = vim_tempname()) == NULL) - || (do_out && (otmp = vim_tempname()) == NULL)) { + || (do_out && (otmp = vim_tempname()) == NULL)) { EMSG(_(e_notmp)); goto filterend; } @@ -1300,7 +1330,7 @@ static void do_filter( * 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 */ + ++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) { msg_putchar('\n'); // Keep message from buf_write(). @@ -1310,13 +1340,15 @@ static void do_filter( } goto filterend; } - if (curbuf != old_curbuf) + if (curbuf != old_curbuf) { goto filterend; + } - if (!do_out) + if (!do_out) { msg_putchar('\n'); + } - /* Create the shell command in allocated memory. */ + // Create the shell command in allocated memory. cmd_buf = make_filter_cmd(cmd, itmp, otmp); ui_cursor_goto(Rows - 1, 0); @@ -1352,8 +1384,9 @@ static void do_filter( } goto error; } - if (curbuf != old_curbuf) + if (curbuf != old_curbuf) { goto filterend; + } } read_linecount = curbuf->b_ml.ml_line_count - read_linecount; @@ -1401,22 +1434,24 @@ static void do_filter( curwin->w_cursor.lnum = curbuf->b_op_end.lnum; } - beginline(BL_WHITE | BL_FIX); /* cursor on first non-blank */ + beginline(BL_WHITE | BL_FIX); // cursor on first non-blank --no_wait_return; if (linecount > p_report) { if (do_in) { vim_snprintf((char *)msg_buf, sizeof(msg_buf), - _("%" PRId64 " lines filtered"), (int64_t)linecount); - if (msg(msg_buf) && !msg_scroll) - /* save message to display it after redraw */ + _("%" PRId64 " lines filtered"), (int64_t)linecount); + if (msg(msg_buf) && !msg_scroll) { + // save message to display it after redraw set_keep_msg(msg_buf, 0); - } else + } + } else { msgmore((long)linecount); + } } } else { error: - /* put cursor back in same position for ":w !cmd" */ + // put cursor back in same position for ":w !cmd" curwin->w_cursor = cursor_save; --no_wait_return; wait_return(FALSE); @@ -1428,21 +1463,21 @@ filterend: --no_wait_return; EMSG(_("E135: *Filter* Autocommands must not change current buffer")); } - if (itmp != NULL) + if (itmp != NULL) { os_remove((char *)itmp); - if (otmp != NULL) + } + if (otmp != NULL) { os_remove((char *)otmp); + } xfree(itmp); xfree(otmp); } -// Call a shell to execute a command. -// When "cmd" is NULL start an interactive shell. -void -do_shell( - char_u *cmd, - int flags // may be SHELL_DOOUT when output is redirected -) +/// Call a shell to execute a command. +/// When "cmd" is NULL start an interactive shell. +/// +/// @param flags may be SHELL_DOOUT when output is redirected +void do_shell(char_u *cmd, int flags) { // Disallow shell commands from .exrc and .vimrc in current directory for // security reasons. @@ -1524,11 +1559,11 @@ char_u *make_filter_cmd(char_u *cmd, char_u *itmp, char_u *otmp) size_t len = STRLEN(cmd) + 1; // At least enough space for cmd + NULL. - len += is_fish_shell ? sizeof("begin; ""; end") - 1 - : sizeof("("")") - 1; + len += is_fish_shell ? sizeof("begin; " "; end") - 1 + : sizeof("(" ")") - 1; if (itmp != NULL) { - len += STRLEN(itmp) + sizeof(" { "" < "" } ") - 1; + len += STRLEN(itmp) + sizeof(" { " " < " " } ") - 1; } if (otmp != NULL) { len += STRLEN(otmp) + STRLEN(p_srr) + 2; // two extra spaces (" "), @@ -1576,9 +1611,9 @@ char_u *make_filter_cmd(char_u *cmd, char_u *itmp, char_u *otmp) } #endif if (otmp != NULL) { - append_redir(buf, len, (char *) p_srr, (char *) otmp); + append_redir(buf, len, (char *)p_srr, (char *)otmp); } - return (char_u *) buf; + return (char_u *)buf; } /// Append output redirection for the given file to the end of the buffer @@ -1590,8 +1625,8 @@ char_u *make_filter_cmd(char_u *cmd, char_u *itmp, char_u *otmp) /// a space, opt, a space and then fname if `%s` is not found /// there. /// @param[in] fname File name to append. -void append_redir(char *const buf, const size_t buflen, - const char *const opt, const char *const fname) +void append_redir(char *const buf, const size_t buflen, const char *const opt, + const char *const fname) { char *const end = buf + strlen(buf); // find "%s" @@ -1605,9 +1640,9 @@ void append_redir(char *const buf, const size_t buflen, } if (p != NULL) { *end = ' '; // not really needed? Not with sh, ksh or bash - vim_snprintf(end + 1, (size_t) (buflen - (end + 1 - buf)), opt, fname); + vim_snprintf(end + 1, (size_t)(buflen - (end + 1 - buf)), opt, fname); } else { - vim_snprintf(end, (size_t) (buflen - (end - buf)), " %s %s", opt, fname); + vim_snprintf(end, (size_t)(buflen - (end - buf)), " %s %s", opt, fname); } } @@ -1649,16 +1684,18 @@ void print_line(linenr_T lnum, int use_number, int list) int rename_buffer(char_u *new_fname) { - char_u *fname, *sfname, *xfname; - buf_T *buf; + char_u *fname, *sfname, *xfname; + buf_T *buf; buf = curbuf; apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf); - /* buffer changed, don't change name now */ - if (buf != curbuf) + // buffer changed, don't change name now + if (buf != curbuf) { return FAIL; - if (aborting()) /* autocmds may abort script processing */ + } + 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 @@ -1686,7 +1723,7 @@ int rename_buffer(char_u *new_fname) xfree(fname); xfree(sfname); apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf); - /* Change directories when the 'acd' option is set. */ + // Change directories when the 'acd' option is set. do_autochdir(); return OK; } @@ -1724,8 +1761,9 @@ void ex_file(exarg_T *eap) */ void ex_update(exarg_T *eap) { - if (curbufIsChanged()) + if (curbufIsChanged()) { (void)do_write(eap); + } } /* @@ -1757,15 +1795,16 @@ void ex_write(exarg_T *eap) int do_write(exarg_T *eap) { int other; - char_u *fname = NULL; /* init to shut up gcc */ - char_u *ffname; + char_u *fname = NULL; // init to shut up gcc + char_u *ffname; int retval = FAIL; - char_u *free_fname = NULL; - buf_T *alt_buf = NULL; + char_u *free_fname = NULL; + buf_T *alt_buf = NULL; int name_was_missing; - if (not_writing()) /* check 'write' option */ + if (not_writing()) { // check 'write' option return FAIL; + } ffname = eap->arg; if (*ffname == NUL) { @@ -1781,8 +1820,9 @@ int do_write(exarg_T *eap) * When out-of-memory, keep unexpanded file name, because we MUST be * able to write the file in this situation. */ - if (free_fname != NULL) + if (free_fname != NULL) { ffname = free_fname; + } other = otherfile(ffname); } @@ -1791,10 +1831,11 @@ int do_write(exarg_T *eap) */ if (other) { if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL - || eap->cmdidx == CMD_saveas) + || eap->cmdidx == CMD_saveas) { alt_buf = setaltfname(ffname, fname, (linenr_T)1); - else + } else { alt_buf = buflist_findname(ffname); + } if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL) { /* Overwriting a file that is loaded in another buffer is not a * good idea. */ @@ -1825,8 +1866,9 @@ int do_write(exarg_T *eap) && !p_wa) { if (p_confirm || cmdmod.confirm) { if (vim_dialog_yesno(VIM_QUESTION, NULL, - (char_u *)_("Write partial file?"), 2) != VIM_YES) + (char_u *)_("Write partial file?"), 2) != VIM_YES) { goto theend; + } eap->forceit = TRUE; } else { EMSG(_("E140: Use ! to write partial buffer")); @@ -1837,12 +1879,12 @@ int do_write(exarg_T *eap) if (check_overwrite(eap, curbuf, fname, ffname, other) == OK) { if (eap->cmdidx == CMD_saveas && alt_buf != NULL) { - buf_T *was_curbuf = curbuf; + buf_T *was_curbuf = curbuf; apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf); if (curbuf != was_curbuf || aborting()) { - /* buffer changed, don't change name now */ + // buffer changed, don't change name now retval = FAIL; goto theend; } @@ -1868,7 +1910,7 @@ int do_write(exarg_T *eap) apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, alt_buf); } if (curbuf != was_curbuf || aborting()) { - /* buffer changed, don't write the file */ + // buffer changed, don't write the file retval = FAIL; goto theend; } @@ -1888,9 +1930,9 @@ int do_write(exarg_T *eap) name_was_missing = curbuf->b_ffname == NULL; retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2, - eap, eap->append, eap->forceit, TRUE, FALSE); + eap, eap->append, eap->forceit, TRUE, FALSE); - /* After ":saveas fname" reset 'readonly'. */ + // After ":saveas fname" reset 'readonly'. if (eap->cmdidx == CMD_saveas) { if (retval == OK) { curbuf->b_p_ro = FALSE; @@ -1910,21 +1952,16 @@ theend: return retval; } -/* - * Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED, - * BF_NEW or BF_READERR, check for overwriting current file. - * May set eap->forceit if a dialog says it's OK to overwrite. - * Return OK if it's OK, FAIL if it is not. - */ -int -check_overwrite( - exarg_T *eap, - buf_T *buf, - char_u *fname, // file name to be used (can differ from - // buf->ffname) - char_u *ffname, // full path version of fname - int other // writing under other name -) +/// Check if it is allowed to overwrite a file. If b_flags has BF_NOTEDITED, +/// BF_NEW or BF_READERR, check for overwriting current file. +/// May set eap->forceit if a dialog says it's OK to overwrite. +/// +/// @param fname file name to be used (can differ from buf->ffname) +/// @param ffname full path version of fname +/// @param other writing under other name +/// +/// @return OK if it's OK, FAIL if it is not. +int check_overwrite(exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int other) { /* * write to other file or b_flags set or not writing the whole file: @@ -1950,8 +1987,9 @@ check_overwrite( char_u buff[DIALOG_MSG_SIZE]; dialog_msg(buff, _("Overwrite existing file \"%s\"?"), fname); - if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES) + if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES) { return FAIL; + } eap->forceit = TRUE; } else { EMSG(_(e_exists)); @@ -1959,11 +1997,11 @@ check_overwrite( } } - /* For ":w! filename" check that no swap file exists for "filename". */ + // For ":w! filename" check that no swap file exists for "filename". if (other && !emsg_silent) { - char_u *dir; - char_u *p; - char_u *swapname; + char_u *dir; + char_u *p; + char_u *swapname; /* We only try the first entry in 'directory', without checking if * it's writable. If the "." directory is not writable the write @@ -1985,8 +2023,8 @@ check_overwrite( char_u buff[DIALOG_MSG_SIZE]; dialog_msg(buff, - _("Swap file \"%s\" exists, overwrite anyway?"), - swapname); + _("Swap file \"%s\" exists, overwrite anyway?"), + swapname); if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES) { xfree(swapname); @@ -1995,7 +2033,7 @@ check_overwrite( eap->forceit = TRUE; } else { EMSG2(_("E768: Swap file exists: %s (:silent! overrides)"), - swapname); + swapname); xfree(swapname); return FAIL; } @@ -2013,14 +2051,16 @@ void ex_wnext(exarg_T *eap) { int i; - if (eap->cmd[1] == 'n') + if (eap->cmd[1] == 'n') { i = curwin->w_arg_idx + (int)eap->line2; - else + } else { i = curwin->w_arg_idx - (int)eap->line2; + } eap->line1 = 1; eap->line2 = curbuf->b_ml.ml_line_count; - if (do_write(eap) != FAIL) + if (do_write(eap) != FAIL) { do_argfile(eap, i); + } } /* @@ -2060,7 +2100,7 @@ void do_wqall(exarg_T *eap) ++error; } else if (check_readonly(&eap->forceit, buf) || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname, - FALSE) == FAIL) { + FALSE) == FAIL) { ++error; } else { bufref_T bufref; @@ -2073,11 +2113,12 @@ void do_wqall(exarg_T *eap) buf = firstbuf; } } - eap->forceit = save_forceit; /* check_overwrite() may set it */ + eap->forceit = save_forceit; // check_overwrite() may set it } if (exiting) { - if (!error) - getout(0); /* exit Vim */ + if (!error) { + getout(0); // exit Vim + } not_exiting(); } } @@ -2088,8 +2129,9 @@ void do_wqall(exarg_T *eap) */ int not_writing(void) { - if (p_write) + if (p_write) { return FALSE; + } EMSG(_("E142: File not written: Writing is disabled by 'write' option")); return TRUE; } @@ -2109,28 +2151,30 @@ static int check_readonly(int *forceit, buf_T *buf) if ((p_confirm || cmdmod.confirm) && buf->b_fname != NULL) { char_u buff[DIALOG_MSG_SIZE]; - if (buf->b_p_ro) + if (buf->b_p_ro) { dialog_msg(buff, - _( - "'readonly' option is set for \"%s\".\nDo you wish to write anyway?"), - buf->b_fname); - else + _( "'readonly' option is set for \"%s\".\nDo you wish to write anyway?"), + buf->b_fname); + } else { dialog_msg(buff, - _( - "File permissions of \"%s\" are read-only.\nIt may still be possible to write it.\nDo you wish to try?"), - buf->b_fname); + _( + "File permissions of \"%s\" are read-only.\nIt may still be possible to write it.\nDo you wish to try?"), + buf->b_fname); + } if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES) { - /* Set forceit, to force the writing of a readonly file */ + // Set forceit, to force the writing of a readonly file *forceit = TRUE; return FALSE; - } else + } else { return TRUE; - } else if (buf->b_p_ro) + } + } else if (buf->b_p_ro) { EMSG(_(e_readonly)); - else + } else { EMSG2(_("E505: \"%s\" is read-only (add ! to override)"), - buf->b_fname); + buf->b_fname); + } return TRUE; } @@ -2146,14 +2190,13 @@ static int check_readonly(int *forceit, buf_T *buf) // GETFILE_NOT_WRITTEN for "not written" error, // GETFILE_SAME_FILE for success // GETFILE_OPEN_OTHER for successfully opening another file. -int getfile(int fnum, char_u *ffname_arg, char_u *sfname_arg, int setpm, - linenr_T lnum, int forceit) +int getfile(int fnum, char_u *ffname_arg, char_u *sfname_arg, int setpm, linenr_T lnum, int forceit) { char_u *ffname = ffname_arg; char_u *sfname = sfname_arg; int other; int retval; - char_u *free_me = NULL; + char_u *free_me = NULL; if (text_locked()) { return GETFILE_ERROR; @@ -2163,12 +2206,13 @@ int getfile(int fnum, char_u *ffname_arg, char_u *sfname_arg, int setpm, } if (fnum == 0) { - /* make ffname full path, set sfname */ + // make ffname full path, set sfname fname_expand(curbuf, &ffname, &sfname); other = otherfile(ffname); - free_me = ffname; /* has been allocated, free() later */ - } else + free_me = ffname; // has been allocated, free() later + } else { other = (fnum != curbuf->b_fnum); + } if (other) { no_wait_return++; // don't wait for autowrite message @@ -2185,10 +2229,12 @@ int getfile(int fnum, char_u *ffname_arg, char_u *sfname_arg, int setpm, goto theend; } } - if (other) + if (other) { --no_wait_return; - if (setpm) + } + if (setpm) { setpcmark(); + } if (!other) { if (lnum != 0) { curwin->w_cursor.lnum = lnum; @@ -2220,7 +2266,7 @@ theend: /// - NULL to start an empty buffer /// @param sfname the short file name (or NULL) /// @param eap contains the command to be executed after loading the file -/// and forced 'ff' and 'fenc' +/// and forced 'ff' and 'fenc'. Can be NULL! /// @param newlnum if > 0: put cursor on this line number (if possible) /// ECMD_LASTL: use last position in loaded file /// ECMD_LAST: use last position in all files @@ -2238,55 +2284,52 @@ theend: /// info of the previous buffer for "oldwin" is stored. /// /// @return FAIL for failure, OK otherwise -int do_ecmd( - int fnum, - char_u *ffname, - char_u *sfname, - exarg_T *eap, /* can be NULL! */ - linenr_T newlnum, - int flags, - win_T *oldwin -) +int do_ecmd(int fnum, char_u *ffname, char_u *sfname, exarg_T *eap, linenr_T newlnum, int flags, + win_T *oldwin) { - int other_file; /* TRUE if editing another file */ - int oldbuf; /* TRUE if using existing buffer */ + int other_file; // TRUE if editing another file + int oldbuf; // TRUE if using existing buffer int auto_buf = FALSE; /* TRUE if autocommands brought us into the buffer unexpectedly */ - char_u *new_name = NULL; + char_u *new_name = NULL; int did_set_swapcommand = FALSE; - buf_T *buf; + buf_T *buf; bufref_T bufref; bufref_T old_curbuf; - char_u *free_fname = NULL; + char_u *free_fname = NULL; int retval = FAIL; long n; pos_T orig_pos; linenr_T topline = 0; int newcol = -1; int solcol = -1; - pos_T *pos; - char_u *command = NULL; + pos_T *pos; + char_u *command = NULL; int did_get_winopts = FALSE; int readfile_flags = 0; bool did_inc_redrawing_disabled = false; long *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so; - if (eap != NULL) + if (eap != NULL) { command = eap->do_ecmd_cmd; + } set_bufref(&old_curbuf, curbuf); if (fnum != 0) { - if (fnum == curbuf->b_fnum) /* file is already being edited */ - return OK; /* nothing to do */ + if (fnum == curbuf->b_fnum) { // file is already being edited + return OK; // nothing to do + } other_file = TRUE; } else { - /* if no short name given, use ffname for short name */ - if (sfname == NULL) + // if no short name given, use ffname for short name + if (sfname == NULL) { sfname = ffname; + } #ifdef USE_FNAME_CASE - if (sfname != NULL) + if (sfname != NULL) { path_fix_case(sfname); // set correct case for sfname + } #endif if ((flags & (ECMD_ADDBUF | ECMD_ALTBUF)) @@ -2294,19 +2337,21 @@ int do_ecmd( goto theend; } - if (ffname == NULL) + if (ffname == NULL) { other_file = TRUE; - /* there is no file name */ - else if (*ffname == NUL && curbuf->b_ffname == NULL) + } + // there is no file name + else if (*ffname == NUL && curbuf->b_ffname == NULL) { other_file = FALSE; - else { - if (*ffname == NUL) { /* re-edit with same file name */ + } else { + if (*ffname == NUL) { // re-edit with same file name ffname = curbuf->b_ffname; sfname = curbuf->b_fname; } - free_fname = (char_u *)fix_fname((char *)ffname); /* may expand to full path name */ - if (free_fname != NULL) + free_fname = (char_u *)fix_fname((char *)ffname); // may expand to full path name + if (free_fname != NULL) { ffname = free_fname; + } other_file = otherfile(ffname); } } @@ -2380,13 +2425,14 @@ int do_ecmd( if (command != NULL) { tlnum = atol((char *)command); - if (tlnum <= 0) + if (tlnum <= 0) { tlnum = 1L; + } } // Add BLN_NOCURWIN to avoid a new wininfo items are associated // with the current window. const buf_T *const newbuf - = buflist_new(ffname, sfname, tlnum, BLN_LISTED | BLN_NOCURWIN); + = buflist_new(ffname, sfname, tlnum, BLN_LISTED | BLN_NOCURWIN); if (newbuf != NULL && (flags & ECMD_ALTBUF)) { curwin->w_alt_fnum = newbuf->b_fnum; } @@ -2400,8 +2446,9 @@ int do_ecmd( } set_bufref(&old_curbuf, curbuf); } - if (buf == NULL) + if (buf == NULL) { goto theend; + } if (buf->b_ml.ml_mfp == NULL) { // No memfile yet. oldbuf = false; @@ -2460,7 +2507,7 @@ int do_ecmd( delbuf_msg(new_name); // Frees new_name. goto theend; } - if (aborting()) { /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing xfree(new_name); goto theend; } @@ -2482,10 +2529,9 @@ int do_ecmd( // Close the link to the current buffer. This will set // oldwin->w_buffer to NULL. u_sync(false); - const bool did_decrement = close_buffer( - oldwin, curbuf, - (flags & ECMD_HIDE) || curbuf->terminal ? 0 : DOBUF_UNLOAD, - false); + const bool did_decrement = close_buffer(oldwin, curbuf, + (flags & ECMD_HIDE) || curbuf->terminal ? 0 : DOBUF_UNLOAD, + false); // Autocommands may have closed the window. if (win_valid(the_curwin)) { @@ -2526,7 +2572,7 @@ int do_ecmd( curbuf = buf; ++curbuf->b_nwindows; - /* Set 'fileformat', 'binary' and 'fenc' when forced. */ + // Set 'fileformat', 'binary' and 'fenc' when forced. if (!oldbuf && eap != NULL) { set_file_options(TRUE, eap); set_forced_fenc(eap); @@ -2539,7 +2585,6 @@ int do_ecmd( * values. Also restores old folding stuff. */ get_winopts(curbuf); did_get_winopts = TRUE; - } xfree(new_name); au_new_curbuf.br_buf = NULL; @@ -2571,10 +2616,12 @@ int do_ecmd( /* If autocommands change buffers under our fingers, forget about * editing the file. */ - if (buf != curbuf) + if (buf != curbuf) { goto theend; - if (aborting()) /* autocmds may abort script processing */ + } + if (aborting()) { // autocmds may abort script processing goto theend; + } /* Since we are starting to edit a file, consider the filetype to be * unset. Helps for when an autocommand changes files and expects syntax @@ -2582,14 +2629,14 @@ int do_ecmd( 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 (!other_file && !oldbuf) { // re-use the buffer + set_last_cursor(curwin); // may set b_last_cursor if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL) { newlnum = curwin->w_cursor.lnum; solcol = curwin->w_cursor.col; @@ -2635,12 +2682,14 @@ int do_ecmd( /* If autocommands change buffers under our fingers, forget about * re-editing the file. Should do the buf_clear_file(), but perhaps * the autocommands changed the buffer... */ - if (buf != curbuf) + if (buf != curbuf) { goto theend; - if (aborting()) /* autocmds may abort script processing */ + } + if (aborting()) { // autocmds may abort script processing goto theend; + } buf_clear_file(curbuf); - curbuf->b_op_start.lnum = 0; /* clear '[ and '] marks */ + curbuf->b_op_start.lnum = 0; // clear '[ and '] marks curbuf->b_op_end.lnum = 0; } @@ -2648,7 +2697,7 @@ int do_ecmd( * If we get here we are sure to start editing */ - /* Assume success now */ + // Assume success now retval = OK; /* @@ -2672,7 +2721,7 @@ int do_ecmd( } } - /* Change directories when the 'acd' option is set. */ + // Change directories when the 'acd' option is set. do_autochdir(); /* @@ -2681,18 +2730,20 @@ int do_ecmd( */ orig_pos = curwin->w_cursor; topline = curwin->w_topline; - if (!oldbuf) { /* need to read the file */ + if (!oldbuf) { // need to read the file swap_exists_action = SEA_DIALOG; - curbuf->b_flags |= BF_CHECK_RO; /* set/reset 'ro' flag */ + curbuf->b_flags |= BF_CHECK_RO; // set/reset 'ro' flag /* * Open the buffer and read the file. */ - if (should_abort(open_buffer(FALSE, eap, readfile_flags))) + if (should_abort(open_buffer(FALSE, eap, readfile_flags))) { retval = FAIL; + } - if (swap_exists_action == SEA_QUIT) + if (swap_exists_action == SEA_QUIT) { retval = FAIL; + } handle_swap_exists(&old_curbuf); } else { /* Read the modelines, but only to set window-local options. Any @@ -2701,9 +2752,9 @@ int do_ecmd( do_modelines(OPT_WINONLY); apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf, - &retval); + &retval); apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf, - &retval); + &retval); } check_arg_idx(curwin); @@ -2719,10 +2770,11 @@ int do_ecmd( newcol = curwin->w_cursor.col; } } - if (curwin->w_topline == topline) + if (curwin->w_topline == topline) { topline = 0; + } - /* Even when cursor didn't move we need to recompute topline. */ + // Even when cursor didn't move we need to recompute topline. changed_line_abv_curs(); maketitle(); @@ -2738,28 +2790,31 @@ int do_ecmd( /* If the window options were changed may need to set the spell language. * Can only do this after the buffer has been properly setup. */ - if (did_get_winopts && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) + if (did_get_winopts && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) { (void)did_set_spelllang(curwin); + } if (command == NULL) { - if (newcol >= 0) { /* position set by autocommands */ + if (newcol >= 0) { // position set by autocommands curwin->w_cursor.lnum = newlnum; curwin->w_cursor.col = newcol; check_cursor(); - } else if (newlnum > 0) { /* line number from caller or old position */ + } else if (newlnum > 0) { // line number from caller or old position curwin->w_cursor.lnum = newlnum; check_cursor_lnum(); if (solcol >= 0 && !p_sol) { - /* 'sol' is off: Use last known column. */ + // 'sol' is off: Use last known column. curwin->w_cursor.col = solcol; check_cursor_col(); curwin->w_cursor.coladd = 0; curwin->w_set_curswant = TRUE; - } else + } else { beginline(BL_SOL | BL_FIX); - } else { /* no line number, go to last line in Ex mode */ - if (exmode_active) + } + } else { // no line number, go to last line in Ex mode + if (exmode_active) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; + } beginline(BL_WHITE | BL_FIX); } } @@ -2772,16 +2827,17 @@ int do_ecmd( * Do this after setting the cursor. */ if (oldbuf - && !auto_buf - ) { + && !auto_buf) { int msg_scroll_save = msg_scroll; /* Obey the 'O' flag in 'cpoptions': overwrite any previous file * message. */ - if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) + if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) { msg_scroll = FALSE; - if (!msg_scroll) /* wait a bit when overwriting an error msg */ + } + if (!msg_scroll) { // wait a bit when overwriting an error msg check_for_delay(FALSE); + } msg_start(); msg_scroll = msg_scroll_save; msg_scrolled_ign = TRUE; @@ -2795,11 +2851,13 @@ int do_ecmd( curbuf->b_last_used = time(NULL); - if (command != NULL) + if (command != NULL) { do_cmdline(command, NULL, NULL, DOCMD_VERBOSE); + } - if (curbuf->b_kmap_state & KEYMAP_INIT) + if (curbuf->b_kmap_state & KEYMAP_INIT) { (void)keymap_init(); + } RedrawingDisabled--; did_inc_redrawing_disabled = false; @@ -2818,7 +2876,7 @@ int do_ecmd( need_start_insertmode = true; } - /* Change directories when the 'acd' option is set. */ + // Change directories when the 'acd' option is set. do_autochdir(); @@ -2840,45 +2898,50 @@ theend: static void delbuf_msg(char_u *name) { EMSG2(_("E143: Autocommands unexpectedly deleted new buffer %s"), - name == NULL ? (char_u *)"" : name); + name == NULL ? (char_u *)"" : name); xfree(name); au_new_curbuf.br_buf = NULL; au_new_curbuf.br_buf_free_count = 0; } -static int append_indent = 0; /* autoindent for first line */ +static int append_indent = 0; // autoindent for first line /* * ":insert" and ":append", also used by ":change" */ void ex_append(exarg_T *eap) { - char_u *theline; + char_u *theline; bool did_undo = false; linenr_T lnum = eap->line2; int indent = 0; - char_u *p; + char_u *p; int vcol; int empty = (curbuf->b_ml.ml_flags & ML_EMPTY); - /* the ! flag toggles autoindent */ - if (eap->forceit) + // the ! flag toggles autoindent + if (eap->forceit) { curbuf->b_p_ai = !curbuf->b_p_ai; + } - /* First autoindent comes from the line we start on */ - if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0) + // First autoindent comes from the line we start on + if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0) { append_indent = get_indent_lnum(lnum); + } - if (eap->cmdidx != CMD_append) + if (eap->cmdidx != CMD_append) { --lnum; + } // when the buffer is empty need to delete the dummy line - if (empty && lnum == 1) + if (empty && lnum == 1) { lnum = 0; + } - State = INSERT; /* behave like in Insert mode */ - if (curbuf->b_p_iminsert == B_IMODE_LMAP) + State = INSERT; // behave like in Insert mode + if (curbuf->b_p_iminsert == B_IMODE_LMAP) { State |= LANGMAP; + } for (;; ) { msg_scroll = TRUE; @@ -2887,17 +2950,20 @@ void ex_append(exarg_T *eap) if (append_indent >= 0) { indent = append_indent; append_indent = -1; - } else if (lnum > 0) + } else if (lnum > 0) { indent = get_indent_lnum(lnum); + } } if (eap->getline == NULL) { /* No getline() function, use the lines that follow. This ends * when there is no more. */ - if (eap->nextcmd == NULL || *eap->nextcmd == NUL) + if (eap->nextcmd == NULL || *eap->nextcmd == NUL) { break; + } p = vim_strchr(eap->nextcmd, NL); - if (p == NULL) + if (p == NULL) { p = eap->nextcmd + STRLEN(eap->nextcmd); + } theline = vim_strnsave(eap->nextcmd, p - eap->nextcmd); if (*p != NUL) { p++; @@ -2908,24 +2974,25 @@ void ex_append(exarg_T *eap) // when getline() returns. int save_State = State; State = CMDLINE; - theline = eap->getline( - eap->cstack->cs_looplevel > 0 ? -1 : - NUL, eap->cookie, indent, true); + theline = eap->getline(eap->cstack->cs_looplevel > 0 ? -1 : + NUL, eap->cookie, indent, true); State = save_State; } lines_left = Rows - 1; - if (theline == NULL) + if (theline == NULL) { break; + } - /* Look for the "." after automatic indent. */ + // Look for the "." after automatic indent. vcol = 0; for (p = theline; indent > vcol; ++p) { - if (*p == ' ') + if (*p == ' ') { ++vcol; - else if (*p == TAB) + } else if (*p == TAB) { vcol += 8 - vcol % 8; - else + } else { break; + } } if ((p[0] == '.' && p[1] == NUL) || (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0)) @@ -2934,9 +3001,10 @@ void ex_append(exarg_T *eap) break; } - /* don't use autoindent if nothing was typed. */ - if (p[0] == NUL) + // don't use autoindent if nothing was typed. + if (p[0] == NUL) { theline[0] = NUL; + } did_undo = true; ml_append(lnum, theline, (colnr_T)0, false); @@ -2952,8 +3020,9 @@ void ex_append(exarg_T *eap) } State = NORMAL; - if (eap->forceit) + if (eap->forceit) { curbuf->b_p_ai = !curbuf->b_p_ai; + } /* "start" is set to eap->line2+1 unless that position is invalid (when * eap->line2 pointed to the end of the buffer and nothing was appended) @@ -2961,8 +3030,9 @@ void ex_append(exarg_T *eap) * it is the same than "start" -- Acevedo */ curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ? eap->line2 + 1 : curbuf->b_ml.ml_line_count; - if (eap->cmdidx != CMD_append) + if (eap->cmdidx != CMD_append) { --curbuf->b_op_start.lnum; + } curbuf->b_op_end.lnum = (eap->line2 < lnum) ? lnum : curbuf->b_op_start.lnum; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; @@ -2982,33 +3052,36 @@ void ex_change(exarg_T *eap) linenr_T lnum; if (eap->line2 >= eap->line1 - && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL) + && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL) { return; + } - /* the ! flag toggles autoindent */ - if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai) + // the ! flag toggles autoindent + if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai) { append_indent = get_indent_lnum(eap->line1); + } for (lnum = eap->line2; lnum >= eap->line1; --lnum) { - if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */ + if (curbuf->b_ml.ml_flags & ML_EMPTY) { // nothing to delete break; + } ml_delete(eap->line1, false); } - /* make sure the cursor is not beyond the end of the file now */ + // make sure the cursor is not beyond the end of the file now check_cursor_lnum(); deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum)); - /* ":append" on the line above the deleted lines. */ + // ":append" on the line above the deleted lines. eap->line2 = eap->line1; ex_append(eap); } void ex_z(exarg_T *eap) { - char_u *x; + char_u *x; int64_t bigness; - char_u *kind; + char_u *kind; int minus = 0; linenr_T start, end, curs, i; int j; @@ -3030,10 +3103,12 @@ void ex_z(exarg_T *eap) x = eap->arg; kind = x; if (*kind == '-' || *kind == '+' || *kind == '=' - || *kind == '^' || *kind == '.') + || *kind == '^' || *kind == '.') { ++x; - while (*x == '-' || *x == '+') + } + while (*x == '-' || *x == '+') { ++x; + } if (*x != 0) { if (!ascii_isdigit(*x)) { @@ -3053,10 +3128,12 @@ void ex_z(exarg_T *eap) } } - /* the number of '-' and '+' multiplies the distance */ - if (*kind == '-' || *kind == '+') - for (x = kind + 1; *x == *kind; ++x) + // the number of '-' and '+' multiplies the distance + if (*kind == '-' || *kind == '+') { + for (x = kind + 1; *x == *kind; ++x) { ; + } + } switch (*kind) { case '-': @@ -3084,22 +3161,25 @@ void ex_z(exarg_T *eap) curs = end; break; - default: /* '+' */ + default: // '+' start = lnum; - if (*kind == '+') + if (*kind == '+') { start += bigness * (linenr_T)(x - kind - 1) + 1; - else if (eap->addr_count == 0) + } else if (eap->addr_count == 0) { ++start; + } end = start + bigness - 1; curs = end; break; } - if (start < 1) + if (start < 1) { start = 1; + } - if (end > curbuf->b_ml.ml_line_count) + if (end > curbuf->b_ml.ml_line_count) { end = curbuf->b_ml.ml_line_count; + } if (curs > curbuf->b_ml.ml_line_count) { curs = curbuf->b_ml.ml_line_count; @@ -3111,8 +3191,9 @@ void ex_z(exarg_T *eap) if (minus && i == lnum) { msg_putchar('\n'); - for (j = 1; j < Columns; j++) + for (j = 1; j < Columns; j++) { msg_putchar('-'); + } } print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST); @@ -3120,8 +3201,9 @@ void ex_z(exarg_T *eap) if (minus && i == lnum) { msg_putchar('\n'); - for (j = 1; j < Columns; j++) + for (j = 1; j < Columns; j++) { msg_putchar('-'); + } } } @@ -3155,7 +3237,7 @@ int check_secure(void) } /// Previous substitute replacement string -static SubReplacementString old_sub = {NULL, 0, NULL}; +static SubReplacementString old_sub = { NULL, 0, NULL }; static int global_need_beginline; // call beginline() after ":g" @@ -3192,8 +3274,7 @@ void sub_set_replacement(SubReplacementString sub) /// @param[in] save Save pattern to options, history /// /// @returns true if :substitute can be replaced with a join command -static bool sub_joining_lines(exarg_T *eap, char_u *pat, char_u *sub, - char_u *cmd, bool save) +static bool sub_joining_lines(exarg_T *eap, char_u *pat, char_u *sub, char_u *cmd, bool save) FUNC_ATTR_NONNULL_ARG(1, 3, 4) { // TODO(vim): find a generic solution to make line-joining operations more @@ -3220,8 +3301,8 @@ static bool sub_joining_lines(exarg_T *eap, char_u *pat, char_u *sub, // The number of lines joined is the number of lines in the range linenr_T joined_lines_count = eap->line2 - eap->line1 + 1 - // plus one extra line if not at the end of file. - + (eap->line2 < curbuf->b_ml.ml_line_count ? 1 : 0); + // plus one extra line if not at the end of file. + + (eap->line2 < curbuf->b_ml.ml_line_count ? 1 : 0); if (joined_lines_count > 1) { do_join(joined_lines_count, FALSE, TRUE, FALSE, true); sub_nsubs = joined_lines_count - 1; @@ -3288,8 +3369,7 @@ static char_u *sub_grow_buf(char_u **new_start, int needed_len) /// @param[in,out] which_pat pattern type from which to get default search /// /// @returns pointer to the end of the flags, which may be the end of the string -static char_u *sub_parse_flags(char_u *cmd, subflags_T *subflags, - int *which_pat) +static char_u *sub_parse_flags(char_u *cmd, subflags_T *subflags, int *which_pat) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { // Find trailing options. When '&' is used, keep old options. @@ -3361,8 +3441,7 @@ static int check_regexp_delim(int c) /// /// @param do_buf_event If `true`, send buffer updates. /// @return buffer used for 'inccommand' preview -static buf_T *do_sub(exarg_T *eap, proftime_T timeout, - bool do_buf_event, handle_T bufnr) +static buf_T *do_sub(exarg_T *eap, proftime_T timeout, bool do_buf_event, handle_T bufnr) { long i = 0; regmmatch_T regmatch; @@ -3407,12 +3486,12 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, } start_nsubs = sub_nsubs; - if (eap->cmdidx == CMD_tilde) - which_pat = RE_LAST; /* use last used regexp */ - else - which_pat = RE_SUBST; /* use last substitute regexp */ - - /* new pattern and substitution */ + if (eap->cmdidx == CMD_tilde) { + which_pat = RE_LAST; // use last used regexp + } else { + which_pat = RE_SUBST; // use last substitute regexp + } + // new pattern and substitution if (eap->cmd[0] == 's' && *cmd != NUL && !ascii_iswhite(*cmd) && vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL) { // don't accept alphanumeric for separator @@ -3450,11 +3529,11 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, * 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 */ + sub = cmd; // remember the start of the substitution while (cmd[0]) { - if (cmd[0] == delimiter) { /* end delimiter found */ - *cmd++ = NUL; /* replace it with a NUL */ + if (cmd[0] == delimiter) { // end delimiter found + *cmd++ = NUL; // replace it with a NUL break; } if (cmd[0] == '\\' && cmd[1] != 0) { // skip escaped characters @@ -3465,18 +3544,18 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, if (!eap->skip && !preview) { sub_set_replacement((SubReplacementString) { - .sub = xstrdup((char *) sub), + .sub = xstrdup((char *)sub), .timestamp = os_time(), .additional_elements = NULL, }); } - } else if (!eap->skip) { /* use previous pattern and substitution */ - if (old_sub.sub == NULL) { /* there is no previous command */ + } else if (!eap->skip) { // use previous pattern and substitution + if (old_sub.sub == NULL) { // there is no previous command EMSG(_(e_nopresub)); return NULL; } - pat = NULL; /* search_regcomp() will use previous pattern */ - sub = (char_u *) old_sub.sub; + pat = NULL; // search_regcomp() will use previous pattern + sub = (char_u *)old_sub.sub; /* Vi compatibility quirk: repeating with ":s" keeps the cursor in the * last column after using "$". */ @@ -3502,15 +3581,16 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, } eap->line1 = eap->line2; eap->line2 += i - 1; - if (eap->line2 > curbuf->b_ml.ml_line_count) + if (eap->line2 > curbuf->b_ml.ml_line_count) { eap->line2 = curbuf->b_ml.ml_line_count; + } } /* * check for trailing command or garbage */ cmd = skipwhite(cmd); - if (*cmd && *cmd != '"') { /* if not end-of-line or comment */ + if (*cmd && *cmd != '"') { // if not end-of-line or comment eap->nextcmd = check_nextcmd(cmd); if (eap->nextcmd == NULL) { EMSG(_(e_trailing)); @@ -3568,8 +3648,8 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, colnr_T copycol; colnr_T matchcol; colnr_T prev_matchcol = MAXCOL; - char_u *new_end, *new_start = NULL; - char_u *p1; + char_u *new_end, *new_start = NULL; + char_u *p1; int did_sub = FALSE; int lastone; long nmatch_tl = 0; // nr of lines matched below lnum @@ -3580,29 +3660,29 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, /* * 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. + * 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. + * 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 @@ -3625,7 +3705,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, copycol = 0; matchcol = 0; - /* At first match, remember current cursor position. */ + // At first match, remember current cursor position. if (!got_match) { setpcmark(); got_match = TRUE; @@ -3721,8 +3801,9 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, did_sub = TRUE; /* Skip the substitution, unless an expression is used, * then it is evaluated in the sandbox. */ - if (!(sub[0] == '\\' && sub[1] == '=')) + if (!(sub[0] == '\\' && sub[1] == '=')) { goto skip; + } } if (subflags.do_ask && !preview) { @@ -3732,7 +3813,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, * properly */ int save_State = State; State = CONFIRM; - setmouse(); /* disable mouse in xterm */ + setmouse(); // disable mouse in xterm curwin->w_cursor.col = regmatch.startpos[0].col; if (curwin->w_p_crb) { @@ -3741,16 +3822,17 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, /* When 'cpoptions' contains "u" don't sync undo when * asking for confirmation. */ - if (vim_strchr(p_cpo, CPO_UNDO) != NULL) + if (vim_strchr(p_cpo, CPO_UNDO) != NULL) { ++no_u_sync; + } /* * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed. */ while (subflags.do_ask) { if (exmode_active) { - char *prompt; - char_u *resp; + char *prompt; + char_u *resp; colnr_T sc, ec; print_line_no_prefix(lnum, subflags.do_number, subflags.do_list); @@ -3861,10 +3943,12 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, got_quit = true; break; } - if (typed == 'n') + if (typed == 'n') { break; - if (typed == 'y') + } + if (typed == 'y') { break; + } if (typed == 'l') { // last: replace and then stop subflags.do_all = false; @@ -3875,15 +3959,17 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, subflags.do_ask = false; break; } - if (typed == Ctrl_E) + if (typed == Ctrl_E) { scrollup_clamp(); - else if (typed == Ctrl_Y) + } else if (typed == Ctrl_Y) { scrolldown_clamp(); + } } State = save_State; setmouse(); - if (vim_strchr(p_cpo, CPO_UNDO) != NULL) + if (vim_strchr(p_cpo, CPO_UNDO) != NULL) { --no_u_sync; + } if (typed == 'n') { /* For a multi-line match, put matchcol at the NUL at @@ -3897,8 +3983,9 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, } goto skip; } - if (got_quit) + if (got_quit) { goto skip; + } } /* Move the cursor to the start of the match, so that we can @@ -3914,28 +4001,28 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout, } #define ADJUST_SUB_FIRSTLNUM() \ - do { \ - /* For a multi-line match, make a copy of the last matched */ \ - /* line and continue in that one. */ \ - if (nmatch > 1) { \ - sub_firstlnum += nmatch - 1; \ - xfree(sub_firstline); \ - sub_firstline = vim_strsave(ml_get(sub_firstlnum)); \ - /* When going beyond the last line, stop substituting. */ \ - if (sub_firstlnum <= line2) { \ - do_again = true; \ - } else { \ - subflags.do_all = false; \ - } \ - } \ - if (skip_match) { \ - /* Already hit end of the buffer, sub_firstlnum is one */ \ - /* less than what it ought to be. */ \ - xfree(sub_firstline); \ - sub_firstline = vim_strsave((char_u *)""); \ - copycol = 0; \ - } \ - } while (0) + do { \ + /* For a multi-line match, make a copy of the last matched */ \ + /* line and continue in that one. */ \ + if (nmatch > 1) { \ + sub_firstlnum += nmatch - 1; \ + xfree(sub_firstline); \ + sub_firstline = vim_strsave(ml_get(sub_firstlnum)); \ + /* When going beyond the last line, stop substituting. */ \ + if (sub_firstlnum <= line2) { \ + do_again = true; \ + } else { \ + subflags.do_all = false; \ + } \ + } \ + if (skip_match) { \ + /* Already hit end of the buffer, sub_firstlnum is one */ \ + /* less than what it ought to be. */ \ + xfree(sub_firstline); \ + sub_firstline = vim_strsave((char_u *)""); \ + copycol = 0; \ + } \ + } while (0) // Save the line numbers for the preview buffer // NOTE: If the pattern matches a final newline, the next line will @@ -4148,8 +4235,9 @@ skip: * it in the buffer. */ ++lnum; - if (u_savedel(lnum, nmatch_tl) != OK) + if (u_savedel(lnum, nmatch_tl) != OK) { break; + } for (i = 0; i < nmatch_tl; i++) { ml_delete(lnum, false); } @@ -4175,7 +4263,7 @@ skip: } sub_firstlnum = lnum; - xfree(sub_firstline); /* free the temp buffer */ + xfree(sub_firstline); // free the temp buffer sub_firstline = new_start; new_start = NULL; matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol; @@ -4183,9 +4271,10 @@ skip: - prev_matchcol; copycol = 0; } - if (nmatch == -1 && !lastone) + if (nmatch == -1 && !lastone) { nmatch = vim_regexec_multi(®match, curwin, curbuf, sub_firstlnum, matchcol, NULL, NULL); + } /* * 5. break if there isn't another match in this line @@ -4194,23 +4283,24 @@ skip: /* If the match found didn't start where we were * searching, do the next search in the line where we * found the match. */ - if (nmatch == -1) + if (nmatch == -1) { lnum -= regmatch.startpos[0].lnum; + } #define PUSH_PREVIEW_LINES() \ - do { \ - linenr_T match_lines = current_match.end.lnum \ - - current_match.start.lnum +1; \ - if (preview_lines.subresults.size > 0) { \ - linenr_T last = kv_last(preview_lines.subresults).end.lnum; \ - if (last == current_match.start.lnum) { \ - preview_lines.lines_needed += match_lines - 1; \ - } \ - } else { \ - preview_lines.lines_needed += match_lines; \ - } \ - kv_push(preview_lines.subresults, current_match); \ - } while (0) + do { \ + linenr_T match_lines = current_match.end.lnum \ + - current_match.start.lnum +1; \ + if (preview_lines.subresults.size > 0) { \ + linenr_T last = kv_last(preview_lines.subresults).end.lnum; \ + if (last == current_match.start.lnum) { \ + preview_lines.lines_needed += match_lines - 1; \ + } \ + } else { \ + preview_lines.lines_needed += match_lines; \ + } \ + kv_push(preview_lines.subresults, current_match); \ + } while (0) // Push the match to preview_lines. PUSH_PREVIEW_LINES(); @@ -4253,7 +4343,7 @@ skip: do_buf_event); } - xfree(sub_firstline); /* may have to free allocated copy of the line */ + xfree(sub_firstline); // may have to free allocated copy of the line // ":s/pat//n" doesn't move the cursor if (subflags.do_count) { @@ -4261,7 +4351,7 @@ skip: } if (sub_nsubs > start_nsubs) { - /* Set the '[ and '] marks. */ + // Set the '[ and '] marks. curbuf->b_op_start.lnum = eap->line1; curbuf->b_op_end.lnum = line2; curbuf->b_op_start.col = curbuf->b_op_end.col = 0; @@ -4340,15 +4430,13 @@ skip: #undef PUSH_PREVIEW_LINES } // NOLINT(readability/fn_size) -/* - * Give message for number of substitutions. - * Can also be used after a ":global" command. - * Return TRUE if a message was given. - */ -bool -do_sub_msg ( - bool count_only /* used 'n' flag for ":s" */ -) +/// Give message for number of substitutions. +/// Can also be used after a ":global" command. +/// +/// @param count_only used 'n' flag for ":s" +/// +/// @return TRUE if a message was given. +bool do_sub_msg(bool count_only) { /* * Only report substitutions when: @@ -4359,27 +4447,31 @@ do_sub_msg ( if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1)) || count_only) && messaging()) { - if (got_int) + if (got_int) { STRCPY(msg_buf, _("(Interrupted) ")); - else + } else { *msg_buf = NUL; - if (sub_nsubs == 1) + } + if (sub_nsubs == 1) { vim_snprintf_add((char *)msg_buf, sizeof(msg_buf), - "%s", count_only ? _("1 match") : _("1 substitution")); - else + "%s", count_only ? _("1 match") : _("1 substitution")); + } else { vim_snprintf_add((char *)msg_buf, sizeof(msg_buf), - count_only ? _("%" PRId64 " matches") - : _("%" PRId64 " substitutions"), - (int64_t)sub_nsubs); - if (sub_nlines == 1) + count_only ? _("%" PRId64 " matches") + : _("%" PRId64 " substitutions"), + (int64_t)sub_nsubs); + } + if (sub_nlines == 1) { vim_snprintf_add((char *)msg_buf, sizeof(msg_buf), - "%s", _(" on 1 line")); - else + "%s", _(" on 1 line")); + } else { vim_snprintf_add((char *)msg_buf, sizeof(msg_buf), - _(" on %" PRId64 " lines"), (int64_t)sub_nlines); - if (msg(msg_buf)) - /* save message to display it after redraw */ + _(" on %" PRId64 " lines"), (int64_t)sub_nlines); + } + if (msg(msg_buf)) { + // save message to display it after redraw set_keep_msg(msg_buf, 0); + } return true; } if (got_int) { @@ -4418,13 +4510,13 @@ static void global_exe_one(char_u *const cmd, const linenr_T lnum) */ void ex_global(exarg_T *eap) { - linenr_T lnum; /* line number according to old situation */ + linenr_T lnum; // line number according to old situation int ndone = 0; - int type; /* first char of cmd: 'v' or 'g' */ - char_u *cmd; /* command argument */ + int type; // first char of cmd: 'v' or 'g' + char_u *cmd; // command argument - char_u delim; /* delimiter, normally '/' */ - char_u *pat; + char_u delim; // delimiter, normally '/' + char_u *pat; regmmatch_T regmatch; int match; int which_pat; @@ -4438,17 +4530,18 @@ void ex_global(exarg_T *eap) return; } - if (eap->forceit) /* ":global!" is like ":vglobal" */ + if (eap->forceit) { // ":global!" is like ":vglobal" type = 'v'; - else + } else { type = *eap->cmd; + } cmd = eap->arg; - which_pat = RE_LAST; /* default: use last used regexp */ + which_pat = RE_LAST; // default: use last used regexp /* * undocumented vi feature: - * "\/" and "\?": use previous search pattern. - * "\&": use previous substitute pattern. + * "\/" and "\?": use previous search pattern. + * "\&": use previous substitute pattern. */ if (*cmd == '\\') { ++cmd; @@ -4456,10 +4549,11 @@ void ex_global(exarg_T *eap) EMSG(_(e_backslash)); return; } - if (*cmd == '&') - which_pat = RE_SUBST; /* use previous substitute pattern */ - else - which_pat = RE_SEARCH; /* use previous search pattern */ + if (*cmd == '&') { + which_pat = RE_SUBST; // use previous substitute pattern + } else { + which_pat = RE_SEARCH; // use previous search pattern + } ++cmd; pat = (char_u *)""; } else if (*cmd == NUL) { @@ -4468,13 +4562,15 @@ void ex_global(exarg_T *eap) } else if (check_regexp_delim(*cmd) == FAIL) { return; } else { - delim = *cmd; /* get the delimiter */ - if (delim) - ++cmd; /* skip delimiter if there is one */ - pat = cmd; /* remember start of pattern */ + delim = *cmd; // get the delimiter + if (delim) { + ++cmd; // skip delimiter if there is one + } + pat = cmd; // remember start of pattern cmd = skip_regexp(cmd, delim, p_magic, &eap->arg); - if (cmd[0] == delim) /* end delimiter found */ - *cmd++ = NUL; /* replace it with a NUL */ + if (cmd[0] == delim) { // end delimiter found + *cmd++ = NUL; // replace it with a NUL + } } if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, ®match) == FAIL) { @@ -4578,19 +4674,17 @@ void global_exe(char_u *cmd) #if defined(EXITFREE) void free_old_sub(void) { - sub_set_replacement((SubReplacementString) {NULL, 0, NULL}); + sub_set_replacement((SubReplacementString) { NULL, 0, NULL }); } #endif -/* - * Set up for a tagpreview. - * Return TRUE when it was created. - */ -bool -prepare_tagpreview ( - bool undo_sync /* sync undo when leaving the window */ -) +/// Set up for a tagpreview. +/// +/// @param undo_sync sync undo when leaving the window +/// +/// @return TRUE when it was created. +bool prepare_tagpreview(bool undo_sync) { /* * If there is already a preview window open, use that one. @@ -4609,8 +4703,9 @@ prepare_tagpreview ( * There is no preview window open yet. Create one. */ if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0) - == FAIL) + == FAIL) { return false; + } curwin->w_p_pvw = TRUE; curwin->w_p_wfh = TRUE; RESET_BINDING(curwin); /* don't take over 'scrollbind' @@ -4631,20 +4726,20 @@ prepare_tagpreview ( */ void ex_help(exarg_T *eap) { - char_u *arg; - char_u *tag; - FILE *helpfd; /* file descriptor of help file */ + char_u *arg; + char_u *tag; + FILE *helpfd; // file descriptor of help file int n; int i; - win_T *wp; + win_T *wp; int num_matches; - char_u **matches; - char_u *p; + char_u **matches; + char_u *p; int empty_fnum = 0; int alt_fnum = 0; - buf_T *buf; + buf_T *buf; int len; - char_u *lang; + char_u *lang; const bool old_KeyTyped = KeyTyped; if (eap != NULL) { @@ -4667,49 +4762,57 @@ void ex_help(exarg_T *eap) return; } - if (eap->skip) /* not executing commands */ + if (eap->skip) { // not executing commands return; - } else + } + } else { arg = (char_u *)""; + } - /* remove trailing blanks */ + // remove trailing blanks p = arg + STRLEN(arg) - 1; - while (p > arg && ascii_iswhite(*p) && p[-1] != '\\') + while (p > arg && ascii_iswhite(*p) && p[-1] != '\\') { *p-- = NUL; + } - /* Check for a specified language */ + // Check for a specified language lang = check_help_lang(arg); - /* When no argument given go to the index. */ - if (*arg == NUL) + // When no argument given go to the index. + if (*arg == NUL) { arg = (char_u *)"help.txt"; + } /* * Check if there is a match for the argument. */ n = find_help_tags(arg, &num_matches, &matches, - eap != NULL && eap->forceit); + eap != NULL && eap->forceit); i = 0; - if (n != FAIL && lang != NULL) - /* Find first item with the requested language. */ + if (n != FAIL && lang != NULL) { + // Find first item with the requested language. for (i = 0; i < num_matches; ++i) { len = (int)STRLEN(matches[i]); if (len > 3 && matches[i][len - 3] == '@' - && STRICMP(matches[i] + len - 2, lang) == 0) + && STRICMP(matches[i] + len - 2, lang) == 0) { break; + } } + } if (i >= num_matches || n == FAIL) { - if (lang != NULL) + if (lang != NULL) { EMSG3(_("E661: Sorry, no '%s' help for %s"), lang, arg); - else + } else { EMSG2(_("E149: Sorry, no help for %s"), arg); - if (n != FAIL) + } + if (n != FAIL) { FreeWild(num_matches, matches); + } return; } - /* The first match (in the requested language) is the best match. */ + // The first match (in the requested language) is the best match. tag = vim_strsave(matches[i]); FreeWild(num_matches, matches); @@ -4718,8 +4821,7 @@ void ex_help(exarg_T *eap) * Always open a new one for ":tab help". */ if (!bt_help(curwin->w_buffer) - || cmdmod.tab != 0 - ) { + || cmdmod.tab != 0) { if (cmdmod.tab != 0) { wp = NULL; } else { @@ -4747,13 +4849,16 @@ void ex_help(exarg_T *eap) * narrow. */ n = WSP_HELP; if (cmdmod.split == 0 && curwin->w_width != Columns - && curwin->w_width < 80) + && curwin->w_width < 80) { n |= WSP_TOP; - if (win_split(0, n) == FAIL) + } + if (win_split(0, n) == FAIL) { goto erret; + } - if (curwin->w_height < p_hh) + if (curwin->w_height < p_hh) { win_setheight((int)p_hh); + } /* * Open help file (do_ecmd() will set b_help flag, readfile() will @@ -4762,18 +4867,19 @@ void ex_help(exarg_T *eap) */ alt_fnum = curbuf->b_fnum; (void)do_ecmd(0, NULL, NULL, NULL, ECMD_LASTL, - ECMD_HIDE + ECMD_SET_HELP, - NULL /* buffer is still open, don't store info */ - ); - if (!cmdmod.keepalt) + ECMD_HIDE + ECMD_SET_HELP, + NULL // buffer is still open, don't store info + ); + if (!cmdmod.keepalt) { curwin->w_alt_fnum = alt_fnum; + } empty_fnum = curbuf->b_fnum; } } - if (!p_im) - restart_edit = 0; /* don't want insert mode in help file */ - + if (!p_im) { + restart_edit = 0; // don't want insert mode in help file + } /* Restore KeyTyped, setting 'filetype=help' may reset it. * It is needed for do_tag top open folds under the cursor. */ KeyTyped = old_KeyTyped; @@ -4790,9 +4896,10 @@ void ex_help(exarg_T *eap) } } - /* keep the previous alternate file */ - if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt) + // keep the previous alternate file + if (alt_fnum != 0 && curwin->w_alt_fnum == empty_fnum && !cmdmod.keepalt) { curwin->w_alt_fnum = alt_fnum; + } erret: xfree(tag); @@ -4810,37 +4917,37 @@ char_u *check_help_lang(char_u *arg) if (len >= 3 && arg[len - 3] == '@' && ASCII_ISALPHA(arg[len - 2]) && ASCII_ISALPHA(arg[len - 1])) { - arg[len - 3] = NUL; /* remove the '@' */ + arg[len - 3] = NUL; // remove the '@' return arg + len - 2; } return NULL; } -/* - * Return a heuristic indicating how well the given string matches. The - * smaller the number, the better the match. This is the order of priorities, - * from best match to worst match: - * - Match with least alphanumeric characters is better. - * - Match with least total characters is better. - * - Match towards the start is better. - * - Match starting with "+" is worse (feature instead of command) - * Assumption is made that the matched_string passed has already been found to - * match some string for which help is requested. webb. - */ -int -help_heuristic( - char_u *matched_string, - int offset, // offset for match - int wrong_case // no matching case -) +/// Return a heuristic indicating how well the given string matches. The +/// smaller the number, the better the match. This is the order of priorities, +/// from best match to worst match: +/// - Match with least alphanumeric characters is better. +/// - Match with least total characters is better. +/// - Match towards the start is better. +/// - Match starting with "+" is worse (feature instead of command) +/// Assumption is made that the matched_string passed has already been found to +/// match some string for which help is requested. webb. +/// +/// @param offset offset for match +/// @param wrong_case no matching case +/// +/// @return a heuristic indicating how well the given string matches. +int help_heuristic(char_u *matched_string, int offset, int wrong_case) { int num_letters; - char_u *p; + char_u *p; num_letters = 0; - for (p = matched_string; *p; p++) - if (ASCII_ISALNUM(*p)) + for (p = matched_string; *p; p++) { + if (ASCII_ISALNUM(*p)) { num_letters++; + } + } /* * Multiply the number of letters by 100 to give it a much bigger @@ -4875,8 +4982,8 @@ help_heuristic( */ static int help_compare(const void *s1, const void *s2) { - char *p1; - char *p2; + char *p1; + char *p2; p1 = *(char **)s1 + strlen(*(char **)s1) + 1; p2 = *(char **)s2 + strlen(*(char **)s2) + 1; @@ -4887,39 +4994,38 @@ static int help_compare(const void *s1, const void *s2) // the number of matches in num_matches. // The matches will be sorted with a "best" match algorithm. // When "keep_lang" is true try keeping the language of the current buffer. -int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, - bool keep_lang) +int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, bool keep_lang) { int i; static const char *(mtable[]) = { - "*", "g*", "[*", "]*", - "/*", "/\\*", "\"*", "**", - "/\\(\\)", "/\\%(\\)", - "?", ":?", "?<CR>", "g?", "g?g?", "g??", - "-?", "q?", "v_g?", - "/\\?", "/\\z(\\)", "\\=", ":s\\=", - "[count]", "[quotex]", - "[range]", ":[range]", - "[pattern]", "\\|", "\\%$", - "s/\\~", "s/\\U", "s/\\L", - "s/\\1", "s/\\2", "s/\\3", "s/\\9" + "*", "g*", "[*", "]*", + "/*", "/\\*", "\"*", "**", + "/\\(\\)", "/\\%(\\)", + "?", ":?", "?<CR>", "g?", "g?g?", "g??", + "-?", "q?", "v_g?", + "/\\?", "/\\z(\\)", "\\=", ":s\\=", + "[count]", "[quotex]", + "[range]", ":[range]", + "[pattern]", "\\|", "\\%$", + "s/\\~", "s/\\U", "s/\\L", + "s/\\1", "s/\\2", "s/\\3", "s/\\9" }; static const char *(rtable[]) = { - "star", "gstar", "[star", "]star", - "/star", "/\\\\star", "quotestar", "starstar", - "/\\\\(\\\\)", "/\\\\%(\\\\)", - "?", ":?", "?<CR>", "g?", "g?g?", "g??", - "-?", "q?", "v_g?", - "/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=", - "\\[count]", "\\[quotex]", - "\\[range]", ":\\[range]", - "\\[pattern]", "\\\\bar", "/\\\\%\\$", - "s/\\\\\\~", "s/\\\\U", "s/\\\\L", - "s/\\\\1", "s/\\\\2", "s/\\\\3", "s/\\\\9" + "star", "gstar", "[star", "]star", + "/star", "/\\\\star", "quotestar", "starstar", + "/\\\\(\\\\)", "/\\\\%(\\\\)", + "?", ":?", "?<CR>", "g?", "g?g?", "g??", + "-?", "q?", "v_g?", + "/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=", + "\\[count]", "\\[quotex]", + "\\[range]", ":\\[range]", + "\\[pattern]", "\\\\bar", "/\\\\%\\$", + "s/\\\\\\~", "s/\\\\U", "s/\\\\L", + "s/\\\\1", "s/\\\\2", "s/\\\\3", "s/\\\\9" }; static const char *(expr_table[]) = { - "!=?", "!~?", "<=?", "<?", "==?", "=~?", - ">=?", ">?", "is?", "isnot?" + "!=?", "!~?", "<=?", "<?", "==?", "=~?", + ">=?", ">?", "is?", "isnot?" }; char_u *d = IObuff; // assume IObuff is long enough! @@ -4952,7 +5058,7 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, } } - if (i < 0) { /* no match in table */ + if (i < 0) { // no match in table /* Replace "\S" with "/\\S", etc. Otherwise every tag is matched. * Also replace "\%^" and "\%(", they match every tag too. * Also "\zs", "\z1", etc. @@ -4964,9 +5070,10 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, && arg[2] != NUL))) { STRCPY(d, "/\\\\"); STRCPY(d + 3, arg + 1); - /* Check for "/\\_$", should be "/\\_\$" */ - if (d[3] == '_' && d[4] == '$') + // Check for "/\\_$", should be "/\\_\$" + if (d[3] == '_' && d[4] == '$') { STRCPY(d + 4, "\\$"); + } } else { /* Replace: * "[:...:]" with "\[:...:]" @@ -4975,12 +5082,13 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, */ if ((arg[0] == '[' && (arg[1] == ':' || (arg[1] == '+' && arg[2] == '+'))) - || (arg[0] == '\\' && arg[1] == '{')) + || (arg[0] == '\\' && arg[1] == '{')) { *d++ = '\\'; + } // If tag starts with "('", skip the "(". Fixes CTRL-] on ('option'. if (*arg == '(' && arg[1] == '\'') { - arg++; + arg++; } for (const char_u *s = arg; *s; s++) { // Replace "|" with "bar" and '"' with "quote" to match the name of @@ -4993,19 +5101,24 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, break; } switch (*s) { - case '|': STRCPY(d, "bar"); + case '|': + STRCPY(d, "bar"); d += 3; continue; - case '"': STRCPY(d, "quote"); + case '"': + STRCPY(d, "quote"); d += 5; continue; - case '*': *d++ = '.'; + case '*': + *d++ = '.'; break; - case '?': *d++ = '.'; + case '?': + *d++ = '.'; continue; case '$': case '.': - case '~': *d++ = '\\'; + case '~': + *d++ = '\\'; break; } @@ -5016,31 +5129,36 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, */ if (*s < ' ' || (*s == '^' && s[1] && (ASCII_ISALPHA(s[1]) || vim_strchr((char_u *) - "?@[\\]^", - s[1]) != NULL))) { - if (d > IObuff && d[-1] != '_' && d[-1] != '\\') - *d++ = '_'; /* prepend a '_' to make x_CTRL-x */ + "?@[\\]^", + s[1]) != NULL))) { + if (d > IObuff && d[-1] != '_' && d[-1] != '\\') { + *d++ = '_'; // prepend a '_' to make x_CTRL-x + } STRCPY(d, "CTRL-"); d += 5; if (*s < ' ') { *d++ = *s + '@'; - if (d[-1] == '\\') - *d++ = '\\'; /* double a backslash */ - } else + if (d[-1] == '\\') { + *d++ = '\\'; // double a backslash + } + } else { *d++ = *++s; - if (s[1] != NUL && s[1] != '_') - *d++ = '_'; /* append a '_' */ + } + if (s[1] != NUL && s[1] != '_') { + *d++ = '_'; // append a '_' + } continue; - } else if (*s == '^') /* "^" or "CTRL-^" or "^_" */ + } else if (*s == '^') { // "^" or "CTRL-^" or "^_" *d++ = '\\'; - + } /* * Insert a backslash before a backslash after a slash, for search * pattern tags: "/\|" --> "/\\|". */ else if (s[0] == '\\' && s[1] != '\\' - && *arg == '/' && s == arg + 1) + && *arg == '/' && s == arg + 1) { *d++ = '\\'; + } /* "CTRL-\_" -> "CTRL-\\_" to avoid the special meaning of "\_" in * "CTRL-\_CTRL-N" */ @@ -5072,16 +5190,16 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, if (*IObuff == '`') { if (d > IObuff + 2 && d[-1] == '`') { - /* remove the backticks from `command` */ + // remove the backticks from `command` memmove(IObuff, IObuff + 1, STRLEN(IObuff)); d[-2] = NUL; } else if (d > IObuff + 3 && d[-2] == '`' && d[-1] == ',') { - /* remove the backticks and comma from `command`, */ + // remove the backticks and comma from `command`, memmove(IObuff, IObuff + 1, STRLEN(IObuff)); d[-3] = NUL; } else if (d > IObuff + 4 && d[-3] == '`' && d[-2] == '\\' && d[-1] == '.') { - /* remove the backticks and dot from `command`\. */ + // remove the backticks and dot from `command`\. memmove(IObuff, IObuff + 1, STRLEN(IObuff)); d[-4] = NUL; } @@ -5100,10 +5218,11 @@ int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, /* Sort the matches found on the heuristic number that is after the * tag name. */ qsort((void *)*matches, (size_t)*num_matches, - sizeof(char_u *), help_compare); - /* Delete more than TAG_MANY to reduce the size of the listing. */ - while (*num_matches > TAG_MANY) + sizeof(char_u *), help_compare); + // Delete more than TAG_MANY to reduce the size of the listing. + while (*num_matches > TAG_MANY) { xfree((*matches)[--*num_matches]); + } } return OK; } @@ -5155,7 +5274,7 @@ static void prepare_help_buffer(void) void fix_help_buffer(void) { linenr_T lnum; - char_u *line; + char_u *line; bool in_example = false; // Set filetype to "help". @@ -5170,7 +5289,7 @@ void fix_help_buffer(void) line = ml_get_buf(curbuf, lnum, false); const size_t len = STRLEN(line); if (in_example && len > 0 && !ascii_iswhite(line[0])) { - /* End of example: non-white or '<' in first column. */ + // End of example: non-white or '<' in first column. if (line[0] == '<') { // blank-out a '<' in the first column line = ml_get_buf(curbuf, lnum, true); @@ -5203,8 +5322,7 @@ void fix_help_buffer(void) && ASCII_ISALPHA(fname[5]) && ASCII_ISALPHA(fname[6]) && TOLOWER_ASC(fname[7]) == 'x' - && fname[8] == NUL) - ) { + && fname[8] == NUL)) { for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; lnum++) { line = ml_get_buf(curbuf, lnum, false); if (strstr((char *)line, "*local-additions*") == NULL) { @@ -5220,10 +5338,10 @@ void fix_help_buffer(void) if (rt != NULL && path_full_compare(rt, NameBuff, false, true) != kEqualFiles) { int fcount; - char_u **fnames; - char_u *s; + char_u **fnames; + char_u *s; vimconv_T vc; - char_u *cp; + char_u *cp; // Find all "doc/ *.txt" files in this directory. if (!add_pathsep((char *)NameBuff) @@ -5235,9 +5353,9 @@ void fix_help_buffer(void) // Note: We cannot just do `&NameBuff` because it is a statically sized array // so `NameBuff == &NameBuff` according to C semantics. - char_u *buff_list[1] = {NameBuff}; + char_u *buff_list[1] = { NameBuff }; if (gen_expand_wildcards(1, buff_list, &fcount, - &fnames, EW_FILE|EW_SILENT) == OK + &fnames, EW_FILE|EW_SILENT) == OK && fcount > 0) { // If foo.abx is found use it instead of foo.txt in // the same directory. @@ -5294,8 +5412,9 @@ void fix_help_buffer(void) IObuff[0] = '|'; *s = '|'; while (*s != NUL) { - if (*s == '\r' || *s == '\n') + if (*s == '\r' || *s == '\n') { *s = NUL; + } /* The text is utf-8 when a byte * above 127 is found and no * illegal byte sequence is found. @@ -5314,10 +5433,9 @@ void fix_help_buffer(void) * conversion to the current * 'encoding' may be required. */ vc.vc_type = CONV_NONE; - convert_setup( - &vc, - (char_u *)(this_utf == kTrue ? "utf-8" : "latin1"), - p_enc); + convert_setup(&vc, + (char_u *)(this_utf == kTrue ? "utf-8" : "latin1"), + p_enc); if (vc.vc_type == CONV_NONE) { // No conversion needed. cp = IObuff; @@ -5374,15 +5492,15 @@ void ex_viusage(exarg_T *eap) /// French) /// @param add_help_tags Whether to add the "help-tags" tag /// @param ignore_writeerr ignore write error -static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, - bool add_help_tags, bool ignore_writeerr) +static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, bool add_help_tags, + bool ignore_writeerr) FUNC_ATTR_NONNULL_ALL { garray_T ga; int filecount; - char_u **files; - char_u *p1, *p2; - char_u *s; + char_u **files; + char_u *p1, *p2; + char_u *s; TriState utf8 = kNone; bool mix = false; // detected mixed encodings @@ -5397,9 +5515,9 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, // Note: We cannot just do `&NameBuff` because it is a statically sized array // so `NameBuff == &NameBuff` according to C semantics. - char_u *buff_list[1] = {NameBuff}; + char_u *buff_list[1] = { NameBuff }; if (gen_expand_wildcards(1, buff_list, &filecount, &files, - EW_FILE|EW_SILENT) == FAIL + EW_FILE|EW_SILENT) == FAIL || filecount == 0) { if (!got_int) { EMSG2(_("E151: No match: %s"), NameBuff); @@ -5470,9 +5588,8 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, if (utf8 == kNone) { // first file utf8 = this_utf8; } else if (utf8 != this_utf8) { - EMSG2(_( - "E670: Mix of help file encodings within a language: %s"), - files[fi]); + EMSG2(_("E670: Mix of help file encodings within a language: %s"), + files[fi]); mix = !got_int; got_int = TRUE; } @@ -5527,8 +5644,8 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, if (*p2 == '\t') { *p2 = NUL; vim_snprintf((char *)NameBuff, MAXPATHL, - _("E154: Duplicate tag \"%s\" in file %s/%s"), - ((char_u **)ga.ga_data)[i], dir, p2 + 1); + _("E154: Duplicate tag \"%s\" in file %s/%s"), + ((char_u **)ga.ga_data)[i], dir, p2 + 1); EMSG(NameBuff); *p2 = '\t'; break; @@ -5570,8 +5687,7 @@ static void helptags_one(char_u *dir, const char_u *ext, const char_u *tagfname, } /// Generate tags in one help directory, taking care of translations. -static void do_helptags(char_u *dirname, bool add_help_tags, - bool ignore_writeerr) +static void do_helptags(char_u *dirname, bool add_help_tags, bool ignore_writeerr) FUNC_ATTR_NONNULL_ALL { int len; @@ -5592,7 +5708,7 @@ static void do_helptags(char_u *dirname, bool add_help_tags, // Note: We cannot just do `&NameBuff` because it is a statically sized array // so `NameBuff == &NameBuff` according to C semantics. - char_u *buff_list[1] = {NameBuff}; + char_u *buff_list[1] = { NameBuff }; if (gen_expand_wildcards(1, buff_list, &filecount, &files, EW_FILE|EW_SILENT) == FAIL || filecount == 0) { @@ -5610,18 +5726,19 @@ static void do_helptags(char_u *dirname, bool add_help_tags, continue; } if (STRICMP(files[i] + len - 4, ".txt") == 0) { - /* ".txt" -> language "en" */ + // ".txt" -> language "en" lang[0] = 'e'; lang[1] = 'n'; } else if (files[i][len - 4] == '.' && ASCII_ISALPHA(files[i][len - 3]) && ASCII_ISALPHA(files[i][len - 2]) && TOLOWER_ASC(files[i][len - 1]) == 'x') { - /* ".abx" -> language "ab" */ + // ".abx" -> language "ab" lang[0] = TOLOWER_ASC(files[i][len - 3]); lang[1] = TOLOWER_ASC(files[i][len - 2]); - } else + } else { continue; + } // Did we find this language already? for (j = 0; j < ga.ga_len; j += 2) { @@ -5645,11 +5762,11 @@ static void do_helptags(char_u *dirname, bool add_help_tags, fname[5] = ((char_u *)ga.ga_data)[j]; fname[6] = ((char_u *)ga.ga_data)[j + 1]; if (fname[5] == 'e' && fname[6] == 'n') { - /* English is an exception: use ".txt" and "tags". */ + // English is an exception: use ".txt" and "tags". fname[4] = NUL; STRCPY(ext, ".txt"); } else { - /* Language "ab" uses ".abx" and "tags-ab". */ + // Language "ab" uses ".abx" and "tags-ab". STRCPY(ext, ".xxx"); ext[1] = fname[5]; ext[2] = fname[6]; @@ -5664,7 +5781,7 @@ static void do_helptags(char_u *dirname, bool add_help_tags, static void helptags_cb(char_u *fname, void *cookie) FUNC_ATTR_NONNULL_ALL { - do_helptags(fname, *(bool *)cookie, true); + do_helptags(fname, *(bool *)cookie, true); } /* @@ -5676,7 +5793,7 @@ void ex_helptags(exarg_T *eap) char_u *dirname; bool add_help_tags = false; - /* Check for ":helptags ++t {dir}". */ + // Check for ":helptags ++t {dir}". if (STRNCMP(eap->arg, "++t", 3) == 0 && ascii_iswhite(eap->arg[3])) { add_help_tags = true; eap->arg = skipwhite(eap->arg + 3); @@ -5732,9 +5849,8 @@ int sub_preview_win(buf_T *preview_buf) /// Shows the effects of the :substitute command being typed ('inccommand'). /// If inccommand=split, shows a preview window and later restores the layout. -static buf_T *show_sub(exarg_T *eap, pos_T old_cusr, - PreviewLines *preview_lines, int hl_id, int src_id, - handle_T bufnr) +static buf_T *show_sub(exarg_T *eap, pos_T old_cusr, PreviewLines *preview_lines, int hl_id, + int src_id, handle_T bufnr) FUNC_ATTR_NONNULL_ALL { win_T *save_curwin = curwin; @@ -5883,12 +5999,12 @@ static buf_T *show_sub(exarg_T *eap, pos_T old_cusr, /// Closes any open windows for inccommand preview buffer. void close_preview_windows(void) { - block_autocmds(); - buf_T *buf = preview_bufnr ? buflist_findnr(preview_bufnr) : NULL; - if (buf != NULL) { - close_windows(buf, false); - } - unblock_autocmds(); + block_autocmds(); + buf_T *buf = preview_bufnr ? buflist_findnr(preview_bufnr) : NULL; + if (buf != NULL) { + close_windows(buf, false); + } + unblock_autocmds(); } /// :substitute command @@ -5936,7 +6052,9 @@ void ex_substitute(exarg_T *eap) if (save_changedtick != buf_get_changedtick(curbuf)) { // Undo invisibly. This also moves the cursor! - if (!u_undo_and_forget(1)) { abort(); } + if (!u_undo_and_forget(1)) { + abort(); + } // Restore newhead. It is meaningless when curhead is valid, but we must // restore it so that undotree() is identical before/after the preview. curbuf->b_u_newhead = save_b_u_newhead; @@ -6007,7 +6125,7 @@ char_u *skip_vimgrep_pat(char_u *p, char_u **s, int *flags) /// List v:oldfiles in a nice way. void ex_oldfiles(exarg_T *eap) { - list_T *l = get_vim_var_list(VV_OLDFILES); + list_T *l = get_vim_var_list(VV_OLDFILES); long nr = 0; if (l == NULL) { diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 3afcd9ec5a..779a5b471f 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -4,14 +4,13 @@ // ex_docmd.c: functions for executing an Ex command line. #include <assert.h> -#include <string.h> +#include <inttypes.h> #include <stdbool.h> #include <stdlib.h> -#include <inttypes.h> +#include <string.h> -#include "nvim/vim.h" +#include "nvim/api/private/helpers.h" #include "nvim/ascii.h" -#include "nvim/ex_docmd.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" @@ -21,16 +20,26 @@ #include "nvim/edit.h" #include "nvim/eval.h" #include "nvim/eval/userfunc.h" +#include "nvim/event/rstream.h" +#include "nvim/event/wstream.h" #include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" +#include "nvim/ex_cmds_defs.h" +#include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" #include "nvim/ex_getln.h" +#include "nvim/ex_session.h" +#include "nvim/file_search.h" #include "nvim/fileio.h" #include "nvim/fold.h" #include "nvim/func_attr.h" +#include "nvim/garray.h" #include "nvim/getchar.h" +#include "nvim/globals.h" #include "nvim/hardcopy.h" #include "nvim/if_cscope.h" +#include "nvim/keymap.h" +#include "nvim/lua/executor.h" #include "nvim/main.h" #include "nvim/mark.h" #include "nvim/mbyte.h" @@ -39,20 +48,21 @@ #include "nvim/menu.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/ex_session.h" -#include "nvim/keymap.h" -#include "nvim/file_search.h" -#include "nvim/garray.h" +#include "nvim/mouse.h" #include "nvim/move.h" #include "nvim/normal.h" #include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/os.h" +#include "nvim/os/time.h" #include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/quickfix.h" #include "nvim/regexp.h" #include "nvim/screen.h" #include "nvim/search.h" +#include "nvim/shada.h" #include "nvim/sign.h" #include "nvim/spell.h" #include "nvim/spellfile.h" @@ -63,36 +73,26 @@ #include "nvim/ui.h" #include "nvim/undo.h" #include "nvim/version.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/os/os.h" -#include "nvim/os/input.h" -#include "nvim/os/time.h" -#include "nvim/ex_cmds_defs.h" -#include "nvim/mouse.h" -#include "nvim/event/rstream.h" -#include "nvim/event/wstream.h" -#include "nvim/shada.h" -#include "nvim/lua/executor.h" -#include "nvim/globals.h" -#include "nvim/api/private/helpers.h" static int quitmore = 0; static bool ex_pressedreturn = false; typedef struct ucmd { - char_u *uc_name; // The command name + char_u *uc_name; // The command name uint32_t uc_argt; // The argument type - char_u *uc_rep; // The command's replacement string + char_u *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_u *uc_compl_arg; // completion argument if any } ucmd_T; -#define UC_BUFFER 1 /* -buffer: local to current buffer */ +#define UC_BUFFER 1 // -buffer: local to current buffer -static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL}; +static garray_T ucmds = { 0, 0, sizeof(ucmd_T), 4, NULL }; #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i]) #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i]) @@ -100,10 +100,10 @@ static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL}; // Whether a command index indicates a user command. # define IS_USER_CMDIDX(idx) ((int)(idx) < 0) -/* Struct for storing a line inside a while/for loop */ +// Struct for storing a line inside a while/for loop typedef struct { - char_u *line; /* command line */ - linenr_T lnum; /* sourcing_lnum of the line */ + char_u *line; // command line + linenr_T lnum; // sourcing_lnum of the line } wcmd_T; #define FREE_WCMD(wcmd) xfree((wcmd)->line) @@ -114,27 +114,27 @@ typedef struct { * reads more lines that may come from the while/for loop. */ struct loop_cookie { - garray_T *lines_gap; // growarray with line info + garray_T *lines_gap; // growarray with line info int current_line; // last read line from growarray int repeating; // TRUE when looping a second time // When "repeating" is FALSE use "getline" and "cookie" to get lines - char_u *(*getline)(int, void *, int, bool); - void *cookie; + char_u *(*getline)(int, void *, int, bool); + void *cookie; }; -/* Struct to save a few things while debugging. Used in do_cmdline() only. */ +// Struct to save a few things while debugging. Used in do_cmdline() only. struct dbg_stuff { int trylevel; int force_abort; - except_T *caught_stack; - char_u *vv_exception; - char_u *vv_throwpoint; + except_T *caught_stack; + char_u *vv_exception; + char_u *vv_throwpoint; int did_emsg; int got_int; int need_rethrow; int check_cstack; - except_T *current_exception; + except_T *current_exception; }; #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -152,7 +152,7 @@ struct dbg_stuff { # include "ex_cmds_defs.generated.h" #endif -static char_u dollar_command[2] = {'$', 0}; +static char_u dollar_command[2] = { '$', 0 }; static void save_dbg_stuff(struct dbg_stuff *dsp) { @@ -198,8 +198,9 @@ void do_exmode(void) /* When using ":global /pat/ visual" and then "Q" we return to continue * the :global command. */ - if (global_busy) + if (global_busy) { return; + } save_msg_scroll = msg_scroll; RedrawingDisabled++; // don't redisplay the window @@ -207,7 +208,7 @@ void do_exmode(void) MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode.")); while (exmode_active) { - /* Check for a ":normal" command and no more characters left. */ + // Check for a ":normal" command and no more characters left. if (ex_normal_busy > 0 && typebuf.tb_len == 0) { exmode_active = false; break; @@ -232,18 +233,20 @@ void do_exmode(void) /* go up one line, to overwrite the ":<CR>" line, so the * output doesn't contain empty lines. */ msg_row = prev_msg_row; - if (prev_msg_row == Rows - 1) + if (prev_msg_row == Rows - 1) { msg_row--; + } } msg_col = 0; print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE); msg_clr_eos(); } - } else if (ex_pressedreturn && !ex_no_reprint) { /* must be at EOF */ - if (curbuf->b_ml.ml_flags & ML_EMPTY) + } else if (ex_pressedreturn && !ex_no_reprint) { // must be at EOF + if (curbuf->b_ml.ml_flags & ML_EMPTY) { EMSG(_(e_emptybuf)); - else + } else { EMSG(_("E501: At end-of-file")); + } } } @@ -301,13 +304,13 @@ int do_cmdline_cmd(const char *cmd) /// DOCMD_EXCRESET - Reset the exception environment (used for debugging). /// DOCMD_KEEPLINE - Store first typed line (for repeating with "."). /// +/// @param cookie argument for fgetline() +/// /// @return FAIL if cmdline could not be executed, OK otherwise -int do_cmdline(char_u *cmdline, LineGetter fgetline, - void *cookie, /* argument for fgetline() */ - int flags) +int do_cmdline(char_u *cmdline, LineGetter fgetline, void *cookie, int flags) { - char_u *next_cmdline; // next cmd to execute - char_u *cmdline_copy = NULL; // copy of cmd line + char_u *next_cmdline; // next cmd to execute + char_u *cmdline_copy = NULL; // copy of cmd line bool used_getline = false; // used "fgetline" to obtain command static int recursive = 0; // recursive depth bool msg_didout_before_start = false; @@ -319,21 +322,21 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, }; garray_T lines_ga; // keep lines for ":while"/":for" int current_line = 0; // active line in lines_ga - char_u *fname = NULL; // function or script name + char_u *fname = NULL; // function or script name linenr_T *breakpoint = NULL; // ptr to breakpoint field in cookie - int *dbg_tick = NULL; // ptr to dbg_tick field in cookie + int *dbg_tick = NULL; // ptr to dbg_tick field in cookie struct dbg_stuff debug_saved; // saved things for debug mode int initial_trylevel; - struct msglist **saved_msg_list = NULL; - struct msglist *private_msg_list; + struct msglist **saved_msg_list = NULL; + struct msglist *private_msg_list; // "fgetline" and "cookie" passed to do_one_cmd() - char_u *(*cmd_getline)(int, void *, int, bool); - void *cmd_cookie; + char_u *(*cmd_getline)(int, void *, int, bool); + void *cmd_cookie; struct loop_cookie cmd_loop_cookie; - void *real_cookie; + void *real_cookie; int getline_is_func; - static int call_depth = 0; /* recursiveness */ + static int call_depth = 0; // recursiveness /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory * location for storing error messages to be converted to an exception. @@ -363,10 +366,11 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, real_cookie = getline_cookie(fgetline, cookie); - /* Inside a function use a higher nesting level. */ + // Inside a function use a higher nesting level. getline_is_func = getline_equal(fgetline, cookie, get_func_line); - if (getline_is_func && ex_nesting_level == func_level(real_cookie)) + if (getline_is_func && ex_nesting_level == func_level(real_cookie)) { ++ex_nesting_level; + } /* Get the function or script name and the address where the next breakpoint * line and the debug tick for a function or script are stored. */ @@ -422,13 +426,14 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, do { getline_is_func = getline_equal(fgetline, cookie, get_func_line); - /* stop skipping cmds for an error msg after all endif/while/for */ + // stop skipping cmds for an error msg after all endif/while/for if (next_cmdline == NULL && !force_abort && cstack.cs_idx < 0 - && !(getline_is_func && func_has_abort(real_cookie)) - ) + && !(getline_is_func && + func_has_abort(real_cookie))) { did_emsg = FALSE; + } /* * 1. If repeating a line in a loop, get a line from lines_ga. @@ -436,7 +441,7 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, * 3. If a line is given: Make a copy, so we can mess with it. */ - /* 1. If repeating, get a previous line from lines_ga. */ + // 1. If repeating, get a previous line from lines_ga. if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len) { /* Each '|' separated command is stored separately in lines_ga, to * be able to jump to it. Don't use next_cmdline now. */ @@ -445,49 +450,50 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, /* Check if a function has returned or, unless it has an unclosed * try conditional, aborted. */ if (getline_is_func) { - if (do_profiling == PROF_YES) + if (do_profiling == PROF_YES) { func_line_end(real_cookie); + } if (func_has_ended(real_cookie)) { retval = FAIL; break; } } else if (do_profiling == PROF_YES - && getline_equal(fgetline, cookie, getsourceline)) + && getline_equal(fgetline, cookie, getsourceline)) { script_line_end(); + } - /* Check if a sourced file hit a ":finish" command. */ + // Check if a sourced file hit a ":finish" command. if (source_finished(fgetline, cookie)) { retval = FAIL; break; } - /* If breakpoints have been added/deleted need to check for it. */ + // If breakpoints have been added/deleted need to check for it. if (breakpoint != NULL && dbg_tick != NULL && *dbg_tick != debug_tick) { - *breakpoint = dbg_find_breakpoint( - getline_equal(fgetline, cookie, getsourceline), - fname, sourcing_lnum); + *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), + fname, sourcing_lnum); *dbg_tick = debug_tick; } next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line; sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum; - /* Did we encounter a breakpoint? */ + // Did we encounter a breakpoint? if (breakpoint != NULL && *breakpoint != 0 && *breakpoint <= sourcing_lnum) { dbg_breakpoint(fname, sourcing_lnum); - /* Find next breakpoint. */ - *breakpoint = dbg_find_breakpoint( - getline_equal(fgetline, cookie, getsourceline), - fname, sourcing_lnum); + // Find next breakpoint. + *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), + fname, sourcing_lnum); *dbg_tick = debug_tick; } if (do_profiling == PROF_YES) { - if (getline_is_func) + if (getline_is_func) { func_line_start(real_cookie); - else if (getline_equal(fgetline, cookie, getsourceline)) + } else if (getline_equal(fgetline, cookie, getsourceline)) { script_line_start(); + } } } @@ -509,7 +515,7 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, cmd_cookie = cookie; } - /* 2. If no line given, get an allocated line with fgetline(). */ + // 2. If no line given, get an allocated line with fgetline(). if (next_cmdline == NULL) { /* * Need to set msg_didout for the first line after an ":if", @@ -539,13 +545,14 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, */ if (flags & DOCMD_KEEPLINE) { xfree(repeat_cmdline); - if (count == 0) + if (count == 0) { repeat_cmdline = vim_strsave(next_cmdline); - else + } else { repeat_cmdline = NULL; + } } } - /* 3. Make a copy of the command so we can mess with it. */ + // 3. Make a copy of the command so we can mess with it. else if (cmdline_copy == NULL) { next_cmdline = vim_strsave(next_cmdline); } @@ -575,8 +582,8 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, msg_didout_before_start = msg_didout; msg_didany = false; // no output yet msg_start(); - msg_scroll = TRUE; /* put messages below each other */ - ++no_wait_return; /* don't wait for return until finished */ + msg_scroll = TRUE; // put messages below each other + ++no_wait_return; // don't wait for return until finished ++RedrawingDisabled; did_inc = TRUE; } @@ -602,10 +609,11 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, next_cmdline = NULL; } - if (cmd_cookie == (void *)&cmd_loop_cookie) + if (cmd_cookie == (void *)&cmd_loop_cookie) { /* Use "current_line" from "cmd_loop_cookie", it may have been * incremented when defining a function. */ current_line = cmd_loop_cookie.current_line; + } if (next_cmdline == NULL) { XFREE_CLEAR(cmdline_copy); @@ -627,11 +635,12 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, } - /* reset did_emsg for a function that is not aborted by an error */ + // reset did_emsg for a function that is not aborted by an error if (did_emsg && !force_abort && getline_equal(fgetline, cookie, get_func_line) - && !func_has_abort(real_cookie)) + && !func_has_abort(real_cookie)) { did_emsg = FALSE; + } if (cstack.cs_looplevel > 0) { ++current_line; @@ -656,24 +665,24 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, && cstack.cs_line[cstack.cs_idx] >= 0 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE)) { current_line = cstack.cs_line[cstack.cs_idx]; - /* remember we jumped there */ + // remember we jumped there cstack.cs_lflags |= CSL_HAD_LOOP; - line_breakcheck(); /* check if CTRL-C typed */ + line_breakcheck(); // check if CTRL-C typed /* Check for the next breakpoint at or after the ":while" * or ":for". */ if (breakpoint != NULL) { - *breakpoint = dbg_find_breakpoint( - getline_equal(fgetline, cookie, getsourceline), - fname, - ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1); + *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), + fname, + ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1); *dbg_tick = debug_tick; } } else { - /* can only get here with ":endwhile" or ":endfor" */ - if (cstack.cs_idx >= 0) + // can only get here with ":endwhile" or ":endfor" + if (cstack.cs_idx >= 0) { rewind_conditionals(&cstack, cstack.cs_idx - 1, - CSF_WHILE | CSF_FOR, &cstack.cs_looplevel); + CSF_WHILE | CSF_FOR, &cstack.cs_looplevel); + } } } /* @@ -726,9 +735,8 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, force_abort = false; } - /* Convert an interrupt to an exception if appropriate. */ + // Convert an interrupt to an exception if appropriate. (void)do_intthrow(&cstack); - } /* * Continue executing command lines when: @@ -766,14 +774,15 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, && !source_finished(fgetline, cookie)) || (getline_equal(fgetline, cookie, get_func_line) && !func_has_ended(real_cookie)))) { - if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY) + if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY) { EMSG(_(e_endtry)); - else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE) + } else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE) { EMSG(_(e_endwhile)); - else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR) + } else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR) { EMSG(_(e_endfor)); - else + } else { EMSG(_(e_endif)); + } } /* @@ -786,10 +795,11 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, do { int idx = cleanup_conditionals(&cstack, 0, TRUE); - if (idx >= 0) - --idx; /* remove try block not in its finally clause */ + if (idx >= 0) { + --idx; // remove try block not in its finally clause + } rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR, - &cstack.cs_looplevel); + &cstack.cs_looplevel); } while (cstack.cs_idx >= 0); trylevel = initial_trylevel; } @@ -821,8 +831,8 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, switch (current_exception->type) { case ET_USER: vim_snprintf((char *)IObuff, IOSIZE, - _("E605: Exception not caught: %s"), - current_exception->value); + _("E605: Exception not caught: %s"), + current_exception->value); p = vim_strsave(IObuff); break; case ET_ERROR: @@ -886,27 +896,30 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, check_cstack = true; } } else { - /* When leaving a function, reduce nesting level. */ - if (getline_equal(fgetline, cookie, get_func_line)) + // When leaving a function, reduce nesting level. + if (getline_equal(fgetline, cookie, get_func_line)) { --ex_nesting_level; + } /* * Go to debug mode when returning from a function in which we are * single-stepping. */ if ((getline_equal(fgetline, cookie, getsourceline) || getline_equal(fgetline, cookie, get_func_line)) - && ex_nesting_level + 1 <= debug_break_level) + && 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")); + } } /* * Restore the exception environment (done after returning from the * debugger). */ - if (flags & DOCMD_EXCRESET) + if (flags & DOCMD_EXCRESET) { restore_dbg_stuff(&debug_saved); + } msg_list = saved_msg_list; @@ -925,8 +938,7 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, * wait for hit-return. Also for an error situation. */ if (retval == FAIL - || (did_endif && KeyTyped && !did_emsg) - ) { + || (did_endif && KeyTyped && !did_emsg)) { need_wait_return = false; msg_didany = false; // don't wait when restarting edit } else if (need_wait_return) { @@ -952,14 +964,14 @@ int do_cmdline(char_u *cmdline, LineGetter fgetline, */ static char_u *get_loop_line(int c, void *cookie, int indent, bool do_concat) { - struct loop_cookie *cp = (struct loop_cookie *)cookie; - wcmd_T *wp; - char_u *line; + struct loop_cookie *cp = (struct loop_cookie *)cookie; + wcmd_T *wp; + char_u *line; if (cp->current_line + 1 >= cp->lines_gap->ga_len) { - if (cp->repeating) - return NULL; /* trying to read past ":endwhile"/":endfor" */ - + if (cp->repeating) { + return NULL; // trying to read past ":endwhile"/":endfor" + } // First time inside the ":while"/":for": get line normally. if (cp->getline == NULL) { line = getcmdline(c, 0L, indent, do_concat); @@ -991,13 +1003,11 @@ static void store_loop_line(garray_T *gap, char_u *line) p->lnum = sourcing_lnum; } -/* - * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals - * "func". * Otherwise return TRUE when "fgetline" equals "func". - */ -int getline_equal(LineGetter fgetline, - void *cookie, /* argument for fgetline() */ - LineGetter func) +/// If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals +/// "func". * Otherwise return TRUE when "fgetline" equals "func". +/// +/// @param cookie argument for fgetline() +int getline_equal(LineGetter fgetline, void *cookie, LineGetter func) { LineGetter gp; struct loop_cookie *cp; @@ -1014,13 +1024,11 @@ int getline_equal(LineGetter fgetline, return gp == func; } -/* - * If "fgetline" is get_loop_line(), return the cookie used by the original - * getline function. Otherwise return "cookie". - */ -void * getline_cookie(LineGetter fgetline, - void *cookie /* argument for fgetline() */ - ) +/// If "fgetline" is get_loop_line(), return the cookie used by the original +/// getline function. Otherwise return "cookie". +/// +/// @param cookie argument for fgetline() +void * getline_cookie(LineGetter fgetline, void *cookie) { LineGetter gp; struct loop_cookie *cp; @@ -1049,16 +1057,18 @@ static int compute_buffer_local_count(int addr_type, int lnum, int offset) int count = offset; buf = firstbuf; - while (buf->b_next != NULL && buf->b_fnum < lnum) + while (buf->b_next != NULL && buf->b_fnum < lnum) { buf = buf->b_next; + } while (count != 0) { count += (count < 0) ? 1 : -1; nextbuf = (offset < 0) ? buf->b_prev : buf->b_next; - if (nextbuf == NULL) + if (nextbuf == NULL) { break; + } buf = nextbuf; - if (addr_type == ADDR_LOADED_BUFFERS) - /* skip over unloaded buffers */ + if (addr_type == ADDR_LOADED_BUFFERS) { + // skip over unloaded buffers while (buf->b_ml.ml_mfp == NULL) { nextbuf = (offset < 0) ? buf->b_prev : buf->b_next; if (nextbuf == NULL) { @@ -1066,13 +1076,15 @@ static int compute_buffer_local_count(int addr_type, int lnum, int offset) } buf = nextbuf; } + } } // we might have gone too far, last buffer is not loaded if (addr_type == ADDR_LOADED_BUFFERS) { while (buf->b_ml.ml_mfp == NULL) { nextbuf = (offset >= 0) ? buf->b_prev : buf->b_next; - if (nextbuf == NULL) + if (nextbuf == NULL) { break; + } buf = nextbuf; } } @@ -1088,8 +1100,9 @@ static int current_win_nr(const win_T *win) FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { ++nr; - if (wp == win) + if (wp == win) { break; + } } return nr; } @@ -1100,8 +1113,9 @@ static int current_tab_nr(tabpage_T *tab) FOR_ALL_TABS(tp) { ++nr; - if (tp == tab) + if (tp == tab) { break; + } } return nr; } @@ -1116,87 +1130,87 @@ static int current_tab_nr(tabpage_T *tab) static void get_wincmd_addr_type(char_u *arg, exarg_T *eap) { switch (*arg) { - case 'S': - case Ctrl_S: - case 's': - case Ctrl_N: - case 'n': - case 'j': - case Ctrl_J: - case 'k': - case Ctrl_K: - case 'T': - case Ctrl_R: - case 'r': - case 'R': - case 'K': - case 'J': - case '+': - case '-': - case Ctrl__: - case '_': - case '|': - case ']': - case Ctrl_RSB: - case 'g': - case Ctrl_G: - case Ctrl_V: - case 'v': - case 'h': - case Ctrl_H: - case 'l': - case Ctrl_L: - case 'H': - case 'L': - case '>': - case '<': - case '}': - case 'f': - case 'F': - case Ctrl_F: - case 'i': - case Ctrl_I: - case 'd': - case Ctrl_D: - // window size or any count - eap->addr_type = ADDR_OTHER; // -V1037 - break; + case 'S': + case Ctrl_S: + case 's': + case Ctrl_N: + case 'n': + case 'j': + case Ctrl_J: + case 'k': + case Ctrl_K: + case 'T': + case Ctrl_R: + case 'r': + case 'R': + case 'K': + case 'J': + case '+': + case '-': + case Ctrl__: + case '_': + case '|': + case ']': + case Ctrl_RSB: + case 'g': + case Ctrl_G: + case Ctrl_V: + case 'v': + case 'h': + case Ctrl_H: + case 'l': + case Ctrl_L: + case 'H': + case 'L': + case '>': + case '<': + case '}': + case 'f': + case 'F': + case Ctrl_F: + case 'i': + case Ctrl_I: + case 'd': + case Ctrl_D: + // window size or any count + eap->addr_type = ADDR_OTHER; // -V1037 + break; - case Ctrl_HAT: - case '^': - // buffer number - eap->addr_type = ADDR_BUFFERS; - break; + case Ctrl_HAT: + case '^': + // buffer number + eap->addr_type = ADDR_BUFFERS; + break; - case Ctrl_Q: - case 'q': - case Ctrl_C: - case 'c': - case Ctrl_O: - case 'o': - case Ctrl_W: - case 'w': - case 'W': - case 'x': - case Ctrl_X: - // window number - eap->addr_type = ADDR_WINDOWS; - break; + case Ctrl_Q: + case 'q': + case Ctrl_C: + case 'c': + case Ctrl_O: + case 'o': + case Ctrl_W: + case 'w': + case 'W': + case 'x': + case Ctrl_X: + // window number + eap->addr_type = ADDR_WINDOWS; + break; - case Ctrl_Z: - case 'z': - case 'P': - case 't': - case Ctrl_T: - case 'b': - case Ctrl_B: - case 'p': - case Ctrl_P: - case '=': - case CAR: - // no count - eap->addr_type = ADDR_NONE; - break; + case Ctrl_Z: + case 'z': + case 'P': + case 't': + case Ctrl_T: + case 'b': + case Ctrl_B: + case 'p': + case Ctrl_P: + case '=': + case CAR: + // no count + eap->addr_type = ADDR_NONE; + break; } } @@ -1217,54 +1231,51 @@ static char_u *skip_colon_white(const char_u *p, bool skipleadingwhite) return (char_u *)p; } -/* - * Execute one Ex command. - * - * If 'sourcing' is TRUE, the command will be included in the error message. - * - * 1. skip comment lines and leading space - * 2. handle command modifiers - * 3. skip over the range to find the command - * 4. parse the range - * 5. parse the command - * 6. parse arguments - * 7. switch on command name - * - * Note: "fgetline" can be NULL. - * - * This function may be called recursively! - */ -static char_u * do_one_cmd(char_u **cmdlinep, - int flags, - cstack_T *cstack, - LineGetter fgetline, - void *cookie /* argument for fgetline() */ - ) -{ - char_u *p; +/// Execute one Ex command. +/// +/// If 'sourcing' is TRUE, the command will be included in the error message. +/// +/// 1. skip comment lines and leading space +/// 2. handle command modifiers +/// 3. skip over the range to find the command +/// 4. parse the range +/// 5. parse the command +/// 6. parse arguments +/// 7. switch on command name +/// +/// Note: "fgetline" can be NULL. +/// +/// This function may be called recursively! +/// +/// @param cookie argument for fgetline() +static char_u * do_one_cmd(char_u **cmdlinep, int flags, cstack_T *cstack, LineGetter fgetline, + void *cookie) +{ + char_u *p; linenr_T lnum; long n; - char_u *errormsg = NULL; // error message - char_u *after_modifier = NULL; + char_u *errormsg = NULL; // error message + char_u *after_modifier = NULL; exarg_T ea; const int save_msg_scroll = msg_scroll; cmdmod_T save_cmdmod; const int save_reg_executing = reg_executing; - char_u *cmd; + char_u *cmd; memset(&ea, 0, sizeof(ea)); ea.line1 = 1; ea.line2 = 1; ex_nesting_level++; - /* When the last file has not been edited :q has to be typed twice. */ + // When the last file has not been edited :q has to be typed twice. if (quitmore - /* avoid that a function call in 'statusline' does this */ + // avoid that a function call in 'statusline' does this && !getline_equal(fgetline, cookie, get_func_line) - /* avoid that an autocommand, e.g. QuitPre, does this */ - && !getline_equal(fgetline, cookie, getnextac) - ) + // avoid that an autocommand, e.g. QuitPre, does this + && !getline_equal(fgetline, cookie, + getnextac)) { --quitmore; + } /* * Reset browse, confirm, etc.. They are restored when returning, for @@ -1421,13 +1432,14 @@ static char_u * do_one_cmd(char_u **cmdlinep, ea.line2 = curbuf->b_ml.ml_line_count; } - if (ea.line2 < 0) + if (ea.line2 < 0) { errormsg = (char_u *)_(e_invrange); - else { - if (ea.line2 == 0) + } else { + if (ea.line2 == 0) { curwin->w_cursor.lnum = 1; - else + } else { curwin->w_cursor.lnum = ea.line2; + } beginline(BL_SOL | BL_FIX); } } @@ -1452,8 +1464,9 @@ static char_u * do_one_cmd(char_u **cmdlinep, } if (p == NULL) { - if (!ea.skip) + if (!ea.skip) { errormsg = (char_u *)_("E464: Ambiguous use of user-defined command"); + } goto doend; } // Check for wrong commands. @@ -1475,8 +1488,8 @@ static char_u * do_one_cmd(char_u **cmdlinep, // set when Not Implemented const int ni = !IS_USER_CMDIDX(ea.cmdidx) - && (cmdnames[ea.cmdidx].cmd_func == ex_ni - || cmdnames[ea.cmdidx].cmd_func == ex_script_ni); + && (cmdnames[ea.cmdidx].cmd_func == ex_ni + || cmdnames[ea.cmdidx].cmd_func == ex_script_ni); // Forced commands. @@ -1502,7 +1515,7 @@ static char_u * do_one_cmd(char_u **cmdlinep, if (!MODIFIABLE(curbuf) && (ea.argt & EX_MODIFY) // allow :put in terminals && (!curbuf->terminal || ea.cmdidx != CMD_put)) { - /* Command not allowed in non-'modifiable' buffer */ + // Command not allowed in non-'modifiable' buffer errormsg = (char_u *)_(e_modifiable); goto doend; } @@ -1561,8 +1574,9 @@ static char_u * do_one_cmd(char_u **cmdlinep, ea.line1 = ea.line2; ea.line2 = lnum; } - if ((errormsg = invalid_range(&ea)) != NULL) + if ((errormsg = invalid_range(&ea)) != NULL) { goto doend; + } } if ((ea.addr_type == ADDR_OTHER) && ea.addr_count == 0) { @@ -1585,17 +1599,19 @@ static char_u * do_one_cmd(char_u **cmdlinep, * option here, so things like % get expanded. */ p = replace_makeprg(&ea, p, cmdlinep); - if (p == NULL) + if (p == NULL) { goto doend; + } /* * Skip to start of argument. * Don't do this for the ":!" command, because ":!! -l" needs the space. */ - if (ea.cmdidx == CMD_bang) + if (ea.cmdidx == CMD_bang) { ea.arg = p; - else + } else { ea.arg = skipwhite(p); + } // ":file" cannot be run with an argument when "curbuf->b_ro_locked" is set if (ea.cmdidx == CMD_file && *ea.arg != NUL && curbuf_locked()) { @@ -1616,14 +1632,14 @@ static char_u * do_one_cmd(char_u **cmdlinep, } if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { - if (*ea.arg == '>') { /* append */ - if (*++ea.arg != '>') { /* typed wrong */ + if (*ea.arg == '>') { // append + if (*++ea.arg != '>') { // typed wrong errormsg = (char_u *)_("E494: Use w or w>>"); goto doend; } ea.arg = skipwhite(ea.arg + 1); ea.append = TRUE; - } else if (*ea.arg == '!' && ea.cmdidx == CMD_write) { /* :w !filter */ + } else if (*ea.arg == '!' && ea.cmdidx == CMD_write) { // :w !filter ++ea.arg; ea.usefilter = TRUE; } @@ -1631,9 +1647,9 @@ static char_u * do_one_cmd(char_u **cmdlinep, if (ea.cmdidx == CMD_read) { if (ea.forceit) { - ea.usefilter = TRUE; /* :r! filter if ea.forceit */ + ea.usefilter = TRUE; // :r! filter if ea.forceit ea.forceit = FALSE; - } else if (*ea.arg == '!') { /* :r !filter */ + } else if (*ea.arg == '!') { // :r !filter ++ea.arg; ea.usefilter = TRUE; } @@ -1641,7 +1657,7 @@ static char_u * do_one_cmd(char_u **cmdlinep, if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { ea.amount = 1; - while (*ea.arg == *ea.cmd) { /* count number of '>' or '<' */ + while (*ea.arg == *ea.cmd) { // count number of '>' or '<' ++ea.arg; ++ea.amount; } @@ -1692,67 +1708,67 @@ static char_u * do_one_cmd(char_u **cmdlinep, ea.line1 = 1; switch (ea.addr_type) { - case ADDR_LINES: - case ADDR_OTHER: - ea.line2 = curbuf->b_ml.ml_line_count; - break; - case ADDR_LOADED_BUFFERS: - buf = firstbuf; - while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) { - buf = buf->b_next; - } - ea.line1 = buf->b_fnum; - buf = lastbuf; - while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) { - buf = buf->b_prev; - } - ea.line2 = buf->b_fnum; - break; - case ADDR_BUFFERS: - ea.line1 = firstbuf->b_fnum; - ea.line2 = lastbuf->b_fnum; - break; - case ADDR_WINDOWS: - ea.line2 = LAST_WIN_NR; - break; - case ADDR_TABS: - ea.line2 = LAST_TAB_NR; - break; - case ADDR_TABS_RELATIVE: + case ADDR_LINES: + case ADDR_OTHER: + ea.line2 = curbuf->b_ml.ml_line_count; + break; + case ADDR_LOADED_BUFFERS: + buf = firstbuf; + while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) { + buf = buf->b_next; + } + ea.line1 = buf->b_fnum; + buf = lastbuf; + while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) { + buf = buf->b_prev; + } + ea.line2 = buf->b_fnum; + break; + case ADDR_BUFFERS: + ea.line1 = firstbuf->b_fnum; + ea.line2 = lastbuf->b_fnum; + break; + case ADDR_WINDOWS: + ea.line2 = LAST_WIN_NR; + break; + case ADDR_TABS: + ea.line2 = LAST_TAB_NR; + break; + case ADDR_TABS_RELATIVE: + ea.line2 = 1; + break; + case ADDR_ARGUMENTS: + if (ARGCOUNT == 0) { + ea.line1 = ea.line2 = 0; + } else { + ea.line2 = ARGCOUNT; + } + break; + case ADDR_QUICKFIX_VALID: + ea.line2 = qf_get_valid_size(&ea); + if (ea.line2 == 0) { ea.line2 = 1; - break; - case ADDR_ARGUMENTS: - if (ARGCOUNT == 0) { - ea.line1 = ea.line2 = 0; - } else { - ea.line2 = ARGCOUNT; - } - break; - case ADDR_QUICKFIX_VALID: - ea.line2 = qf_get_valid_size(&ea); - if (ea.line2 == 0) { - ea.line2 = 1; - } - break; - case ADDR_NONE: - case ADDR_UNSIGNED: - case ADDR_QUICKFIX: - IEMSG(_("INTERNAL: Cannot use EX_DFLALL " - "with ADDR_NONE, ADDR_UNSIGNED or ADDR_QUICKFIX")); - break; + } + break; + case ADDR_NONE: + case ADDR_UNSIGNED: + case ADDR_QUICKFIX: + IEMSG(_("INTERNAL: Cannot use EX_DFLALL " + "with ADDR_NONE, ADDR_UNSIGNED or ADDR_QUICKFIX")); + break; } } // accept numbered register only when no count allowed (:put) if ((ea.argt & EX_REGSTR) && *ea.arg != NUL - /* Do not allow register = for user commands */ + // Do not allow register = for user commands && (!IS_USER_CMDIDX(ea.cmdidx) || *ea.arg != '=') && !((ea.argt & EX_COUNT) && ascii_isdigit(*ea.arg))) { if (valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put && !IS_USER_CMDIDX(ea.cmdidx)))) { ea.regname = *ea.arg++; - /* for '=' register: accept the rest of the line as an expression */ + // for '=' register: accept the rest of the line as an expression if (ea.arg[-1] == '=' && ea.arg[0] != NUL) { set_expr_line(vim_strsave(ea.arg)); ea.arg += STRLEN(ea.arg); @@ -1776,8 +1792,9 @@ static char_u * do_one_cmd(char_u **cmdlinep, } if (ea.addr_type != ADDR_LINES) { // e.g. :buffer 2, :sleep 3 ea.line2 = n; - if (ea.addr_count == 0) + if (ea.addr_count == 0) { ea.addr_count = 1; + } } else { ea.line1 = ea.line2; ea.line2 += n - 1; @@ -1815,7 +1832,7 @@ static char_u * do_one_cmd(char_u **cmdlinep, */ if (ea.skip) { switch (ea.cmdidx) { - /* commands that need evaluation */ + // commands that need evaluation case CMD_while: case CMD_endwhile: case CMD_for: @@ -1916,20 +1933,20 @@ static char_u * do_one_cmd(char_u **cmdlinep, * number. Don't do this for a user command. */ if ((ea.argt & EX_BUFNAME) && *ea.arg != NUL && ea.addr_count == 0 - && !IS_USER_CMDIDX(ea.cmdidx) - ) { + && !IS_USER_CMDIDX(ea.cmdidx)) { /* * :bdelete, :bwipeout and :bunload take several arguments, separated * by spaces: find next space (skipping over escaped characters). * The others take one argument: ignore trailing spaces. */ if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout - || ea.cmdidx == CMD_bunload) + || ea.cmdidx == CMD_bunload) { p = skiptowhite_esc(ea.arg); - else { + } else { p = ea.arg + STRLEN(ea.arg); - while (p > ea.arg && ascii_iswhite(p[-1])) + while (p > ea.arg && ascii_iswhite(p[-1])) { --p; + } } ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & EX_BUFUNL) != 0, false, false); @@ -1962,8 +1979,9 @@ static char_u * do_one_cmd(char_u **cmdlinep, */ ea.errmsg = NULL; (cmdnames[ea.cmdidx].cmd_func)(&ea); - if (ea.errmsg != NULL) + if (ea.errmsg != NULL) { errormsg = (char_u *)_(ea.errmsg); + } } /* @@ -1973,14 +1991,15 @@ static char_u * do_one_cmd(char_u **cmdlinep, * exception, or reanimate a returned function or finished script file and * return or finish it again. */ - if (need_rethrow) + if (need_rethrow) { do_throw(cstack); - else if (check_cstack) { - if (source_finished(fgetline, cookie)) + } else if (check_cstack) { + if (source_finished(fgetline, cookie)) { do_finish(&ea, TRUE); - else if (getline_equal(fgetline, cookie, get_func_line) - && current_func_returned()) + } else if (getline_equal(fgetline, cookie, get_func_line) + && current_func_returned()) { do_return(&ea, TRUE, FALSE, NULL); + } } need_rethrow = check_cstack = FALSE; @@ -2002,7 +2021,7 @@ doend: emsg(errormsg); } do_errthrow(cstack, - (ea.cmdidx != CMD_SIZE && !IS_USER_CMDIDX(ea.cmdidx)) + (ea.cmdidx != CMD_SIZE && !IS_USER_CMDIDX(ea.cmdidx)) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL); @@ -2014,8 +2033,9 @@ doend: sandbox--; } - if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */ + if (ea.nextcmd && *ea.nextcmd == NUL) { // not really a next command ea.nextcmd = NULL; + } --ex_nesting_level; @@ -2074,12 +2094,15 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) p = skip_range(eap->cmd, NULL); switch (*p) { // When adding an entry, also modify cmd_exists(). - case 'a': if (!checkforcmd(&eap->cmd, "aboveleft", 3)) + case 'a': + if (!checkforcmd(&eap->cmd, "aboveleft", 3)) { break; + } cmdmod.split |= WSP_ABOVE; continue; - case 'b': if (checkforcmd(&eap->cmd, "belowright", 3)) { + case 'b': + if (checkforcmd(&eap->cmd, "belowright", 3)) { cmdmod.split |= WSP_BELOW; continue; } @@ -2093,15 +2116,18 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) cmdmod.split |= WSP_BOT; continue; - case 'c': if (!checkforcmd(&eap->cmd, "confirm", 4)) + case 'c': + if (!checkforcmd(&eap->cmd, "confirm", 4)) { break; + } cmdmod.confirm = true; continue; - case 'k': if (checkforcmd(&eap->cmd, "keepmarks", 3)) { + case 'k': + if (checkforcmd(&eap->cmd, "keepmarks", 3)) { cmdmod.keepmarks = true; continue; - } + } if (checkforcmd(&eap->cmd, "keepalt", 5)) { cmdmod.keepalt = true; continue; @@ -2117,49 +2143,52 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) continue; case 'f': { // only accept ":filter {pat} cmd" - char_u *reg_pat; + char_u *reg_pat; - if (!checkforcmd(&p, "filter", 4) || *p == NUL || ends_excmd(*p)) { - break; - } - if (*p == '!') { - cmdmod.filter_force = true; - p = skipwhite(p + 1); - if (*p == NUL || ends_excmd(*p)) { + if (!checkforcmd(&p, "filter", 4) || *p == NUL || ends_excmd(*p)) { break; } - } - if (skip_only) { - p = skip_vimgrep_pat(p, NULL, NULL); - } else { - // NOTE: This puts a NUL after the pattern. - p = skip_vimgrep_pat(p, ®_pat, NULL); - } - if (p == NULL || *p == NUL) { - break; - } - if (!skip_only) { - cmdmod.filter_regmatch.regprog = vim_regcomp(reg_pat, RE_MAGIC); - if (cmdmod.filter_regmatch.regprog == NULL) { + if (*p == '!') { + cmdmod.filter_force = true; + p = skipwhite(p + 1); + if (*p == NUL || ends_excmd(*p)) { + break; + } + } + if (skip_only) { + p = skip_vimgrep_pat(p, NULL, NULL); + } else { + // NOTE: This puts a NUL after the pattern. + p = skip_vimgrep_pat(p, ®_pat, NULL); + } + if (p == NULL || *p == NUL) { break; } + if (!skip_only) { + cmdmod.filter_regmatch.regprog = vim_regcomp(reg_pat, RE_MAGIC); + if (cmdmod.filter_regmatch.regprog == NULL) { + break; + } + } + eap->cmd = p; + continue; } - eap->cmd = p; - continue; - } // ":hide" and ":hide | cmd" are not modifiers - case 'h': if (p != eap->cmd || !checkforcmd(&p, "hide", 3) - || *p == NUL || ends_excmd(*p)) + case 'h': + if (p != eap->cmd || !checkforcmd(&p, "hide", 3) + || *p == NUL || ends_excmd(*p)) { break; + } eap->cmd = p; cmdmod.hide = true; continue; - case 'l': if (checkforcmd(&eap->cmd, "lockmarks", 3)) { + case 'l': + if (checkforcmd(&eap->cmd, "lockmarks", 3)) { cmdmod.lockmarks = true; continue; - } + } if (!checkforcmd(&eap->cmd, "leftabove", 5)) { break; @@ -2184,12 +2213,15 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) cmdmod.noswapfile = true; continue; - case 'r': if (!checkforcmd(&eap->cmd, "rightbelow", 6)) + case 'r': + if (!checkforcmd(&eap->cmd, "rightbelow", 6)) { break; + } cmdmod.split |= WSP_BELOW; continue; - case 's': if (checkforcmd(&eap->cmd, "sandbox", 3)) { + case 's': + if (checkforcmd(&eap->cmd, "sandbox", 3)) { if (!skip_only) { if (!eap->did_sandbox) { sandbox++; @@ -2197,7 +2229,7 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) eap->did_sandbox = true; } continue; - } + } if (!checkforcmd(&eap->cmd, "silent", 3)) { break; } @@ -2217,32 +2249,34 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) } continue; - case 't': if (checkforcmd(&p, "tab", 3)) { - if (!skip_only) { - long tabnr = get_address( - eap, &eap->cmd, ADDR_TABS, eap->skip, skip_only, false, 1); + case 't': + if (checkforcmd(&p, "tab", 3)) { + if (!skip_only) { + long tabnr = get_address(eap, &eap->cmd, ADDR_TABS, eap->skip, skip_only, false, 1); - if (tabnr == MAXLNUM) { - cmdmod.tab = tabpage_index(curtab) + 1; - } else { - if (tabnr < 0 || tabnr > LAST_TAB_NR) { - *errormsg = (char_u *)_(e_invrange); - return false; + if (tabnr == MAXLNUM) { + cmdmod.tab = tabpage_index(curtab) + 1; + } else { + if (tabnr < 0 || tabnr > LAST_TAB_NR) { + *errormsg = (char_u *)_(e_invrange); + return false; + } + cmdmod.tab = tabnr + 1; } - cmdmod.tab = tabnr + 1; } + eap->cmd = p; + continue; } - eap->cmd = p; - continue; - } if (!checkforcmd(&eap->cmd, "topleft", 2)) { break; } cmdmod.split |= WSP_TOP; continue; - case 'u': if (!checkforcmd(&eap->cmd, "unsilent", 3)) + case 'u': + if (!checkforcmd(&eap->cmd, "unsilent", 3)) { break; + } if (!skip_only) { if (eap->save_msg_silent == -1) { eap->save_msg_silent = msg_silent; @@ -2251,12 +2285,14 @@ int parse_command_modifiers(exarg_T *eap, char_u **errormsg, bool skip_only) } continue; - case 'v': if (checkforcmd(&eap->cmd, "vertical", 4)) { + case 'v': + if (checkforcmd(&eap->cmd, "vertical", 4)) { cmdmod.split |= WSP_VERT; continue; - } - if (!checkforcmd(&p, "verbose", 4)) + } + if (!checkforcmd(&p, "verbose", 4)) { break; + } if (!skip_only) { if (eap->verbose_save < 0) { eap->verbose_save = p_verbose; @@ -2328,40 +2364,40 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) for (;;) { eap->line1 = eap->line2; switch (eap->addr_type) { - case ADDR_LINES: - case ADDR_OTHER: - // default is current line number - eap->line2 = curwin->w_cursor.lnum; - break; - case ADDR_WINDOWS: - eap->line2 = CURRENT_WIN_NR; - break; - case ADDR_ARGUMENTS: - eap->line2 = curwin->w_arg_idx + 1; - if (eap->line2 > ARGCOUNT) { - eap->line2 = ARGCOUNT; - } - break; - case ADDR_LOADED_BUFFERS: - case ADDR_BUFFERS: - eap->line2 = curbuf->b_fnum; - break; - case ADDR_TABS: - eap->line2 = CURRENT_TAB_NR; - break; - case ADDR_TABS_RELATIVE: - case ADDR_UNSIGNED: - eap->line2 = 1; - break; - case ADDR_QUICKFIX: - eap->line2 = qf_get_cur_idx(eap); - break; - case ADDR_QUICKFIX_VALID: - eap->line2 = qf_get_cur_valid_idx(eap); - break; - case ADDR_NONE: - // Will give an error later if a range is found. - break; + case ADDR_LINES: + case ADDR_OTHER: + // default is current line number + eap->line2 = curwin->w_cursor.lnum; + break; + case ADDR_WINDOWS: + eap->line2 = CURRENT_WIN_NR; + break; + case ADDR_ARGUMENTS: + eap->line2 = curwin->w_arg_idx + 1; + if (eap->line2 > ARGCOUNT) { + eap->line2 = ARGCOUNT; + } + break; + case ADDR_LOADED_BUFFERS: + case ADDR_BUFFERS: + eap->line2 = curbuf->b_fnum; + break; + case ADDR_TABS: + eap->line2 = CURRENT_TAB_NR; + break; + case ADDR_TABS_RELATIVE: + case ADDR_UNSIGNED: + eap->line2 = 1; + break; + case ADDR_QUICKFIX: + eap->line2 = qf_get_cur_idx(eap); + break; + case ADDR_QUICKFIX_VALID: + eap->line2 = qf_get_cur_valid_idx(eap); + break; + case ADDR_NONE: + // Will give an error later if a range is found. + break; } eap->cmd = skipwhite(eap->cmd); lnum = get_address(eap, &eap->cmd, eap->addr_type, eap->skip, silent, @@ -2373,12 +2409,12 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) if (*eap->cmd == '%') { // '%' - all lines eap->cmd++; switch (eap->addr_type) { - case ADDR_LINES: - case ADDR_OTHER: - eap->line1 = 1; - eap->line2 = curbuf->b_ml.ml_line_count; - break; - case ADDR_LOADED_BUFFERS: { + case ADDR_LINES: + case ADDR_OTHER: + eap->line1 = 1; + eap->line2 = curbuf->b_ml.ml_line_count; + break; + case ADDR_LOADED_BUFFERS: { buf_T *buf = firstbuf; while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) { @@ -2392,46 +2428,46 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) eap->line2 = buf->b_fnum; break; } - case ADDR_BUFFERS: - eap->line1 = firstbuf->b_fnum; - eap->line2 = lastbuf->b_fnum; - break; - case ADDR_WINDOWS: - case ADDR_TABS: - if (IS_USER_CMDIDX(eap->cmdidx)) { - eap->line1 = 1; - eap->line2 = eap->addr_type == ADDR_WINDOWS + case ADDR_BUFFERS: + eap->line1 = firstbuf->b_fnum; + eap->line2 = lastbuf->b_fnum; + break; + case ADDR_WINDOWS: + case ADDR_TABS: + if (IS_USER_CMDIDX(eap->cmdidx)) { + eap->line1 = 1; + eap->line2 = eap->addr_type == ADDR_WINDOWS ? LAST_WIN_NR : LAST_TAB_NR; - } else { - // there is no Vim command which uses '%' and - // ADDR_WINDOWS or ADDR_TABS - *errormsg = (char_u *)_(e_invrange); - return FAIL; - } - break; - case ADDR_TABS_RELATIVE: - case ADDR_UNSIGNED: - case ADDR_QUICKFIX: + } else { + // there is no Vim command which uses '%' and + // ADDR_WINDOWS or ADDR_TABS *errormsg = (char_u *)_(e_invrange); return FAIL; - case ADDR_ARGUMENTS: - if (ARGCOUNT == 0) { - eap->line1 = eap->line2 = 0; - } else { - eap->line1 = 1; - eap->line2 = ARGCOUNT; - } - break; - case ADDR_QUICKFIX_VALID: + } + break; + case ADDR_TABS_RELATIVE: + case ADDR_UNSIGNED: + case ADDR_QUICKFIX: + *errormsg = (char_u *)_(e_invrange); + return FAIL; + case ADDR_ARGUMENTS: + if (ARGCOUNT == 0) { + eap->line1 = eap->line2 = 0; + } else { eap->line1 = 1; - eap->line2 = qf_get_valid_size(eap); - if (eap->line2 == 0) { - eap->line2 = 1; - } - break; - case ADDR_NONE: - // Will give an error later if a range is found. - break; + eap->line2 = ARGCOUNT; + } + break; + case ADDR_QUICKFIX_VALID: + eap->line1 = 1; + eap->line2 = qf_get_valid_size(eap); + if (eap->line2 == 0) { + eap->line2 = 1; + } + break; + case ADDR_NONE: + // Will give an error later if a range is found. + break; } eap->addr_count++; } else if (*eap->cmd == '*') { @@ -2487,22 +2523,21 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) return OK; } -/* - * Check for an Ex command with optional tail. - * If there is a match advance "pp" to the argument and return TRUE. - */ -int -checkforcmd( - char_u **pp, // start of command - char *cmd, // name of command - int len // required length -) +/// Check for an Ex command with optional tail. +/// If there is a match advance "pp" to the argument and return TRUE. +/// +/// @param pp start of command +/// @param cmd name of command +/// @param len required length +int checkforcmd(char_u **pp, char *cmd, int len) { int i; - for (i = 0; cmd[i] != NUL; ++i) - if (((char_u *)cmd)[i] != (*pp)[i]) + for (i = 0; cmd[i] != NUL; ++i) { + if (((char_u *)cmd)[i] != (*pp)[i]) { break; + } + } if (i >= len && !isalpha((*pp)[i])) { *pp = skipwhite(*pp + i); return TRUE; @@ -2527,8 +2562,9 @@ static void append_command(char_u *cmd) s += 2; STRCPY(d, "<a0>"); d += 4; - } else + } else { MB_COPY_CHAR(s, d); + } } *d = NUL; } @@ -2542,7 +2578,7 @@ static char_u *find_command(exarg_T *eap, int *full) FUNC_ATTR_NONNULL_ARG(1) { int len; - char_u *p; + char_u *p; int i; /* @@ -2550,8 +2586,8 @@ static char_u *find_command(exarg_T *eap, int *full) * Exceptions: * - the 'k' command can directly be followed by any character. * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r' - * but :sre[wind] is another command, as are :scr[iptnames], - * :scs[cope], :sim[alt], :sig[ns] and :sil[ent]. + * but :sre[wind] is another command, as are :scr[iptnames], + * :scs[cope], :sim[alt], :sig[ns] and :sil[ent]. * - the "d" command can directly be followed by 'l' or 'p' flag. */ p = eap->cmd; @@ -2571,29 +2607,36 @@ static char_u *find_command(exarg_T *eap, int *full) eap->cmdidx = CMD_substitute; ++p; } else { - while (ASCII_ISALPHA(*p)) + while (ASCII_ISALPHA(*p)) { ++p; - /* for python 3.x support ":py3", ":python3", ":py3file", etc. */ - if (eap->cmd[0] == 'p' && eap->cmd[1] == 'y') - while (ASCII_ISALNUM(*p)) + } + // for python 3.x support ":py3", ":python3", ":py3file", etc. + if (eap->cmd[0] == 'p' && eap->cmd[1] == 'y') { + while (ASCII_ISALNUM(*p)) { ++p; + } + } - /* check for non-alpha command */ - if (p == eap->cmd && vim_strchr((char_u *)"@!=><&~#", *p) != NULL) + // check for non-alpha command + if (p == eap->cmd && vim_strchr((char_u *)"@!=><&~#", *p) != NULL) { ++p; + } len = (int)(p - eap->cmd); if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p')) { /* Check for ":dl", ":dell", etc. to ":deletel": that's * :delete with the 'l' flag. Same for 'p'. */ - for (i = 0; i < len; ++i) - if (eap->cmd[i] != ((char_u *)"delete")[i]) + for (i = 0; i < len; ++i) { + if (eap->cmd[i] != ((char_u *)"delete")[i]) { break; + } + } if (i == len - 1) { --len; - if (p[-1] == 'l') + if (p[-1] == 'l') { eap->flags |= EXFLAG_LIST; - else + } else { eap->flags |= EXFLAG_PRINT; + } } } @@ -2617,52 +2660,52 @@ static char_u *find_command(exarg_T *eap, int *full) } for (; (int)eap->cmdidx < (int)CMD_SIZE; - eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1)) + eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1)) { if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd, - (size_t)len) == 0) { + (size_t)len) == 0) { if (full != NULL - && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL) + && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL) { *full = TRUE; + } break; } + } // Look for a user defined command as a last resort. if ((eap->cmdidx == CMD_SIZE) && *eap->cmd >= 'A' && *eap->cmd <= 'Z') { - /* User defined commands may contain digits. */ - while (ASCII_ISALNUM(*p)) + // User defined commands may contain digits. + while (ASCII_ISALNUM(*p)) { ++p; + } p = find_ucmd(eap, p, full, NULL, NULL); } - if (p == eap->cmd) + if (p == eap->cmd) { eap->cmdidx = CMD_SIZE; + } } return p; } -/* - * Search for a user command that matches "eap->cmd". - * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx". - * Return a pointer to just after the command. - * Return NULL if there is no matching command. - */ -static char_u * -find_ucmd ( - exarg_T *eap, - char_u *p, // end of the command (possibly including count) - int *full, // set to TRUE for a full match - expand_T *xp, // used for completion, NULL otherwise - int *complp // completion flags or NULL -) +/// Search for a user command that matches "eap->cmd". +/// Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx". +/// Return a pointer to just after the command. +/// Return NULL if there is no matching command. +/// +/// @param *p end of the command (possibly including count) +/// @param full set to TRUE for a full match +/// @param xp used for completion, NULL otherwise +/// @param complp completion flags or NULL +static char_u *find_ucmd(exarg_T *eap, char_u *p, int *full, expand_T *xp, int *complp) { int len = (int)(p - eap->cmd); int j, k, matchlen = 0; - ucmd_T *uc; + ucmd_T *uc; int found = FALSE; int possible = FALSE; - char_u *cp, *np; /* Point into typed cmd and test name */ - garray_T *gap; + char_u *cp, *np; // Point into typed cmd and test name + garray_T *gap; int amb_local = FALSE; /* Found ambiguous buffer-local command, only full match global is accepted. */ @@ -2676,15 +2719,17 @@ find_ucmd ( cp = eap->cmd; np = uc->uc_name; k = 0; - while (k < len && *np != NUL && *cp++ == *np++) + while (k < len && *np != NUL && *cp++ == *np++) { k++; + } if (k == len || (*np == NUL && ascii_isdigit(eap->cmd[k]))) { /* If finding a second match, the command is ambiguous. But * not if a buffer-local command wasn't a full match and a * global command is a full match. */ if (k == len && found && *np != NUL) { - if (gap == &ucmds) + if (gap == &ucmds) { return NULL; + } amb_local = TRUE; } @@ -2693,15 +2738,17 @@ find_ucmd ( * be another command including the digit that we * should use instead. */ - if (k == len) + if (k == len) { found = TRUE; - else + } else { possible = TRUE; + } - if (gap == &ucmds) + if (gap == &ucmds) { eap->cmdidx = CMD_USER; - else + } else { eap->cmdidx = CMD_USER_BUF; + } eap->argt = uc->uc_argt; eap->useridx = j; eap->addr_type = uc->uc_addr_type; @@ -2718,8 +2765,9 @@ find_ucmd ( * if this is an exact match. */ matchlen = k; if (k == len && *np == NUL) { - if (full != NULL) + if (full != NULL) { *full = TRUE; + } amb_local = FALSE; break; } @@ -2727,30 +2775,33 @@ find_ucmd ( } } - /* Stop if we found a full match or searched all. */ - if (j < gap->ga_len || gap == &ucmds) + // Stop if we found a full match or searched all. + if (j < gap->ga_len || gap == &ucmds) { break; + } gap = &ucmds; } - /* Only found ambiguous matches. */ + // Only found ambiguous matches. if (amb_local) { - if (xp != NULL) + if (xp != NULL) { xp->xp_context = EXPAND_UNSUCCESSFUL; + } return NULL; } /* The match we found may be followed immediately by a number. Move "p" * back to point to it. */ - if (found || possible) + if (found || possible) { return p + (matchlen - len); + } return p; } static struct cmdmod { - char *name; + char *name; int minlen; - int has_count; /* :123verbose :3tab */ + int has_count; // :123verbose :3tab } cmdmods[] = { { "aboveleft", 3, false }, { "belowright", 3, false }, @@ -2783,7 +2834,7 @@ static struct cmdmod { */ int modifier_len(char_u *cmd) { - char_u *p = cmd; + char_u *p = cmd; if (ascii_isdigit(*cmd)) { p = skipwhite(skipdigits(cmd + 1)); @@ -2812,7 +2863,7 @@ int modifier_len(char_u *cmd) int cmd_exists(const char *const name) { exarg_T ea; - char_u *p; + char_u *p; // Check command modifiers. for (int i = 0; i < (int)ARRAY_SIZE(cmdmods); i++) { @@ -2833,26 +2884,26 @@ int cmd_exists(const char *const name) ea.cmdidx = (cmdidx_T)0; int full = false; p = find_command(&ea, &full); - if (p == NULL) + if (p == NULL) { return 3; - if (ascii_isdigit(*name) && ea.cmdidx != CMD_match) + } + if (ascii_isdigit(*name) && ea.cmdidx != CMD_match) { return 0; - if (*skipwhite(p) != NUL) - return 0; /* trailing garbage */ + } + if (*skipwhite(p) != NUL) { + return 0; // trailing garbage + } return ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1); } -/* - * This is all pretty much copied from do_one_cmd(), with all the extra stuff - * we don't need/want deleted. Maybe this could be done better if we didn't - * repeat all this stuff. The only problem is that they may not stay - * perfectly compatible with each other, but then the command line syntax - * probably won't change that much -- webb. - */ -const char * set_one_cmd_context( - expand_T *xp, - const char *buff // buffer for command string -) +/// This is all pretty much copied from do_one_cmd(), with all the extra stuff +/// we don't need/want deleted. Maybe this could be done better if we didn't +/// repeat all this stuff. The only problem is that they may not stay +/// perfectly compatible with each other, but then the command line syntax +/// probably won't change that much -- webb. +/// +/// @param buff buffer for command string +const char * set_one_cmd_context(expand_T *xp, const char *buff) { size_t len = 0; exarg_T ea; @@ -2871,9 +2922,10 @@ const char * set_one_cmd_context( } xp->xp_pattern = (char_u *)cmd; - if (*cmd == NUL) + if (*cmd == NUL) { return NULL; - if (*cmd == '"') { /* ignore comment lines */ + } + if (*cmd == '"') { // ignore comment lines xp->xp_context = EXPAND_NOTHING; return NULL; } @@ -2895,9 +2947,9 @@ const char * set_one_cmd_context( return NULL; } - if (*cmd == '|' || *cmd == '\n') - return cmd + 1; /* There's another command */ - + if (*cmd == '|' || *cmd == '\n') { + return cmd + 1; // There's another command + } /* * Isolate the command and search for it in the command table. * Exceptions: @@ -2972,12 +3024,12 @@ const char * set_one_cmd_context( } } if (ea.cmdidx == CMD_SIZE) { - /* Not still touching the command and it was an illegal one */ + // Not still touching the command and it was an illegal one xp->xp_context = EXPAND_UNSUCCESSFUL; return NULL; } - xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */ + xp->xp_context = EXPAND_NOTHING; // Default now that we're past command if (*p == '!') { // forced commands forceit = true; @@ -3050,9 +3102,10 @@ const char * set_one_cmd_context( */ if ((ea.argt & EX_TRLBAR) && !usefilter) { p = arg; - /* ":redir @" is not the start of a comment */ - if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"') + // ":redir @" is not the start of a comment + if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"') { p += 2; + } while (*p) { if (*p == Ctrl_V) { if (p[1] != NUL) { @@ -3062,9 +3115,10 @@ const char * set_one_cmd_context( || *p == '|' || *p == '\n') { if (*(p - 1) != '\\') { - if (*p == '|' || *p == '\n') + if (*p == '|' || *p == '\n') { return p + 1; - return NULL; /* It's a comment */ + } + return NULL; // It's a comment } } MB_PTR_ADV(p); @@ -3076,7 +3130,7 @@ const char * set_one_cmd_context( return NULL; } - /* Find start of last argument (argument just before cursor): */ + // Find start of last argument (argument just before cursor): p = buff; xp->xp_pattern = (char_u *)p; len = strlen(buff); @@ -3117,10 +3171,10 @@ const char * set_one_cmd_context( /* An argument can contain just about everything, except * characters that end the command and white space. */ else if (c == '|' - || c == '\n' - || c == '"' - || ascii_iswhite(c)) { - len = 0; /* avoid getting stuck when space is in 'isfname' */ + || c == '\n' + || c == '"' + || ascii_iswhite(c)) { + len = 0; // avoid getting stuck when space is in 'isfname' while (*p != NUL) { c = utf_ptr2char((const char_u *)p); if (c == '`' || vim_isfilec_or_wc(c)) { @@ -3148,7 +3202,7 @@ const char * set_one_cmd_context( } xp->xp_context = EXPAND_FILES; - /* For a shell command more chars need to be escaped. */ + // For a shell command more chars need to be escaped. if (usefilter || ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal) { #ifndef BACKSLASH_IN_FILENAME xp->xp_shell = TRUE; @@ -3175,7 +3229,7 @@ const char * set_one_cmd_context( } } } - /* Check for user names */ + // Check for user names if (*xp->xp_pattern == '~') { for (p = (const char *)xp->xp_pattern + 1; *p != NUL && *p != '/'; p++) { } @@ -3197,8 +3251,9 @@ const char * set_one_cmd_context( case CMD_find: case CMD_sfind: case CMD_tabfind: - if (xp->xp_context == EXPAND_FILES) + if (xp->xp_context == EXPAND_FILES) { xp->xp_context = EXPAND_FILES_IN_PATH; + } break; case CMD_cd: case CMD_chdir: @@ -3263,7 +3318,7 @@ const char * set_one_cmd_context( case CMD_match: if (*arg == NUL || !ends_excmd(*arg)) { - /* also complete "None" */ + // also complete "None" set_context_in_echohl_cmd(xp, arg); arg = (const char *)skipwhite(skiptowhite((const char_u *)arg)); if (*arg != NUL) { @@ -3279,7 +3334,7 @@ const char * set_one_cmd_context( */ case CMD_command: - /* Check for attributes */ + // Check for attributes while (*arg == '-') { arg++; // Skip "-". p = (const char *)skiptowhite((const char_u *)arg); @@ -3331,47 +3386,48 @@ const char * set_one_cmd_context( case CMD_global: case CMD_vglobal: { - const int delim = (uint8_t)(*arg); // Get the delimiter. - if (delim) { - arg++; // Skip delimiter if there is one. - } + const int delim = (uint8_t)(*arg); // Get the delimiter. + if (delim) { + arg++; // Skip delimiter if there is one. + } - while (arg[0] != NUL && (uint8_t)arg[0] != delim) { - if (arg[0] == '\\' && arg[1] != NUL) { + while (arg[0] != NUL && (uint8_t)arg[0] != delim) { + if (arg[0] == '\\' && arg[1] != NUL) { + arg++; + } arg++; } - arg++; + if (arg[0] != NUL) { + return arg + 1; + } + break; } - if (arg[0] != NUL) - return arg + 1; - break; - } case CMD_and: case CMD_substitute: { - const int delim = (uint8_t)(*arg); - if (delim) { - // Skip "from" part. - arg++; - arg = (const char *)skip_regexp((char_u *)arg, delim, p_magic, NULL); - } - // Skip "to" part. - while (arg[0] != NUL && (uint8_t)arg[0] != delim) { - if (arg[0] == '\\' && arg[1] != NUL) { + const int delim = (uint8_t)(*arg); + if (delim) { + // Skip "from" part. arg++; + arg = (const char *)skip_regexp((char_u *)arg, delim, p_magic, NULL); } - arg++; - } - if (arg[0] != NUL) { // Skip delimiter. - arg++; - } - while (arg[0] && strchr("|\"#", arg[0]) == NULL) { - arg++; - } - if (arg[0] != NUL) { - return arg; + // Skip "to" part. + while (arg[0] != NUL && (uint8_t)arg[0] != delim) { + if (arg[0] == '\\' && arg[1] != NUL) { + arg++; + } + arg++; + } + if (arg[0] != NUL) { // Skip delimiter. + arg++; + } + while (arg[0] && strchr("|\"#", arg[0]) == NULL) { + arg++; + } + if (arg[0] != NUL) { + return arg; + } + break; } - break; - } case CMD_isearch: case CMD_dsearch: case CMD_ilist: @@ -3528,9 +3584,9 @@ const char * set_one_cmd_context( } else if (context == EXPAND_COMMANDS) { return arg; } else if (context == EXPAND_MAPPINGS) { - return (const char *)set_context_in_map_cmd( - xp, (char_u *)"map", (char_u *)arg, forceit, false, false, - CMD_map); + return (const char *)set_context_in_map_cmd(xp, (char_u *)"map", (char_u *)arg, forceit, + false, false, + CMD_map); } // Find start of last argument. p = arg; @@ -3548,17 +3604,26 @@ const char * set_one_cmd_context( xp->xp_context = context; } break; - case CMD_map: case CMD_noremap: - case CMD_nmap: case CMD_nnoremap: - case CMD_vmap: case CMD_vnoremap: - case CMD_omap: case CMD_onoremap: - case CMD_imap: case CMD_inoremap: - case CMD_cmap: case CMD_cnoremap: - case CMD_lmap: case CMD_lnoremap: - case CMD_smap: case CMD_snoremap: - case CMD_xmap: case CMD_xnoremap: - return (const char *)set_context_in_map_cmd( - xp, (char_u *)cmd, (char_u *)arg, forceit, false, false, ea.cmdidx); + case CMD_map: + case CMD_noremap: + case CMD_nmap: + case CMD_nnoremap: + case CMD_vmap: + case CMD_vnoremap: + case CMD_omap: + case CMD_onoremap: + case CMD_imap: + case CMD_inoremap: + case CMD_cmap: + case CMD_cnoremap: + case CMD_lmap: + case CMD_lnoremap: + case CMD_smap: + case CMD_snoremap: + case CMD_xmap: + case CMD_xnoremap: + return (const char *)set_context_in_map_cmd(xp, (char_u *)cmd, (char_u *)arg, forceit, false, + false, ea.cmdidx); case CMD_unmap: case CMD_nunmap: case CMD_vunmap: @@ -3568,8 +3633,8 @@ const char * set_one_cmd_context( case CMD_lunmap: case CMD_sunmap: case CMD_xunmap: - return (const char *)set_context_in_map_cmd( - xp, (char_u *)cmd, (char_u *)arg, forceit, false, true, ea.cmdidx); + return (const char *)set_context_in_map_cmd(xp, (char_u *)cmd, (char_u *)arg, forceit, false, + true, ea.cmdidx); case CMD_mapclear: case CMD_nmapclear: case CMD_vmapclear: @@ -3583,27 +3648,45 @@ const char * set_one_cmd_context( xp->xp_pattern = (char_u *)arg; break; - case CMD_abbreviate: case CMD_noreabbrev: - case CMD_cabbrev: case CMD_cnoreabbrev: - case CMD_iabbrev: case CMD_inoreabbrev: - return (const char *)set_context_in_map_cmd( - xp, (char_u *)cmd, (char_u *)arg, forceit, true, false, ea.cmdidx); + case CMD_abbreviate: + case CMD_noreabbrev: + case CMD_cabbrev: + case CMD_cnoreabbrev: + case CMD_iabbrev: + case CMD_inoreabbrev: + return (const char *)set_context_in_map_cmd(xp, (char_u *)cmd, (char_u *)arg, forceit, true, + false, ea.cmdidx); case CMD_unabbreviate: case CMD_cunabbrev: case CMD_iunabbrev: - return (const char *)set_context_in_map_cmd( - xp, (char_u *)cmd, (char_u *)arg, forceit, true, true, ea.cmdidx); - case CMD_menu: case CMD_noremenu: case CMD_unmenu: - case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu: - case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu: - case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu: - case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu: - case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu: - case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu: - case CMD_tmenu: case CMD_tunmenu: - case CMD_popup: case CMD_emenu: - return (const char *)set_context_in_menu_cmd( - xp, cmd, (char_u *)arg, forceit); + return (const char *)set_context_in_map_cmd(xp, (char_u *)cmd, (char_u *)arg, forceit, true, + true, ea.cmdidx); + case CMD_menu: + case CMD_noremenu: + case CMD_unmenu: + case CMD_amenu: + case CMD_anoremenu: + case CMD_aunmenu: + case CMD_nmenu: + case CMD_nnoremenu: + case CMD_nunmenu: + case CMD_vmenu: + case CMD_vnoremenu: + case CMD_vunmenu: + case CMD_omenu: + case CMD_onoremenu: + case CMD_ounmenu: + case CMD_imenu: + case CMD_inoremenu: + case CMD_iunmenu: + case CMD_cmenu: + case CMD_cnoremenu: + case CMD_cunmenu: + case CMD_tmenu: + case CMD_tunmenu: + case CMD_popup: + case CMD_emenu: + return (const char *)set_context_in_menu_cmd(xp, cmd, (char_u *)arg, forceit); case CMD_colorscheme: xp->xp_context = EXPAND_COLORS; @@ -3693,17 +3776,17 @@ const char * set_one_cmd_context( return NULL; } -// Skip a range specifier of the form: addr [,addr] [;addr] .. -// -// Backslashed delimiters after / or ? will be skipped, and commands will -// not be expanded between /'s and ?'s or after "'". -// -// Also skip white space and ":" characters. -// Returns the "cmd" pointer advanced to beyond the range. -char_u *skip_range( - const char_u *cmd, - int *ctx // pointer to xp_context or NULL -) +/// Skip a range specifier of the form: addr [,addr] [;addr] .. +/// +/// Backslashed delimiters after / or ? will be skipped, and commands will +/// not be expanded between /'s and ?'s or after "'". +/// +/// Also skip white space and ":" characters. +/// +/// @param ctx pointer to xp_context or NULL +/// +/// @return the "cmd" pointer advanced to beyond the range. +char_u *skip_range(const char_u *cmd, int *ctx) { unsigned delim; @@ -3720,14 +3803,18 @@ char_u *skip_range( } } else if (*cmd == '/' || *cmd == '?') { delim = *cmd++; - while (*cmd != NUL && *cmd != delim) - if (*cmd++ == '\\' && *cmd != NUL) + while (*cmd != NUL && *cmd != delim) { + if (*cmd++ == '\\' && *cmd != NUL) { ++cmd; - if (*cmd == NUL && ctx != NULL) + } + } + if (*cmd == NUL && ctx != NULL) { *ctx = EXPAND_NOTHING; + } } - if (*cmd != NUL) + if (*cmd != NUL) { ++cmd; + } } // Skip ":" and white space. @@ -3745,28 +3832,28 @@ static void addr_error(cmd_addr_T addr_type) } } -// Get a single EX address -// -// Set ptr to the next character after the part that was interpreted. -// Set ptr to NULL when an error is encountered. -// This may set the last used search pattern. -// -// Return MAXLNUM when no Ex address was found. -static linenr_T get_address(exarg_T *eap, - char_u **ptr, - cmd_addr_T addr_type, - int skip, // only skip the address, don't use it - bool silent, // no errors or side effects - int to_other_file, // flag: may jump to other file - int address_count) // 1 for first, >1 after comma +/// Get a single EX address +/// +/// Set ptr to the next character after the part that was interpreted. +/// Set ptr to NULL when an error is encountered. +/// This may set the last used search pattern. +/// +/// @param skip only skip the address, don't use it +/// @param silent no errors or side effects +/// @param to_other_file flag: may jump to other file +/// @param address_count 1 for first, >1 after comma +/// +/// @return MAXLNUM when no Ex address was found. +static linenr_T get_address(exarg_T *eap, char_u **ptr, cmd_addr_T addr_type, int skip, bool silent, + int to_other_file, int address_count) FUNC_ATTR_NONNULL_ALL { int c; int i; long n; - char_u *cmd; + char_u *cmd; pos_T pos; - pos_T *fp; + pos_T *fp; linenr_T lnum; buf_T *buf; @@ -3774,94 +3861,94 @@ static linenr_T get_address(exarg_T *eap, lnum = MAXLNUM; do { switch (*cmd) { - case '.': /* '.' - Cursor position */ + case '.': // '.' - Cursor position ++cmd; switch (addr_type) { - case ADDR_LINES: - case ADDR_OTHER: - lnum = curwin->w_cursor.lnum; - break; - case ADDR_WINDOWS: - lnum = CURRENT_WIN_NR; - break; - case ADDR_ARGUMENTS: - lnum = curwin->w_arg_idx + 1; - break; - case ADDR_LOADED_BUFFERS: - case ADDR_BUFFERS: - lnum = curbuf->b_fnum; - break; - case ADDR_TABS: - lnum = CURRENT_TAB_NR; - break; - case ADDR_NONE: - case ADDR_TABS_RELATIVE: - case ADDR_UNSIGNED: - addr_error(addr_type); - cmd = NULL; - goto error; - break; - case ADDR_QUICKFIX: - lnum = qf_get_cur_idx(eap); - break; - case ADDR_QUICKFIX_VALID: - lnum = qf_get_cur_valid_idx(eap); - break; + case ADDR_LINES: + case ADDR_OTHER: + lnum = curwin->w_cursor.lnum; + break; + case ADDR_WINDOWS: + lnum = CURRENT_WIN_NR; + break; + case ADDR_ARGUMENTS: + lnum = curwin->w_arg_idx + 1; + break; + case ADDR_LOADED_BUFFERS: + case ADDR_BUFFERS: + lnum = curbuf->b_fnum; + break; + case ADDR_TABS: + lnum = CURRENT_TAB_NR; + break; + case ADDR_NONE: + case ADDR_TABS_RELATIVE: + case ADDR_UNSIGNED: + addr_error(addr_type); + cmd = NULL; + goto error; + break; + case ADDR_QUICKFIX: + lnum = qf_get_cur_idx(eap); + break; + case ADDR_QUICKFIX_VALID: + lnum = qf_get_cur_valid_idx(eap); + break; } break; - case '$': /* '$' - last line */ + case '$': // '$' - last line ++cmd; switch (addr_type) { - case ADDR_LINES: - case ADDR_OTHER: - lnum = curbuf->b_ml.ml_line_count; - break; - case ADDR_WINDOWS: - lnum = LAST_WIN_NR; - break; - case ADDR_ARGUMENTS: - lnum = ARGCOUNT; - break; - case ADDR_LOADED_BUFFERS: - buf = lastbuf; - while (buf->b_ml.ml_mfp == NULL) { - if (buf->b_prev == NULL) { - break; - } - buf = buf->b_prev; - } - lnum = buf->b_fnum; - break; - case ADDR_BUFFERS: - lnum = lastbuf->b_fnum; - break; - case ADDR_TABS: - lnum = LAST_TAB_NR; - break; - case ADDR_NONE: - case ADDR_TABS_RELATIVE: - case ADDR_UNSIGNED: - addr_error(addr_type); - cmd = NULL; - goto error; - break; - case ADDR_QUICKFIX: - lnum = qf_get_size(eap); - if (lnum == 0) { - lnum = 1; - } - break; - case ADDR_QUICKFIX_VALID: - lnum = qf_get_valid_size(eap); - if (lnum == 0) { - lnum = 1; + case ADDR_LINES: + case ADDR_OTHER: + lnum = curbuf->b_ml.ml_line_count; + break; + case ADDR_WINDOWS: + lnum = LAST_WIN_NR; + break; + case ADDR_ARGUMENTS: + lnum = ARGCOUNT; + break; + case ADDR_LOADED_BUFFERS: + buf = lastbuf; + while (buf->b_ml.ml_mfp == NULL) { + if (buf->b_prev == NULL) { + break; } - break; + buf = buf->b_prev; + } + lnum = buf->b_fnum; + break; + case ADDR_BUFFERS: + lnum = lastbuf->b_fnum; + break; + case ADDR_TABS: + lnum = LAST_TAB_NR; + break; + case ADDR_NONE: + case ADDR_TABS_RELATIVE: + case ADDR_UNSIGNED: + addr_error(addr_type); + cmd = NULL; + goto error; + break; + case ADDR_QUICKFIX: + lnum = qf_get_size(eap); + if (lnum == 0) { + lnum = 1; + } + break; + case ADDR_QUICKFIX_VALID: + lnum = qf_get_valid_size(eap); + if (lnum == 0) { + lnum = 1; + } + break; } break; - case '\'': /* ''' - mark */ + case '\'': // ''' - mark if (*++cmd == NUL) { cmd = NULL; goto error; @@ -3871,17 +3958,17 @@ static linenr_T get_address(exarg_T *eap, cmd = NULL; goto error; } - if (skip) + if (skip) { ++cmd; - else { + } else { /* Only accept a mark in another file when it is * used by itself: ":'M". */ fp = getmark(*cmd, to_other_file && cmd[1] == NUL); ++cmd; - if (fp == (pos_T *)-1) - /* Jumped to another file. */ + if (fp == (pos_T *)-1) { + // Jumped to another file. lnum = curwin->w_cursor.lnum; - else { + } else { if (check_mark(fp) == FAIL) { cmd = NULL; goto error; @@ -3892,17 +3979,18 @@ static linenr_T get_address(exarg_T *eap, break; case '/': - case '?': /* '/' or '?' - search */ + case '?': // '/' or '?' - search c = *cmd++; if (addr_type != ADDR_LINES) { addr_error(addr_type); cmd = NULL; goto error; } - if (skip) { /* skip "/pat/" */ + if (skip) { // skip "/pat/" cmd = skip_regexp(cmd, c, p_magic, NULL); - if (*cmd == c) + if (*cmd == c) { ++cmd; + } } else { int flags; @@ -3934,23 +4022,23 @@ static linenr_T get_address(exarg_T *eap, } lnum = curwin->w_cursor.lnum; curwin->w_cursor = pos; - /* adjust command string pointer */ + // adjust command string pointer cmd += searchcmdlen; } break; - case '\\': /* "\?", "\/" or "\&", repeat search */ + case '\\': // "\?", "\/" or "\&", repeat search ++cmd; if (addr_type != ADDR_LINES) { addr_error(addr_type); cmd = NULL; goto error; } - if (*cmd == '&') + if (*cmd == '&') { i = RE_SUBST; - else if (*cmd == '?' || *cmd == '/') + } else if (*cmd == '?' || *cmd == '/') { i = RE_SEARCH; - else { + } else { EMSG(_(e_backslash)); cmd = NULL; goto error; @@ -3988,37 +4076,37 @@ static linenr_T get_address(exarg_T *eap, if (lnum == MAXLNUM) { switch (addr_type) { - case ADDR_LINES: - case ADDR_OTHER: - // "+1" is same as ".+1" - lnum = curwin->w_cursor.lnum; - break; - case ADDR_WINDOWS: - lnum = CURRENT_WIN_NR; - break; - case ADDR_ARGUMENTS: - lnum = curwin->w_arg_idx + 1; - break; - case ADDR_LOADED_BUFFERS: - case ADDR_BUFFERS: - lnum = curbuf->b_fnum; - break; - case ADDR_TABS: - lnum = CURRENT_TAB_NR; - break; - case ADDR_TABS_RELATIVE: - lnum = 1; - break; - case ADDR_QUICKFIX: - lnum = qf_get_cur_idx(eap); - break; - case ADDR_QUICKFIX_VALID: - lnum = qf_get_cur_valid_idx(eap); - break; - case ADDR_NONE: - case ADDR_UNSIGNED: - lnum = 0; - break; + case ADDR_LINES: + case ADDR_OTHER: + // "+1" is same as ".+1" + lnum = curwin->w_cursor.lnum; + break; + case ADDR_WINDOWS: + lnum = CURRENT_WIN_NR; + break; + case ADDR_ARGUMENTS: + lnum = curwin->w_arg_idx + 1; + break; + case ADDR_LOADED_BUFFERS: + case ADDR_BUFFERS: + lnum = curbuf->b_fnum; + break; + case ADDR_TABS: + lnum = CURRENT_TAB_NR; + break; + case ADDR_TABS_RELATIVE: + lnum = 1; + break; + case ADDR_QUICKFIX: + lnum = qf_get_cur_idx(eap); + break; + case ADDR_QUICKFIX_VALID: + lnum = qf_get_cur_valid_idx(eap); + break; + case ADDR_NONE: + case ADDR_UNSIGNED: + lnum = 0; + break; } } @@ -4038,8 +4126,7 @@ static linenr_T get_address(exarg_T *eap, cmd = NULL; goto error; } else if (addr_type == ADDR_LOADED_BUFFERS || addr_type == ADDR_BUFFERS) { - lnum = compute_buffer_local_count( - addr_type, lnum, (i == '-') ? -1 * n : n); + lnum = compute_buffer_local_count(addr_type, lnum, (i == '-') ? -1 * n : n); } else { // Relative line addressing, need to adjust for folded lines // now, but only do it after the first address. @@ -4067,12 +4154,13 @@ error: static void get_flags(exarg_T *eap) { while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL) { - if (*eap->arg == 'l') + if (*eap->arg == 'l') { eap->flags |= EXFLAG_LIST; - else if (*eap->arg == 'p') + } else if (*eap->arg == 'p') { eap->flags |= EXFLAG_PRINT; - else + } else { eap->flags |= EXFLAG_NR; + } eap->arg = skipwhite(eap->arg + 1); } } @@ -4080,9 +4168,9 @@ static void get_flags(exarg_T *eap) /// Stub function for command which is Not Implemented. NI! void ex_ni(exarg_T *eap) { - if (!eap->skip) - eap->errmsg = (char_u *)N_( - "E319: The command is not available in this version"); + if (!eap->skip) { + eap->errmsg = (char_u *)N_("E319: The command is not available in this version"); + } } /// Stub function for script command which is Not Implemented. NI! @@ -4110,77 +4198,77 @@ static char_u *invalid_range(exarg_T *eap) if (eap->argt & EX_RANGE) { switch (eap->addr_type) { - case ADDR_LINES: - if (eap->line2 > (curbuf->b_ml.ml_line_count - + (eap->cmdidx == CMD_diffget))) { - return (char_u *)_(e_invrange); - } - break; - case ADDR_ARGUMENTS: - // add 1 if ARGCOUNT is 0 - if (eap->line2 > ARGCOUNT + (!ARGCOUNT)) { - return (char_u *)_(e_invrange); - } - break; - case ADDR_BUFFERS: - if (eap->line1 < firstbuf->b_fnum - || eap->line2 > lastbuf->b_fnum) { - return (char_u *)_(e_invrange); - } - break; - case ADDR_LOADED_BUFFERS: - buf = firstbuf; - while (buf->b_ml.ml_mfp == NULL) { - if (buf->b_next == NULL) { - return (char_u *)_(e_invrange); - } - buf = buf->b_next; - } - if (eap->line1 < buf->b_fnum) { - return (char_u *)_(e_invrange); - } - buf = lastbuf; - while (buf->b_ml.ml_mfp == NULL) { - if (buf->b_prev == NULL) { - return (char_u *)_(e_invrange); - } - buf = buf->b_prev; - } - if (eap->line2 > buf->b_fnum) { - return (char_u *)_(e_invrange); - } - break; - case ADDR_WINDOWS: - if (eap->line2 > LAST_WIN_NR) { - return (char_u *)_(e_invrange); - } - break; - case ADDR_TABS: - if (eap->line2 > LAST_TAB_NR) { - return (char_u *)_(e_invrange); - } - break; - case ADDR_TABS_RELATIVE: - case ADDR_OTHER: - // Any range is OK. - break; - case ADDR_QUICKFIX: - assert(eap->line2 >= 0); - // No error for value that is too big, will use the last entry. - if (eap->line2 <= 0) { + case ADDR_LINES: + if (eap->line2 > (curbuf->b_ml.ml_line_count + + (eap->cmdidx == CMD_diffget))) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_ARGUMENTS: + // add 1 if ARGCOUNT is 0 + if (eap->line2 > ARGCOUNT + (!ARGCOUNT)) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_BUFFERS: + if (eap->line1 < firstbuf->b_fnum + || eap->line2 > lastbuf->b_fnum) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_LOADED_BUFFERS: + buf = firstbuf; + while (buf->b_ml.ml_mfp == NULL) { + if (buf->b_next == NULL) { return (char_u *)_(e_invrange); } - break; - case ADDR_QUICKFIX_VALID: - if ((eap->line2 != 1 && (size_t)eap->line2 > qf_get_valid_size(eap)) - || eap->line2 < 0) { + buf = buf->b_next; + } + if (eap->line1 < buf->b_fnum) { + return (char_u *)_(e_invrange); + } + buf = lastbuf; + while (buf->b_ml.ml_mfp == NULL) { + if (buf->b_prev == NULL) { return (char_u *)_(e_invrange); } - break; - case ADDR_UNSIGNED: - case ADDR_NONE: - // Will give an error elsewhere. - break; + buf = buf->b_prev; + } + if (eap->line2 > buf->b_fnum) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_WINDOWS: + if (eap->line2 > LAST_WIN_NR) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_TABS: + if (eap->line2 > LAST_TAB_NR) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_TABS_RELATIVE: + case ADDR_OTHER: + // Any range is OK. + break; + case ADDR_QUICKFIX: + assert(eap->line2 >= 0); + // No error for value that is too big, will use the last entry. + if (eap->line2 <= 0) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_QUICKFIX_VALID: + if ((eap->line2 != 1 && (size_t)eap->line2 > qf_get_valid_size(eap)) + || eap->line2 < 0) { + return (char_u *)_(e_invrange); + } + break; + case ADDR_UNSIGNED: + case ADDR_NONE: + // Will give an error elsewhere. + break; } } return NULL; @@ -4208,15 +4296,16 @@ static void correct_range(exarg_T *eap) */ static char_u *skip_grep_pat(exarg_T *eap) { - char_u *p = eap->arg; + char_u *p = eap->arg; if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep || eap->cmdidx == CMD_vimgrepadd || eap->cmdidx == CMD_lvimgrepadd || grep_internal(eap->cmdidx))) { p = skip_vimgrep_pat(p, NULL, NULL); - if (p == NULL) + if (p == NULL) { p = eap->arg; + } } return p; } @@ -4227,10 +4316,10 @@ static char_u *skip_grep_pat(exarg_T *eap) */ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) { - char_u *new_cmdline; - char_u *program; - char_u *pos; - char_u *ptr; + char_u *new_cmdline; + char_u *program; + char_u *pos; + char_u *ptr; int len; int i; @@ -4244,24 +4333,27 @@ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) && !grep_internal(eap->cmdidx)) { if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd) { - if (*curbuf->b_p_gp == NUL) + if (*curbuf->b_p_gp == NUL) { program = p_gp; - else + } else { program = curbuf->b_p_gp; + } } else { - if (*curbuf->b_p_mp == NUL) + if (*curbuf->b_p_mp == NUL) { program = p_mp; - else + } else { program = curbuf->b_p_mp; + } } p = skipwhite(p); if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL) { - /* replace $* by given arguments */ + // replace $* by given arguments i = 1; - while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL) + while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL) { ++i; + } len = (int)STRLEN(p); new_cmdline = xmalloc(STRLEN(program) + i * (len - 2) + 1); ptr = new_cmdline; @@ -4281,7 +4373,7 @@ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) } msg_make(p); - /* 'eap->cmd' is not set here, because it is not used at CMD_make */ + // 'eap->cmd' is not set here, because it is not used at CMD_make xfree(*cmdlinep); *cmdlinep = new_cmdline; p = new_cmdline; @@ -4294,13 +4386,13 @@ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep) // Return FAIL for failure, OK otherwise. int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) { - int has_wildcards; /* need to expand wildcards */ - char_u *repl; + int has_wildcards; // need to expand wildcards + char_u *repl; size_t srclen; - char_u *p; + char_u *p; int escaped; - /* Skip a regexp pattern for ":vimgrep[add] pat file..." */ + // Skip a regexp pattern for ":vimgrep[add] pat file..." p = skip_grep_pat(eap); /* @@ -4310,12 +4402,13 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) */ has_wildcards = path_has_wildcard(p); while (*p != NUL) { - /* Skip over `=expr`, wildcards in it are not expanded. */ + // Skip over `=expr`, wildcards in it are not expanded. if (p[0] == '`' && p[1] == '=') { p += 2; (void)skip_expr(&p); - if (*p == '`') + if (*p == '`') { ++p; + } continue; } /* @@ -4331,10 +4424,11 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) * Try to find a match at this position. */ repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum), - errormsgp, &escaped); - if (*errormsgp != NULL) /* error detected */ + errormsgp, &escaped); + if (*errormsgp != NULL) { // error detected return FAIL; - if (repl == NULL) { /* no match found */ + } + if (repl == NULL) { // no match found p += srclen; continue; } @@ -4364,9 +4458,8 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) && eap->cmdidx != CMD_lmake && eap->cmdidx != CMD_make && eap->cmdidx != CMD_terminal - && !(eap->argt & EX_NOSPC) - ) { - char_u *l; + && !(eap->argt & EX_NOSPC)) { + char_u *l; #ifdef BACKSLASH_IN_FILENAME /* Don't escape a backslash here, because rem_backslash() doesn't * remove it later. */ @@ -4376,13 +4469,14 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) # define ESCAPE_CHARS escape_chars #endif - for (l = repl; *l; ++l) + for (l = repl; *l; ++l) { if (vim_strchr(ESCAPE_CHARS, *l) != NULL) { l = vim_strsave_escaped(repl, ESCAPE_CHARS); xfree(repl); repl = l; break; } + } } // For a shell command a '!' must be escaped. @@ -4390,7 +4484,7 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) || eap->cmdidx == CMD_bang || eap->cmdidx == CMD_terminal) && vim_strpbrk(repl, (char_u *)"!") != NULL) { - char_u *l; + char_u *l; l = vim_strsave_escaped(repl, (char_u *)"!"); xfree(repl); @@ -4418,11 +4512,12 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) if (vim_strchr(eap->arg, '$') != NULL || vim_strchr(eap->arg, '~') != NULL) { expand_env_esc(eap->arg, NameBuff, MAXPATHL, - TRUE, TRUE, NULL); + TRUE, TRUE, NULL); has_wildcards = path_has_wildcard(NameBuff); p = NameBuff; - } else + } else { p = NULL; + } if (p != NULL) { (void)repl_cmdline(eap, eap->arg, STRLEN(eap->arg), p, cmdlinep); } @@ -4444,8 +4539,9 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; - if (p_wic) + if (p_wic) { options += WILD_ICASE; + } p = ExpandOne(&xpc, eap->arg, NULL, options, WILD_EXPAND_FREE); if (p == NULL) { return FAIL; @@ -4464,8 +4560,8 @@ int expand_filename(exarg_T *eap, char_u **cmdlinep, char_u **errormsgp) * "repl" is the replacement string. * Returns a pointer to the character after the replaced string. */ -static char_u *repl_cmdline(exarg_T *eap, char_u *src, size_t srclen, - char_u *repl, char_u **cmdlinep) +static char_u *repl_cmdline(exarg_T *eap, char_u *src, size_t srclen, char_u *repl, + char_u **cmdlinep) { /* * The new command line is build in new_cmdline[]. @@ -4474,8 +4570,9 @@ static char_u *repl_cmdline(exarg_T *eap, char_u *src, size_t srclen, */ size_t len = STRLEN(repl); size_t i = (size_t)(src - *cmdlinep) + STRLEN(src + srclen) + len + 3; - if (eap->nextcmd != NULL) - i += STRLEN(eap->nextcmd); /* add space for next command */ + if (eap->nextcmd != NULL) { + i += STRLEN(eap->nextcmd); // add space for next command + } char_u *new_cmdline = xmalloc(i); /* @@ -4484,23 +4581,24 @@ static char_u *repl_cmdline(exarg_T *eap, char_u *src, size_t srclen, * Copy what came after the expanded part. * Copy the next commands, if there are any. */ - i = (size_t)(src - *cmdlinep); /* length of part before match */ + i = (size_t)(src - *cmdlinep); // length of part before match memmove(new_cmdline, *cmdlinep, i); memmove(new_cmdline + i, repl, len); - i += len; /* remember the end of the string */ + i += len; // remember the end of the string STRCPY(new_cmdline + i, src + srclen); - src = new_cmdline + i; /* remember where to continue */ + src = new_cmdline + i; // remember where to continue - if (eap->nextcmd != NULL) { /* append next command */ + if (eap->nextcmd != NULL) { // append next command i = STRLEN(new_cmdline) + 1; STRCPY(new_cmdline + i, eap->nextcmd); eap->nextcmd = new_cmdline + i; } eap->cmd = new_cmdline + (eap->cmd - *cmdlinep); eap->arg = new_cmdline + (eap->arg - *cmdlinep); - if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command) + if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command) { eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep); + } xfree(*cmdlinep); *cmdlinep = new_cmdline; @@ -4512,7 +4610,7 @@ static char_u *repl_cmdline(exarg_T *eap, char_u *src, size_t srclen, */ void separate_nextcmd(exarg_T *eap) { - char_u *p; + char_u *p; p = skip_grep_pat(eap); @@ -4535,16 +4633,16 @@ void separate_nextcmd(exarg_T *eap) break; } } else if ( - // Check for '"': start of comment or '|': next command */ - // :@" does not start a comment! - // :redir @" doesn't either. - (*p == '"' - && !(eap->argt & EX_NOTRLCOM) - && (eap->cmdidx != CMD_at || p != eap->arg) - && (eap->cmdidx != CMD_redir - || p != eap->arg + 1 || p[-1] != '@')) - || *p == '|' - || *p == '\n') { + // Check for '"': start of comment or '|': next command */ + // :@" does not start a comment! + // :redir @" doesn't either. + (*p == '"' + && !(eap->argt & EX_NOTRLCOM) + && (eap->cmdidx != CMD_at || p != eap->arg) + && (eap->cmdidx != CMD_redir + || p != eap->arg + 1 || p[-1] != '@')) + || *p == '|' + || *p == '\n') { // We remove the '\' before the '|', unless EX_CTRLV is used // AND 'b' is present in 'cpoptions'. if ((vim_strchr(p_cpo, CPO_BAR) == NULL @@ -4572,38 +4670,36 @@ static char_u *getargcmd(char_u **argp) char_u *arg = *argp; char_u *command = NULL; - if (*arg == '+') { /* +[command] */ + if (*arg == '+') { // +[command] ++arg; - if (ascii_isspace(*arg) || *arg == '\0') + if (ascii_isspace(*arg) || *arg == '\0') { command = dollar_command; - else { + } else { command = arg; arg = skip_cmd_arg(command, TRUE); - if (*arg != NUL) - *arg++ = NUL; /* terminate command with NUL */ + if (*arg != NUL) { + *arg++ = NUL; // terminate command with NUL + } } - arg = skipwhite(arg); /* skip over spaces */ + arg = skipwhite(arg); // skip over spaces *argp = arg; } return command; } -/* - * Find end of "+command" argument. Skip over "\ " and "\\". - */ -static char_u * -skip_cmd_arg ( - char_u *p, - int rembs /* TRUE to halve the number of backslashes */ -) +/// Find end of "+command" argument. Skip over "\ " and "\\". +/// +/// @param rembs TRUE to halve the number of backslashes +static char_u *skip_cmd_arg(char_u *p, int rembs) { while (*p && !ascii_isspace(*p)) { if (*p == '\\' && p[1] != NUL) { - if (rembs) + if (rembs) { STRMOVE(p, p + 1); - else + } else { ++p; + } } MB_PTR_ADV(p); } @@ -4631,25 +4727,27 @@ int get_bad_opt(const char_u *p, exarg_T *eap) */ static int getargopt(exarg_T *eap) { - char_u *arg = eap->arg + 2; - int *pp = NULL; + char_u *arg = eap->arg + 2; + int *pp = NULL; int bad_char_idx; - char_u *p; + char_u *p; - /* ":edit ++[no]bin[ary] file" */ + // ":edit ++[no]bin[ary] file" if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0) { if (*arg == 'n') { arg += 2; eap->force_bin = FORCE_NOBIN; - } else + } else { eap->force_bin = FORCE_BIN; - if (!checkforcmd(&arg, "binary", 3)) + } + if (!checkforcmd(&arg, "binary", 3)) { return FAIL; + } eap->arg = skipwhite(arg); return OK; } - /* ":read ++edit file" */ + // ":read ++edit file" if (STRNCMP(arg, "edit", 4) == 0) { eap->read_edit = TRUE; eap->arg = skipwhite(arg + 4); @@ -4663,18 +4761,20 @@ static int getargopt(exarg_T *eap) arg += 10; pp = &eap->force_ff; } else if (STRNCMP(arg, "enc", 3) == 0) { - if (STRNCMP(arg, "encoding", 8) == 0) + if (STRNCMP(arg, "encoding", 8) == 0) { arg += 8; - else + } else { arg += 3; + } pp = &eap->force_enc; } else if (STRNCMP(arg, "bad", 3) == 0) { arg += 3; pp = &bad_char_idx; } - if (pp == NULL || *arg != '=') + if (pp == NULL || *arg != '=') { return FAIL; + } ++arg; *pp = (int)(arg - eap->cmd); @@ -4688,9 +4788,10 @@ static int getargopt(exarg_T *eap) } eap->force_ff = eap->cmd[eap->force_ff]; } else if (pp == &eap->force_enc) { - /* Make 'fileencoding' lower case. */ - for (p = eap->cmd + eap->force_enc; *p != NUL; ++p) + // Make 'fileencoding' lower case. + for (p = eap->cmd + eap->force_enc; *p != NUL; ++p) { *p = TOLOWER_ASC(*p); + } } else { /* Check ++bad= argument. Must be a single-byte character, "keep" or * "drop". */ @@ -4713,8 +4814,8 @@ static int get_tabpage_arg(exarg_T *eap) if (eap->arg && *eap->arg != NUL) { char_u *p = eap->arg; char_u *p_save; - int relative = 0; // argument +N/-N means: go to N places to the - // right/left relative to the current position. + int relative = 0; // argument +N/-N means: go to N places to the + // right/left relative to the current position. if (*p == '-') { relative = -1; @@ -4741,8 +4842,7 @@ static int get_tabpage_arg(exarg_T *eap) } else { if (*p_save == NUL) { tab_number = 1; - } - else if (p == p_save || *p_save == '-' || *p != NUL || tab_number == 0) { + } else if (p == p_save || *p_save == '-' || *p != NUL || tab_number == 0) { // No numbers as argument. eap->errmsg = e_invarg; goto theend; @@ -4772,8 +4872,9 @@ static int get_tabpage_arg(exarg_T *eap) switch (eap->cmdidx) { case CMD_tabnext: tab_number = tabpage_index(curtab) + 1; - if (tab_number > LAST_TAB_NR) + if (tab_number > LAST_TAB_NR) { tab_number = 1; + } break; case CMD_tabmove: tab_number = LAST_TAB_NR; @@ -4792,7 +4893,7 @@ theend: */ static void ex_abbreviate(exarg_T *eap) { - do_exmap(eap, TRUE); /* almost the same as mapping */ + do_exmap(eap, TRUE); // almost the same as mapping } /* @@ -4843,10 +4944,11 @@ static void ex_autocmd(exarg_T *eap) if (secure) { secure = 2; eap->errmsg = e_curdir; - } else if (eap->cmdidx == CMD_autocmd) + } else if (eap->cmdidx == CMD_autocmd) { do_autocmd(eap->arg, eap->forceit); - else + } else { do_augroup(eap->arg, eap->forceit); + } } /* @@ -4872,16 +4974,16 @@ static void ex_doautocmd(exarg_T *eap) */ static void ex_bunload(exarg_T *eap) { - eap->errmsg = do_bufdel( - eap->cmdidx == CMD_bdelete ? DOBUF_DEL - : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE - : DOBUF_UNLOAD, eap->arg, - eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit); + eap->errmsg = do_bufdel(eap->cmdidx == CMD_bdelete ? DOBUF_DEL + : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE + : DOBUF_UNLOAD, + eap->arg, + eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit); } /* - * :[N]buffer [N] to buffer N - * :[N]sbuffer [N] to buffer N + * :[N]buffer [N] to buffer N + * :[N]sbuffer [N] to buffer N */ static void ex_buffer(exarg_T *eap) { @@ -4900,8 +5002,8 @@ static void ex_buffer(exarg_T *eap) } /* - * :[N]bmodified [N] to next mod. buffer - * :[N]sbmodified [N] to next mod. buffer + * :[N]bmodified [N] to next mod. buffer + * :[N]sbmodified [N] to next mod. buffer */ static void ex_bmodified(exarg_T *eap) { @@ -4912,8 +5014,8 @@ static void ex_bmodified(exarg_T *eap) } /* - * :[N]bnext [N] to next buffer - * :[N]sbnext [N] split and to next buffer + * :[N]bnext [N] to next buffer + * :[N]sbnext [N] split and to next buffer */ static void ex_bnext(exarg_T *eap) { @@ -4924,10 +5026,10 @@ static void ex_bnext(exarg_T *eap) } /* - * :[N]bNext [N] to previous buffer - * :[N]bprevious [N] to previous buffer - * :[N]sbNext [N] split and to previous buffer - * :[N]sbprevious [N] split and to previous buffer + * :[N]bNext [N] to previous buffer + * :[N]bprevious [N] to previous buffer + * :[N]sbNext [N] split and to previous buffer + * :[N]sbprevious [N] split and to previous buffer */ static void ex_bprevious(exarg_T *eap) { @@ -4938,10 +5040,10 @@ static void ex_bprevious(exarg_T *eap) } /* - * :brewind to first buffer - * :bfirst to first buffer - * :sbrewind split and to first buffer - * :sbfirst split and to first buffer + * :brewind to first buffer + * :bfirst to first buffer + * :sbrewind split and to first buffer + * :sbfirst split and to first buffer */ static void ex_brewind(exarg_T *eap) { @@ -4952,8 +5054,8 @@ static void ex_brewind(exarg_T *eap) } /* - * :blast to last buffer - * :sblast split and to last buffer + * :blast to last buffer + * :sblast split and to last buffer */ static void ex_blast(exarg_T *eap) { @@ -4987,28 +5089,23 @@ char_u *find_nextcmd(const char_u *p) /// Return NULL if it isn't, the following character if it is. char_u *check_nextcmd(char_u *p) { - char_u *s = skipwhite(p); + char_u *s = skipwhite(p); - if (*s == '|' || *s == '\n') { - return (s + 1); - } else { - return NULL; - } + if (*s == '|' || *s == '\n') { + return (s + 1); + } else { + return NULL; + } } -/* - * - if there are more files to edit - * - and this is the last window - * - and forceit not used - * - and not repeated twice on a row - * return FAIL and give error message if 'message' TRUE - * return OK otherwise - */ -static int -check_more( - int message, // when FALSE check only, no messages - bool forceit -) +/// - if there are more files to edit +/// - and this is the last window +/// - and forceit not used +/// - and not repeated twice on a row +/// @return FAIL and give error message if 'message' TRUE, return OK otherwise +/// +/// @param message when FALSE check only, no messages +static int check_more(int message, bool forceit) { int n = ARGCOUNT - curwin->w_arg_idx - 1; @@ -5018,21 +5115,24 @@ check_more( if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL) { char_u buff[DIALOG_MSG_SIZE]; - if (n == 1) + if (n == 1) { STRLCPY(buff, _("1 more file to edit. Quit anyway?"), - DIALOG_MSG_SIZE); - else + DIALOG_MSG_SIZE); + } else { vim_snprintf((char *)buff, DIALOG_MSG_SIZE, - _("%d more files to edit. Quit anyway?"), n); - if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES) + _("%d more files to edit. Quit anyway?"), n); + } + if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES) { return OK; + } return FAIL; } - if (n == 1) + if (n == 1) { EMSG(_("E173: 1 more file to edit")); - else + } else { EMSGN(_("E173: %" PRId64 " more files to edit"), n); - quitmore = 2; /* next try to quit is allowed */ + } + quitmore = 2; // next try to quit is allowed } return FAIL; } @@ -5044,38 +5144,40 @@ check_more( */ char_u *get_command_name(expand_T *xp, int idx) { - if (idx >= (int)CMD_SIZE) + if (idx >= (int)CMD_SIZE) { return get_user_command_name(idx); + } return cmdnames[idx].cmd_name; } -static int uc_add_command(char_u *name, size_t name_len, char_u *rep, - uint32_t argt, long def, int flags, int compl, - char_u *compl_arg, cmd_addr_T addr_type, bool force) +static int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t argt, long def, + int flags, int compl, char_u *compl_arg, cmd_addr_T addr_type, bool force) FUNC_ATTR_NONNULL_ARG(1, 3) { - ucmd_T *cmd = NULL; + ucmd_T *cmd = NULL; int i; int cmp = 1; - char_u *rep_buf = NULL; - garray_T *gap; + char_u *rep_buf = NULL; + garray_T *gap; replace_termcodes(rep, STRLEN(rep), &rep_buf, false, false, true, CPO_TO_CPO_FLAGS); if (rep_buf == NULL) { - /* Can't replace termcodes - try using the string as is */ + // Can't replace termcodes - try using the string as is rep_buf = vim_strsave(rep); } - /* get address of growarray: global or in curbuf */ + // get address of growarray: global or in curbuf if (flags & UC_BUFFER) { gap = &curbuf->b_ucmds; - if (gap->ga_itemsize == 0) + if (gap->ga_itemsize == 0) { ga_init(gap, (int)sizeof(ucmd_T), 4); - } else + } + } else { gap = &ucmds; + } - /* Search for the command in the already defined commands. */ + // Search for the command in the already defined commands. for (i = 0; i < gap->ga_len; ++i) { size_t len; @@ -5083,10 +5185,11 @@ static int uc_add_command(char_u *name, size_t name_len, char_u *rep, len = STRLEN(cmd->uc_name); cmp = STRNCMP(name, cmd->uc_name, name_len); if (cmp == 0) { - if (name_len < len) + if (name_len < len) { cmp = -1; - else if (name_len > len) + } else if (name_len > len) { cmp = 1; + } } if (cmp == 0) { @@ -5105,12 +5208,13 @@ static int uc_add_command(char_u *name, size_t name_len, char_u *rep, break; } - /* Stop as soon as we pass the name to add */ - if (cmp < 0) + // Stop as soon as we pass the name to add + if (cmp < 0) { break; + } } - /* Extend the array unless we're replacing an existing command */ + // Extend the array unless we're replacing an existing command if (cmp != 0) { ga_grow(gap, 1); @@ -5221,7 +5325,7 @@ static void uc_list(char_u *name, size_t name_len) { int i, j; bool found = false; - ucmd_T *cmd; + ucmd_T *cmd; uint32_t a; // In cmdwin, the alternative buffer should be used. @@ -5247,8 +5351,9 @@ static void uc_list(char_u *name, size_t name_len) } found = true; msg_putchar('\n'); - if (got_int) + if (got_int) { break; + } // Special cases int len = 4; @@ -5287,21 +5392,21 @@ static void uc_list(char_u *name, size_t name_len) // Arguments switch (a & (EX_EXTRA | EX_NOSPC | EX_NEEDARG)) { - case 0: - IObuff[len++] = '0'; - break; - case (EX_EXTRA): - IObuff[len++] = '*'; - break; - case (EX_EXTRA | EX_NOSPC): - IObuff[len++] = '?'; - break; - case (EX_EXTRA | EX_NEEDARG): - IObuff[len++] = '+'; - break; - case (EX_EXTRA | EX_NOSPC | EX_NEEDARG): - IObuff[len++] = '1'; - break; + case 0: + IObuff[len++] = '0'; + break; + case (EX_EXTRA): + IObuff[len++] = '*'; + break; + case (EX_EXTRA | EX_NOSPC): + IObuff[len++] = '?'; + break; + case (EX_EXTRA | EX_NEEDARG): + IObuff[len++] = '+'; + break; + case (EX_EXTRA | EX_NOSPC | EX_NEEDARG): + IObuff[len++] = '1'; + break; } do { @@ -5369,21 +5474,22 @@ static void uc_list(char_u *name, size_t name_len) break; } } - if (gap == &ucmds || i < gap->ga_len) + if (gap == &ucmds || i < gap->ga_len) { break; + } gap = &ucmds; } - if (!found) + if (!found) { MSG(_("No user-defined commands found")); + } } -static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, - int *flags, int *complp, char_u **compl_arg, - cmd_addr_T *addr_type_arg) +static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, int *flags, + int *complp, char_u **compl_arg, cmd_addr_T *addr_type_arg) FUNC_ATTR_NONNULL_ALL { - char_u *p; + char_u *p; if (len == 0) { EMSG(_("E175: No attribute specified")); @@ -5401,7 +5507,7 @@ static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, *argt |= EX_TRLBAR; } else { int i; - char_u *val = NULL; + char_u *val = NULL; size_t vallen = 0; size_t attrlen = len; @@ -5469,17 +5575,20 @@ invalid_count: if (val != NULL) { p = val; - if (*def >= 0) + if (*def >= 0) { goto two_count; + } *def = getdigits_long(&p, true, 0); - if (p != val + vallen) + if (p != val + vallen) { goto invalid_count; + } } - if (*def < 0) + if (*def < 0) { *def = 0; + } } else if (STRNICMP(attr, "complete", attrlen) == 0) { if (val == NULL) { EMSG(_("E179: argument required for -complete")); @@ -5514,29 +5623,28 @@ invalid_count: return OK; } -static char e_complete_used_without_nargs[] = N_( - "E1208: -complete used without -nargs"); +static char e_complete_used_without_nargs[] = N_("E1208: -complete used without -nargs"); /* * ":command ..." */ static void ex_command(exarg_T *eap) { - char_u *name; - char_u *end; - char_u *p; + char_u *name; + char_u *end; + char_u *p; uint32_t argt = 0; long def = -1; int flags = 0; int compl = EXPAND_NOTHING; - char_u *compl_arg = NULL; + char_u *compl_arg = NULL; cmd_addr_T addr_type_arg = ADDR_NONE; int has_attr = (eap->arg[0] == '-'); int name_len; p = eap->arg; - /* Check for attributes */ + // Check for attributes while (*p == '-') { ++p; end = skiptowhite(p); @@ -5588,7 +5696,7 @@ void ex_comclear(exarg_T *eap) uc_clear(&curbuf->b_ucmds); } -static void free_ucmd(ucmd_T* cmd) { +static void free_ucmd(ucmd_T * cmd) { xfree(cmd->uc_name); xfree(cmd->uc_rep); xfree(cmd->uc_compl_arg); @@ -5605,20 +5713,22 @@ void uc_clear(garray_T *gap) static void ex_delcommand(exarg_T *eap) { int i = 0; - ucmd_T *cmd = NULL; + ucmd_T *cmd = NULL; int cmp = -1; - garray_T *gap; + garray_T *gap; gap = &curbuf->b_ucmds; for (;; ) { for (i = 0; i < gap->ga_len; ++i) { cmd = USER_CMD_GA(gap, i); cmp = STRCMP(eap->arg, cmd->uc_name); - if (cmp <= 0) + if (cmp <= 0) { break; + } } - if (gap == &ucmds || cmp == 0) + if (gap == &ucmds || cmp == 0) { break; + } gap = &ucmds; } @@ -5633,8 +5743,9 @@ static void ex_delcommand(exarg_T *eap) --gap->ga_len; - if (i < gap->ga_len) + if (i < gap->ga_len) { memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T)); + } } /* @@ -5647,9 +5758,9 @@ static char_u *uc_split_args(char_u *arg, size_t *lenp) char_u *q; int len; - /* Precalculate length */ + // Precalculate length p = arg; - len = 2; /* Initial and final quotes */ + len = 2; // Initial and final quotes while (*p) { if (p[0] == '\\' && p[1] == '\\') { @@ -5663,9 +5774,10 @@ static char_u *uc_split_args(char_u *arg, size_t *lenp) p += 1; } else if (ascii_iswhite(*p)) { p = skipwhite(p); - if (*p == NUL) + if (*p == NUL) { break; - len += 3; /* "," */ + } + len += 3; // "," } else { const int charlen = utfc_ptr2len(p); @@ -5692,8 +5804,9 @@ static char_u *uc_split_args(char_u *arg, size_t *lenp) *q++ = *p++; } else if (ascii_iswhite(*p)) { p = skipwhite(p); - if (*p == NUL) + if (*p == NUL) { break; + } *q++ = '"'; *q++ = ','; *q++ = '"'; @@ -5726,28 +5839,22 @@ static size_t add_cmd_modifier(char_u *buf, char *mod_str, bool *multi_mods) return result; } -/* - * Check for a <> code in a user command. - * "code" points to the '<'. "len" the length of the <> (inclusive). - * "buf" is where the result is to be added. - * "split_buf" points to a buffer used for splitting, caller should free it. - * "split_len" is the length of what "split_buf" contains. - * Returns the length of the replacement, which has been added to "buf". - * Returns -1 if there was no match, and only the "<" has been copied. - */ -static size_t -uc_check_code( - char_u *code, - size_t len, - char_u *buf, - ucmd_T *cmd, /* the user command we're expanding */ - exarg_T *eap, /* ex arguments */ - char_u **split_buf, - size_t *split_len -) +/// Check for a <> code in a user command. +/// +/// @param code points to the '<'. "len" the length of the <> (inclusive). +/// @param buf is where the result is to be added. +/// @param cmd the user command we're expanding +/// @param eap ex arguments +/// @param split_buf points to a buffer used for splitting, caller should free it. +/// @param split_len is the length of what "split_buf" contains. +/// +/// @return the length of the replacement, which has been added to "buf". +/// Return -1 if there was no match, and only the "<" has been copied. +static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd, exarg_T *eap, + char_u **split_buf, size_t *split_len) { size_t result = 0; - char_u *p = code + 1; + char_u *p = code + 1; size_t l = len - 2; int quote = 0; enum { @@ -5794,14 +5901,16 @@ uc_check_code( switch (type) { case ct_ARGS: - /* Simple case first */ + // Simple case first if (*eap->arg == NUL) { if (quote == 1) { result = 2; - if (buf != NULL) + if (buf != NULL) { STRCPY(buf, "''"); - } else + } + } else { result = 0; + } break; } @@ -5812,12 +5921,13 @@ uc_check_code( } switch (quote) { - case 0: /* No quoting, no splitting */ + case 0: // No quoting, no splitting result = STRLEN(eap->arg); - if (buf != NULL) + if (buf != NULL) { STRCPY(buf, eap->arg); + } break; - case 1: /* Quote, but don't split */ + case 1: // Quote, but don't split result = STRLEN(eap->arg) + 2; for (p = eap->arg; *p; p++) { if (*p == '\\' || *p == '"') { @@ -5837,14 +5947,16 @@ uc_check_code( } break; - case 2: /* Quote and split (<f-args>) */ - /* This is hard, so only do it once, and cache the result */ - if (*split_buf == NULL) + case 2: // Quote and split (<f-args>) + // This is hard, so only do it once, and cache the result + if (*split_buf == NULL) { *split_buf = uc_split_args(eap->arg, split_len); + } result = *split_len; - if (buf != NULL && result != 0) + if (buf != NULL && result != 0) { STRCPY(buf, *split_buf); + } break; } @@ -5852,155 +5964,166 @@ uc_check_code( case ct_BANG: result = eap->forceit ? 1 : 0; - if (quote) + if (quote) { result += 2; + } if (buf != NULL) { - if (quote) + if (quote) { *buf++ = '"'; - if (eap->forceit) + } + if (eap->forceit) { *buf++ = '!'; - if (quote) + } + if (quote) { *buf = '"'; + } } break; case ct_LINE1: case ct_LINE2: case ct_RANGE: - case ct_COUNT: - { - char num_buf[20]; - long num = (type == ct_LINE1) ? eap->line1 : - (type == ct_LINE2) ? eap->line2 : - (type == ct_RANGE) ? eap->addr_count : - (eap->addr_count > 0) ? eap->line2 : cmd->uc_def; - size_t num_len; - - sprintf(num_buf, "%" PRId64, (int64_t)num); - num_len = STRLEN(num_buf); - result = num_len; - - if (quote) - result += 2; + case ct_COUNT: { + char num_buf[20]; + long num = (type == ct_LINE1) ? eap->line1 : + (type == ct_LINE2) ? eap->line2 : + (type == ct_RANGE) ? eap->addr_count : + (eap->addr_count > 0) ? eap->line2 : cmd->uc_def; + size_t num_len; + + sprintf(num_buf, "%" PRId64, (int64_t)num); + num_len = STRLEN(num_buf); + result = num_len; - if (buf != NULL) { - if (quote) - *buf++ = '"'; - STRCPY(buf, num_buf); - buf += num_len; - if (quote) - *buf = '"'; - } - - break; - } - - case ct_MODS: - { - result = quote ? 2 : 0; - if (buf != NULL) { if (quote) { - *buf++ = '"'; + result += 2; } - *buf = '\0'; - } - bool multi_mods = false; + if (buf != NULL) { + if (quote) { + *buf++ = '"'; + } + STRCPY(buf, num_buf); + buf += num_len; + if (quote) { + *buf = '"'; + } + } - // :aboveleft and :leftabove - if (cmdmod.split & WSP_ABOVE) { - result += add_cmd_modifier(buf, "aboveleft", &multi_mods); - } - // :belowright and :rightbelow - if (cmdmod.split & WSP_BELOW) { - result += add_cmd_modifier(buf, "belowright", &multi_mods); - } - // :botright - if (cmdmod.split & WSP_BOT) { - result += add_cmd_modifier(buf, "botright", &multi_mods); + break; } - typedef struct { - bool *set; - char *name; - } mod_entry_T; - static mod_entry_T mod_entries[] = { - { &cmdmod.browse, "browse" }, - { &cmdmod.confirm, "confirm" }, - { &cmdmod.hide, "hide" }, - { &cmdmod.keepalt, "keepalt" }, - { &cmdmod.keepjumps, "keepjumps" }, - { &cmdmod.keepmarks, "keepmarks" }, - { &cmdmod.keeppatterns, "keeppatterns" }, - { &cmdmod.lockmarks, "lockmarks" }, - { &cmdmod.noswapfile, "noswapfile" } - }; - // the modifiers that are simple flags - for (size_t i = 0; i < ARRAY_SIZE(mod_entries); i++) { - if (*mod_entries[i].set) { - result += add_cmd_modifier(buf, mod_entries[i].name, &multi_mods); + case ct_MODS: { + result = quote ? 2 : 0; + if (buf != NULL) { + if (quote) { + *buf++ = '"'; + } + *buf = '\0'; + } + + bool multi_mods = false; + + // :aboveleft and :leftabove + if (cmdmod.split & WSP_ABOVE) { + result += add_cmd_modifier(buf, "aboveleft", &multi_mods); + } + // :belowright and :rightbelow + if (cmdmod.split & WSP_BELOW) { + result += add_cmd_modifier(buf, "belowright", &multi_mods); + } + // :botright + if (cmdmod.split & WSP_BOT) { + result += add_cmd_modifier(buf, "botright", &multi_mods); + } + + typedef struct { + bool *set; + char *name; + } mod_entry_T; + static mod_entry_T mod_entries[] = { + { &cmdmod.browse, "browse" }, + { &cmdmod.confirm, "confirm" }, + { &cmdmod.hide, "hide" }, + { &cmdmod.keepalt, "keepalt" }, + { &cmdmod.keepjumps, "keepjumps" }, + { &cmdmod.keepmarks, "keepmarks" }, + { &cmdmod.keeppatterns, "keeppatterns" }, + { &cmdmod.lockmarks, "lockmarks" }, + { &cmdmod.noswapfile, "noswapfile" } + }; + // the modifiers that are simple flags + for (size_t i = 0; i < ARRAY_SIZE(mod_entries); i++) { + if (*mod_entries[i].set) { + result += add_cmd_modifier(buf, mod_entries[i].name, &multi_mods); + } } - } - // TODO(vim): How to support :noautocmd? - // TODO(vim): How to support :sandbox? + // TODO(vim): How to support :noautocmd? + // TODO(vim): How to support :sandbox? - // :silent - if (msg_silent > 0) { - result += add_cmd_modifier(buf, emsg_silent > 0 ? "silent!" : "silent", - &multi_mods); - } - // :tab - if (cmdmod.tab > 0) { - result += add_cmd_modifier(buf, "tab", &multi_mods); - } - // :topleft - if (cmdmod.split & WSP_TOP) { - result += add_cmd_modifier(buf, "topleft", &multi_mods); - } + // :silent + if (msg_silent > 0) { + result += add_cmd_modifier(buf, emsg_silent > 0 ? "silent!" : "silent", + &multi_mods); + } + // :tab + if (cmdmod.tab > 0) { + result += add_cmd_modifier(buf, "tab", &multi_mods); + } + // :topleft + if (cmdmod.split & WSP_TOP) { + result += add_cmd_modifier(buf, "topleft", &multi_mods); + } - // TODO(vim): How to support :unsilent? + // TODO(vim): How to support :unsilent? - // :verbose - if (p_verbose > 0) { - result += add_cmd_modifier(buf, "verbose", &multi_mods); - } - // :vertical - if (cmdmod.split & WSP_VERT) { - result += add_cmd_modifier(buf, "vertical", &multi_mods); - } - if (quote && buf != NULL) { - buf += result - 2; - *buf = '"'; + // :verbose + if (p_verbose > 0) { + result += add_cmd_modifier(buf, "verbose", &multi_mods); + } + // :vertical + if (cmdmod.split & WSP_VERT) { + result += add_cmd_modifier(buf, "vertical", &multi_mods); + } + if (quote && buf != NULL) { + buf += result - 2; + *buf = '"'; + } + break; } - break; - } case ct_REGISTER: result = eap->regname ? 1 : 0; - if (quote) + if (quote) { result += 2; + } if (buf != NULL) { - if (quote) + if (quote) { *buf++ = '\''; - if (eap->regname) + } + if (eap->regname) { *buf++ = eap->regname; - if (quote) + } + if (quote) { *buf = '\''; + } } break; case ct_LT: result = 1; - if (buf != NULL) + if (buf != NULL) { *buf = '<'; + } break; default: - /* Not recognized: just copy the '<' and return -1. */ + // Not recognized: just copy the '<' and return -1. result = (size_t)-1; - if (buf != NULL) + if (buf != NULL) { *buf = '<'; + } break; } @@ -6009,24 +6132,25 @@ uc_check_code( static void do_ucmd(exarg_T *eap) { - char_u *buf; - char_u *p; - char_u *q; + char_u *buf; + char_u *p; + char_u *q; - char_u *start; - char_u *end = NULL; - char_u *ksp; + char_u *start; + char_u *end = NULL; + char_u *ksp; size_t len, totlen; size_t split_len = 0; - char_u *split_buf = NULL; - ucmd_T *cmd; + char_u *split_buf = NULL; + ucmd_T *cmd; const sctx_T save_current_sctx = current_sctx; - if (eap->cmdidx == CMD_USER) + if (eap->cmdidx == CMD_USER) { cmd = USER_CMD(eap->useridx); - else + } else { cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx); + } /* * Replace <> in the command by the arguments. @@ -6035,14 +6159,15 @@ static void do_ucmd(exarg_T *eap) */ buf = NULL; for (;; ) { - p = cmd->uc_rep; /* source */ - q = buf; /* destination */ + p = cmd->uc_rep; // source + q = buf; // destination totlen = 0; for (;; ) { start = vim_strchr(p, '<'); - if (start != NULL) + if (start != NULL) { end = vim_strchr(start + 1, '>'); + } if (buf != NULL) { for (ksp = p; *ksp != NUL && *ksp != K_SPECIAL; ksp++) { } @@ -6064,41 +6189,44 @@ static void do_ucmd(exarg_T *eap) } } - /* break if there no <item> is found */ - if (start == NULL || end == NULL) + // break if there no <item> is found + if (start == NULL || end == NULL) { break; + } - /* Include the '>' */ + // Include the '>' ++end; - /* Take everything up to the '<' */ + // Take everything up to the '<' len = start - p; - if (buf == NULL) + if (buf == NULL) { totlen += len; - else { + } else { memmove(q, p, len); q += len; } len = uc_check_code(start, end - start, q, cmd, eap, - &split_buf, &split_len); + &split_buf, &split_len); if (len == (size_t)-1) { - /* no match, continue after '<' */ + // no match, continue after '<' p = start + 1; len = 1; - } else + } else { p = end; - if (buf == NULL) + } + if (buf == NULL) { totlen += len; - else + } else { q += len; + } } - if (buf != NULL) { /* second time here, finished */ + if (buf != NULL) { // second time here, finished STRCPY(q, p); break; } - totlen += STRLEN(p); /* Add on the trailing characters */ + totlen += STRLEN(p); // Add on the trailing characters buf = xmalloc(totlen + 1); } @@ -6149,12 +6277,13 @@ char_u *get_user_commands(expand_T *xp FUNC_ATTR_UNUSED, int idx) */ char_u *get_user_cmd_flags(expand_T *xp, int idx) { - static char *user_cmd_flags[] = {"addr", "bang", "bar", - "buffer", "complete", "count", - "nargs", "range", "register"}; + static char *user_cmd_flags[] = { "addr", "bang", "bar", + "buffer", "complete", "count", + "nargs", "range", "register" }; - if (idx >= (int)ARRAY_SIZE(user_cmd_flags)) + if (idx >= (int)ARRAY_SIZE(user_cmd_flags)) { return NULL; + } return (char_u *)user_cmd_flags[idx]; } @@ -6163,10 +6292,11 @@ char_u *get_user_cmd_flags(expand_T *xp, int idx) */ char_u *get_user_cmd_nargs(expand_T *xp, int idx) { - static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"}; + static char *user_cmd_nargs[] = { "0", "1", "*", "?", "+" }; - if (idx >= (int)ARRAY_SIZE(user_cmd_nargs)) + if (idx >= (int)ARRAY_SIZE(user_cmd_nargs)) { return NULL; + } return (char_u *)user_cmd_nargs[idx]; } @@ -6222,8 +6352,8 @@ int parse_addr_type_arg(char_u *value, int vallen, cmd_addr_T *addr_type_arg) * copied to allocated memory and stored in "*compl_arg". * Returns FAIL if something is wrong. */ -int parse_compl_arg(const char_u *value, int vallen, int *complp, - uint32_t *argt, char_u **compl_arg) +int parse_compl_arg(const char_u *value, int vallen, int *complp, uint32_t *argt, + char_u **compl_arg) FUNC_ATTR_NONNULL_ALL { const char_u *arg = NULL; @@ -6231,7 +6361,7 @@ int parse_compl_arg(const char_u *value, int vallen, int *complp, int i; int valend = vallen; - /* Look for any argument part - which is the part after any ',' */ + // Look for any argument part - which is the part after any ',' for (i = 0; i < vallen; ++i) { if (value[i] == ',') { arg = &value[i + 1]; @@ -6282,17 +6412,17 @@ int parse_compl_arg(const char_u *value, int vallen, int *complp, int cmdcomplete_str_to_type(const char *complete_str) { - for (int i = 0; i < (int)(ARRAY_SIZE(command_complete)); i++) { - char *cmd_compl = get_command_complete(i); - if (cmd_compl == NULL) { - continue; - } - if (strcmp(complete_str, command_complete[i]) == 0) { - return i; - } + for (int i = 0; i < (int)(ARRAY_SIZE(command_complete)); i++) { + char *cmd_compl = get_command_complete(i); + if (cmd_compl == NULL) { + continue; } + if (strcmp(complete_str, command_complete[i]) == 0) { + return i; + } + } - return EXPAND_NOTHING; + return EXPAND_NOTHING; } static void ex_colorscheme(exarg_T *eap) @@ -6309,10 +6439,12 @@ static void ex_colorscheme(exarg_T *eap) if (p != NULL) { MSG(p); xfree(p); - } else + } else { MSG("default"); - } else if (load_colors(eap->arg) == FAIL) + } + } else if (load_colors(eap->arg) == FAIL) { EMSG2(_("E185: Cannot find color scheme '%s'"), eap->arg); + } } static void ex_highlight(exarg_T *eap) @@ -6370,7 +6502,7 @@ static void ex_quit(exarg_T *eap) cmdwin_result = Ctrl_C; return; } - /* Don't quit while editing the command line. */ + // Don't quit while editing the command line. if (text_locked()) { text_locked_msg(); return; @@ -6382,8 +6514,9 @@ static void ex_quit(exarg_T *eap) int wnr = eap->line2; for (wp = firstwin; wp->w_next != NULL; wp = wp->w_next) { - if (--wnr <= 0) + if (--wnr <= 0) { break; + } } } else { wp = curwin; @@ -6445,7 +6578,7 @@ static void ex_quit_all(exarg_T *eap) return; } - /* Don't quit while editing the command line. */ + // Don't quit while editing the command line. if (text_locked()) { text_locked_msg(); return; @@ -6482,8 +6615,9 @@ static void ex_close(exarg_T *eap) break; } } - if (win == NULL) + if (win == NULL) { win = lastwin; + } ex_win_close(eap->forceit, win, NULL); } } @@ -6502,19 +6636,14 @@ static void ex_pclose(exarg_T *eap) } } -/* - * Close window "win" and take care of handling closing the last window for a - * modified buffer. - */ -void -ex_win_close( - int forceit, - win_T *win, - tabpage_T *tp /* NULL or the tab page "win" is in */ -) +/// Close window "win" and take care of handling closing the last window for a +/// modified buffer. +/// +/// @param tp NULL or the tab page "win" is in +void ex_win_close(int forceit, win_T *win, tabpage_T *tp) { int need_hide; - buf_T *buf = win->w_buffer; + buf_T *buf = win->w_buffer; // Never close the autocommand window. if (win == aucmd_win) { @@ -6553,13 +6682,13 @@ ex_win_close( */ static void ex_tabclose(exarg_T *eap) { - tabpage_T *tp; + tabpage_T *tp; - if (cmdwin_type != 0) + if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; - else if (first_tabpage->tp_next == NULL) + } else if (first_tabpage->tp_next == NULL) { EMSG(_("E784: Cannot close last tab page")); - else { + } else { int tab_number = get_tabpage_arg(eap); if (eap->errmsg == NULL) { tp = find_tabpage(tab_number); @@ -6583,7 +6712,7 @@ static void ex_tabonly(exarg_T *eap) if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; } else if (first_tabpage->tp_next == NULL) { - MSG(_("Already only one tab page")); + MSG(_("Already only one tab page")); } else { int tab_number = get_tabpage_arg(eap); if (eap->errmsg == NULL) { @@ -6638,7 +6767,7 @@ void tabpage_close(int forceit) void tabpage_close_other(tabpage_T *tp, int forceit) { int done = 0; - win_T *wp; + win_T *wp; int h = tabline_height(); char_u prev_idx[NUMBUFLEN]; @@ -6651,8 +6780,9 @@ void tabpage_close_other(tabpage_T *tp, int forceit) /* Autocommands may delete the tab page under our fingers and we may * fail to close a window with a modified buffer. */ - if (!valid_tabpage(tp) || tp->tp_firstwin == wp) + if (!valid_tabpage(tp) || tp->tp_firstwin == wp) { break; + } } redraw_tabline = true; @@ -6672,10 +6802,11 @@ static void ex_only(exarg_T *eap) if (eap->addr_count > 0) { wnr = eap->line2; for (wp = firstwin; --wnr > 0;) { - if (wp->w_next == NULL) + if (wp->w_next == NULL) { break; - else + } else { wp = wp->w_next; + } } } else { wp = curwin; @@ -6692,34 +6823,35 @@ static void ex_only(exarg_T *eap) */ void ex_all(exarg_T *eap) { - if (eap->addr_count == 0) + if (eap->addr_count == 0) { eap->line2 = 9999; + } do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop); } static void ex_hide(exarg_T *eap) { - // ":hide" or ":hide | cmd": hide current window - if (!eap->skip) { - if (eap->addr_count == 0) { - win_close(curwin, false); // don't free buffer - } else { - int winnr = 0; - win_T *win = NULL; - - FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { - winnr++; - if (winnr == eap->line2) { - win = wp; - break; - } - } - if (win == NULL) { - win = lastwin; - } - win_close(win, false); + // ":hide" or ":hide | cmd": hide current window + if (!eap->skip) { + if (eap->addr_count == 0) { + win_close(curwin, false); // don't free buffer + } else { + int winnr = 0; + win_T *win = NULL; + + FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { + winnr++; + if (winnr == eap->line2) { + win = wp; + break; } + } + if (win == NULL) { + win = lastwin; + } + win_close(win, false); } + } } /// ":stop" and ":suspend": Suspend Vim. @@ -6750,7 +6882,7 @@ static void ex_exit(exarg_T *eap) cmdwin_result = Ctrl_C; return; } - /* Don't quit while editing the command line. */ + // Don't quit while editing the command line. if (text_locked()) { text_locked_msg(); return; @@ -6784,20 +6916,21 @@ static void ex_exit(exarg_T *eap) */ static void ex_print(exarg_T *eap) { - if (curbuf->b_ml.ml_flags & ML_EMPTY) + if (curbuf->b_ml.ml_flags & ML_EMPTY) { EMSG(_(e_emptybuf)); - else { + } else { for (; !got_int; os_breakcheck()) { print_line(eap->line1, - (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound - || (eap->flags & EXFLAG_NR)), - eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST)); - if (++eap->line1 > eap->line2) + (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound + || (eap->flags & EXFLAG_NR)), + eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST)); + if (++eap->line1 > eap->line2) { break; - ui_flush(); /* show one line at a time */ + } + ui_flush(); // show one line at a time } setpcmark(); - /* put cursor at last line */ + // put cursor at last line curwin->w_cursor.lnum = eap->line2; beginline(BL_SOL | BL_FIX); } @@ -6860,11 +6993,11 @@ void alist_new(void) */ void alist_expand(int *fnum_list, int fnum_len) { - char_u **old_arg_files; + char_u **old_arg_files; int old_arg_count; - char_u **new_arg_files; + char_u **new_arg_files; int new_arg_file_count; - char_u *save_p_su = p_su; + char_u *save_p_su = p_su; int i; /* Don't use 'suffixes' here. This should work like the shell did the @@ -6872,15 +7005,16 @@ void alist_expand(int *fnum_list, int fnum_len) * can't set the options. */ p_su = empty_option; old_arg_files = xmalloc(sizeof(*old_arg_files) * GARGCOUNT); - for (i = 0; i < GARGCOUNT; ++i) + for (i = 0; i < GARGCOUNT; ++i) { old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname); + } old_arg_count = GARGCOUNT; if (expand_wildcards(old_arg_count, old_arg_files, - &new_arg_file_count, &new_arg_files, - EW_FILE|EW_NOTFOUND|EW_ADDSLASH|EW_NOERROR) == OK + &new_arg_file_count, &new_arg_files, + EW_FILE|EW_NOTFOUND|EW_ADDSLASH|EW_NOERROR) == OK && new_arg_file_count > 0) { alist_set(&global_alist, new_arg_file_count, new_arg_files, - TRUE, fnum_list, fnum_len); + TRUE, fnum_list, fnum_len); FreeWild(old_arg_count, old_arg_files); } p_su = save_p_su; @@ -6909,15 +7043,17 @@ void alist_set(alist_T *al, int count, char_u **files, int use_curbuf, int *fnum if (got_int) { /* When adding many buffers this can take a long time. Allow * interrupting here. */ - while (i < count) + while (i < count) { xfree(files[i++]); + } break; } /* May set buffer name of a buffer previously used for the * argument list, so that it's re-used by alist_add. */ - if (fnum_list != NULL && i < fnum_len) + if (fnum_list != NULL && i < fnum_len) { buf_set_name(fnum_list[i], files[i]); + } alist_add(al, files[i], use_curbuf ? 2 : 1); os_breakcheck(); @@ -6931,26 +7067,23 @@ void alist_set(alist_T *al, int count, char_u **files, int use_curbuf, int *fnum recursive--; } -/* - * Add file "fname" to argument list "al". - * "fname" must have been allocated and "al" must have been checked for room. - */ -void -alist_add( - alist_T *al, - char_u *fname, - int set_fnum /* 1: set buffer number; 2: re-use curbuf */ -) -{ - if (fname == NULL) /* don't add NULL file names */ +/// Add file "fname" to argument list "al". +/// "fname" must have been allocated and "al" must have been checked for room. +/// +/// @param set_fnum 1: set buffer number; 2: re-use curbuf +void alist_add(alist_T *al, char_u *fname, int set_fnum) +{ + if (fname == NULL) { // don't add NULL file names return; + } #ifdef BACKSLASH_IN_FILENAME slash_adjust(fname); #endif AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname; - if (set_fnum > 0) + if (set_fnum > 0) { AARGLIST(al)[al->al_ga.ga_len].ae_fnum = buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0)); + } ++al->al_ga.ga_len; } @@ -6992,9 +7125,9 @@ static void ex_recover(exarg_T *eap) // Set recoverymode right away to avoid the ATTENTION prompt. recoverymode = true; if (!check_changed(curbuf, (p_awa ? CCGD_AW : 0) - | CCGD_MULTWIN - | (eap->forceit ? CCGD_FORCEIT : 0) - | CCGD_EXCMD) + | CCGD_MULTWIN + | (eap->forceit ? CCGD_FORCEIT : 0) + | CCGD_EXCMD) && (*eap->arg == NUL || setfname(curbuf, eap->arg, NULL, true) == OK)) { @@ -7012,40 +7145,43 @@ static void ex_wrongmodifier(exarg_T *eap) } /* - * :sview [+command] file split window with new file, read-only - * :split [[+command] file] split window with current or new file - * :vsplit [[+command] file] split window vertically with current or new file - * :new [[+command] file] split window with no or new file - * :vnew [[+command] file] split vertically window with no or new file - * :sfind [+command] file split window with file in 'path' + * :sview [+command] file split window with new file, read-only + * :split [[+command] file] split window with current or new file + * :vsplit [[+command] file] split window vertically with current or new file + * :new [[+command] file] split window with no or new file + * :vnew [[+command] file] split vertically window with no or new file + * :sfind [+command] file split window with file in 'path' * - * :tabedit open new Tab page with empty window - * :tabedit [+command] file open new Tab page and edit "file" - * :tabnew [[+command] file] just like :tabedit - * :tabfind [+command] file open new Tab page and find "file" + * :tabedit open new Tab page with empty window + * :tabedit [+command] file open new Tab page and edit "file" + * :tabnew [[+command] file] just like :tabedit + * :tabfind [+command] file open new Tab page and find "file" */ void ex_splitview(exarg_T *eap) { - win_T *old_curwin = curwin; - char_u *fname = NULL; + win_T *old_curwin = curwin; + char_u *fname = NULL; const bool use_tab = eap->cmdidx == CMD_tabedit - || eap->cmdidx == CMD_tabfind - || eap->cmdidx == CMD_tabnew; + || eap->cmdidx == CMD_tabfind + || eap->cmdidx == CMD_tabnew; /* A ":split" in the quickfix window works like ":new". Don't want two * quickfix windows. But it's OK when doing ":tab split". */ if (bt_quickfix(curbuf) && cmdmod.tab == 0) { - if (eap->cmdidx == CMD_split) + if (eap->cmdidx == CMD_split) { eap->cmdidx = CMD_new; - if (eap->cmdidx == CMD_vsplit) + } + if (eap->cmdidx == CMD_vsplit) { eap->cmdidx = CMD_vnew; + } } if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind) { fname = find_file_in_path(eap->arg, STRLEN(eap->arg), FNAME_MESS, TRUE, curbuf->b_ffname); - if (fname == NULL) + if (fname == NULL) { goto theend; + } eap->arg = fname; } @@ -7058,15 +7194,16 @@ void ex_splitview(exarg_T *eap) do_exedit(eap, old_curwin); apply_autocmds(EVENT_TABNEWENTERED, NULL, NULL, FALSE, curbuf); - /* set the alternate buffer for the window we came from */ + // set the alternate buffer for the window we came from if (curwin != old_curwin && win_valid(old_curwin) && old_curwin->w_buffer != curbuf - && !cmdmod.keepalt) + && !cmdmod.keepalt) { old_curwin->w_alt_fnum = curbuf->b_fnum; + } } } else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0, - *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL) { + *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL) { /* Reset 'scrollbind' when editing another file, but keep it when * doing ":split" without arguments. */ if (*eap->arg != NUL @@ -7173,7 +7310,7 @@ static void ex_tabs(exarg_T *eap) FOR_ALL_TABS(tp) { if (got_int) { - break; + break; } msg_putchar('\n'); @@ -7192,13 +7329,14 @@ static void ex_tabs(exarg_T *eap) msg_putchar(' '); msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' '); msg_putchar(' '); - if (buf_spname(wp->w_buffer) != NULL) + if (buf_spname(wp->w_buffer) != NULL) { STRLCPY(IObuff, buf_spname(wp->w_buffer), IOSIZE); - else + } else { home_replace(wp->w_buffer, wp->w_buffer->b_fname, - IObuff, IOSIZE, TRUE); + IObuff, IOSIZE, TRUE); + } msg_outtrans(IObuff); - ui_flush(); /* output one line at a time */ + ui_flush(); // output one line at a time os_breakcheck(); } } @@ -7226,12 +7364,13 @@ static void ex_mode(exarg_T *eap) static void ex_resize(exarg_T *eap) { int n; - win_T *wp = curwin; + win_T *wp = curwin; if (eap->addr_count > 0) { n = eap->line2; - for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next) + for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next) { ; + } } n = atol((char *)eap->arg); @@ -7257,7 +7396,7 @@ static void ex_resize(exarg_T *eap) */ static void ex_find(exarg_T *eap) { - char_u *fname; + char_u *fname; int count; fname = find_file_in_path(eap->arg, STRLEN(eap->arg), @@ -7285,14 +7424,10 @@ static void ex_edit(exarg_T *eap) do_exedit(eap, NULL); } -/* - * ":edit <file>" command and alikes. - */ -void -do_exedit( - exarg_T *eap, - win_T *old_curwin /* curwin before doing a split or NULL */ -) +/// ":edit <file>" command and alikes. +/// +/// @param old_curwin curwin before doing a split or NULL +void do_exedit(exarg_T *eap, win_T *old_curwin) { int n; int need_hide; @@ -7305,7 +7440,7 @@ do_exedit( exmode_active = false; ex_pressedreturn = false; if (*eap->arg == NUL) { - /* Special case: ":global/pat/visual\NLvi-commands" */ + // Special case: ":global/pat/visual\NLvi-commands" if (global_busy) { int rd = RedrawingDisabled; int nwr = no_wait_return; @@ -7337,11 +7472,11 @@ do_exedit( || eap->cmdidx == CMD_tabedit || eap->cmdidx == CMD_vnew ) && *eap->arg == NUL) { - /* ":new" or ":tabnew" without argument: edit an new empty buffer */ + // ":new" or ":tabnew" without argument: edit an new empty buffer setpcmark(); (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE, - ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0), - old_curwin == NULL ? curwin : NULL); + ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0), + old_curwin == NULL ? curwin : NULL); } else if ((eap->cmdidx != CMD_split && eap->cmdidx != CMD_vsplit) || *eap->arg != NUL) { // Can't edit another file when "curbuf->b_ro_lockec" is set. Only ":edit" @@ -7394,12 +7529,14 @@ do_exedit( } readonlymode = n; } else { - if (eap->do_ecmd_cmd != NULL) + if (eap->do_ecmd_cmd != NULL) { do_cmdline_cmd((char *)eap->do_ecmd_cmd); + } n = curwin->w_arg_idx_invalid; check_arg_idx(curwin); - if (n != curwin->w_arg_idx_invalid) + if (n != curwin->w_arg_idx_invalid) { maketitle(); + } } /* @@ -7411,8 +7548,9 @@ do_exedit( && curwin != old_curwin && win_valid(old_curwin) && old_curwin->w_buffer != curbuf - && !cmdmod.keepalt) + && !cmdmod.keepalt) { old_curwin->w_alt_fnum = curbuf->b_fnum; + } ex_no_reprint = true; } @@ -7427,10 +7565,11 @@ static void ex_nogui(exarg_T *eap) static void ex_swapname(exarg_T *eap) { - if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL) + if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL) { MSG(_("No swap file")); - else + } else { msg(curbuf->b_ml.ml_mfp->mf_fname); + } } /* @@ -7440,8 +7579,8 @@ static void ex_swapname(exarg_T *eap) */ static void ex_syncbind(exarg_T *eap) { - win_T *save_curwin = curwin; - buf_T *save_curbuf = curbuf; + win_T *save_curwin = curwin; + buf_T *save_curbuf = curbuf; long topline; long y; linenr_T old_linenr = curwin->w_cursor.lnum; @@ -7477,10 +7616,11 @@ static void ex_syncbind(exarg_T *eap) if (curwin->w_p_scb) { curbuf = curwin->w_buffer; y = topline - curwin->w_topline; - if (y > 0) + if (y > 0) { scrollup(y, TRUE); - else + } else { scrolldown(-y, TRUE); + } curwin->w_scbind_pos = topline; redraw_later(curwin, VALID); cursor_correct(); @@ -7521,13 +7661,13 @@ static void ex_read(exarg_T *eap) return; } i = readfile(curbuf->b_ffname, curbuf->b_fname, - eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); + eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); } else { - if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL) + if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL) { (void)setaltfname(eap->arg, eap->arg, (linenr_T)1); + } i = readfile(eap->arg, NULL, - eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); - + eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); } if (i != OK) { if (!aborting()) { @@ -7537,10 +7677,11 @@ static void ex_read(exarg_T *eap) if (empty && exmode_active) { /* Delete the empty line that remains. Historically ex does * this but vi doesn't. */ - if (eap->line2 == 0) + if (eap->line2 == 0) { lnum = curbuf->b_ml.ml_line_count; - else + } else { lnum = 1; + } if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK) { ml_delete(lnum, false); if (curwin->w_cursor.lnum > 1 @@ -7555,7 +7696,7 @@ static void ex_read(exarg_T *eap) } } -static char_u *prev_dir = NULL; +static char_u *prev_dir = NULL; #if defined(EXITFREE) void free_cd_dir(void) @@ -7615,21 +7756,22 @@ void post_chdir(CdScope scope, bool trigger_dirchanged) /// `:cd`, `:tcd`, `:lcd`, `:chdir`, `:tchdir` and `:lchdir`. void ex_cd(exarg_T *eap) { - char_u *new_dir; - char_u *tofree; + char_u *new_dir; + char_u *tofree; new_dir = eap->arg; #if !defined(UNIX) - /* for non-UNIX ":cd" means: print current directory */ - if (*new_dir == NUL) + // for non-UNIX ":cd" means: print current directory + if (*new_dir == NUL) { ex_pwd(NULL); - else + } else #endif { - if (allbuf_locked()) + if (allbuf_locked()) { return; + } - /* ":cd -": Change to previous directory */ + // ":cd -": Change to previous directory if (STRCMP(new_dir, "-") == 0) { if (prev_dir == NULL) { EMSG(_("E186: No previous directory")); @@ -7638,12 +7780,13 @@ void ex_cd(exarg_T *eap) new_dir = prev_dir; } - /* Save current directory for next ":cd -" */ + // Save current directory for next ":cd -" tofree = prev_dir; - if (os_dirname(NameBuff, MAXPATHL) == OK) + if (os_dirname(NameBuff, MAXPATHL) == OK) { prev_dir = vim_strsave(NameBuff); - else + } else { prev_dir = NULL; + } #if defined(UNIX) // On Unix ":cd" means: go to home directory. @@ -7692,8 +7835,9 @@ static void ex_pwd(exarg_T *eap) slash_adjust(NameBuff); #endif msg(NameBuff); - } else + } else { EMSG(_("E187: Unknown")); + } } /* @@ -7712,15 +7856,19 @@ static void ex_sleep(exarg_T *eap) if (cursor_valid()) { n = curwin->w_winrow + curwin->w_wrow - msg_scrolled; - if (n >= 0) + if (n >= 0) { ui_cursor_goto(n, curwin->w_wincol + curwin->w_wcol); + } } len = eap->line2; switch (*eap->arg) { - case 'm': break; - case NUL: len *= 1000L; break; - default: EMSG2(_(e_invarg2), eap->arg); return; + case 'm': + break; + case NUL: + len *= 1000L; break; + default: + EMSG2(_(e_invarg2), eap->arg); return; } do_sleep(len); } @@ -7747,16 +7895,18 @@ void do_sleep(long msec) static void do_exmap(exarg_T *eap, int isabbrev) { int mode; - char_u *cmdp; + char_u *cmdp; cmdp = eap->cmd; mode = get_map_mode(&cmdp, eap->forceit || isabbrev); switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'), - eap->arg, mode, isabbrev)) { - case 1: EMSG(_(e_invarg)); + eap->arg, mode, isabbrev)) { + case 1: + EMSG(_(e_invarg)); break; - case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap)); + case 2: + EMSG(isabbrev ? _(e_noabbr) : _(e_nomap)); break; } } @@ -7786,25 +7936,26 @@ static void ex_winsize(exarg_T *eap) static void ex_wincmd(exarg_T *eap) { int xchar = NUL; - char_u *p; + char_u *p; if (*eap->arg == 'g' || *eap->arg == Ctrl_G) { - /* CTRL-W g and CTRL-W CTRL-G have an extra command character */ + // CTRL-W g and CTRL-W CTRL-G have an extra command character if (eap->arg[1] == NUL) { EMSG(_(e_invarg)); return; } xchar = eap->arg[1]; p = eap->arg + 2; - } else + } else { p = eap->arg + 1; + } eap->nextcmd = check_nextcmd(p); p = skipwhite(p); - if (*p != NUL && *p != '"' && eap->nextcmd == NULL) + if (*p != NUL && *p != '"' && eap->nextcmd == NULL) { EMSG(_(e_invarg)); - else if (!eap->skip) { - /* Pass flags on for ":vertical wincmd ]". */ + } else if (!eap->skip) { + // Pass flags on for ":vertical wincmd ]". postponed_split_flags = cmdmod.split; postponed_split_tab = cmdmod.tab; do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar); @@ -7833,8 +7984,9 @@ static void ex_operators(exarg_T *eap) beginline(BL_SOL | BL_FIX); } - if (VIsual_active) + if (VIsual_active) { end_visual_mode(); + } switch (eap->cmdidx) { case CMD_delete: @@ -7847,13 +7999,14 @@ static void ex_operators(exarg_T *eap) (void)op_yank(&oa, true, false); break; - default: /* CMD_rshift or CMD_lshift */ + default: // CMD_rshift or CMD_lshift if ( - (eap->cmdidx == CMD_rshift) ^ curwin->w_p_rl - ) + (eap->cmdidx == CMD_rshift) ^ curwin->w_p_rl + ) { oa.op_type = OP_RSHIFT; - else + } else { oa.op_type = OP_LSHIFT; + } op_shift(&oa, FALSE, eap->amount); break; } @@ -7866,7 +8019,7 @@ static void ex_operators(exarg_T *eap) */ static void ex_put(exarg_T *eap) { - /* ":0put" works like ":1put!". */ + // ":0put" works like ":1put!". if (eap->line2 == 0) { eap->line2 = 1; eap->forceit = TRUE; @@ -7897,10 +8050,12 @@ static void ex_copymove(exarg_T *eap) } if (eap->cmdidx == CMD_move) { - if (do_move(eap->line1, eap->line2, n) == FAIL) + if (do_move(eap->line1, eap->line2, n) == FAIL) { return; - } else + } + } else { ex_copy(eap->line1, eap->line2, n); + } u_clearline(); beginline(BL_SOL | BL_FIX); ex_may_print(eap); @@ -7935,8 +8090,9 @@ static void ex_join(exarg_T *eap) { curwin->w_cursor.lnum = eap->line1; if (eap->line1 == eap->line2) { - if (eap->addr_count >= 2) /* :2,2join does nothing */ + if (eap->addr_count >= 2) { // :2,2join does nothing return; + } if (eap->line2 == curbuf->b_ml.ml_line_count) { beep_flush(); return; @@ -7964,7 +8120,7 @@ static void ex_at(exarg_T *eap) c = '@'; } - /* Put the register in the typeahead buffer with the "silent" flag. */ + // Put the register in the typeahead buffer with the "silent" flag. if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE) == FAIL) { beep_flush(); @@ -7978,8 +8134,9 @@ static void ex_at(exarg_T *eap) * Continue until the stuff buffer is empty and all added characters * have been consumed. */ - while (!stuff_empty() || typebuf.tb_len > prev_len) + while (!stuff_empty() || typebuf.tb_len > prev_len) { (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE); + } exec_from_reg = save_efr; } @@ -8033,18 +8190,23 @@ static void ex_later(exarg_T *eap) long count = 0; bool sec = false; bool file = false; - char_u *p = eap->arg; + char_u *p = eap->arg; if (*p == NUL) { count = 1; } else if (isdigit(*p)) { count = getdigits_long(&p, false, 0); switch (*p) { - case 's': ++p; sec = true; break; - case 'm': ++p; sec = true; count *= 60; break; - case 'h': ++p; sec = true; count *= 60 * 60; break; - case 'd': ++p; sec = true; count *= 24 * 60 * 60; break; - case 'f': ++p; file = true; break; + case 's': + ++p; sec = true; break; + case 'm': + ++p; sec = true; count *= 60; break; + case 'h': + ++p; sec = true; count *= 60 * 60; break; + case 'd': + ++p; sec = true; count *= 24 * 60 * 60; break; + case 'f': + ++p; file = true; break; } } @@ -8061,43 +8223,46 @@ static void ex_later(exarg_T *eap) */ static void ex_redir(exarg_T *eap) { - char *mode; - char_u *fname; - char_u *arg = eap->arg; + char *mode; + char_u *fname; + char_u *arg = eap->arg; - if (STRICMP(eap->arg, "END") == 0) + if (STRICMP(eap->arg, "END") == 0) { close_redir(); - else { + } else { if (*arg == '>') { ++arg; if (*arg == '>') { ++arg; mode = "a"; - } else + } else { mode = "w"; + } arg = skipwhite(arg); close_redir(); - /* Expand environment variables and "~/". */ + // Expand environment variables and "~/". fname = expand_env_save(arg); - if (fname == NULL) + if (fname == NULL) { return; + } redir_fd = open_exfile(fname, eap->forceit, mode); xfree(fname); } else if (*arg == '@') { - /* redirect to a register a-z (resp. A-Z for appending) */ + // redirect to a register a-z (resp. A-Z for appending) close_redir(); ++arg; if (valid_yank_reg(*arg, true) && *arg != '_') { redir_reg = *arg++; - if (*arg == '>' && arg[1] == '>') /* append */ + if (*arg == '>' && arg[1] == '>') { // append arg += 2; - else { - /* Can use both "@a" and "@a>". */ - if (*arg == '>') + } else { + // Can use both "@a" and "@a>". + if (*arg == '>') { arg++; + } // Make register empty when not using @A-@Z and the // command is valid. if (*arg == NUL && !isupper(redir_reg)) { @@ -8112,30 +8277,33 @@ static void ex_redir(exarg_T *eap) } else if (*arg == '=' && arg[1] == '>') { int append; - /* redirect to a variable */ + // redirect to a variable close_redir(); arg += 2; if (*arg == '>') { ++arg; append = TRUE; - } else + } else { append = FALSE; + } - if (var_redir_start(skipwhite(arg), append) == OK) + if (var_redir_start(skipwhite(arg), append) == OK) { redir_vname = 1; + } } - /* TODO: redirect to a buffer */ - else + // TODO: redirect to a buffer + else { EMSG2(_(e_invarg2), eap->arg); + } } /* Make sure redirection is not off. Can happen for cmdline completion * that indirectly invokes a command to catch its output. */ if (redir_fd != NULL - || redir_reg || redir_vname - ) + || redir_reg || redir_vname) { redir_off = false; + } } /// ":redraw": force redraw @@ -8155,7 +8323,7 @@ static void ex_redraw(exarg_T *eap) redraw_all_later(NOT_VALID); } update_screen(eap->forceit ? NOT_VALID - : VIsual_active ? INVERTED : 0); + : VIsual_active ? INVERTED : 0); if (need_maketitle) { maketitle(); } @@ -8183,13 +8351,13 @@ static void ex_redrawstatus(exarg_T *eap) RedrawingDisabled = 0; p_lz = FALSE; - if (eap->forceit) + if (eap->forceit) { status_redraw_all(); - else + } else { status_redraw_curbuf(); - update_screen( - VIsual_active ? INVERTED : - 0); + } + update_screen(VIsual_active ? INVERTED : + 0); RedrawingDisabled = r; p_lz = p; ui_flush(); @@ -8241,21 +8409,17 @@ int vim_mkdir_emsg(const char *const name, const int prot) return OK; } -/* - * Open a file for writing for an Ex command, with some checks. - * Return file descriptor, or NULL on failure. - */ -FILE * -open_exfile ( - char_u *fname, - int forceit, - char *mode /* "w" for create new file or "a" for append */ -) +/// Open a file for writing for an Ex command, with some checks. +/// +/// @param mode "w" for create new file or "a" for append +/// +/// @return file descriptor, or NULL on failure. +FILE *open_exfile(char_u *fname, int forceit, char *mode) { - FILE *fd; + FILE *fd; #ifdef UNIX - /* with Unix it is possible to open a directory */ + // with Unix it is possible to open a directory if (os_isdir(fname)) { EMSG2(_(e_isadir2), fname); return NULL; @@ -8280,17 +8444,18 @@ static void ex_mark(exarg_T *eap) { pos_T pos; - if (*eap->arg == NUL) /* No argument? */ + if (*eap->arg == NUL) { // No argument? EMSG(_(e_argreq)); - else if (eap->arg[1] != NUL) /* more than one character? */ + } else if (eap->arg[1] != NUL) { // more than one character? EMSG(_(e_trailing)); - else { - pos = curwin->w_cursor; /* save curwin->w_cursor */ + } else { + pos = curwin->w_cursor; // save curwin->w_cursor curwin->w_cursor.lnum = eap->line2; beginline(BL_WHITE | BL_FIX); - if (setmark(*eap->arg) == FAIL) /* set mark */ + if (setmark(*eap->arg) == FAIL) { // set mark EMSG(_("E191: Argument must be a letter or forward/backward quote")); - curwin->w_cursor = pos; /* restore curwin->w_cursor */ + } + curwin->w_cursor = pos; // restore curwin->w_cursor } } @@ -8370,9 +8535,9 @@ static void ex_normal(exarg_T *eap) return; } save_state_T save_state; - char_u *arg = NULL; + char_u *arg = NULL; int l; - char_u *p; + char_u *p; if (ex_normal_lock > 0) { EMSG(_(e_secure)); @@ -8389,12 +8554,14 @@ static void ex_normal(exarg_T *eap) { int len = 0; - /* Count the number of characters to be escaped. */ + // Count the number of characters to be escaped. for (p = eap->arg; *p != NUL; ++p) { - for (l = (*mb_ptr2len)(p) - 1; l > 0; --l) - if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */ - ) + for (l = (*mb_ptr2len)(p) - 1; l > 0; --l) { + if (*++p == K_SPECIAL // trailbyte K_SPECIAL or CSI + ) { len += 2; + } + } } if (len > 0) { arg = xmalloc(STRLEN(eap->arg) + len + 1); @@ -8430,7 +8597,7 @@ static void ex_normal(exarg_T *eap) } while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int); } - /* Might not return to the main loop when in an event handler. */ + // Might not return to the main loop when in an event handler. update_topline_cursor(); restore_current_state(&save_state); @@ -8461,16 +8628,18 @@ static void ex_startinsert(exarg_T *eap) return; } - if (eap->cmdidx == CMD_startinsert) + if (eap->cmdidx == CMD_startinsert) { restart_edit = 'a'; - else if (eap->cmdidx == CMD_startreplace) + } else if (eap->cmdidx == CMD_startreplace) { restart_edit = 'R'; - else + } else { restart_edit = 'V'; + } if (!eap->forceit) { - if (eap->cmdidx == CMD_startinsert) + if (eap->cmdidx == CMD_startinsert) { restart_edit = 'i'; + } curwin->w_curswant = 0; // avoid MAXCOL } @@ -8539,23 +8708,24 @@ static void ex_findpat(exarg_T *eap) { int whole = TRUE; long n; - char_u *p; + char_u *p; int action; switch (cmdnames[eap->cmdidx].cmd_name[2]) { - case 'e': /* ":psearch", ":isearch" and ":dsearch" */ - if (cmdnames[eap->cmdidx].cmd_name[0] == 'p') + case 'e': // ":psearch", ":isearch" and ":dsearch" + if (cmdnames[eap->cmdidx].cmd_name[0] == 'p') { action = ACTION_GOTO; - else + } else { action = ACTION_SHOW; + } break; - case 'i': /* ":ilist" and ":dlist" */ + case 'i': // ":ilist" and ":dlist" action = ACTION_SHOW_ALL; break; - case 'u': /* ":ijump" and ":djump" */ + case 'u': // ":ijump" and ":djump" action = ACTION_GOTO; break; - default: /* ":isplit" and ":dsplit" */ + default: // ":isplit" and ":dsplit" action = ACTION_SPLIT; break; } @@ -8581,10 +8751,11 @@ static void ex_findpat(exarg_T *eap) } } } - if (!eap->skip) + if (!eap->skip) { find_pattern_in_path(eap->arg, 0, STRLEN(eap->arg), whole, !eap->forceit, *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY, n, action, eap->line1, eap->line2); + } } @@ -8593,7 +8764,7 @@ static void ex_findpat(exarg_T *eap) */ static void ex_ptag(exarg_T *eap) { - g_do_tagpreview = p_pvh; /* will be reset to 0 in ex_tag_cmd() */ + g_do_tagpreview = p_pvh; // will be reset to 0 in ex_tag_cmd() ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1); } @@ -8602,7 +8773,7 @@ static void ex_ptag(exarg_T *eap) */ static void ex_pedit(exarg_T *eap) { - win_T *curwin_save = curwin; + win_T *curwin_save = curwin; // Open the preview window or popup and make it the current window. g_do_tagpreview = p_pvh; @@ -8646,21 +8817,28 @@ static void ex_tag_cmd(exarg_T *eap, char_u *name) int cmd; switch (name[1]) { - case 'j': cmd = DT_JUMP; // ":tjump" + case 'j': + cmd = DT_JUMP; // ":tjump" break; - case 's': cmd = DT_SELECT; // ":tselect" + case 's': + cmd = DT_SELECT; // ":tselect" break; case 'p': // ":tprevious" - case 'N': cmd = DT_PREV; // ":tNext" + case 'N': + cmd = DT_PREV; // ":tNext" break; - case 'n': cmd = DT_NEXT; // ":tnext" + case 'n': + cmd = DT_NEXT; // ":tnext" break; - case 'o': cmd = DT_POP; // ":pop" + case 'o': + cmd = DT_POP; // ":pop" break; case 'f': // ":tfirst" - case 'r': cmd = DT_FIRST; // ":trewind" + case 'r': + cmd = DT_FIRST; // ":trewind" break; - case 'l': cmd = DT_LAST; // ":tlast" + case 'l': + cmd = DT_LAST; // ":tlast" break; default: // ":tag" if (p_cst && *eap->arg != NUL) { @@ -8676,7 +8854,7 @@ static void ex_tag_cmd(exarg_T *eap, char_u *name) } do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1, - eap->forceit, TRUE); + eap->forceit, TRUE); } enum { @@ -8735,58 +8913,57 @@ ssize_t find_cmdline_var(const char_u *src, size_t *usedlen) return -1; } -/* - * Evaluate cmdline variables. - * - * change '%' to curbuf->b_ffname - * '#' to curwin->w_alt_fnum - * '<cword>' to word under the cursor - * '<cWORD>' to WORD under the cursor - * '<cexpr>' to C-expression under the cursor - * '<cfile>' to path name under the cursor - * '<sfile>' to sourced file name - * '<slnum>' to sourced file line number - * '<afile>' to file name for autocommand - * '<abuf>' to buffer number for autocommand - * '<amatch>' to matching name for autocommand - * - * When an error is detected, "errormsg" is set to a non-NULL pointer (may be - * "" for error without a message) and NULL is returned. - * Returns an allocated string if a valid match was found. - * Returns NULL if no match was found. "usedlen" then still contains the - * number of characters to skip. - */ -char_u * -eval_vars ( - char_u *src, /* pointer into commandline */ - char_u *srcstart, /* beginning of valid memory for src */ - size_t *usedlen, /* characters after src that are used */ - linenr_T *lnump, /* line number for :e command, or NULL */ - char_u **errormsg, /* pointer to error message */ - int *escaped /* return value has escaped white space (can - * be NULL) */ -) +/// Evaluate cmdline variables. +/// +/// change '%' to curbuf->b_ffname +/// '#' to curwin->w_alt_fnum +/// '<cword>' to word under the cursor +/// '<cWORD>' to WORD under the cursor +/// '<cexpr>' to C-expression under the cursor +/// '<cfile>' to path name under the cursor +/// '<sfile>' to sourced file name +/// '<slnum>' to sourced file line number +/// '<afile>' to file name for autocommand +/// '<abuf>' to buffer number for autocommand +/// '<amatch>' to matching name for autocommand +/// +/// When an error is detected, "errormsg" is set to a non-NULL pointer (may be +/// "" for error without a message) and NULL is returned. +/// +/// @param src pointer into commandline +/// @param srcstart beginning of valid memory for src +/// @param usedlen characters after src that are used +/// @param lnump line number for :e command, or NULL +/// @param errormsg pointer to error message +/// @param escaped return value has escaped white space (can be NULL) +/// +/// @return an allocated string if a valid match was found. +/// Returns NULL if no match was found. "usedlen" then still contains the +/// number of characters to skip. +char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnump, + char_u **errormsg, int *escaped) { int i; - char_u *s; - char_u *result; - char_u *resultbuf = NULL; + char_u *s; + char_u *result; + char_u *resultbuf = NULL; size_t resultlen; - buf_T *buf; + buf_T *buf; int valid = VALID_HEAD | VALID_PATH; // Assume valid result. bool tilde_file = false; int skip_mod = false; char strbuf[30]; *errormsg = NULL; - if (escaped != NULL) + if (escaped != NULL) { *escaped = FALSE; + } /* * Check if there is something to do. */ ssize_t spec_idx = find_cmdline_var(src, usedlen); - if (spec_idx < 0) { /* no match */ + if (spec_idx < 0) { // no match *usedlen = 1; return NULL; } @@ -8797,7 +8974,7 @@ eval_vars ( */ if (src > srcstart && src[-1] == '\\') { *usedlen = 0; - STRMOVE(src - 1, src); /* remove backslash */ + STRMOVE(src - 1, src); // remove backslash return NULL; } @@ -8807,9 +8984,8 @@ eval_vars ( if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD || spec_idx == SPEC_CEXPR) { - resultlen = find_ident_under_cursor( - &result, - spec_idx == SPEC_CWORD + resultlen = find_ident_under_cursor(&result, + spec_idx == SPEC_CWORD ? (FIND_IDENT | FIND_STRING) : (spec_idx == SPEC_CEXPR ? (FIND_IDENT | FIND_STRING | FIND_EVAL) @@ -8818,13 +8994,13 @@ eval_vars ( *errormsg = (char_u *)""; return NULL; } - // - // '#': Alternate file name - // '%': Current file name - // File name under the cursor - // File name for autocommand - // and following modifiers - // + // + // '#': Alternate file name + // '%': Current file name + // File name under the cursor + // File name for autocommand + // and following modifiers + // } else { switch (spec_idx) { case SPEC_PERC: // '%': current file @@ -8837,13 +9013,14 @@ eval_vars ( } break; - case SPEC_HASH: /* '#' or "#99": alternate file */ - if (src[1] == '#') { /* "##": the argument list */ + case SPEC_HASH: // '#' or "#99": alternate file + if (src[1] == '#') { // "##": the argument list result = arg_all(); resultbuf = result; *usedlen = 2; - if (escaped != NULL) + if (escaped != NULL) { *escaped = TRUE; + } skip_mod = TRUE; break; } @@ -8860,7 +9037,7 @@ eval_vars ( if (src[1] == '<' && i != 0) { if (*usedlen < 2) { - /* Should we give an error message for #<text? */ + // Should we give an error message for #<text? *usedlen = 1; return NULL; } @@ -8876,12 +9053,12 @@ eval_vars ( } buf = buflist_findnr(i); if (buf == NULL) { - *errormsg = (char_u *)_( - "E194: No alternate file name to substitute for '#'"); + *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'"); return NULL; } - if (lnump != NULL) + if (lnump != NULL) { *lnump = ECMD_LAST; + } if (buf->b_fname == NULL) { result = (char_u *)""; valid = 0; // Must have ":p:h" to be valid @@ -8892,13 +9069,13 @@ eval_vars ( } break; - case SPEC_CFILE: /* file name under cursor */ + case SPEC_CFILE: // file name under cursor result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL); if (result == NULL) { *errormsg = (char_u *)""; return NULL; } - resultbuf = result; /* remember allocated string */ + resultbuf = result; // remember allocated string break; case SPEC_AFILE: // file name for autocommand @@ -8915,37 +9092,33 @@ eval_vars ( } result = autocmd_fname; if (result == NULL) { - *errormsg = (char_u *)_( - "E495: no autocommand file name to substitute for \"<afile>\""); + *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\""); return NULL; } result = path_try_shorten_fname(result); break; - case SPEC_ABUF: /* buffer number for autocommand */ + case SPEC_ABUF: // buffer number for autocommand if (autocmd_bufnr <= 0) { - *errormsg = (char_u *)_( - "E496: no autocommand buffer number to substitute for \"<abuf>\""); + *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\""); return NULL; } snprintf(strbuf, sizeof(strbuf), "%d", autocmd_bufnr); result = (char_u *)strbuf; break; - case SPEC_AMATCH: /* match name for autocommand */ + case SPEC_AMATCH: // match name for autocommand result = autocmd_match; if (result == NULL) { - *errormsg = (char_u *)_( - "E497: no autocommand match name to substitute for \"<amatch>\""); + *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\""); return NULL; } break; - case SPEC_SFILE: /* file name for ":so" command */ + case SPEC_SFILE: // file name for ":so" command result = sourcing_name; if (result == NULL) { - *errormsg = (char_u *)_( - "E498: no :source file name to substitute for \"<sfile>\""); + *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\""); return NULL; } break; @@ -9005,15 +9178,16 @@ eval_vars ( } if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH) { - if (valid != VALID_HEAD + VALID_PATH) - /* xgettext:no-c-format */ - *errormsg = (char_u *)_( - "E499: Empty file name for '%' or '#', only works with \":p:h\""); - else + if (valid != VALID_HEAD + VALID_PATH) { + // xgettext:no-c-format + *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\""); + } else { *errormsg = (char_u *)_("E500: Evaluates to an empty string"); + } result = NULL; - } else + } else { result = vim_strnsave(result, resultlen); + } xfree(resultbuf); return result; } @@ -9027,8 +9201,8 @@ static char_u *arg_all(void) { int len; int idx; - char_u *retval = NULL; - char_u *p; + char_u *retval = NULL; + char_u *p; /* * Do this loop two times: @@ -9043,9 +9217,10 @@ static char_u *arg_all(void) continue; } if (len > 0) { - /* insert a space in between names */ - if (retval != NULL) + // insert a space in between names + if (retval != NULL) { retval[len] = ' '; + } ++len; } for (; *p != NUL; p++) { @@ -9067,13 +9242,13 @@ static char_u *arg_all(void) } } - /* second time: break here */ + // second time: break here if (retval != NULL) { retval[len] = NUL; break; } - /* allocate memory */ + // allocate memory retval = xmalloc(len + 1); } @@ -9087,29 +9262,30 @@ static char_u *arg_all(void) */ char_u *expand_sfile(char_u *arg) { - char_u *errormsg; + char_u *errormsg; size_t len; - char_u *result; - char_u *newres; - char_u *repl; + char_u *result; + char_u *newres; + char_u *repl; size_t srclen; - char_u *p; + char_u *p; result = vim_strsave(arg); for (p = result; *p; ) { - if (STRNCMP(p, "<sfile>", 7) != 0) + if (STRNCMP(p, "<sfile>", 7) != 0) { ++p; - else { - /* replace "<sfile>" with the sourced file name, and do ":" stuff */ + } else { + // replace "<sfile>" with the sourced file name, and do ":" stuff repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL); if (errormsg != NULL) { - if (*errormsg) + if (*errormsg) { emsg(errormsg); + } xfree(result); return NULL; } - if (repl == NULL) { /* no match (cannot happen) */ + if (repl == NULL) { // no match (cannot happen) p += srclen; continue; } @@ -9122,7 +9298,7 @@ char_u *expand_sfile(char_u *arg) xfree(repl); xfree(result); result = newres; - p = newres + len; /* continue after the match */ + p = newres + len; // continue after the match } } @@ -9134,15 +9310,16 @@ char_u *expand_sfile(char_u *arg) */ static void ex_shada(exarg_T *eap) { - char_u *save_shada; + char_u *save_shada; save_shada = p_shada; - if (*p_shada == NUL) + if (*p_shada == NUL) { p_shada = (char_u *)"'100"; + } if (eap->cmdidx == CMD_rviminfo || eap->cmdidx == CMD_rshada) { - (void) shada_read_everything((char *) eap->arg, eap->forceit, false); + (void)shada_read_everything((char *)eap->arg, eap->forceit, false); } else { - shada_write_file((char *) eap->arg, eap->forceit); + shada_write_file((char *)eap->arg, eap->forceit); } p_shada = save_shada; } @@ -9153,8 +9330,9 @@ static void ex_shada(exarg_T *eap) */ void dialog_msg(char_u *buff, char *format, char_u *fname) { - if (fname == NULL) + if (fname == NULL) { fname = (char_u *)_("Untitled"); + } vim_snprintf((char *)buff, DIALOG_MSG_SIZE, format, fname); } @@ -9184,10 +9362,12 @@ static void ex_behave(exarg_T *eap) */ char_u *get_behave_arg(expand_T *xp, int idx) { - if (idx == 0) + if (idx == 0) { return (char_u *)"mswin"; - if (idx == 1) + } + if (idx == 1) { return (char_u *)"xterm"; + } return NULL; } @@ -9224,12 +9404,12 @@ static TriState filetype_indent = kNone; */ static void ex_filetype(exarg_T *eap) { - char_u *arg = eap->arg; + char_u *arg = eap->arg; bool plugin = false; bool indent = false; if (*eap->arg == NUL) { - /* Print current status. */ + // Print current status. smsg("filetype detection:%s plugin:%s indent:%s", filetype_detect == kTrue ? "ON" : "OFF", filetype_plugin == kTrue ? (filetype_detect == kTrue ? "ON" : "(on)") : "OFF", // NOLINT(whitespace/line_length) @@ -9237,7 +9417,7 @@ static void ex_filetype(exarg_T *eap) return; } - /* Accept "plugin" and "indent" in any order. */ + // Accept "plugin" and "indent" in any order. for (;; ) { if (STRNCMP(arg, "plugin", 6) == 0) { plugin = true; @@ -9282,8 +9462,9 @@ static void ex_filetype(exarg_T *eap) source_runtime((char_u *)FTOFF_FILE, DIP_ALL); filetype_detect = kFalse; } - } else + } else { EMSG2(_(e_invarg2), arg); + } } /// Set all :filetype options ON if user did not explicitly set any to OFF. @@ -9333,10 +9514,11 @@ static void ex_set(exarg_T *eap) { int flags = 0; - if (eap->cmdidx == CMD_setlocal) + if (eap->cmdidx == CMD_setlocal) { flags = OPT_LOCAL; - else if (eap->cmdidx == CMD_setglobal) + } else if (eap->cmdidx == CMD_setglobal) { flags = OPT_GLOBAL; + } (void)do_set(eap->arg, flags); } @@ -9536,16 +9718,16 @@ bool cmd_can_preview(char_u *cmd) char_u *end = find_command(&ea, NULL); switch (ea.cmdidx) { - case CMD_substitute: - case CMD_smagic: - case CMD_snomagic: - // Only preview once the pattern delimiter has been typed - if (*end && !ASCII_ISALNUM(*end)) { - return true; - } - break; - default: - break; + case CMD_substitute: + case CMD_smagic: + case CMD_snomagic: + // Only preview once the pattern delimiter has been typed + if (*end && !ASCII_ISALNUM(*end)) { + return true; + } + break; + default: + break; } return false; @@ -9576,11 +9758,16 @@ Dictionary commands_array(buf_T *buf) PUT(d, "register", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_REGSTR))); switch (cmd->uc_argt & (EX_EXTRA | EX_NOSPC | EX_NEEDARG)) { - case 0: arg[0] = '0'; break; - case(EX_EXTRA): arg[0] = '*'; break; - case(EX_EXTRA | EX_NOSPC): arg[0] = '?'; break; - case(EX_EXTRA | EX_NEEDARG): arg[0] = '+'; break; - case(EX_EXTRA | EX_NOSPC | EX_NEEDARG): arg[0] = '1'; break; + case 0: + arg[0] = '0'; break; + case (EX_EXTRA): + arg[0] = '*'; break; + case (EX_EXTRA | EX_NOSPC): + arg[0] = '?'; break; + case (EX_EXTRA | EX_NEEDARG): + arg[0] = '+'; break; + case (EX_EXTRA | EX_NOSPC | EX_NEEDARG): + arg[0] = '1'; break; } PUT(d, "nargs", STRING_OBJ(cstr_to_string(arg))); diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 0f98c9cd34..b90773ce83 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -6056,7 +6056,7 @@ int get_list_range(char_u **str, int *num1, int *num2) *str = skipwhite(*str); if (**str == '-' || ascii_isdigit(**str)) { // parse "from" part of range - vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0); + vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false); *str += len; *num1 = (int)num; first = true; @@ -6064,7 +6064,7 @@ int get_list_range(char_u **str, int *num1, int *num2) *str = skipwhite(*str); if (**str == ',') { // parse "to" part of range *str = skipwhite(*str + 1); - vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0); + vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false); if (len > 0) { *num2 = (int)num; *str = skipwhite(*str + len); diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index 92b48c36cb..e87520359e 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -5,15 +5,13 @@ #include <assert.h> #include <errno.h> +#include <fcntl.h> +#include <inttypes.h> #include <stdbool.h> #include <string.h> -#include <inttypes.h> -#include <fcntl.h> -#include "nvim/vim.h" #include "nvim/api/private/helpers.h" #include "nvim/ascii.h" -#include "nvim/fileio.h" #include "nvim/buffer.h" #include "nvim/buffer_updates.h" #include "nvim/change.h" @@ -25,8 +23,10 @@ #include "nvim/ex_cmds.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" +#include "nvim/fileio.h" #include "nvim/fold.h" #include "nvim/func_attr.h" +#include "nvim/garray.h" #include "nvim/getchar.h" #include "nvim/hashtab.h" #include "nvim/iconv.h" @@ -36,10 +36,13 @@ #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/garray.h" #include "nvim/move.h" #include "nvim/normal.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/os.h" +#include "nvim/os/os_defs.h" +#include "nvim/os/time.h" #include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/quickfix.h" @@ -47,21 +50,18 @@ #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/sha256.h" +#include "nvim/shada.h" #include "nvim/state.h" #include "nvim/strings.h" +#include "nvim/types.h" #include "nvim/ui.h" #include "nvim/ui_compositor.h" -#include "nvim/types.h" #include "nvim/undo.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/shada.h" -#include "nvim/os/os.h" -#include "nvim/os/os_defs.h" -#include "nvim/os/time.h" -#include "nvim/os/input.h" -#define BUFSIZE 8192 /* size of normal write buffer */ -#define SMBUFSIZE 256 /* size of emergency write buffer */ +#define BUFSIZE 8192 // size of normal write buffer +#define SMBUFSIZE 256 // size of emergency write buffer // For compatibility with libuv < 1.20.0 (tested on 1.18.0) #ifndef UV_FS_COPYFILE_FICLONE @@ -69,15 +69,15 @@ #endif #define HAS_BW_FLAGS -#define FIO_LATIN1 0x01 /* convert Latin1 */ -#define FIO_UTF8 0x02 /* convert UTF-8 */ -#define FIO_UCS2 0x04 /* convert UCS-2 */ -#define FIO_UCS4 0x08 /* convert UCS-4 */ -#define FIO_UTF16 0x10 /* convert UTF-16 */ -#define FIO_ENDIAN_L 0x80 /* little endian */ -#define FIO_NOCONVERT 0x2000 /* skip encoding conversion */ -#define FIO_UCSBOM 0x4000 /* check for BOM at start of file */ -#define FIO_ALL -1 /* allow all formats */ +#define FIO_LATIN1 0x01 // convert Latin1 +#define FIO_UTF8 0x02 // convert UTF-8 +#define FIO_UCS2 0x04 // convert UCS-2 +#define FIO_UCS4 0x08 // convert UCS-4 +#define FIO_UTF16 0x10 // convert UTF-16 +#define FIO_ENDIAN_L 0x80 // little endian +#define FIO_NOCONVERT 0x2000 // skip encoding conversion +#define FIO_UCSBOM 0x4000 // check for BOM at start of file +#define FIO_ALL -1 // allow all formats /* When converting, a read() or write() may leave some bytes to be converted * for the next call. The value is guessed... */ @@ -92,7 +92,7 @@ */ struct bw_info { int bw_fd; // file descriptor - char_u *bw_buf; // buffer with data to be written + char_u *bw_buf; // buffer with data to be written int bw_len; // length of data #ifdef HAS_BW_FLAGS int bw_flags; // FIO_ flags @@ -100,7 +100,7 @@ struct bw_info { char_u bw_rest[CONV_RESTLEN]; // not converted bytes int bw_restlen; // nr of bytes in bw_rest[] int bw_first; // first write call - char_u *bw_conv_buf; // buffer for writing converted chars + char_u *bw_conv_buf; // buffer for writing converted chars int bw_conv_buflen; // size of bw_conv_buf int bw_conv_error; // set for conversion error linenr_T bw_conv_error_lnum; // first line with error or zero @@ -114,8 +114,7 @@ struct bw_info { # include "fileio.c.generated.h" #endif -static char *e_auchangedbuf = N_( - "E812: Autocommands changed buffer or buffer name"); +static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name"); void filemess(buf_T *buf, char_u *name, char_u *s, int attr) { @@ -131,14 +130,16 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr) // For further ones overwrite the previous one, reset msg_scroll before // calling filemess(). msg_scroll_save = msg_scroll; - if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) + if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) { msg_scroll = FALSE; - if (!msg_scroll) /* wait a bit when overwriting an error msg */ + } + if (!msg_scroll) { // wait a bit when overwriting an error msg check_for_delay(FALSE); + } msg_start(); msg_scroll = msg_scroll_save; msg_scrolled_ign = TRUE; - /* may truncate the message to avoid a hit-return prompt */ + // may truncate the message to avoid a hit-return prompt msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr); msg_clr_eos(); ui_flush(); @@ -146,41 +147,33 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr) } -/* - * Read lines from file "fname" into the buffer after line "from". - * - * 1. We allocate blocks with try_malloc, as big as possible. - * 2. Each block is filled with characters from the file with a single read(). - * 3. The lines are inserted in the buffer with ml_append(). - * - * (caller must check that fname != NULL, unless READ_STDIN is used) - * - * "lines_to_skip" is the number of lines that must be skipped - * "lines_to_read" is the number of lines that are appended - * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM. - * - * flags: - * READ_NEW starting to edit a new buffer - * READ_FILTER reading filter output - * READ_STDIN read from stdin instead of a file - * READ_BUFFER read from curbuf instead of a file (converting after reading - * stdin) - * READ_DUMMY read into a dummy buffer (to check if file contents changed) - * READ_KEEP_UNDO don't clear undo info or read it from a file - * READ_FIFO read from fifo/socket instead of a file - * - * return FAIL for failure, NOTDONE for directory (failure), or OK - */ -int -readfile( - char_u *fname, - char_u *sfname, - linenr_T from, - linenr_T lines_to_skip, - linenr_T lines_to_read, - exarg_T *eap, // can be NULL! - int flags -) +/// Read lines from file "fname" into the buffer after line "from". +/// +/// 1. We allocate blocks with try_malloc, as big as possible. +/// 2. Each block is filled with characters from the file with a single read(). +/// 3. The lines are inserted in the buffer with ml_append(). +/// +/// (caller must check that fname != NULL, unless READ_STDIN is used) +/// +/// "lines_to_skip" is the number of lines that must be skipped +/// "lines_to_read" is the number of lines that are appended +/// When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM. +/// +/// flags: +/// READ_NEW starting to edit a new buffer +/// READ_FILTER reading filter output +/// READ_STDIN read from stdin instead of a file +/// READ_BUFFER read from curbuf instead of a file (converting after reading +/// stdin) +/// READ_DUMMY read into a dummy buffer (to check if file contents changed) +/// READ_KEEP_UNDO don't clear undo info or read it from a file +/// READ_FIFO read from fifo/socket instead of a file +/// +/// @param eap can be NULL! +/// +/// @return FAIL for failure, NOTDONE for directory (failure), or OK +int readfile(char_u *fname, char_u *sfname, linenr_T from, linenr_T lines_to_skip, + linenr_T lines_to_read, exarg_T *eap, int flags) { int fd = 0; int newfile = (flags & READ_NEW); @@ -191,15 +184,15 @@ readfile( int read_fifo = (flags & READ_FIFO); int set_options = newfile || read_buffer || (eap != NULL && eap->read_edit); - linenr_T read_buf_lnum = 1; /* next line to read from curbuf */ - colnr_T read_buf_col = 0; /* next char to read from this line */ + linenr_T read_buf_lnum = 1; // next line to read from curbuf + colnr_T read_buf_col = 0; // next char to read from this line char_u c; linenr_T lnum = from; - char_u *ptr = NULL; /* pointer into read buffer */ - char_u *buffer = NULL; /* read buffer */ - char_u *new_buffer = NULL; /* init to shut up gcc */ - char_u *line_start = NULL; /* init to shut up gcc */ - int wasempty; /* buffer was empty before reading */ + char_u *ptr = NULL; // pointer into read buffer + char_u *buffer = NULL; // read buffer + char_u *new_buffer = NULL; // init to shut up gcc + char_u *line_start = NULL; // init to shut up gcc + int wasempty; // buffer was empty before reading colnr_T len; long size = 0; uint8_t *p = NULL; @@ -209,12 +202,12 @@ readfile( int read_undo_file = false; int split = 0; // number of split lines linenr_T linecnt; - int error = FALSE; /* errors encountered */ - int ff_error = EOL_UNKNOWN; /* file format with errors */ - long linerest = 0; /* remaining chars in line */ + int error = FALSE; // errors encountered + int ff_error = EOL_UNKNOWN; // file format with errors + long linerest = 0; // remaining chars in line int perm = 0; #ifdef UNIX - int swap_mode = -1; /* protection bits for swap file */ + int swap_mode = -1; // protection bits for swap file #endif int fileformat = 0; // end-of-line format bool keep_fileformat = false; @@ -234,11 +227,11 @@ readfile( int bad_char_behavior = BAD_REPLACE; /* BAD_KEEP, BAD_DROP or character to * replace with */ - char_u *tmpname = NULL; /* name of 'charconvert' output file */ + char_u *tmpname = NULL; // name of 'charconvert' output file int fio_flags = 0; - char_u *fenc; // fileencoding to use + char_u *fenc; // fileencoding to use bool fenc_alloced; // fenc_next is in allocated memory - char_u *fenc_next = NULL; // next item in 'fencs' or NULL + char_u *fenc_next = NULL; // next item in 'fencs' or NULL bool advance_fenc = false; long real_size = 0; # ifdef HAVE_ICONV @@ -246,21 +239,21 @@ readfile( int did_iconv = false; // TRUE when iconv() failed and trying // 'charconvert' next # endif - int converted = FALSE; /* TRUE if conversion done */ + int converted = FALSE; // TRUE if conversion done int notconverted = FALSE; /* TRUE if conversion wanted but it wasn't possible */ char_u conv_rest[CONV_RESTLEN]; - int conv_restlen = 0; /* nr of bytes in conv_rest[] */ - buf_T *old_curbuf; - char_u *old_b_ffname; - char_u *old_b_fname; + int conv_restlen = 0; // nr of bytes in conv_rest[] + buf_T *old_curbuf; + char_u *old_b_ffname; + char_u *old_b_fname; int using_b_ffname; int using_b_fname; static char *msg_is_a_directory = N_("is a directory"); au_did_filetype = false; // reset before triggering any autocommands - curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */ + 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. @@ -273,8 +266,9 @@ readfile( && fname != NULL && vim_strchr(p_cpo, CPO_FNAMER) != NULL && !(flags & READ_DUMMY)) { - if (set_rw_fname(fname, sfname) == FAIL) + if (set_rw_fname(fname, sfname) == FAIL) { return FAIL; + } } /* Remember the initial values of curbuf, curbuf->b_ffname and @@ -315,7 +309,7 @@ readfile( pos = curbuf->b_op_start; - /* Set '[ mark to the line above where the lines go (line 1 if zero). */ + // Set '[ mark to the line above where the lines go (line 1 if zero). curbuf->b_op_start.lnum = ((from == 0) ? 1 : from); curbuf->b_op_start.col = 0; @@ -346,11 +340,11 @@ readfile( curbuf->b_op_start = pos; } - if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0) - msg_scroll = FALSE; /* overwrite previous file message */ - else - msg_scroll = TRUE; /* don't overwrite previous file message */ - + if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0) { + msg_scroll = FALSE; // overwrite previous file message + } else { + msg_scroll = TRUE; // don't overwrite previous file message + } // If the name is too long we might crash further on, quit here. if (fname != NULL && *fname != NUL) { size_t namelen = STRLEN(fname); @@ -397,7 +391,7 @@ readfile( } } - /* Set default or forced 'fileformat' and 'binary'. */ + // Set default or forced 'fileformat' and 'binary'. set_file_options(set_options, eap); /* @@ -407,8 +401,9 @@ readfile( * 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) + if (check_readonly && !readonlymode) { curbuf->b_p_ro = FALSE; + } if (newfile && !read_stdin && !read_buffer && !read_fifo) { // Remember time of file. @@ -466,7 +461,7 @@ readfile( * "nofile" or "nowrite" buffer type. */ if (!bt_dontwrite(curbuf)) { check_need_swap(newfile); - /* SwapExists autocommand may mess things up */ + // SwapExists autocommand may mess things up if (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) @@ -493,19 +488,20 @@ readfile( // remember the current fileformat save_file_ff(curbuf); - if (aborting()) /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing return FAIL; - return OK; /* a new file is not an error */ + } + return OK; // a new file is not an error } else { filemess(curbuf, sfname, (char_u *)( - (fd == UV_EFBIG) ? _("[File too big]") : + (fd == UV_EFBIG) ? _("[File too big]") : # if defined(UNIX) && defined(EOVERFLOW) - // libuv only returns -errno in Unix and in Windows open() does not - // set EOVERFLOW - (fd == -EOVERFLOW) ? _("[File too big]") : + // libuv only returns -errno in Unix and in Windows open() does not + // set EOVERFLOW + (fd == -EOVERFLOW) ? _("[File too big]") : # endif - _("[Permission Denied]")), 0); - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + _("[Permission Denied]")), 0); + curbuf->b_p_ro = TRUE; // must use "w!" now } return FAIL; @@ -513,10 +509,11 @@ readfile( /* * Only set the 'ro' flag for readonly files the first time they are - * loaded. Help files always get readonly mode + * loaded. Help files always get readonly mode */ - if ((check_readonly && file_readonly) || curbuf->b_help) + if ((check_readonly && file_readonly) || curbuf->b_help) { curbuf->b_p_ro = TRUE; + } if (set_options) { /* Don't change 'eol' if reading from buffer as it will already be @@ -573,12 +570,13 @@ readfile( // If "Quit" selected at ATTENTION dialog, don't load the file. if (swap_exists_action == SEA_QUIT) { - if (!read_buffer && !read_stdin) + if (!read_buffer && !read_stdin) { close(fd); + } return FAIL; } - ++no_wait_return; /* don't wait for return yet */ + ++no_wait_return; // don't wait for return yet /* * Set '[ mark to the line above where the lines go (line 1 if zero). @@ -627,10 +625,10 @@ readfile( msg_scroll = m; } - if (aborting()) { /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing --no_wait_return; msg_scroll = msg_save; - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + curbuf->b_p_ro = TRUE; // must use "w!" now return FAIL; } /* @@ -646,16 +644,17 @@ readfile( || (fd = os_open((char *)fname, O_RDONLY, 0)) < 0)) { --no_wait_return; msg_scroll = msg_save; - if (fd < 0) + if (fd < 0) { EMSG(_("E200: *ReadPre autocommands made the file unreadable")); - else + } else { EMSG(_("E201: *ReadPre autocommands must not change current buffer")); - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + } + curbuf->b_p_ro = TRUE; // must use "w!" now return FAIL; } } - /* Autocommands may add lines to the file, need to check if it is empty */ + // Autocommands may add lines to the file, need to check if it is empty wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY); if (!recoverymode && !filtering && !(flags & READ_DUMMY)) { @@ -664,7 +663,7 @@ readfile( } } - msg_scroll = FALSE; /* overwrite the file message */ + msg_scroll = FALSE; // overwrite the file message /* * Set linecnt now, before the "retry" caused by a wrong guess for @@ -672,13 +671,15 @@ readfile( */ linecnt = curbuf->b_ml.ml_line_count; - /* "++bad=" argument. */ + // "++bad=" argument. if (eap != NULL && eap->bad_char != 0) { bad_char_behavior = eap->bad_char; - if (set_options) + if (set_options) { curbuf->b_bad_char = eap->bad_char; - } else + } + } else { curbuf->b_bad_char = 0; + } /* * Decide which 'encoding' to use or use first. @@ -715,16 +716,16 @@ readfile( * - "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'. + * "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(). + * "tmpname" When != NULL did conversion with 'charconvert'. + * Output file has to be deleted afterwards. + * "iconv_fd" When != -1 did conversion with iconv(). */ retry: @@ -759,17 +760,19 @@ retry: if (eap != NULL && eap->force_ff != 0) { fileformat = get_fileformat_force(curbuf, eap); try_unix = try_dos = try_mac = FALSE; - } else if (curbuf->b_p_bin) - fileformat = EOL_UNIX; /* binary: use Unix format */ - else if (*p_ffs == NUL) - fileformat = get_fileformat(curbuf); /* use format from buffer */ - else - fileformat = EOL_UNKNOWN; /* detect from file */ + } else if (curbuf->b_p_bin) { + fileformat = EOL_UNIX; // binary: use Unix format + } else if (*p_ffs == + NUL) { + fileformat = get_fileformat(curbuf); // use format from buffer + } else { + fileformat = EOL_UNKNOWN; // detect from file + } } # ifdef HAVE_ICONV if (iconv_fd != (iconv_t)-1) { - /* aborted conversion with iconv(), close the descriptor */ + // aborted conversion with iconv(), close the descriptor iconv_close(iconv_fd); iconv_fd = (iconv_t)-1; } @@ -786,13 +789,15 @@ retry: * without conversion. */ notconverted = TRUE; conv_error = 0; - if (fenc_alloced) + if (fenc_alloced) { xfree(fenc); + } fenc = (char_u *)""; fenc_alloced = false; } else { - if (fenc_alloced) + if (fenc_alloced) { xfree(fenc); + } if (fenc_next != NULL) { fenc = next_fenc(&fenc_next, &fenc_alloced); } else { @@ -813,7 +818,6 @@ retry: fio_flags = 0; converted = need_conversion(fenc); if (converted) { - /* "ucs-bom" means we need to check the first bytes of the file * for a BOM. */ if (STRCMP(fenc, ENC_UCSBOM) == 0) { @@ -834,8 +838,7 @@ retry: # ifdef HAVE_ICONV // Try using iconv() if we can't convert internally. if (fio_flags == 0 - && !did_iconv - ) { + && !did_iconv) { iconv_fd = (iconv_t)my_iconv_open((char_u *)"utf-8", fenc); } # endif @@ -861,7 +864,7 @@ retry: // Conversion failed. Try another one. advance_fenc = true; if (fd < 0) { - /* Re-opening the original file failed! */ + // Re-opening the original file failed! EMSG(_("E202: Conversion made file unreadable!")); error = TRUE; goto failed; @@ -901,8 +904,9 @@ retry: && !read_fifo && !read_stdin && !read_buffer); - if (read_undo_file) + if (read_undo_file) { sha256_start(&sha_ctx); + } } while (!error && !got_int) { @@ -939,8 +943,9 @@ retry: error = TRUE; break; } - if (linerest) /* copy characters from the previous buffer */ + if (linerest) { // copy characters from the previous buffer memmove(new_buffer, ptr - linerest, (size_t)linerest); + } xfree(buffer); buffer = new_buffer; ptr = buffer + linerest; @@ -972,7 +977,7 @@ retry: size = size / ICONV_MULT; // worst case } # ifdef HAVE_ICONV - } + } # endif if (conv_restlen > 0) { // Insert unconverted bytes from previous line. @@ -986,9 +991,9 @@ retry: * Read bytes from curbuf. Used for converting text read * from stdin. */ - if (read_buf_lnum > from) + if (read_buf_lnum > from) { size = 0; - else { + } else { int n, ni; long tlen; @@ -1002,10 +1007,11 @@ retry: * below. */ n = (int)(size - tlen); for (ni = 0; ni < n; ++ni) { - if (p[ni] == NL) + if (p[ni] == NL) { ptr[tlen++] = NUL; - else + } else { ptr[tlen++] = p[ni]; + } } read_buf_col += n; break; @@ -1013,18 +1019,20 @@ retry: /* Append whole line and new-line. Change NL * to NUL to reverse the effect done below. */ for (ni = 0; ni < n; ++ni) { - if (p[ni] == NL) + if (p[ni] == NL) { ptr[tlen++] = NUL; - else + } else { ptr[tlen++] = p[ni]; + } } ptr[tlen++] = NL; read_buf_col = 0; if (++read_buf_lnum > from) { /* When the last line didn't have an * end-of-line don't add it now either. */ - if (!curbuf->b_p_eol) + if (!curbuf->b_p_eol) { --tlen; + } size = tlen; break; } @@ -1039,30 +1047,33 @@ retry: } if (size <= 0) { - if (size < 0) /* read error */ + if (size < 0) { // read error error = TRUE; - else if (conv_restlen > 0) { + } else if (conv_restlen > 0) { /* * Reached end-of-file but some trailing bytes could * not be converted. Truncated file? */ - /* When we did a conversion report an error. */ + // When we did a conversion report an error. if (fio_flags != 0 # ifdef HAVE_ICONV || iconv_fd != (iconv_t)-1 # endif ) { - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = curbuf->b_ml.ml_line_count - linecnt + 1; + } } - /* Remember the first linenr with an illegal byte */ - else if (illegal_byte == 0) + // Remember the first linenr with an illegal byte + else if (illegal_byte == 0) { illegal_byte = curbuf->b_ml.ml_line_count - linecnt + 1; + } if (bad_char_behavior == BAD_DROP) { *(ptr - conv_restlen) = NUL; conv_restlen = 0; @@ -1106,17 +1117,18 @@ retry: || (!curbuf->b_p_bomb && tmpname == NULL && (*fenc == 'u' || *fenc == NUL)))) { - char_u *ccname; + char_u *ccname; int blen; - /* no BOM detection in a short file or in binary mode */ - if (size < 2 || curbuf->b_p_bin) + // no BOM detection in a short file or in binary mode + if (size < 2 || curbuf->b_p_bin) { ccname = NULL; - else + } else { ccname = check_for_bom(ptr, size, &blen, - fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc)); + fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc)); + } if (ccname != NULL) { - /* Remove BOM from the text */ + // Remove BOM from the text filesize += blen; size -= blen; memmove(ptr, ptr + blen, (size_t)size); @@ -1131,27 +1143,29 @@ retry: // No BOM detected: retry with next encoding. advance_fenc = true; } else { - /* BOM detected: set "fenc" and jump back */ - if (fenc_alloced) + // BOM detected: set "fenc" and jump back + if (fenc_alloced) { xfree(fenc); + } fenc = ccname; fenc_alloced = false; } - /* retry reading without getting new bytes or rewinding */ + // retry reading without getting new bytes or rewinding skip_read = TRUE; goto retry; } } - /* Include not converted bytes. */ + // Include not converted bytes. ptr -= conv_restlen; size += conv_restlen; conv_restlen = 0; /* * Break here for a read error or end-of-file. */ - if (size <= 0) + if (size <= 0) { break; + } # ifdef HAVE_ICONV if (iconv_fd != (iconv_t)-1) { @@ -1159,8 +1173,8 @@ retry: * Attempt conversion of the read bytes to 'encoding' using * iconv(). */ - const char *fromp; - char *top; + const char *fromp; + char *top; size_t from_size; size_t to_size; @@ -1176,16 +1190,18 @@ retry: * alternative (help files). */ while ((iconv(iconv_fd, (void *)&fromp, &from_size, - &top, &to_size) + &top, &to_size) == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) || from_size > CONV_RESTLEN) { - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, (char_u *)top); + ptr, (char_u *)top); + } - /* Deal with a bad byte and continue with the next. */ + // Deal with a bad byte and continue with the next. ++fromp; --from_size; if (bad_char_behavior == BAD_KEEP) { @@ -1204,7 +1220,7 @@ retry: conv_restlen = (int)from_size; } - /* move the linerest to before the converted characters */ + // move the linerest to before the converted characters line_start = ptr - linerest; memmove(line_start, buffer, (size_t)linerest); size = (long)((char_u *)top - ptr); @@ -1213,8 +1229,8 @@ retry: if (fio_flags != 0) { unsigned int u8c; - char_u *dest; - char_u *tail = NULL; + char_u *dest; + char_u *tail = NULL; // Convert Unicode or Latin1 to UTF-8. // Go from end to start through the buffer, because the number @@ -1225,22 +1241,25 @@ retry: if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8) { p = ptr + size; if (fio_flags == FIO_UTF8) { - /* Check for a trailing incomplete UTF-8 sequence */ + // Check for a trailing incomplete UTF-8 sequence tail = ptr + size - 1; - while (tail > ptr && (*tail & 0xc0) == 0x80) + while (tail > ptr && (*tail & 0xc0) == 0x80) { --tail; - if (tail + utf_byte2len(*tail) <= ptr + size) + } + if (tail + utf_byte2len(*tail) <= ptr + size) { tail = NULL; - else + } else { p = tail; + } } } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { - /* Check for a trailing byte */ + // Check for a trailing byte p = ptr + (size & ~1); - if (size & 1) + if (size & 1) { tail = p; + } if ((fio_flags & FIO_UTF16) && p > ptr) { - /* Check for a trailing leading word */ + // Check for a trailing leading word if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 8); u8c += *--p; @@ -1248,16 +1267,18 @@ retry: u8c = *--p; u8c += (*--p << 8); } - if (u8c >= 0xd800 && u8c <= 0xdbff) + if (u8c >= 0xd800 && u8c <= 0xdbff) { tail = p; - else + } else { p += 2; + } } - } else { /* FIO_UCS4 */ - /* Check for trailing 1, 2 or 3 bytes */ + } else { // FIO_UCS4 + // Check for trailing 1, 2 or 3 bytes p = ptr + (size & ~3); - if (size & 3) + if (size & 3) { tail = p; + } } /* If there is a trailing incomplete sequence move it to @@ -1270,9 +1291,9 @@ retry: while (p > ptr) { - if (fio_flags & FIO_LATIN1) + if (fio_flags & FIO_LATIN1) { u8c = *--p; - else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { + } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 8); u8c += *--p; @@ -1285,16 +1306,20 @@ retry: int u16c; if (p == ptr) { - /* Missing leading word. */ - if (can_retry) + // Missing leading word. + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, p); - if (bad_char_behavior == BAD_DROP) + ptr, p); + } + if (bad_char_behavior == BAD_DROP) { continue; - if (bad_char_behavior != BAD_KEEP) + } + if (bad_char_behavior != BAD_KEEP) { u8c = bad_char_behavior; + } } /* found second word of double-word, get the first @@ -1309,17 +1334,21 @@ retry: u8c = 0x10000 + ((u16c & 0x3ff) << 10) + (u8c & 0x3ff); - /* Check if the word is indeed a leading word. */ + // Check if the word is indeed a leading word. if (u16c < 0xd800 || u16c > 0xdbff) { - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, p); - if (bad_char_behavior == BAD_DROP) + ptr, p); + } + if (bad_char_behavior == BAD_DROP) { continue; - if (bad_char_behavior != BAD_KEEP) + } + if (bad_char_behavior != BAD_KEEP) { u8c = bad_char_behavior; + } } } } else if (fio_flags & FIO_UCS4) { @@ -1328,16 +1357,16 @@ retry: u8c += (unsigned)(*--p) << 16; u8c += (unsigned)(*--p) << 8; u8c += *--p; - } else { /* big endian */ + } else { // big endian u8c = *--p; u8c += (unsigned)(*--p) << 8; u8c += (unsigned)(*--p) << 16; u8c += (unsigned)(*--p) << 24; } - } else { /* UTF-8 */ - if (*--p < 0x80) + } else { // UTF-8 + if (*--p < 0x80) { u8c = *p; - else { + } else { len = utf_head_off(ptr, p); p -= len; u8c = utf_ptr2char(p); @@ -1345,15 +1374,19 @@ retry: /* Not a valid UTF-8 character, retry with * another fenc when possible, otherwise just * report the error. */ - if (can_retry) + if (can_retry) { goto rewind_retry; - if (conv_error == 0) + } + if (conv_error == 0) { conv_error = readfile_linenr(linecnt, - ptr, p); - if (bad_char_behavior == BAD_DROP) + ptr, p); + } + if (bad_char_behavior == BAD_DROP) { continue; - if (bad_char_behavior != BAD_KEEP) + } + if (bad_char_behavior != BAD_KEEP) { u8c = bad_char_behavior; + } } } } @@ -1407,31 +1440,35 @@ retry: /* Illegal byte. If we can try another encoding * do that, unless at EOF where a truncated * file is more likely than a conversion error. */ - if (can_retry && !incomplete_tail) + if (can_retry && !incomplete_tail) { break; + } # ifdef HAVE_ICONV // When we did a conversion report an error. if (iconv_fd != (iconv_t)-1 && conv_error == 0) { conv_error = readfile_linenr(linecnt, ptr, p); } # endif - /* Remember the first linenr with an illegal byte */ - if (conv_error == 0 && illegal_byte == 0) + // Remember the first linenr with an illegal byte + if (conv_error == 0 && illegal_byte == 0) { illegal_byte = readfile_linenr(linecnt, ptr, p); + } - /* Drop, keep or replace the bad byte. */ + // Drop, keep or replace the bad byte. if (bad_char_behavior == BAD_DROP) { memmove(p, p + 1, todo - 1); --p; --size; - } else if (bad_char_behavior != BAD_KEEP) + } else if (bad_char_behavior != BAD_KEEP) { *p = bad_char_behavior; - } else + } + } else { p += l - 1; + } } } if (p < ptr + size && !incomplete_tail) { - /* Detected a UTF-8 error. */ + // Detected a UTF-8 error. rewind_retry: // Retry reading with another conversion. # ifdef HAVE_ICONV @@ -1443,21 +1480,21 @@ rewind_retry: // use next item from 'fileencodings' advance_fenc = true; # ifdef HAVE_ICONV - } + } # endif file_rewind = true; goto retry; } } - /* count the number of characters (after conversion!) */ + // count the number of characters (after conversion!) filesize += size; /* * when reading the first part of a file: guess EOL type */ if (fileformat == EOL_UNKNOWN) { - /* First try finding a NL, for Dos and Unix */ + // First try finding a NL, for Dos and Unix if (try_dos || try_unix) { // Reset the carriage return counter. if (try_mac) { @@ -1467,32 +1504,36 @@ rewind_retry: for (p = ptr; p < ptr + size; ++p) { if (*p == NL) { if (!try_unix - || (try_dos && p > ptr && p[-1] == CAR)) + || (try_dos && p > ptr && p[-1] == CAR)) { fileformat = EOL_DOS; - else + } else { fileformat = EOL_UNIX; + } break; } else if (*p == CAR && try_mac) { try_mac++; } } - /* Don't give in to EOL_UNIX if EOL_MAC is more likely */ + // Don't give in to EOL_UNIX if EOL_MAC is more likely if (fileformat == EOL_UNIX && try_mac) { - /* Need to reset the counters when retrying fenc. */ + // Need to reset the counters when retrying fenc. try_mac = 1; try_unix = 1; - for (; p >= ptr && *p != CAR; p--) + for (; p >= ptr && *p != CAR; p--) { ; + } if (p >= ptr) { for (p = ptr; p < ptr + size; ++p) { - if (*p == NL) + if (*p == NL) { try_unix++; - else if (*p == CAR) + } else if (*p == CAR) { try_mac++; + } } - if (try_mac > try_unix) + if (try_mac > try_unix) { fileformat = EOL_MAC; + } } } else if (fileformat == EOL_UNKNOWN && try_mac == 1) { // Looking for CR but found no end-of-line markers at all: @@ -1501,13 +1542,15 @@ rewind_retry: } } - /* No NL found: may use Mac format */ - if (fileformat == EOL_UNKNOWN && try_mac) + // No NL found: may use Mac format + if (fileformat == EOL_UNKNOWN && try_mac) { fileformat = EOL_MAC; + } - /* Still nothing found? Use first format in 'ffs' */ - if (fileformat == EOL_UNKNOWN) + // Still nothing found? Use first format in 'ffs' + if (fileformat == EOL_UNKNOWN) { fileformat = default_fileformat(); + } // May set 'p_ff' if editing a new file. if (set_options) { @@ -1523,44 +1566,48 @@ rewind_retry: if (fileformat == EOL_MAC) { --ptr; while (++ptr, --size >= 0) { - /* catch most common case first */ - if ((c = *ptr) != NUL && c != CAR && c != NL) + // catch most common case first + if ((c = *ptr) != NUL && c != CAR && c != NL) { continue; - if (c == NUL) - *ptr = NL; /* NULs are replaced by newlines! */ - else if (c == NL) - *ptr = CAR; /* NLs are replaced by CRs! */ - else { + } + if (c == NUL) { + *ptr = NL; // NULs are replaced by newlines! + } else if (c == NL) { + *ptr = CAR; // NLs are replaced by CRs! + } else { if (skip_count == 0) { - *ptr = NUL; /* end of line */ - len = (colnr_T) (ptr - line_start + 1); + *ptr = NUL; // end of line + len = (colnr_T)(ptr - line_start + 1); if (ml_append(lnum, line_start, len, newfile) == FAIL) { error = TRUE; break; } - if (read_undo_file) + if (read_undo_file) { sha256_update(&sha_ctx, line_start, len); + } ++lnum; if (--read_count == 0) { - error = TRUE; /* break loop */ - line_start = ptr; /* nothing left to write */ + error = TRUE; // break loop + line_start = ptr; // nothing left to write break; } - } else + } else { --skip_count; + } line_start = ptr + 1; } } } else { --ptr; while (++ptr, --size >= 0) { - if ((c = *ptr) != NUL && c != NL) /* catch most common case */ + if ((c = *ptr) != NUL && c != NL) { // catch most common case continue; - if (c == NUL) - *ptr = NL; /* NULs are replaced by newlines! */ - else { + } + if (c == NUL) { + *ptr = NL; // NULs are replaced by newlines! + } else { if (skip_count == 0) { - *ptr = NUL; /* end of line */ + *ptr = NUL; // end of line len = (colnr_T)(ptr - line_start + 1); if (fileformat == EOL_DOS) { if (ptr > line_start && ptr[-1] == CAR) { @@ -1577,8 +1624,9 @@ rewind_retry: && (read_buffer || vim_lseek(fd, (off_T)0L, SEEK_SET) == 0)) { fileformat = EOL_UNIX; - if (set_options) + if (set_options) { set_fileformat(EOL_UNIX, OPT_LOCAL); + } file_rewind = true; keep_fileformat = true; goto retry; @@ -1590,16 +1638,18 @@ rewind_retry: error = TRUE; break; } - if (read_undo_file) + if (read_undo_file) { sha256_update(&sha_ctx, line_start, len); + } ++lnum; if (--read_count == 0) { - error = TRUE; /* break loop */ - line_start = ptr; /* nothing left to write */ + error = TRUE; // break loop + line_start = ptr; // nothing left to write break; } - } else + } else { --skip_count; + } line_start = ptr + 1; } } @@ -1609,9 +1659,10 @@ rewind_retry: } failed: - /* not an error, max. number of lines reached */ - if (error && read_count == 0) + // not an error, max. number of lines reached + if (error && read_count == 0) { error = FALSE; + } /* * If we get EOF in the middle of a line, note the fact and @@ -1625,16 +1676,18 @@ failed: && fileformat == EOL_DOS && *line_start == Ctrl_Z && ptr == line_start + 1)) { - /* remember for when writing */ - if (set_options) + // remember for when writing + if (set_options) { curbuf->b_p_eol = FALSE; + } *ptr = NUL; len = (colnr_T)(ptr - line_start + 1); - if (ml_append(lnum, line_start, len, newfile) == FAIL) + if (ml_append(lnum, line_start, len, newfile) == FAIL) { error = TRUE; - else { - if (read_undo_file) + } else { + if (read_undo_file) { sha256_update(&sha_ctx, line_start, len); + } read_no_eol_lnum = ++lnum; } } @@ -1646,8 +1699,9 @@ failed: // Also for ":read ++edit file". set_string_option_direct("fenc", -1, fenc, OPT_FREE | OPT_LOCAL, 0); } - if (fenc_alloced) + if (fenc_alloced) { xfree(fenc); + } # ifdef HAVE_ICONV if (iconv_fd != (iconv_t)-1) { iconv_close(iconv_fd); @@ -1679,13 +1733,13 @@ failed: os_remove((char *)tmpname); // delete converted file xfree(tmpname); } - --no_wait_return; /* may wait for return now */ + --no_wait_return; // may wait for return now /* * In recovery mode everything but autocommands is skipped. */ if (!recoverymode) { - /* need to delete the last line, which comes from the empty buffer */ + // need to delete the last line, which comes from the empty buffer if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY)) { ml_delete(curbuf->b_ml.ml_line_count, false); linecnt--; @@ -1695,8 +1749,9 @@ failed: curbuf->deleted_codepoints = 0; curbuf->deleted_codeunits = 0; linecnt = curbuf->b_ml.ml_line_count - linecnt; - if (filesize == 0) + if (filesize == 0) { linecnt = 0; + } if (newfile || read_buffer) { redraw_curbuf_later(NOT_VALID); /* After reading the text into the buffer the diff info needs to @@ -1705,8 +1760,9 @@ failed: /* All folds in the window are invalid now. Mark them for update * before triggering autocommands. */ foldUpdateAll(curwin); - } else if (linecnt) /* appended at least one line */ + } else if (linecnt) { // appended at least one line appended_lines_mark(from, linecnt); + } /* * If we were reading from the same terminal as where messages go, @@ -1720,12 +1776,13 @@ failed: if (got_int) { if (!(flags & READ_DUMMY)) { filemess(curbuf, sfname, (char_u *)_(e_interr), 0); - if (newfile) - curbuf->b_p_ro = TRUE; /* must use "w!" now */ + if (newfile) { + curbuf->b_p_ro = TRUE; // must use "w!" now + } } msg_scroll = msg_save; check_marks_read(); - return OK; /* an interrupt isn't really an error */ + return OK; // an interrupt isn't really an error } if (!filtering && !(flags & READ_DUMMY)) { @@ -1742,7 +1799,7 @@ failed: c = TRUE; } # ifdef OPEN_CHR_FILES - if (S_ISCHR(perm)) { /* or character special */ + if (S_ISCHR(perm)) { // or character special STRCAT(IObuff, _("[character special]")); c = TRUE; } @@ -1773,18 +1830,19 @@ failed: } if (conv_error != 0) { sprintf((char *)IObuff + STRLEN(IObuff), - _("[CONVERSION ERROR in line %" PRId64 "]"), (int64_t)conv_error); + _("[CONVERSION ERROR in line %" PRId64 "]"), (int64_t)conv_error); c = TRUE; } else if (illegal_byte > 0) { sprintf((char *)IObuff + STRLEN(IObuff), - _("[ILLEGAL BYTE in line %" PRId64 "]"), (int64_t)illegal_byte); + _("[ILLEGAL BYTE in line %" PRId64 "]"), (int64_t)illegal_byte); c = TRUE; - } else if (error) { + } else if (error) { STRCAT(IObuff, _("[READ ERRORS]")); c = TRUE; } - if (msg_add_fileformat(fileformat)) + if (msg_add_fileformat(fileformat)) { c = TRUE; + } msg_add_lines(c, (long)linecnt, filesize); @@ -1808,25 +1866,27 @@ failed: msg_scrolled_ign = FALSE; } - /* with errors writing the file requires ":w!" */ + // with errors writing the file requires ":w!" if (newfile && (error || conv_error != 0 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP) - )) + )) { curbuf->b_p_ro = TRUE; + } - u_clearline(); /* cannot use "U" command after adding lines */ + u_clearline(); // cannot use "U" command after adding lines /* * In Ex mode: cursor at last new line. * Otherwise: cursor at first new line. */ - if (exmode_active) + if (exmode_active) { curwin->w_cursor.lnum = from + linecnt; - else + } else { curwin->w_cursor.lnum = from + 1; + } check_cursor_lnum(); - beginline(BL_WHITE | BL_FIX); /* on first non-blank */ + beginline(BL_WHITE | BL_FIX); // on first non-blank /* * Set '[ and '] marks to the newly read lines. @@ -1835,7 +1895,6 @@ failed: curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = from + linecnt; curbuf->b_op_end.col = 0; - } msg_scroll = msg_save; @@ -1854,8 +1913,9 @@ failed: /* When reloading a buffer put the cursor at the first line that is * different. */ - if (flags & READ_KEEP_UNDO) + if (flags & READ_KEEP_UNDO) { u_find_first_changed(); + } /* * When opening a new file locate undo info and read it. @@ -1873,8 +1933,9 @@ failed: /* Save the fileformat now, otherwise the buffer will be considered * modified if the format/encoding was automatically detected. */ - if (set_options) + if (set_options) { save_file_ff(curbuf); + } /* * The output from the autocommands should not overwrite anything and @@ -1906,8 +1967,9 @@ failed: } } - if (recoverymode && error) + if (recoverymode && error) { return FAIL; + } return OK; } @@ -1930,25 +1992,24 @@ bool is_dev_fd_file(char_u *fname) #endif -/* - * From the current line count and characters read after that, estimate the - * line number where we are now. - * Used for error messages that include a line number. - */ -static linenr_T -readfile_linenr( - linenr_T linecnt, // line count before reading more bytes - char_u *p, // start of more bytes read - char_u *endp // end of more bytes read -) +/// From the current line count and characters read after that, estimate the +/// line number where we are now. +/// Used for error messages that include a line number. +/// +/// @param linecnt line count before reading more bytes +/// @param p start of more bytes read +/// @param endp end of more bytes read +static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp) { - char_u *s; + char_u *s; linenr_T lnum; lnum = curbuf->b_ml.ml_line_count - linecnt + 1; - for (s = p; s < endp; ++s) - if (*s == '\n') + for (s = p; s < endp; ++s) { + if (*s == '\n') { ++lnum; + } + } return lnum; } @@ -1977,15 +2038,16 @@ void prep_exarg(exarg_T *eap, const buf_T *buf) */ void set_file_options(int set_options, exarg_T *eap) { - /* set default 'fileformat' */ + // set default 'fileformat' if (set_options) { - if (eap != NULL && eap->force_ff != 0) + if (eap != NULL && eap->force_ff != 0) { set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL); - else if (*p_ffs != NUL) + } else if (*p_ffs != NUL) { set_fileformat(default_fileformat(), OPT_LOCAL); + } } - /* set or reset 'binary' */ + // set or reset 'binary' if (eap != NULL && eap->force_bin != 0) { int oldval = curbuf->b_p_bin; @@ -2015,8 +2077,8 @@ void set_forced_fenc(exarg_T *eap) static char_u *next_fenc(char_u **pp, bool *alloced) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET { - char_u *p; - char_u *r; + char_u *p; + char_u *r; *alloced = false; if (**pp == NUL) { @@ -2038,29 +2100,26 @@ static char_u *next_fenc(char_u **pp, bool *alloced) return r; } -/* - * Convert a file with the 'charconvert' expression. - * This closes the file which is to be read, converts it and opens the - * resulting file for reading. - * Returns name of the resulting converted file (the caller should delete it - * after reading it). - * Returns NULL if the conversion failed ("*fdp" is not set) . - */ -static char_u * -readfile_charconvert ( - char_u *fname, /* name of input file */ - char_u *fenc, /* converted from */ - int *fdp /* in/out: file descriptor of file */ -) +/// Convert a file with the 'charconvert' expression. +/// This closes the file which is to be read, converts it and opens the +/// resulting file for reading. +/// +/// @param fname name of input file +/// @param fenc converted from +/// @param fdp in/out: file descriptor of file +/// +/// @return name of the resulting converted file (the caller should delete it after reading it). +/// Returns NULL if the conversion failed ("*fdp" is not set) . +static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp) { - char_u *tmpname; - char_u *errmsg = NULL; + char_u *tmpname; + char_u *errmsg = NULL; tmpname = vim_tempname(); - if (tmpname == NULL) + if (tmpname == NULL) { errmsg = (char_u *)_("Can't find temp file for conversion"); - else { - close(*fdp); /* close the input file, ignore errors */ + } else { + close(*fdp); // close the input file, ignore errors *fdp = -1; if (eval_charconvert((char *)fenc, "utf-8", (char *)fname, (char *)tmpname) == FAIL) { @@ -2081,7 +2140,7 @@ readfile_charconvert ( } } - /* If the input file is closed, open it (caller should check for error). */ + // If the input file is closed, open it (caller should check for error). if (*fdp < 0) { *fdp = os_open((char *)fname, O_RDONLY, 0); } @@ -2111,45 +2170,35 @@ char *new_file_message(void) return shortmess(SHM_NEW) ? _("[New]") : _("[New File]"); } -/* - * buf_write() - write to file "fname" lines "start" through "end" - * - * We do our own buffering here because fwrite() is so slow. - * - * If "forceit" is true, we don't care for errors when attempting backups. - * In case of an error everything possible is done to restore the original - * file. But when "forceit" is TRUE, we risk losing it. - * - * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and - * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed. - * - * This function must NOT use NameBuff (because it's called by autowrite()). - * - * return FAIL for failure, OK otherwise - */ -int -buf_write( - buf_T *buf, - char_u *fname, - char_u *sfname, - linenr_T start, - linenr_T end, - exarg_T *eap, /* for forced 'ff' and 'fenc', can be - NULL! */ - int append, /* append to the file */ - int forceit, - int reset_changed, - int filtering -) +/// buf_write() - write to file "fname" lines "start" through "end" +/// +/// We do our own buffering here because fwrite() is so slow. +/// +/// If "forceit" is true, we don't care for errors when attempting backups. +/// In case of an error everything possible is done to restore the original +/// file. But when "forceit" is TRUE, we risk losing it. +/// +/// When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and +/// "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed. +/// +/// This function must NOT use NameBuff (because it's called by autowrite()). +/// +/// +/// @param eap for forced 'ff' and 'fenc', can be NULL! +/// @param append append to the file +/// +/// @return FAIL for failure, OK otherwise +int buf_write(buf_T *buf, char_u *fname, char_u *sfname, linenr_T start, linenr_T end, exarg_T *eap, + int append, int forceit, int reset_changed, int filtering) { int fd; - char_u *backup = NULL; - int backup_copy = FALSE; /* copy the original file? */ + char_u *backup = NULL; + int backup_copy = FALSE; // copy the original file? int dobackup; - char_u *ffname; - char_u *wfname = NULL; /* name of file to write to */ - char_u *s; - char_u *ptr; + char_u *ffname; + char_u *wfname = NULL; // name of file to write to + char_u *s; + char_u *ptr; char_u c; int len; linenr_T lnum; @@ -2164,9 +2213,9 @@ buf_write( char *errmsg = NULL; int errmsgarg = 0; bool errmsg_allocated = false; - char_u *buffer; + char_u *buffer; char_u smallbuf[SMBUFSIZE]; - char_u *backup_ext; + char_u *backup_ext; int bufsize; long perm; // file permissions int retval = OK; @@ -2178,21 +2227,21 @@ buf_write( int prev_got_int = got_int; int checking_conversion; bool file_readonly = false; // overwritten file is read-only - static char *err_readonly = + static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')"; #if defined(UNIX) - int made_writable = FALSE; /* 'w' bit has been set */ + int made_writable = FALSE; // 'w' bit has been set #endif - /* writing everything */ + // writing everything int whole = (start == 1 && end == buf->b_ml.ml_line_count); linenr_T old_line_count = buf->b_ml.ml_line_count; int fileformat; int write_bin; - struct bw_info write_info; /* info for buf_write_bytes() */ + struct bw_info write_info; // info for buf_write_bytes() int converted = FALSE; int notconverted = FALSE; - char_u *fenc; /* effective 'fileencoding' */ - char_u *fenc_tofree = NULL; /* allocated "fenc" */ + char_u *fenc; // effective 'fileencoding' + char_u *fenc_tofree = NULL; // allocated "fenc" #ifdef HAS_BW_FLAGS int wb_flags = 0; #endif @@ -2204,8 +2253,9 @@ buf_write( context_sha256_T sha_ctx; unsigned int bkc = get_bkc_value(buf); - if (fname == NULL || *fname == NUL) /* safety check */ + if (fname == NULL || *fname == NUL) { // safety check return FAIL; + } if (buf->b_ml.ml_mfp == NULL) { /* This can happen during startup when there is a stray "w" in the * vimrc file. */ @@ -2217,16 +2267,17 @@ buf_write( * Disallow writing from .exrc and .vimrc in current directory for * security reasons. */ - if (check_secure()) + if (check_secure()) { return FAIL; + } - /* Avoid a crash for a long name. */ + // Avoid a crash for a long name. if (STRLEN(fname) >= MAXPATHL) { EMSG(_(e_longname)); return FAIL; } - /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */ + // must init bw_conv_buf and bw_iconv_fd before jumping to "fail" write_info.bw_conv_buf = NULL; write_info.bw_conv_error = FALSE; write_info.bw_conv_error_lnum = 0; @@ -2254,13 +2305,15 @@ buf_write( && !filtering && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL) && vim_strchr(p_cpo, CPO_FNAMEW) != NULL) { - if (set_rw_fname(fname, sfname) == FAIL) + if (set_rw_fname(fname, sfname) == FAIL) { return FAIL; - buf = curbuf; /* just in case autocmds made "buf" invalid */ + } + buf = curbuf; // just in case autocmds made "buf" invalid } - if (sfname == NULL) + if (sfname == NULL) { sfname = fname; + } // For Unix: Use the short file name whenever possible. // Avoids problems with networks and when directory names are changed. @@ -2271,12 +2324,13 @@ buf_write( fname = sfname; #endif - if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0) + if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0) { overwriting = TRUE; - else + } else { overwriting = FALSE; + } - ++no_wait_return; /* don't wait for return yet */ + ++no_wait_return; // don't wait for return yet /* * Set '[ and '] marks to the lines to be written. @@ -2302,14 +2356,18 @@ buf_write( * Set curbuf to the buffer to be written. * Careful: The autocommands may call buf_write() recursively! */ - if (ffname == buf->b_ffname) + if (ffname == buf->b_ffname) { buf_ffname = TRUE; - if (sfname == buf->b_sfname) + } + if (sfname == buf->b_sfname) { buf_sfname = TRUE; - if (fname == buf->b_ffname) + } + if (fname == buf->b_ffname) { buf_fname_f = TRUE; - if (fname == buf->b_sfname) + } + if (fname == buf->b_sfname) { buf_fname_s = TRUE; + } // Set curwin/curbuf to buf and save a few things. aucmd_prepbuf(&aco, buf); @@ -2317,21 +2375,22 @@ buf_write( if (append) { if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD, - sfname, sfname, FALSE, curbuf, eap))) { - if (overwriting && bt_nofile(curbuf)) + sfname, sfname, FALSE, curbuf, eap))) { + if (overwriting && bt_nofile(curbuf)) { nofile_err = TRUE; - else + } else { apply_autocmds_exarg(EVENT_FILEAPPENDPRE, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); + } } } else if (filtering) { apply_autocmds_exarg(EVENT_FILTERWRITEPRE, - NULL, sfname, FALSE, curbuf, eap); - } else if (reset_changed && whole) { + NULL, sfname, FALSE, curbuf, eap); + } else if (reset_changed && whole) { int was_changed = curbufIsChanged(); did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); if (did_cmd) { if (was_changed && !curbufIsChanged()) { /* Written everything correctly and BufWriteCmd has reset @@ -2341,24 +2400,26 @@ buf_write( u_update_save_nr(curbuf); } } else { - if (overwriting && bt_nofile(curbuf)) + if (overwriting && bt_nofile(curbuf)) { nofile_err = TRUE; - else + } else { apply_autocmds_exarg(EVENT_BUFWRITEPRE, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); + } } } else { if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD, - sfname, sfname, FALSE, curbuf, eap))) { - if (overwriting && bt_nofile(curbuf)) + sfname, sfname, FALSE, curbuf, eap))) { + if (overwriting && bt_nofile(curbuf)) { nofile_err = TRUE; - else + } else { apply_autocmds_exarg(EVENT_FILEWRITEPRE, - sfname, sfname, FALSE, curbuf, eap); + sfname, sfname, FALSE, curbuf, eap); + } } } - /* restore curwin/curbuf and a few other things */ + // restore curwin/curbuf and a few other things aucmd_restbuf(&aco); // In three situations we return here and don't write the file: @@ -2370,41 +2431,45 @@ buf_write( } if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline) || did_cmd || nofile_err - || aborting() - ) { + || aborting()) { --no_wait_return; msg_scroll = msg_save; - if (nofile_err) + if (nofile_err) { EMSG(_("E676: No matching autocommands for acwrite buffer")); + } if (nofile_err - || aborting() - ) + || aborting()) { /* An aborting error, interrupt or exception in the * autocommands. */ return FAIL; + } if (did_cmd) { - if (buf == NULL) + if (buf == NULL) { /* The buffer was deleted. We assume it was written * (can't retry anyway). */ return OK; + } if (overwriting) { - /* Assume the buffer was written, update the timestamp. */ + // Assume the buffer was written, update the timestamp. ml_timestamp(buf); - if (append) + if (append) { buf->b_flags &= ~BF_NEW; - else + } else { buf->b_flags &= ~BF_WRITE_MASK; + } } if (reset_changed && buf->b_changed && !append - && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) + && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) { /* Buffer still changed, the autocommands didn't work * properly. */ return FAIL; + } return OK; } - if (!aborting()) + if (!aborting()) { EMSG(_("E203: Autocommands deleted or unloaded buffer to be written")); + } return FAIL; } @@ -2415,11 +2480,11 @@ buf_write( * 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 */ + if (whole) { // write all end = buf->b_ml.ml_line_count; - else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */ + } else if (buf->b_ml.ml_line_count > old_line_count) { // more lines end += buf->b_ml.ml_line_count - old_line_count; - else { /* less lines */ + } else { // less lines end -= old_line_count - buf->b_ml.ml_line_count; if (end < start) { --no_wait_return; @@ -2434,30 +2499,36 @@ buf_write( * The autocommands may have changed the name of the buffer, which may * be kept in fname, ffname and sfname. */ - if (buf_ffname) + if (buf_ffname) { ffname = buf->b_ffname; - if (buf_sfname) + } + if (buf_sfname) { sfname = buf->b_sfname; - if (buf_fname_f) + } + if (buf_fname_f) { fname = buf->b_ffname; - if (buf_fname_s) + } + if (buf_fname_s) { fname = buf->b_sfname; + } } - if (shortmess(SHM_OVER) && !exiting) - msg_scroll = FALSE; /* overwrite previous file message */ - else - msg_scroll = TRUE; /* don't overwrite previous file message */ - if (!filtering) + if (shortmess(SHM_OVER) && !exiting) { + msg_scroll = FALSE; // overwrite previous file message + } else { + msg_scroll = TRUE; // don't overwrite previous file message + } + if (!filtering) { filemess(buf, #ifndef UNIX - sfname, + sfname, #else - fname, + fname, #endif - (char_u *)"", 0); /* show that we are busy */ - msg_scroll = FALSE; /* always overwrite the file message now */ + (char_u *)"", 0); // show that we are busy + } + msg_scroll = FALSE; // always overwrite the file message now buffer = verbose_try_malloc(BUFSIZE); // can't allocate big buffer, use small one (to be able to write when out of @@ -2465,8 +2536,9 @@ buf_write( if (buffer == NULL) { buffer = smallbuf; bufsize = SMBUFSIZE; - } else + } else { bufsize = BUFSIZE; + } /* * Get information about original file (if there is one). @@ -2478,7 +2550,7 @@ buf_write( newfile = TRUE; } else { perm = file_info_old.stat.st_mode; - if (!S_ISREG(file_info_old.stat.st_mode)) { /* not a file */ + if (!S_ISREG(file_info_old.stat.st_mode)) { // not a file if (S_ISDIR(file_info_old.stat.st_mode)) { SET_ERRMSG_NUM("E502", _("is a directory")); goto fail; @@ -2540,8 +2612,9 @@ buf_write( */ if (overwriting) { retval = check_mtime(buf, &file_info_old); - if (retval == FAIL) + if (retval == FAIL) { goto fail; + } } } @@ -2549,16 +2622,18 @@ buf_write( /* * For systems that support ACL: get the ACL from the original file. */ - if (!newfile) + if (!newfile) { acl = mch_get_acl(fname); + } #endif /* * 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, sfname, ffname)) + if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) { dobackup = FALSE; + } /* * Save the value of got_int and reset it. We don't want a previous @@ -2568,7 +2643,7 @@ buf_write( prev_got_int = got_int; got_int = FALSE; - /* Mark the buffer as 'being saved' to prevent changed buffer warnings */ + // Mark the buffer as 'being saved' to prevent changed buffer warnings buf->b_saving = true; /* @@ -2583,9 +2658,9 @@ buf_write( FileInfo file_info; const bool no_prepend_dot = false; - if ((bkc & BKC_YES) || append) { /* "yes" */ + if ((bkc & BKC_YES) || append) { // "yes" backup_copy = TRUE; - } else if ((bkc & BKC_AUTO)) { /* "auto" */ + } else if ((bkc & BKC_AUTO)) { // "auto" int i; /* @@ -2613,10 +2688,10 @@ buf_write( } } fd = os_open((char *)IObuff, - O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); - if (fd < 0) /* can't write in directory */ + O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); + if (fd < 0) { // can't write in directory backup_copy = TRUE; - else { + } else { # ifdef UNIX os_fchown(fd, file_info_old.stat.st_uid, file_info_old.stat.st_gid); if (!os_fileinfo((char *)IObuff, &file_info) @@ -2641,14 +2716,14 @@ buf_write( # ifdef UNIX bool file_info_link_ok = os_fileinfo_link((char *)fname, &file_info); - /* Symlinks. */ + // Symlinks. if ((bkc & BKC_BREAKSYMLINK) && file_info_link_ok && !os_fileinfo_id_equal(&file_info, &file_info_old)) { backup_copy = FALSE; } - /* Hardlinks. */ + // Hardlinks. if ((bkc & BKC_BREAKHARDLINK) && os_fileinfo_hardlinks(&file_info_old) > 1 && (!file_info_link_ok @@ -2658,18 +2733,19 @@ buf_write( # endif } - /* make sure we have a valid backup extension to use */ - if (*p_bex == NUL) + // make sure we have a valid backup extension to use + if (*p_bex == NUL) { backup_ext = (char_u *)".bak"; - else + } else { backup_ext = p_bex; + } if (backup_copy) { char_u *wp; int some_error = false; - char_u *dirp; - char_u *rootname; - char_u *p; + char_u *dirp; + char_u *rootname; + char_u *p; /* * Try to make the backup in each directory in the 'bdir' option. @@ -2715,7 +2791,7 @@ buf_write( rootname = get_file_in_dir(fname, IObuff); if (rootname == NULL) { - some_error = TRUE; /* out of memory */ + some_error = TRUE; // out of memory goto nobackup; } @@ -2731,7 +2807,7 @@ buf_write( if (backup == NULL) { xfree(rootname); - some_error = TRUE; /* out of memory */ + some_error = TRUE; // out of memory goto nobackup; } @@ -2774,7 +2850,7 @@ buf_write( * Try to create the backup file */ if (backup != NULL) { - /* remove old backup, if present */ + // remove old backup, if present os_remove((char *)backup); // set file protection same as original file, but @@ -2815,8 +2891,7 @@ buf_write( nobackup: if (backup == NULL && errmsg == NULL) { - SET_ERRMSG(_( - "E509: Cannot create backup file (add ! to override)")); + SET_ERRMSG(_("E509: Cannot create backup file (add ! to override)")); } // Ignore errors when forceit is TRUE. if ((some_error || errmsg != NULL) && !forceit) { @@ -2825,9 +2900,9 @@ nobackup: } SET_ERRMSG(NULL); } else { - char_u *dirp; - char_u *p; - char_u *rootname; + char_u *dirp; + char_u *p; + char_u *rootname; /* * Make a backup by renaming the original file. @@ -2897,8 +2972,9 @@ nobackup: */ if (!p_bk && os_path_exists(backup)) { p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext); - if (p < backup) /* empty file name ??? */ + if (p < backup) { // empty file name ??? p = backup; + } *p = 'z'; while (*p > 'a' && os_path_exists(backup)) { (*p)--; @@ -2951,10 +3027,12 @@ nobackup: status_redraw_all(); // redraw status lines later } - if (end > buf->b_ml.ml_line_count) + if (end > buf->b_ml.ml_line_count) { end = buf->b_ml.ml_line_count; - if (buf->b_ml.ml_flags & ML_EMPTY) + } + if (buf->b_ml.ml_flags & ML_EMPTY) { start = end + 1; + } // If the original file is being overwritten, there is a small chance that // we crash in the middle of writing. Therefore the file is preserved now. @@ -3014,7 +3092,7 @@ nobackup: // internally. write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc, (char_u *)"utf-8"); if (write_info.bw_iconv_fd != (iconv_t)-1) { - /* We're going to use iconv(), allocate a buffer to convert in. */ + // We're going to use iconv(), allocate a buffer to convert in. write_info.bw_conv_buflen = bufsize * ICONV_MULT; write_info.bw_conv_buf = verbose_try_malloc(write_info.bw_conv_buflen); if (!write_info.bw_conv_buf) { @@ -3041,11 +3119,9 @@ nobackup: # ifdef HAVE_ICONV && write_info.bw_iconv_fd == (iconv_t)-1 # endif - && wfname == fname - ) { + && wfname == fname) { if (!forceit) { - SET_ERRMSG(_( - "E213: Cannot convert (add ! to write without conversion)")); + SET_ERRMSG(_("E213: Cannot convert (add ! to write without conversion)")); goto restore_backup; } notconverted = TRUE; @@ -3080,7 +3156,7 @@ nobackup: O_WRONLY | (append ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND) - : (O_CREAT | O_TRUNC)) + : (O_CREAT | O_TRUNC)) , perm < 0 ? 0666 : (perm & 0777))) < 0) { // A forced write will try to create a new file if the old one // is still readonly. This may also happen when the directory @@ -3096,28 +3172,28 @@ nobackup: SET_ERRMSG(_("E166: Can't open linked file for writing")); } else { #endif - SET_ERRMSG_ARG(_("E212: Can't open file for writing: %s"), fd); - if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL - && perm >= 0) { + SET_ERRMSG_ARG(_("E212: Can't open file for writing: %s"), fd); + if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL + && perm >= 0) { #ifdef UNIX - // we write to the file, thus it should be marked - // writable after all - if (!(perm & 0200)) { - made_writable = true; - } - perm |= 0200; - if (file_info_old.stat.st_uid != getuid() - || file_info_old.stat.st_gid != getgid()) { - perm &= 0777; - } + // we write to the file, thus it should be marked + // writable after all + if (!(perm & 0200)) { + made_writable = true; + } + perm |= 0200; + if (file_info_old.stat.st_uid != getuid() + || file_info_old.stat.st_gid != getgid()) { + perm &= 0777; + } #endif - if (!append) { // don't remove when appending - os_remove((char *)wfname); - } - continue; + if (!append) { // don't remove when appending + os_remove((char *)wfname); } -#ifdef UNIX + continue; } +#ifdef UNIX + } #endif } @@ -3282,7 +3358,7 @@ restore_backup: // Stop when writing done or an error was encountered. if (!checking_conversion || end == 0) { - break; + break; } // If no error happened until now, writing should be ok, so loop to @@ -3371,17 +3447,15 @@ restore_backup: if (errmsg == NULL) { if (write_info.bw_conv_error) { if (write_info.bw_conv_error_lnum == 0) { - SET_ERRMSG(_( - "E513: write error, conversion failed " - "(make 'fenc' empty to override)")); + SET_ERRMSG(_("E513: write error, conversion failed " + "(make 'fenc' empty to override)")); } else { errmsg_allocated = true; SET_ERRMSG(xmalloc(300)); - vim_snprintf( - errmsg, 300, - _("E513: write error, conversion failed in line %" PRIdLINENR - " (make 'fenc' empty to override)"), - write_info.bw_conv_error_lnum); + vim_snprintf(errmsg, 300, + _("E513: write error, conversion failed in line %" PRIdLINENR + " (make 'fenc' empty to override)"), + write_info.bw_conv_error_lnum); } } else if (got_int) { SET_ERRMSG(_(e_interr)); @@ -3420,11 +3494,11 @@ restore_backup: goto fail; } - lnum -= start; /* compute number of written lines */ - --no_wait_return; /* may wait for return now */ + lnum -= start; // compute number of written lines + --no_wait_return; // may wait for return now #if !defined(UNIX) - fname = sfname; /* use shortname now, for the messages */ + fname = sfname; // use shortname now, for the messages #endif if (!filtering) { add_quoted_fname((char *)IObuff, IOSIZE, buf, (const char *)fname); @@ -3432,9 +3506,10 @@ restore_backup: if (write_info.bw_conv_error) { STRCAT(IObuff, _(" CONVERSION ERROR")); c = TRUE; - if (write_info.bw_conv_error_lnum != 0) + if (write_info.bw_conv_error_lnum != 0) { vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %" PRId64 ";"), - (int64_t)write_info.bw_conv_error_lnum); + (int64_t)write_info.bw_conv_error_lnum); + } } else if (notconverted) { STRCAT(IObuff, _("[NOT converted]")); c = TRUE; @@ -3453,15 +3528,17 @@ restore_backup: msg_add_eol(); c = TRUE; } - /* may add [unix/dos/mac] */ - if (msg_add_fileformat(fileformat)) + // may add [unix/dos/mac] + if (msg_add_fileformat(fileformat)) { c = TRUE; - msg_add_lines(c, (long)lnum, nchars); /* add line/char count */ + } + msg_add_lines(c, (long)lnum, nchars); // add line/char count if (!shortmess(SHM_WRITE)) { - if (append) + if (append) { STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended")); - else + } else { STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written")); + } } set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0); @@ -3489,10 +3566,11 @@ restore_backup: */ if (overwriting) { ml_timestamp(buf); - if (append) + if (append) { buf->b_flags &= ~BF_NEW; - else + } else { buf->b_flags &= ~BF_WRITE_MASK; + } } /* @@ -3528,11 +3606,12 @@ restore_backup: if (org == NULL || (empty_fd = os_open(org, - O_CREAT | O_EXCL | O_NOFOLLOW, - perm < 0 ? 0666 : (perm & 0777))) < 0) + O_CREAT | O_EXCL | O_NOFOLLOW, + perm < 0 ? 0666 : (perm & 0777))) < 0) { EMSG(_("E206: patchmode: can't touch empty original file")); - else + } else { close(empty_fd); + } } if (org != NULL) { os_setperm(org, os_getperm((const char *)fname) & 0777); @@ -3555,15 +3634,16 @@ restore_backup: * Finish up. We get here either after failure or success. */ fail: - --no_wait_return; /* may wait for return now */ + --no_wait_return; // may wait for return now nofail: - /* Done saving, we accept changed buffer warnings again */ + // Done saving, we accept changed buffer warnings again buf->b_saving = false; xfree(backup); - if (buffer != smallbuf) + if (buffer != smallbuf) { xfree(buffer); + } xfree(fenc_tofree); xfree(write_info.bw_conv_buf); # ifdef HAVE_ICONV @@ -3603,9 +3683,8 @@ nofail: const int attr = HL_ATTR(HLF_E); // Set highlight for error messages. MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"), attr | MSG_HIST); - MSG_PUTS_ATTR(_( - "don't quit the editor until the file is successfully written!"), - attr | MSG_HIST); + MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"), + attr | MSG_HIST); /* Update the timestamp to avoid an "overwrite changed file" * prompt when writing again. */ @@ -3631,7 +3710,7 @@ nofail: if (!should_abort(retval)) { aco_save_T aco; - curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */ + curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read /* * Apply POST autocommands. @@ -3639,24 +3718,26 @@ nofail: */ aucmd_prepbuf(&aco, buf); - if (append) + if (append) { apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname, - FALSE, curbuf, eap); - else if (filtering) + FALSE, curbuf, eap); + } else if (filtering) { apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname, - FALSE, curbuf, eap); - else if (reset_changed && whole) + FALSE, curbuf, eap); + } else if (reset_changed && whole) { apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname, - FALSE, curbuf, eap); - else + FALSE, curbuf, eap); + } else { apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname, - FALSE, curbuf, eap); + FALSE, curbuf, eap); + } - /* restore curwin/curbuf and a few other things */ + // restore curwin/curbuf and a few other things aucmd_restbuf(&aco); - if (aborting()) /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing retval = FALSE; + } } got_int |= prev_got_int; @@ -3673,16 +3754,18 @@ nofail: */ static int set_rw_fname(char_u *fname, char_u *sfname) { - buf_T *buf = curbuf; + buf_T *buf = curbuf; - /* It's like the unnamed buffer is deleted.... */ - if (curbuf->b_p_bl) + // It's like the unnamed buffer is deleted.... + if (curbuf->b_p_bl) { apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); + } apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf); - if (aborting()) /* autocmds may abort script processing */ + if (aborting()) { // autocmds may abort script processing return FAIL; + } if (curbuf != buf) { - /* We are in another buffer now, don't do the renaming. */ + // We are in another buffer now, don't do the renaming. EMSG(_(e_auchangedbuf)); return FAIL; } @@ -3691,14 +3774,16 @@ static int set_rw_fname(char_u *fname, char_u *sfname) curbuf->b_flags |= BF_NOTEDITED; } - /* ....and a new named one is created */ + // ....and a new named one is created apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf); - if (curbuf->b_p_bl) + if (curbuf->b_p_bl) { apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf); - if (aborting()) /* autocmds may abort script processing */ + } + if (aborting()) { // autocmds may abort script processing return FAIL; + } - /* Do filetype detection now if 'filetype' is empty. */ + // Do filetype detection now if 'filetype' is empty. if (*curbuf->b_p_ft == NUL) { if (au_has_group((char_u *)"filetypedetect")) { (void)do_doautocmd((char_u *)"filetypedetect BufRead", false, NULL); @@ -3717,8 +3802,8 @@ static int set_rw_fname(char_u *fname, char_u *sfname) /// @param[in] buf_len ret_buf length. /// @param[in] buf buf_T file name is coming from. /// @param[in] fname File name to write. -static void add_quoted_fname(char *const ret_buf, const size_t buf_len, - const buf_T *const buf, const char *fname) +static void add_quoted_fname(char *const ret_buf, const size_t buf_len, const buf_T *const buf, + const char *fname) FUNC_ATTR_NONNULL_ARG(1) { if (fname == NULL) { @@ -3761,25 +3846,26 @@ static bool msg_add_fileformat(int eol_type) */ void msg_add_lines(int insert_space, long lnum, off_T nchars) { - char_u *p; + char_u *p; p = IObuff + STRLEN(IObuff); - if (insert_space) + if (insert_space) { *p++ = ' '; - if (shortmess(SHM_LINES)) { - sprintf((char *)p, "%" PRId64 "L, %" PRId64 "C", - (int64_t)lnum, (int64_t)nchars); } - else { - if (lnum == 1) + if (shortmess(SHM_LINES)) { + sprintf((char *)p, "%" PRId64 "L, %" PRId64 "C", + (int64_t)lnum, (int64_t)nchars); + } else { + if (lnum == 1) { STRCPY(p, _("1 line, ")); - else + } else { sprintf((char *)p, _("%" PRId64 " lines, "), (int64_t)lnum); + } p += STRLEN(p); - if (nchars == 1) + if (nchars == 1) { STRCPY(p, _("1 character")); - else { + } else { sprintf((char *)p, _("%" PRId64 " characters"), (int64_t)nchars); } } @@ -3791,7 +3877,7 @@ void msg_add_lines(int insert_space, long lnum, off_T nchars) static void msg_add_eol(void) { STRCAT(IObuff, - shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]")); + shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]")); } /* @@ -3842,17 +3928,17 @@ static bool time_differs(long t1, long t2) FUNC_ATTR_CONST static int buf_write_bytes(struct bw_info *ip) { int wlen; - char_u *buf = ip->bw_buf; /* data to write */ - int len = ip->bw_len; /* length of data */ + char_u *buf = ip->bw_buf; // data to write + int len = ip->bw_len; // length of data #ifdef HAS_BW_FLAGS - int flags = ip->bw_flags; /* extra flags */ + int flags = ip->bw_flags; // extra flags #endif /* * Skip conversion when writing the BOM. */ if (!(flags & FIO_NOCONVERT)) { - char_u *p; + char_u *p; unsigned c; int n; @@ -3860,9 +3946,10 @@ static int buf_write_bytes(struct bw_info *ip) /* * 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 = ip->bw_conv_buf; // translate to buffer + for (wlen = 0; wlen < len; ++wlen) { p += utf_char2bytes(buf[wlen], p); + } buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) { @@ -3870,10 +3957,11 @@ static int buf_write_bytes(struct bw_info *ip) * 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 - p = ip->bw_conv_buf; /* translate to buffer */ + if (flags & FIO_LATIN1) { + p = buf; // translate in-place (can only get shorter) + } else { + p = ip->bw_conv_buf; // translate to buffer + } for (wlen = 0; wlen < len; wlen += n) { if (wlen == 0 && ip->bw_restlen != 0) { int l; @@ -3882,30 +3970,33 @@ static int buf_write_bytes(struct bw_info *ip) * buf[] to get a full sequence. Might still be too * short! */ l = CONV_RESTLEN - ip->bw_restlen; - if (l > len) + if (l > len) { l = len; + } memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l); n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l); if (n > ip->bw_restlen + len) { /* We have an incomplete byte sequence at the end to * be written. We can't convert it without the * remaining bytes. Keep them for the next call. */ - if (ip->bw_restlen + len > CONV_RESTLEN) + if (ip->bw_restlen + len > CONV_RESTLEN) { return FAIL; + } ip->bw_restlen += len; break; } - if (n > 1) + if (n > 1) { c = utf_ptr2char(ip->bw_rest); - else + } else { c = ip->bw_rest[0]; + } if (n >= ip->bw_restlen) { n -= ip->bw_restlen; ip->bw_restlen = 0; } else { ip->bw_restlen -= n; memmove(ip->bw_rest, ip->bw_rest + n, - (size_t)ip->bw_restlen); + (size_t)ip->bw_restlen); n = 0; } } else { @@ -3914,29 +4005,32 @@ static int buf_write_bytes(struct bw_info *ip) /* We have an incomplete byte sequence at the end to * be written. We can't convert it without the * remaining bytes. Keep them for the next call. */ - if (len - wlen > CONV_RESTLEN) + if (len - wlen > CONV_RESTLEN) { return FAIL; + } ip->bw_restlen = len - wlen; memmove(ip->bw_rest, buf + wlen, - (size_t)ip->bw_restlen); + (size_t)ip->bw_restlen); break; } - if (n > 1) + if (n > 1) { c = utf_ptr2char(buf + wlen); - else + } else { c = buf[wlen]; + } } if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error) { ip->bw_conv_error = TRUE; ip->bw_conv_error_lnum = ip->bw_start_lnum; } - if (c == NL) + if (c == NL) { ++ip->bw_start_lnum; + } } - if (flags & FIO_LATIN1) + if (flags & FIO_LATIN1) { len = (int)(p - buf); - else { + } else { buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } @@ -3944,12 +4038,12 @@ static int buf_write_bytes(struct bw_info *ip) # ifdef HAVE_ICONV if (ip->bw_iconv_fd != (iconv_t)-1) { - const char *from; + const char *from; size_t fromlen; - char *to; + char *to; size_t tolen; - /* Convert with iconv(). */ + // Convert with iconv(). if (ip->bw_restlen > 0) { char *fp; @@ -3972,7 +4066,7 @@ static int buf_write_bytes(struct bw_info *ip) if (ip->bw_first) { size_t save_len = tolen; - /* output the initial shift state sequence */ + // output the initial shift state sequence (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen); /* There is a bug in iconv() on Linux (which appears to be @@ -3995,9 +4089,10 @@ static int buf_write_bytes(struct bw_info *ip) return FAIL; } - /* copy remainder to ip->bw_rest[] to be used for the next call. */ - if (fromlen > 0) + // copy remainder to ip->bw_rest[] to be used for the next call. + if (fromlen > 0) { memmove(ip->bw_rest, (void *)from, fromlen); + } ip->bw_restlen = (int)fromlen; buf = ip->bw_conv_buf; @@ -4023,7 +4118,7 @@ static int buf_write_bytes(struct bw_info *ip) /// @return true for an error, false when it's OK. static bool ucs2bytes(unsigned c, char_u **pp, int flags) FUNC_ATTR_NONNULL_ALL { - char_u *p = *pp; + char_u *p = *pp; bool error = false; int cc; @@ -4069,12 +4164,13 @@ static bool ucs2bytes(unsigned c, char_u **pp, int flags) FUNC_ATTR_NONNULL_ALL *p++ = (c >> 8); *p++ = c; } - } else { /* Latin1 */ + } else { // Latin1 if (c >= 0x100) { error = true; *p++ = 0xBF; - } else + } else { *p++ = c; + } } *pp = p; @@ -4129,25 +4225,29 @@ static int get_fio_flags(const char_u *name) prop = enc_canon_props(name); if (prop & ENC_UNICODE) { if (prop & ENC_2BYTE) { - if (prop & ENC_ENDIAN_L) + if (prop & ENC_ENDIAN_L) { return FIO_UCS2 | FIO_ENDIAN_L; + } return FIO_UCS2; } if (prop & ENC_4BYTE) { - if (prop & ENC_ENDIAN_L) + if (prop & ENC_ENDIAN_L) { return FIO_UCS4 | FIO_ENDIAN_L; + } return FIO_UCS4; } if (prop & ENC_2WORD) { - if (prop & ENC_ENDIAN_L) + if (prop & ENC_ENDIAN_L) { return FIO_UTF16 | FIO_ENDIAN_L; + } return FIO_UTF16; } return FIO_UTF8; } - if (prop & ENC_LATIN1) + if (prop & ENC_LATIN1) { return FIO_LATIN1; - /* must be ENC_DBCS, requires iconv() */ + } + // must be ENC_DBCS, requires iconv() return 0; } @@ -4161,34 +4261,37 @@ static int get_fio_flags(const char_u *name) */ static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags) { - char *name = NULL; + char *name = NULL; int len = 2; if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0)) { - name = "utf-8"; /* EF BB BF */ + name = "utf-8"; // EF BB BF len = 3; } else if (p[0] == 0xff && p[1] == 0xfe) { if (size >= 4 && p[2] == 0 && p[3] == 0 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L))) { - name = "ucs-4le"; /* FF FE 00 00 */ + name = "ucs-4le"; // FF FE 00 00 len = 4; - } else if (flags == (FIO_UCS2 | FIO_ENDIAN_L)) - name = "ucs-2le"; /* FF FE */ - else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L)) - /* utf-16le is preferred, it also works for ucs-2le text */ - name = "utf-16le"; /* FF FE */ + } else if (flags == (FIO_UCS2 | FIO_ENDIAN_L)) { + name = "ucs-2le"; // FF FE + } else if (flags == FIO_ALL || + flags == (FIO_UTF16 | FIO_ENDIAN_L)) { + // utf-16le is preferred, it also works for ucs-2le text + name = "utf-16le"; // FF FE + } } else if (p[0] == 0xfe && p[1] == 0xff && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16)) { - /* Default to utf-16, it works also for ucs-2 text. */ - if (flags == FIO_UCS2) - name = "ucs-2"; /* FE FF */ - else - name = "utf-16"; /* FE FF */ + // Default to utf-16, it works also for ucs-2 text. + if (flags == FIO_UCS2) { + name = "ucs-2"; // FE FF + } else { + name = "utf-16"; // FE FF + } } else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4)) { - name = "ucs-4"; /* 00 00 FE FF */ + name = "ucs-4"; // 00 00 FE FF len = 4; } @@ -4203,15 +4306,16 @@ static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags) static int make_bom(char_u *buf, char_u *name) { int flags; - char_u *p; + char_u *p; flags = get_fio_flags(name); - /* Can't put a BOM in a non-Unicode file. */ - if (flags == FIO_LATIN1 || flags == 0) + // Can't put a BOM in a non-Unicode file. + if (flags == FIO_LATIN1 || flags == 0) { return 0; + } - if (flags == FIO_UTF8) { /* UTF-8 */ + if (flags == FIO_UTF8) { // UTF-8 buf[0] = 0xef; buf[1] = 0xbb; buf[2] = 0xbf; @@ -4231,7 +4335,7 @@ static int make_bom(char_u *buf, char_u *name) /// name. void shorten_buf_fname(buf_T *buf, char_u *dirname, int force) { - char_u *p; + char_u *p; if (buf->b_fname != NULL && !bt_nofile(buf) @@ -4260,7 +4364,7 @@ void shorten_fnames(int force) os_dirname(dirname, MAXPATHL); FOR_ALL_BUFFERS(buf) { - shorten_buf_fname(buf, dirname, force); + shorten_buf_fname(buf, dirname, force); // Always make the swap file name a full path, a "nofile" buffer may // also have a swap file. @@ -4533,11 +4637,11 @@ int vim_rename(const char_u *from, const char_u *to) int fd_in; int fd_out; int n; - char *errmsg = NULL; - char *buffer; + char *errmsg = NULL; + char *buffer; long perm; #ifdef HAVE_ACL - vim_acl_T acl; /* ACL from original file */ + vim_acl_T acl; // ACL from original file #endif bool use_tmp_file = false; @@ -4577,8 +4681,9 @@ int vim_rename(const char_u *from, const char_u *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) + if (STRLEN(from) >= MAXPATHL - 5) { return -1; + } STRCPY(tempname, from); for (n = 123; n < 99999; n++) { char * tail = (char *)path_tail(tempname); @@ -4613,8 +4718,9 @@ int vim_rename(const char_u *from, const char_u *to) /* * First try a normal rename, return if it works. */ - if (os_rename(from, to) == OK) + if (os_rename(from, to) == OK) { return 0; + } /* * Rename() failed, try copying the file. @@ -4632,9 +4738,9 @@ int vim_rename(const char_u *from, const char_u *to) return -1; } - /* Create the new file with same permissions as the original. */ + // Create the new file with same permissions as the original. fd_out = os_open((char *)to, - O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, (int)perm); + O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, (int)perm); if (fd_out < 0) { close(fd_in); #ifdef HAVE_ACL @@ -4655,16 +4761,18 @@ int vim_rename(const char_u *from, const char_u *to) return -1; } - while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0) + while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0) { if (write_eintr(fd_out, buffer, n) != n) { errmsg = _("E208: Error writing to \"%s\""); break; } + } xfree(buffer); close(fd_in); - if (close(fd_out) < 0) + if (close(fd_out) < 0) { errmsg = _("E209: Error closing \"%s\""); + } if (n < 0) { errmsg = _("E210: Error reading \"%s\""); to = from; @@ -4686,23 +4794,23 @@ int vim_rename(const char_u *from, const char_u *to) static int already_warned = FALSE; -// Check if any not hidden buffer has been changed. -// Postpone the check if there are characters in the stuff buffer, a global -// command is being executed, a mapping is being executed or an autocommand is -// busy. -// Returns TRUE if some message was written (screen should be redrawn and -// cursor positioned). -int -check_timestamps( - int focus // called for GUI focus event -) +/// Check if any not hidden buffer has been changed. +/// Postpone the check if there are characters in the stuff buffer, a global +/// command is being executed, a mapping is being executed or an autocommand is +/// busy. +/// +/// @param focus called for GUI focus event +/// +/// @return TRUE if some message was written (screen should be redrawn and cursor positioned). +int check_timestamps(int focus) { int didit = 0; /* Don't check timestamps while system() or another low-level function may * cause us to lose and gain focus. */ - if (no_check_timestamps > 0) + if (no_check_timestamps > 0) { return FALSE; + } /* Avoid doing a check twice. The OK/Reload dialog can cause a focus * event and we would keep on checking if the file is steadily growing. @@ -4713,8 +4821,8 @@ check_timestamps( } if (!stuff_empty() || global_busy || !typebuf_typed() - || autocmd_busy || curbuf->b_ro_locked > 0 || allbuf_lock > 0 - ) { + || autocmd_busy || curbuf->b_ro_locked > 0 || + allbuf_lock > 0) { need_check_timestamps = true; // check later } else { no_wait_return++; @@ -4754,12 +4862,12 @@ check_timestamps( */ static int move_lines(buf_T *frombuf, buf_T *tobuf) { - buf_T *tbuf = curbuf; + buf_T *tbuf = curbuf; int retval = OK; linenr_T lnum; - char_u *p; + char_u *p; - /* Copy the lines in "frombuf" to "tobuf". */ + // Copy the lines in "frombuf" to "tobuf". curbuf = tobuf; for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; lnum++) { p = vim_strsave(ml_get_buf(frombuf, lnum, false)); @@ -4771,7 +4879,7 @@ static int move_lines(buf_T *frombuf, buf_T *tobuf) xfree(p); } - /* Delete all the lines in "frombuf". */ + // Delete all the lines in "frombuf". if (retval != FAIL) { curbuf = frombuf; for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; lnum--) { @@ -4799,17 +4907,17 @@ int buf_check_timestamp(buf_T *buf) FUNC_ATTR_NONNULL_ALL { int retval = 0; - char_u *path; - char *mesg = NULL; - char *mesg2 = ""; + char_u *path; + char *mesg = NULL; + char *mesg2 = ""; bool helpmesg = false; bool reload = false; bool can_reload = false; uint64_t orig_size = buf->b_orig_size; int orig_mode = buf->b_orig_mode; static bool busy = false; - char_u *s; - char *reason; + char_u *s; + char *reason; bufref_T bufref; set_bufref(&bufref, buf); @@ -4822,9 +4930,9 @@ int buf_check_timestamp(buf_T *buf) || buf->b_ml.ml_mfp == NULL || !bt_normal(buf) || buf->b_saving - || busy - ) + || busy) { return 0; + } FileInfo file_info; bool file_info_ok; @@ -4910,24 +5018,22 @@ int buf_check_timestamp(buf_T *buf) // changed. if (reason[2] == 'n') { mesg = _( - "W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well"); + "W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well"); mesg2 = _("See \":help W12\" for more info."); } else if (reason[1] == 'h') { - mesg = _( - "W11: Warning: File \"%s\" has changed since editing started"); + mesg = _("W11: Warning: File \"%s\" has changed since editing started"); mesg2 = _("See \":help W11\" for more info."); } else if (*reason == 'm') { - mesg = _( - "W16: Warning: Mode of file \"%s\" has changed since editing started"); + mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started"); mesg2 = _("See \":help W16\" for more info."); - } else + } else { /* Only timestamp changed, store it to avoid a warning * in check_mtime() later. */ buf->b_mtime_read = buf->b_mtime; + } } } } - } else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W) && os_path_exists(buf->b_ffname)) { retval = 1; @@ -4952,8 +5058,8 @@ int buf_check_timestamp(buf_T *buf) xstrlcat(tbuf, "\n", tbuf_len - 1); xstrlcat(tbuf, mesg2, tbuf_len - 1); } - if (do_dialog(VIM_WARNING, (char_u *) _("Warning"), (char_u *) tbuf, - (char_u *) _("&OK\n&Load File"), 1, NULL, true) == 2) { + if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), (char_u *)tbuf, + (char_u *)_("&OK\n&Load File"), 1, NULL, true) == 2) { reload = true; } } else if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned) { @@ -4989,7 +5095,7 @@ int buf_check_timestamp(buf_T *buf) } if (reload) { - /* Reload the buffer. */ + // Reload the buffer. buf_reload(buf, orig_mode); if (buf->b_p_udf && buf->b_ffname != NULL) { char_u hash[UNDO_HASH_SIZE]; @@ -5020,13 +5126,13 @@ void buf_reload(buf_T *buf, int orig_mode) pos_T old_cursor; linenr_T old_topline; int old_ro = buf->b_p_ro; - buf_T *savebuf; + buf_T *savebuf; bufref_T bufref; int saved = OK; aco_save_T aco; int flags = READ_NEW; - /* set curwin/curbuf for "buf" and save some things */ + // set curwin/curbuf for "buf" and save some things aucmd_prepbuf(&aco, buf); // We only want to read the text from the file, not reset the syntax @@ -5057,7 +5163,7 @@ void buf_reload(buf_T *buf, int orig_mode) savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY); set_bufref(&bufref, savebuf); if (savebuf != NULL && buf == curbuf) { - /* Open the memline. */ + // Open the memline. curbuf = savebuf; curwin->w_buffer = savebuf; saved = ml_open(curbuf); @@ -5067,7 +5173,7 @@ void buf_reload(buf_T *buf, int orig_mode) if (savebuf == NULL || saved == FAIL || buf != curbuf || move_lines(buf, savebuf) == FAIL) { EMSG2(_("E462: Could not prepare for reloading \"%s\""), - buf->b_fname); + buf->b_fname); saved = FAIL; } } @@ -5110,21 +5216,22 @@ void buf_reload(buf_T *buf, int orig_mode) wipe_buffer(savebuf, false); } - /* Invalidate diff info if necessary. */ + // Invalidate diff info if necessary. diff_invalidate(curbuf); /* Restore the topline and cursor position and check it (lines may * have been removed). */ - if (old_topline > curbuf->b_ml.ml_line_count) + if (old_topline > curbuf->b_ml.ml_line_count) { curwin->w_topline = curbuf->b_ml.ml_line_count; - else + } else { curwin->w_topline = old_topline; + } curwin->w_cursor = old_cursor; check_cursor(); update_topline(curwin); keep_filetype = false; - /* Update folds unless they are defined manually. */ + // Update folds unless they are defined manually. FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp->w_buffer == curwin->w_buffer && !foldmethodIsManual(wp)) { @@ -5135,15 +5242,16 @@ void buf_reload(buf_T *buf, int orig_mode) /* If the mode didn't change and 'readonly' was set, keep the old * value; the user probably used the ":view" command. But don't * reset it, might have had a read error. */ - if (orig_mode == curbuf->b_orig_mode) + if (orig_mode == curbuf->b_orig_mode) { curbuf->b_p_ro |= old_ro; + } - /* Modelines must override settings done by autocommands. */ + // Modelines must override settings done by autocommands. do_modelines(0); - /* restore curwin/curbuf and a few other things */ + // restore curwin/curbuf and a few other things aucmd_restbuf(&aco); - /* Careful: autocommands may have made "buf" invalid! */ + // Careful: autocommands may have made "buf" invalid! } void buf_store_file_info(buf_T *buf, FileInfo *file_info) @@ -5160,8 +5268,9 @@ void buf_store_file_info(buf_T *buf, FileInfo *file_info) */ void write_lnum_adjust(linenr_T offset) { - if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */ + if (curbuf->b_no_eol_lnum != 0) { // only if there is a missing eol curbuf->b_no_eol_lnum += offset; + } } #if defined(BACKSLASH_IN_FILENAME) @@ -5169,7 +5278,7 @@ void write_lnum_adjust(linenr_T offset) /// unless when it looks like a URL. void forward_slash(char_u *fname) { - char_u *p; + char_u *p; if (path_with_url((const char *)fname)) { return; @@ -5344,18 +5453,19 @@ char_u *vim_tempname(void) /// @param allow_dirs Allow matching with dir /// /// @return true if there is a match, false otherwise -bool match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, - char_u *sfname, char_u *tail, int allow_dirs) +bool match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, + int allow_dirs) { regmatch_T regmatch; bool result = false; - regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */ + regmatch.rm_ic = p_fic; // ignore case if 'fileignorecase' is set { - if (prog != NULL) + if (prog != NULL) { regmatch.regprog = *prog; - else + } else { regmatch.regprog = vim_regcomp(pattern, RE_MAGIC); + } } /* @@ -5394,11 +5504,11 @@ bool match_file_list(char_u *list, char_u *sfname, char_u *ffname) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1, 3) { char_u buf[100]; - char_u *tail; - char_u *regpat; + char_u *tail; + char_u *regpat; char allow_dirs; bool match; - char_u *p; + char_u *p; tail = path_tail(sfname); @@ -5425,25 +5535,27 @@ bool match_file_list(char_u *list, char_u *sfname, char_u *ffname) /// allow_dirs, otherwise FALSE is put there -- webb. /// Handle backslashes before special characters, like "\*" and "\ ". /// -/// Returns NULL on failure. -char_u * file_pat_to_reg_pat( - const char_u *pat, - const char_u *pat_end, // first char after pattern or NULL - char *allow_dirs, // Result passed back out in here - int no_bslash // Don't use a backward slash as pathsep -) +/// @param pat_end first char after pattern or NULL +/// @param allow_dirs Result passed back out in here +/// @param no_bslash Don't use a backward slash as pathsep +/// +/// @return NULL on failure. +char_u * file_pat_to_reg_pat(const char_u *pat, const char_u *pat_end, char *allow_dirs, + int no_bslash) FUNC_ATTR_NONNULL_ARG(1) { const char_u *endp; - char_u *reg_pat; + char_u *reg_pat; const char_u *p; int nested = 0; int add_dollar = TRUE; - if (allow_dirs != NULL) + if (allow_dirs != NULL) { *allow_dirs = FALSE; - if (pat_end == NULL) + } + if (pat_end == NULL) { pat_end = pat + STRLEN(pat); + } if (pat_end == pat) { return (char_u *)xstrdup("^$"); @@ -5459,12 +5571,12 @@ char_u * file_pat_to_reg_pat( case '{': case '}': case '~': - size += 2; /* extra backslash */ + size += 2; // extra backslash break; #ifdef BACKSLASH_IN_FILENAME case '\\': case '/': - size += 4; /* could become "[\/]" */ + size += 4; // could become "[\/]" break; #endif default: @@ -5476,11 +5588,13 @@ char_u * file_pat_to_reg_pat( size_t i = 0; - if (pat[0] == '*') - while (pat[0] == '*' && pat < pat_end - 1) + if (pat[0] == '*') { + while (pat[0] == '*' && pat < pat_end - 1) { pat++; - else + } + } else { reg_pat[i++] = '^'; + } endp = pat_end - 1; if (endp >= pat && *endp == '*') { while (endp - pat > 0 && *endp == '*') { @@ -5493,8 +5607,9 @@ char_u * file_pat_to_reg_pat( case '*': reg_pat[i++] = '.'; reg_pat[i++] = '*'; - while (p[1] == '*') /* "**" matches like "*" */ + while (p[1] == '*') { // "**" matches like "*" ++p; + } break; case '.': case '~': @@ -5505,8 +5620,9 @@ char_u * file_pat_to_reg_pat( reg_pat[i++] = '.'; break; case '\\': - if (p[1] == NUL) + if (p[1] == NUL) { break; + } #ifdef BACKSLASH_IN_FILENAME if (!no_bslash) { /* translate: @@ -5521,8 +5637,9 @@ char_u * file_pat_to_reg_pat( reg_pat[i++] = '\\'; reg_pat[i++] = '/'; reg_pat[i++] = ']'; - if (allow_dirs != NULL) + if (allow_dirs != NULL) { *allow_dirs = TRUE; + } break; } } @@ -5555,8 +5672,9 @@ char_u * file_pat_to_reg_pat( #ifdef BACKSLASH_IN_FILENAME && (!no_bslash || *p != '\\') #endif - ) + ) { *allow_dirs = TRUE; + } reg_pat[i++] = '\\'; reg_pat[i++] = *p; } @@ -5567,8 +5685,9 @@ char_u * file_pat_to_reg_pat( reg_pat[i++] = '\\'; reg_pat[i++] = '/'; reg_pat[i++] = ']'; - if (allow_dirs != NULL) + if (allow_dirs != NULL) { *allow_dirs = TRUE; + } break; #endif case '{': @@ -5585,8 +5704,9 @@ char_u * file_pat_to_reg_pat( if (nested) { reg_pat[i++] = '\\'; reg_pat[i++] = '|'; - } else + } else { reg_pat[i++] = ','; + } break; default: if (allow_dirs != NULL && vim_ispathsep(*p)) { @@ -5596,8 +5716,9 @@ char_u * file_pat_to_reg_pat( break; } } - if (add_dollar) + if (add_dollar) { reg_pat[i++] = '$'; + } reg_pat[i] = NUL; if (nested != 0) { if (nested < 0) { @@ -5621,8 +5742,9 @@ long read_eintr(int fd, void *buf, size_t bufsize) for (;; ) { ret = read(fd, buf, bufsize); - if (ret >= 0 || errno != EINTR) + if (ret >= 0 || errno != EINTR) { break; + } } return ret; } @@ -5641,10 +5763,12 @@ long write_eintr(int fd, void *buf, size_t bufsize) while (ret < (long)bufsize) { wlen = write(fd, (char *)buf + ret, bufsize - ret); if (wlen < 0) { - if (errno != EINTR) + if (errno != EINTR) { break; - } else + } + } else { ret += wlen; + } } return ret; } diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 51a8a85aa0..567cf9c8c3 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -7,12 +7,11 @@ * fold.c: code for folding */ -#include <string.h> #include <inttypes.h> +#include <string.h> -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/fold.h" +#include "nvim/buffer_updates.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" @@ -20,27 +19,28 @@ #include "nvim/eval.h" #include "nvim/ex_docmd.h" #include "nvim/ex_session.h" +#include "nvim/extmark.h" +#include "nvim/fold.h" #include "nvim/func_attr.h" +#include "nvim/garray.h" #include "nvim/indent.h" -#include "nvim/buffer_updates.h" -#include "nvim/extmark.h" #include "nvim/mark.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/plines.h" -#include "nvim/garray.h" #include "nvim/move.h" +#include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/plines.h" #include "nvim/screen.h" #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/undo.h" -#include "nvim/ops.h" +#include "nvim/vim.h" -/* local declarations. {{{1 */ -/* typedef fold_T {{{2 */ +// local declarations. {{{1 +// typedef fold_T {{{2 /* * The toplevel folds for each window are stored in the w_folds growarray. * Each toplevel fold can contain an array of second level folds in the @@ -58,20 +58,20 @@ typedef struct { // folds too } fold_T; -#define FD_OPEN 0 /* fold is open (nested ones can be closed) */ -#define FD_CLOSED 1 /* fold is closed */ -#define FD_LEVEL 2 /* depends on 'foldlevel' (nested folds too) */ +#define FD_OPEN 0 // fold is open (nested ones can be closed) +#define FD_CLOSED 1 // fold is closed +#define FD_LEVEL 2 // depends on 'foldlevel' (nested folds too) -#define MAX_LEVEL 20 /* maximum fold depth */ +#define MAX_LEVEL 20 // maximum fold depth -/* Define "fline_T", passed to get fold level for a line. {{{2 */ +// Define "fline_T", passed to get fold level for a line. {{{2 typedef struct { - win_T *wp; /* window */ - linenr_T lnum; /* current line number */ - linenr_T off; /* offset between lnum and real line number */ - linenr_T lnum_save; /* line nr used by foldUpdateIEMSRecurse() */ - int lvl; /* current level (-1 for undefined) */ - int lvl_next; /* level used for next line */ + win_T *wp; // window + linenr_T lnum; // current line number + linenr_T off; // offset between lnum and real line number + linenr_T lnum_save; // line nr used by foldUpdateIEMSRecurse() + int lvl; // current level (-1 for undefined) + int lvl_next; // level used for next line int start; /* number of folds that are forced to start at this line. */ int end; /* level of fold that is forced to end below @@ -83,10 +83,10 @@ typedef struct { // Flag is set when redrawing is needed. static bool fold_changed; -/* Function used by foldUpdateIEMSRecurse */ +// Function used by foldUpdateIEMSRecurse typedef void (*LevelGetter)(fline_T *); -/* static functions {{{2 */ +// static functions {{{2 #ifdef INCLUDE_GENERATED_DECLARATIONS # include "fold.c.generated.h" @@ -110,17 +110,17 @@ static linenr_T invalid_bot = (linenr_T)0; static linenr_T prev_lnum = 0; static int prev_lnum_lvl = -1; -/* Flags used for "done" argument of setManualFold. */ +// Flags used for "done" argument of setManualFold. #define DONE_NOTHING 0 -#define DONE_ACTION 1 /* did close or open a fold */ -#define DONE_FOLD 2 /* did find a fold */ +#define DONE_ACTION 1 // did close or open a fold +#define DONE_FOLD 2 // did find a fold static size_t foldstartmarkerlen; static char_u *foldendmarker; static size_t foldendmarkerlen; -/* Exported folding functions. {{{1 */ -/* copyFoldingState() {{{2 */ +// Exported folding functions. {{{1 +// copyFoldingState() {{{2 /* * Copy that folding state from window "wp_from" to window "wp_to". */ @@ -131,18 +131,18 @@ void copyFoldingState(win_T *wp_from, win_T *wp_to) cloneFoldGrowArray(&wp_from->w_folds, &wp_to->w_folds); } -/* hasAnyFolding() {{{2 */ +// hasAnyFolding() {{{2 /* * Return TRUE if there may be folded lines in the current window. */ int hasAnyFolding(win_T *win) { - /* very simple now, but can become more complex later */ + // very simple now, but can become more complex later return !win->w_buffer->terminal && win->w_p_fen && (!foldmethodIsManual(win) || !GA_EMPTY(&win->w_folds)); } -/* hasFolding() {{{2 */ +// hasFolding() {{{2 /* * Return TRUE if line "lnum" in the current window is part of a closed * fold. @@ -163,20 +163,14 @@ bool hasFolding(linenr_T lnum, linenr_T *firstp, linenr_T *lastp) /// @param[out] infop where to store fold info /// /// @return true if range contains folds -bool hasFoldingWin( - win_T *const win, - const linenr_T lnum, - linenr_T *const firstp, - linenr_T *const lastp, - const bool cache, - foldinfo_T *const infop -) +bool hasFoldingWin(win_T *const win, const linenr_T lnum, linenr_T *const firstp, + linenr_T *const lastp, const bool cache, foldinfo_T *const infop) { bool had_folded = false; linenr_T first = 0; linenr_T last = 0; linenr_T lnum_rel = lnum; - fold_T *fp; + fold_T *fp; int level = 0; bool use_level = false; bool maybe_small = false; @@ -186,8 +180,9 @@ bool hasFoldingWin( // Return quickly when there is no folding at all in this window. if (!hasAnyFolding(win)) { - if (infop != NULL) + if (infop != NULL) { infop->fi_level = 0; + } return false; } @@ -210,21 +205,23 @@ bool hasFoldingWin( */ garray_T *gap = &win->w_folds; for (;; ) { - if (!foldFind(gap, lnum_rel, &fp)) + if (!foldFind(gap, lnum_rel, &fp)) { break; + } - /* Remember lowest level of fold that starts in "lnum". */ - if (lnum_rel == fp->fd_top && low_level == 0) + // Remember lowest level of fold that starts in "lnum". + if (lnum_rel == fp->fd_top && low_level == 0) { low_level = level + 1; + } first += fp->fd_top; last += fp->fd_top; - /* is this fold closed? */ + // is this fold closed? had_folded = check_closed(win, fp, &use_level, level, - &maybe_small, lnum - lnum_rel); + &maybe_small, lnum - lnum_rel); if (had_folded) { - /* Fold closed: Set last and quit loop. */ + // Fold closed: Set last and quit loop. last += fp->fd_len - 1; break; } @@ -249,10 +246,12 @@ bool hasFoldingWin( if (last > win->w_buffer->b_ml.ml_line_count) { last = win->w_buffer->b_ml.ml_line_count; } - if (lastp != NULL) + if (lastp != NULL) { *lastp = last; - if (firstp != NULL) + } + if (firstp != NULL) { *firstp = first; + } if (infop != NULL) { infop->fi_level = level + 1; infop->fi_lnum = first; @@ -261,7 +260,7 @@ bool hasFoldingWin( return true; } -/* foldLevel() {{{2 */ +// foldLevel() {{{2 /* * Return fold level at line number "lnum" in the current window. */ @@ -269,16 +268,18 @@ int foldLevel(linenr_T lnum) { /* While updating the folds lines between invalid_top and invalid_bot have * an undefined fold level. Otherwise update the folds first. */ - if (invalid_top == (linenr_T)0) + if (invalid_top == (linenr_T)0) { checkupdate(curwin); - else if (lnum == prev_lnum && prev_lnum_lvl >= 0) + } else if (lnum == prev_lnum && prev_lnum_lvl >= 0) { return prev_lnum_lvl; - else if (lnum >= invalid_top && lnum <= invalid_bot) + } else if (lnum >= invalid_top && lnum <= invalid_bot) { return -1; + } - /* Return quickly when there is no folding at all in this window. */ - if (!hasAnyFolding(curwin)) + // Return quickly when there is no folding at all in this window. + if (!hasAnyFolding(curwin)) { return 0; + } return foldLevelWin(curwin, lnum); } @@ -316,7 +317,7 @@ foldinfo_T fold_info(win_T *win, linenr_T lnum) return info; } -/* foldmethodIsManual() {{{2 */ +// foldmethodIsManual() {{{2 /* * Return TRUE if 'foldmethod' is "manual" */ @@ -325,7 +326,7 @@ int foldmethodIsManual(win_T *wp) return wp->w_p_fdm[3] == 'u'; } -/* foldmethodIsIndent() {{{2 */ +// foldmethodIsIndent() {{{2 /* * Return TRUE if 'foldmethod' is "indent" */ @@ -334,7 +335,7 @@ int foldmethodIsIndent(win_T *wp) return wp->w_p_fdm[0] == 'i'; } -/* foldmethodIsExpr() {{{2 */ +// foldmethodIsExpr() {{{2 /* * Return TRUE if 'foldmethod' is "expr" */ @@ -343,7 +344,7 @@ int foldmethodIsExpr(win_T *wp) return wp->w_p_fdm[1] == 'x'; } -/* foldmethodIsMarker() {{{2 */ +// foldmethodIsMarker() {{{2 /* * Return TRUE if 'foldmethod' is "marker" */ @@ -352,7 +353,7 @@ int foldmethodIsMarker(win_T *wp) return wp->w_p_fdm[2] == 'r'; } -/* foldmethodIsSyntax() {{{2 */ +// foldmethodIsSyntax() {{{2 /* * Return TRUE if 'foldmethod' is "syntax" */ @@ -361,7 +362,7 @@ int foldmethodIsSyntax(win_T *wp) return wp->w_p_fdm[0] == 's'; } -/* foldmethodIsDiff() {{{2 */ +// foldmethodIsDiff() {{{2 /* * Return TRUE if 'foldmethod' is "diff" */ @@ -378,7 +379,7 @@ void closeFold(pos_T pos, long count) setFoldRepeat(pos, count, false); } -/* closeFoldRecurse() {{{2 */ +// closeFoldRecurse() {{{2 /* * Close fold for current window at line "lnum" recursively. */ @@ -387,19 +388,15 @@ void closeFoldRecurse(pos_T pos) (void)setManualFold(pos, false, true, NULL); } -/* opFoldRange() {{{2 */ -/* - * Open or Close folds for current window in lines "first" to "last". - * Used for "zo", "zO", "zc" and "zC" in Visual mode. - */ -void -opFoldRange( - pos_T firstpos, - pos_T lastpos, - int opening, // TRUE to open, FALSE to close - int recurse, // TRUE to do it recursively - int had_visual // TRUE when Visual selection used -) +// opFoldRange() {{{2 +/// +/// Open or Close folds for current window in lines "first" to "last". +/// Used for "zo", "zO", "zc" and "zC" in Visual mode. +/// +/// @param opening TRUE to open, FALSE to close +/// @param recurse TRUE to do it recursively +/// @param had_visual TRUE when Visual selection used +void opFoldRange(pos_T firstpos, pos_T lastpos, int opening, int recurse, int had_visual) { int done = DONE_NOTHING; // avoid error messages linenr_T first = firstpos.lnum; @@ -412,8 +409,9 @@ opFoldRange( lnum_next = lnum; /* Opening one level only: next fold to open is after the one going to * be opened. */ - if (opening && !recurse) + if (opening && !recurse) { (void)hasFolding(lnum, NULL, &lnum_next); + } (void)setManualFold(temp, opening, recurse, &done); // Closing one level only: next line to close a fold is after just // closed fold. @@ -421,14 +419,16 @@ opFoldRange( (void)hasFolding(lnum, NULL, &lnum_next); } } - if (done == DONE_NOTHING) + if (done == DONE_NOTHING) { EMSG(_(e_nofold)); - /* Force a redraw to remove the Visual highlighting. */ - if (had_visual) + } + // Force a redraw to remove the Visual highlighting. + if (had_visual) { redraw_curbuf_later(INVERTED); + } } -/* openFold() {{{2 */ +// openFold() {{{2 /* * Open fold for current window at line "lnum". * Repeat "count" times. @@ -438,7 +438,7 @@ void openFold(pos_T pos, long count) setFoldRepeat(pos, count, true); } -/* openFoldRecurse() {{{2 */ +// openFoldRecurse() {{{2 /* * Open fold for current window at line "lnum" recursively. */ @@ -447,7 +447,7 @@ void openFoldRecurse(pos_T pos) (void)setManualFold(pos, true, true, NULL); } -/* foldOpenCursor() {{{2 */ +// foldOpenCursor() {{{2 /* * Open folds until the cursor line is not in a closed fold. */ @@ -456,7 +456,7 @@ void foldOpenCursor(void) int done; checkupdate(curwin); - if (hasAnyFolding(curwin)) + if (hasAnyFolding(curwin)) { for (;; ) { done = DONE_NOTHING; (void)setManualFold(curwin->w_cursor, true, false, &done); @@ -464,9 +464,10 @@ void foldOpenCursor(void) break; } } + } } -/* newFoldLevel() {{{2 */ +// newFoldLevel() {{{2 /* * Set new foldlevel for current window. */ @@ -489,7 +490,7 @@ void newFoldLevel(void) static void newFoldLevelWin(win_T *wp) { - fold_T *fp; + fold_T *fp; checkupdate(wp); if (wp->w_fold_manual) { @@ -497,62 +498,67 @@ static void newFoldLevelWin(win_T *wp) * manual open/close will then change the flags to FD_OPEN or * FD_CLOSED for those folds that don't use 'foldlevel'. */ fp = (fold_T *)wp->w_folds.ga_data; - for (int i = 0; i < wp->w_folds.ga_len; ++i) + for (int i = 0; i < wp->w_folds.ga_len; ++i) { fp[i].fd_flags = FD_LEVEL; + } wp->w_fold_manual = false; } changed_window_setting_win(wp); } -/* foldCheckClose() {{{2 */ +// foldCheckClose() {{{2 /* * Apply 'foldlevel' to all folds that don't contain the cursor. */ void foldCheckClose(void) { - if (*p_fcl != NUL) { /* can only be "all" right now */ + if (*p_fcl != NUL) { // can only be "all" right now checkupdate(curwin); if (checkCloseRec(&curwin->w_folds, curwin->w_cursor.lnum, - (int)curwin->w_p_fdl)) + (int)curwin->w_p_fdl)) { changed_window_setting(); + } } } -/* checkCloseRec() {{{2 */ +// checkCloseRec() {{{2 static int checkCloseRec(garray_T *gap, linenr_T lnum, int level) { - fold_T *fp; + fold_T *fp; int retval = FALSE; fp = (fold_T *)gap->ga_data; for (int i = 0; i < gap->ga_len; ++i) { - /* Only manually opened folds may need to be closed. */ + // Only manually opened folds may need to be closed. if (fp[i].fd_flags == FD_OPEN) { if (level <= 0 && (lnum < fp[i].fd_top || lnum >= fp[i].fd_top + fp[i].fd_len)) { fp[i].fd_flags = FD_LEVEL; retval = TRUE; - } else + } else { retval |= checkCloseRec(&fp[i].fd_nested, lnum - fp[i].fd_top, - level - 1); + level - 1); + } } } return retval; } -/* foldCreateAllowed() {{{2 */ +// foldCreateAllowed() {{{2 /* * Return TRUE if it's allowed to manually create or delete a fold. * Give an error message and return FALSE if not. */ int foldManualAllowed(int create) { - if (foldmethodIsManual(curwin) || foldmethodIsMarker(curwin)) + if (foldmethodIsManual(curwin) || foldmethodIsMarker(curwin)) { return TRUE; - if (create) + } + if (create) { EMSG(_("E350: Cannot create fold with current 'foldmethod'")); - else + } else { EMSG(_("E351: Cannot delete fold with current 'foldmethod'")); + } return FALSE; } @@ -561,8 +567,8 @@ int foldManualAllowed(int create) /// window. void foldCreate(win_T *wp, pos_T start, pos_T end) { - fold_T *fp; - garray_T *gap; + fold_T *fp; + garray_T *gap; garray_T fold_ga; int i; int cont; @@ -659,13 +665,14 @@ void foldCreate(win_T *wp, pos_T start, pos_T end) ((fold_T *)fold_ga.ga_data)[j].fd_top -= start_rel.lnum; } } - /* Move remaining entries to after the new fold. */ - if (i < gap->ga_len) + // Move remaining entries to after the new fold. + if (i < gap->ga_len) { memmove(fp + 1, (fold_T *)gap->ga_data + i, sizeof(fold_T) * (size_t)(gap->ga_len - i)); + } gap->ga_len = gap->ga_len + 1 - cont; - /* insert new fold */ + // insert new fold fp->fd_nested = fold_ga; fp->fd_top = start_rel.lnum; fp->fd_len = end_rel.lnum - start_rel.lnum + 1; @@ -693,16 +700,11 @@ void foldCreate(win_T *wp, pos_T start, pos_T end) /// @param end delete all folds from start to end when not 0 /// @param recursive delete recursively if true /// @param had_visual true when Visual selection used -void deleteFold( - win_T *const wp, - const linenr_T start, - const linenr_T end, - const int recursive, - const bool had_visual // true when Visual selection used -) -{ - fold_T *fp; - fold_T *found_fp = NULL; +void deleteFold(win_T *const wp, const linenr_T start, const linenr_T end, const int recursive, + const bool had_visual) +{ + fold_T *fp; + fold_T *found_fp = NULL; linenr_T found_off = 0; bool maybe_small = false; int level = 0; @@ -720,9 +722,10 @@ void deleteFold( linenr_T lnum_off = 0; bool use_level = false; for (;; ) { - if (!foldFind(gap, lnum - lnum_off, &fp)) + if (!foldFind(gap, lnum - lnum_off, &fp)) { break; - /* lnum is inside this fold, remember info */ + } + // lnum is inside this fold, remember info found_ga = gap; found_fp = fp; found_off = lnum_off; @@ -733,7 +736,7 @@ void deleteFold( break; } - /* check nested folds */ + // check nested folds gap = &fp->fd_nested; lnum_off += fp->fd_top; ++level; @@ -791,7 +794,7 @@ void deleteFold( } } -/* clearFolding() {{{2 */ +// clearFolding() {{{2 /* * Remove all folding for window "win". */ @@ -801,7 +804,7 @@ void clearFolding(win_T *win) win->w_foldinvalid = false; } -/* foldUpdate() {{{2 */ +// foldUpdate() {{{2 /* * Update folds for changes in the buffer of a window. * Note that inserted/deleted lines must have already been taken care of by @@ -837,7 +840,7 @@ void foldUpdate(win_T *wp, linenr_T top, linenr_T bot) || foldmethodIsSyntax(wp)) { int save_got_int = got_int; - /* reset got_int here, otherwise it won't work */ + // reset got_int here, otherwise it won't work got_int = FALSE; foldUpdateIEMS(wp, top, bot); got_int |= save_got_int; @@ -857,7 +860,7 @@ void foldUpdateAfterInsert(void) foldOpenCursor(); } -/* foldUpdateAll() {{{2 */ +// foldUpdateAll() {{{2 /* * Update all lines in a window for folding. * Used when a fold setting changes or after reloading the buffer. @@ -871,19 +874,17 @@ void foldUpdateAll(win_T *win) } // foldMoveTo() {{{2 -// -// If "updown" is false: Move to the start or end of the fold. -// If "updown" is true: move to fold at the same level. -// If not moved return FAIL. -int foldMoveTo( - const bool updown, - const int dir, // FORWARD or BACKWARD - const long count -) +/// +/// If "updown" is false: Move to the start or end of the fold. +/// If "updown" is true: move to fold at the same level. +/// @return FAIL if not moved. +/// +/// @param dir FORWARD or BACKWARD +int foldMoveTo(const bool updown, const int dir, const long count) { int retval = FAIL; linenr_T lnum; - fold_T *fp; + fold_T *fp; checkupdate(curwin); @@ -910,12 +911,14 @@ int foldMoveTo( /* When moving up, consider a fold above the cursor; when * moving down consider a fold below the cursor. */ if (dir == FORWARD) { - if (fp - (fold_T *)gap->ga_data >= gap->ga_len) + if (fp - (fold_T *)gap->ga_data >= gap->ga_len) { break; + } --fp; } else { - if (fp == (fold_T *)gap->ga_data) + if (fp == (fold_T *)gap->ga_data) { break; + } } /* don't look for contained folds, they will always move * the cursor too far. */ @@ -923,31 +926,34 @@ int foldMoveTo( } if (!last) { - /* Check if this fold is closed. */ + // Check if this fold is closed. if (check_closed(curwin, fp, &use_level, level, &maybe_small, lnum_off)) { last = true; } - /* "[z" and "]z" stop at closed fold */ - if (last && !updown) + // "[z" and "]z" stop at closed fold + if (last && !updown) { break; + } } if (updown) { if (dir == FORWARD) { - /* to start of next fold if there is one */ + // to start of next fold if there is one if (fp + 1 - (fold_T *)gap->ga_data < gap->ga_len) { lnum = fp[1].fd_top + lnum_off; - if (lnum > curwin->w_cursor.lnum) + if (lnum > curwin->w_cursor.lnum) { lnum_found = lnum; + } } } else { - /* to end of previous fold if there is one */ + // to end of previous fold if there is one if (fp > (fold_T *)gap->ga_data) { lnum = fp[-1].fd_top + lnum_off + fp[-1].fd_len - 1; - if (lnum < curwin->w_cursor.lnum) + if (lnum < curwin->w_cursor.lnum) { lnum_found = lnum; + } } } } else { @@ -955,37 +961,42 @@ int foldMoveTo( * nested folds. */ if (dir == FORWARD) { lnum = fp->fd_top + lnum_off + fp->fd_len - 1; - if (lnum > curwin->w_cursor.lnum) + if (lnum > curwin->w_cursor.lnum) { lnum_found = lnum; + } } else { lnum = fp->fd_top + lnum_off; - if (lnum < curwin->w_cursor.lnum) + if (lnum < curwin->w_cursor.lnum) { lnum_found = lnum; + } } } - if (last) + if (last) { break; + } - /* Check nested folds (if any). */ + // Check nested folds (if any). gap = &fp->fd_nested; lnum_off += fp->fd_top; ++level; } if (lnum_found != curwin->w_cursor.lnum) { - if (retval == FAIL) + if (retval == FAIL) { setpcmark(); + } curwin->w_cursor.lnum = lnum_found; curwin->w_cursor.col = 0; retval = OK; - } else + } else { break; + } } return retval; } -/* foldInitWin() {{{2 */ +// foldInitWin() {{{2 /* * Init the fold info in a new window. */ @@ -994,7 +1005,7 @@ void foldInitWin(win_T *new_win) ga_init(&new_win->w_folds, (int)sizeof(fold_T), 10); } -/* find_wl_entry() {{{2 */ +// find_wl_entry() {{{2 /* * Find an entry in the win->w_lines[] array for buffer line "lnum". * Only valid entries are considered (for entries where wl_valid is FALSE the @@ -1005,27 +1016,31 @@ int find_wl_entry(win_T *win, linenr_T lnum) { int i; - for (i = 0; i < win->w_lines_valid; ++i) + for (i = 0; i < win->w_lines_valid; ++i) { if (win->w_lines[i].wl_valid) { - if (lnum < win->w_lines[i].wl_lnum) + if (lnum < win->w_lines[i].wl_lnum) { return -1; - if (lnum <= win->w_lines[i].wl_lastlnum) + } + if (lnum <= win->w_lines[i].wl_lastlnum) { return i; + } } + } return -1; } -/* foldAdjustVisual() {{{2 */ +// foldAdjustVisual() {{{2 /* * Adjust the Visual area to include any fold at the start or end completely. */ void foldAdjustVisual(void) { - pos_T *start, *end; - char_u *ptr; + pos_T *start, *end; + char_u *ptr; - if (!VIsual_active || !hasAnyFolding(curwin)) + if (!VIsual_active || !hasAnyFolding(curwin)) { return; + } if (ltoreq(VIsual, curwin->w_cursor)) { start = &VIsual; @@ -1034,8 +1049,9 @@ void foldAdjustVisual(void) start = &curwin->w_cursor; end = &VIsual; } - if (hasFolding(start->lnum, &start->lnum, NULL)) + if (hasFolding(start->lnum, &start->lnum, NULL)) { start->col = 0; + } if (hasFolding(end->lnum, NULL, &end->lnum)) { ptr = ml_get(end->lnum); end->col = (colnr_T)STRLEN(ptr); @@ -1047,7 +1063,7 @@ void foldAdjustVisual(void) } } -/* cursor_foldstart() {{{2 */ +// cursor_foldstart() {{{2 /* * Move the cursor to the first line of a closed fold. */ @@ -1056,20 +1072,21 @@ void foldAdjustCursor(void) (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); } -/* Internal functions for "fold_T" {{{1 */ -/* cloneFoldGrowArray() {{{2 */ +// Internal functions for "fold_T" {{{1 +// cloneFoldGrowArray() {{{2 /* * Will "clone" (i.e deep copy) a garray_T of folds. */ void cloneFoldGrowArray(garray_T *from, garray_T *to) { - fold_T *from_p; - fold_T *to_p; + fold_T *from_p; + fold_T *to_p; ga_init(to, from->ga_itemsize, from->ga_growsize); - if (GA_EMPTY(from)) + if (GA_EMPTY(from)) { return; + } ga_grow(to, from->ga_len); @@ -1088,7 +1105,7 @@ void cloneFoldGrowArray(garray_T *from, garray_T *to) } } -/* foldFind() {{{2 */ +// foldFind() {{{2 /* * Search for line "lnum" in folds of growarray "gap". * Set *fpp to the fold struct for the fold that contains "lnum" or @@ -1098,7 +1115,7 @@ void cloneFoldGrowArray(garray_T *from, garray_T *to) static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp) { linenr_T low, high; - fold_T *fp; + fold_T *fp; if (gap->ga_len == 0) { *fpp = NULL; @@ -1115,14 +1132,14 @@ static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp) high = gap->ga_len - 1; while (low <= high) { linenr_T i = (low + high) / 2; - if (fp[i].fd_top > lnum) - /* fold below lnum, adjust high */ + if (fp[i].fd_top > lnum) { + // fold below lnum, adjust high high = i - 1; - else if (fp[i].fd_top + fp[i].fd_len <= lnum) - /* fold above lnum, adjust low */ + } else if (fp[i].fd_top + fp[i].fd_len <= lnum) { + // fold above lnum, adjust low low = i + 1; - else { - /* lnum is inside this fold */ + } else { + // lnum is inside this fold *fpp = fp + i; return TRUE; } @@ -1131,23 +1148,24 @@ static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp) return false; } -/* foldLevelWin() {{{2 */ +// foldLevelWin() {{{2 /* * Return fold level at line number "lnum" in window "wp". */ static int foldLevelWin(win_T *wp, linenr_T lnum) { - fold_T *fp; + fold_T *fp; linenr_T lnum_rel = lnum; int level = 0; - garray_T *gap; + garray_T *gap; - /* Recursively search for a fold that contains "lnum". */ + // Recursively search for a fold that contains "lnum". gap = &wp->w_folds; for (;; ) { - if (!foldFind(gap, lnum_rel, &fp)) + if (!foldFind(gap, lnum_rel, &fp)) { break; - /* Check nested folds. Line number is relative to containing fold. */ + } + // Check nested folds. Line number is relative to containing fold. gap = &fp->fd_nested; lnum_rel -= fp->fd_top; ++level; @@ -1156,19 +1174,19 @@ static int foldLevelWin(win_T *wp, linenr_T lnum) return level; } -/* checkupdate() {{{2 */ +// checkupdate() {{{2 /* * Check if the folds in window "wp" are invalid and update them if needed. */ static void checkupdate(win_T *wp) { if (wp->w_foldinvalid) { - foldUpdate(wp, (linenr_T)1, (linenr_T)MAXLNUM); /* will update all */ + foldUpdate(wp, (linenr_T)1, (linenr_T)MAXLNUM); // will update all wp->w_foldinvalid = false; } } -/* setFoldRepeat() {{{2 */ +// setFoldRepeat() {{{2 /* * Open or close fold for current window at line "lnum". * Repeat "count" times. @@ -1182,26 +1200,23 @@ static void setFoldRepeat(pos_T pos, long count, int do_open) done = DONE_NOTHING; (void)setManualFold(pos, do_open, false, &done); if (!(done & DONE_ACTION)) { - /* Only give an error message when no fold could be opened. */ - if (n == 0 && !(done & DONE_FOLD)) + // Only give an error message when no fold could be opened. + if (n == 0 && !(done & DONE_FOLD)) { EMSG(_(e_nofold)); + } break; } } } -/* setManualFold() {{{2 */ -/* - * Open or close the fold in the current window which contains "lnum". - * Also does this for other windows in diff mode when needed. - */ -static linenr_T -setManualFold( - pos_T pos, - int opening, // TRUE when opening, FALSE when closing - int recurse, // TRUE when closing/opening recursive - int *donep -) +// setManualFold() {{{2 +/// +/// Open or close the fold in the current window which contains "lnum". +/// Also does this for other windows in diff mode when needed. +/// +/// @param opening TRUE when opening, FALSE when closing +/// @param recurse TRUE when closing/opening recursive +static linenr_T setManualFold(pos_T pos, int opening, int recurse, int *donep) { linenr_T lnum = pos.lnum; if (foldmethodIsDiff(curwin) && curwin->w_p_scb) { @@ -1224,33 +1239,28 @@ setManualFold( return setManualFoldWin(curwin, lnum, opening, recurse, donep); } -/* setManualFoldWin() {{{2 */ -/* - * Open or close the fold in window "wp" which contains "lnum". - * "donep", when not NULL, points to flag that is set to DONE_FOLD when some - * fold was found and to DONE_ACTION when some fold was opened or closed. - * When "donep" is NULL give an error message when no fold was found for - * "lnum", but only if "wp" is "curwin". - * Return the line number of the next line that could be closed. - * It's only valid when "opening" is TRUE! - */ -static linenr_T -setManualFoldWin( - win_T *wp, - linenr_T lnum, - int opening, // TRUE when opening, FALSE when closing - int recurse, // TRUE when closing/opening recursive - int *donep -) -{ - fold_T *fp; - fold_T *fp2; - fold_T *found = NULL; +// setManualFoldWin() {{{2 +/// Open or close the fold in window "wp" which contains "lnum". +/// "donep", when not NULL, points to flag that is set to DONE_FOLD when some +/// fold was found and to DONE_ACTION when some fold was opened or closed. +/// When "donep" is NULL give an error message when no fold was found for +/// "lnum", but only if "wp" is "curwin". +/// +/// @param opening TRUE when opening, FALSE when closing +/// @param recurse TRUE when closing/opening recursive +/// +/// @return the line number of the next line that could be closed. +/// It's only valid when "opening" is TRUE! +static linenr_T setManualFoldWin(win_T *wp, linenr_T lnum, int opening, int recurse, int *donep) +{ + fold_T *fp; + fold_T *fp2; + fold_T *found = NULL; int j; int level = 0; int use_level = FALSE; int found_fold = FALSE; - garray_T *gap; + garray_T *gap; linenr_T next = MAXLNUM; linenr_T off = 0; int done = 0; @@ -1270,43 +1280,47 @@ setManualFoldWin( break; } - /* lnum is inside this fold */ + // lnum is inside this fold found_fold = TRUE; - /* If there is a following fold, continue there next time. */ - if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len) + // If there is a following fold, continue there next time. + if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len) { next = fp[1].fd_top + off; + } - /* Change from level-dependent folding to manual. */ + // Change from level-dependent folding to manual. if (use_level || fp->fd_flags == FD_LEVEL) { use_level = TRUE; - if (level >= wp->w_p_fdl) + if (level >= wp->w_p_fdl) { fp->fd_flags = FD_CLOSED; - else + } else { fp->fd_flags = FD_OPEN; + } fp2 = (fold_T *)fp->fd_nested.ga_data; - for (j = 0; j < fp->fd_nested.ga_len; ++j) + for (j = 0; j < fp->fd_nested.ga_len; ++j) { fp2[j].fd_flags = FD_LEVEL; + } } - /* Simple case: Close recursively means closing the fold. */ + // Simple case: Close recursively means closing the fold. if (!opening && recurse) { if (fp->fd_flags != FD_CLOSED) { done |= DONE_ACTION; fp->fd_flags = FD_CLOSED; } } else if (fp->fd_flags == FD_CLOSED) { - /* When opening, open topmost closed fold. */ + // When opening, open topmost closed fold. if (opening) { fp->fd_flags = FD_OPEN; done |= DONE_ACTION; - if (recurse) + if (recurse) { foldOpenNested(fp); + } } break; } - /* fold is open, check nested folds */ + // fold is open, check nested folds found = fp; gap = &fp->fd_nested; lnum -= fp->fd_top; @@ -1314,31 +1328,34 @@ setManualFoldWin( ++level; } if (found_fold) { - /* When closing and not recurse, close deepest open fold. */ + // When closing and not recurse, close deepest open fold. if (!opening && found != NULL) { found->fd_flags = FD_CLOSED; done |= DONE_ACTION; } wp->w_fold_manual = true; - if (done & DONE_ACTION) + if (done & DONE_ACTION) { changed_window_setting_win(wp); + } done |= DONE_FOLD; - } else if (donep == NULL && wp == curwin) + } else if (donep == NULL && wp == curwin) { EMSG(_(e_nofold)); + } - if (donep != NULL) + if (donep != NULL) { *donep |= done; + } return next; } -/* foldOpenNested() {{{2 */ +// foldOpenNested() {{{2 /* * Open all nested folds in fold "fpr" recursively. */ static void foldOpenNested(fold_T *fpr) { - fold_T *fp; + fold_T *fp; fp = (fold_T *)fpr->fd_nested.ga_data; for (int i = 0; i < fpr->fd_nested.ga_len; ++i) { @@ -1368,15 +1385,16 @@ static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx, int moved = fp->fd_nested.ga_len; ga_grow(gap, moved - 1); { - /* Get "fp" again, the array may have been reallocated. */ + // Get "fp" again, the array may have been reallocated. fp = (fold_T *)gap->ga_data + idx; // adjust fd_top and fd_flags for the moved folds fold_T *nfp = (fold_T *)fp->fd_nested.ga_data; for (int i = 0; i < moved; i++) { nfp[i].fd_top += fp->fd_top; - if (fp->fd_flags == FD_LEVEL) + if (fp->fd_flags == FD_LEVEL) { nfp[i].fd_flags = FD_LEVEL; + } if (fp->fd_small == kNone) { nfp[i].fd_small = kNone; } @@ -1395,7 +1413,7 @@ static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx, } } -/* deleteFoldRecurse() {{{2 */ +// deleteFoldRecurse() {{{2 /* * Delete nested folds in a fold. */ @@ -1405,7 +1423,7 @@ void deleteFoldRecurse(buf_T *bp, garray_T *gap) GA_DEEP_CLEAR(gap, fold_T, DELETE_FOLD_NESTED); } -/* foldMarkAdjust() {{{2 */ +// foldMarkAdjust() {{{2 /* * Update line numbers of folds for inserted/deleted lines. */ @@ -1413,8 +1431,9 @@ void foldMarkAdjust(win_T *wp, linenr_T line1, linenr_T line2, long amount, long { /* If deleting marks from line1 to line2, but not deleting all those * lines, set line2 so that only deleted lines have their folds removed. */ - if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after) + if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after) { line2 = line1 - amount_after - 1; + } /* If appending a line in Insert mode, it should be included in the fold * just above the line. */ if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM) { @@ -1424,12 +1443,10 @@ void foldMarkAdjust(win_T *wp, linenr_T line1, linenr_T line2, long amount, long } // foldMarkAdjustRecurse() {{{2 -static void foldMarkAdjustRecurse( - win_T *wp, garray_T *gap, - linenr_T line1, linenr_T line2, long amount, long amount_after -) +static void foldMarkAdjustRecurse(win_T *wp, garray_T *gap, linenr_T line1, linenr_T line2, + long amount, long amount_after) { - fold_T *fp; + fold_T *fp; linenr_T last; linenr_T top; @@ -1439,12 +1456,13 @@ static void foldMarkAdjustRecurse( /* In Insert mode an inserted line at the top of a fold is considered part * of the fold, otherwise it isn't. */ - if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM) + if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM) { top = line1 + 1; - else + } else { top = line1; + } - /* Find the fold containing or just below "line1". */ + // Find the fold containing or just below "line1". (void)foldFind(gap, line1, &fp); /* @@ -1453,26 +1471,28 @@ static void foldMarkAdjustRecurse( for (int i = (int)(fp - (fold_T *)gap->ga_data); i < gap->ga_len; ++i, ++fp) { /* * Check for these situations: - * 1 2 3 - * 1 2 3 - * line1 2 3 4 5 - * 2 3 4 5 - * 2 3 4 5 - * line2 2 3 4 5 - * 3 5 6 - * 3 5 6 + * 1 2 3 + * 1 2 3 + * line1 2 3 4 5 + * 2 3 4 5 + * 2 3 4 5 + * line2 2 3 4 5 + * 3 5 6 + * 3 5 6 */ - last = fp->fd_top + fp->fd_len - 1; /* last line of fold */ + last = fp->fd_top + fp->fd_len - 1; // last line of fold - /* 1. fold completely above line1: nothing to do */ - if (last < line1) + // 1. fold completely above line1: nothing to do + if (last < line1) { continue; + } - /* 6. fold below line2: only adjust for amount_after */ + // 6. fold below line2: only adjust for amount_after if (fp->fd_top > line2) { - if (amount_after == 0) + if (amount_after == 0) { break; + } fp->fd_top += amount_after; } else { if (fp->fd_top >= top && last <= line2) { @@ -1491,13 +1511,14 @@ static void foldMarkAdjustRecurse( foldMarkAdjustRecurse(wp, &fp->fd_nested, line1 - fp->fd_top, line2 - fp->fd_top, amount, amount_after); if (last <= line2) { - /* 2. fold contains line1, line2 is below fold */ - if (amount == MAXLNUM) + // 2. fold contains line1, line2 is below fold + if (amount == MAXLNUM) { fp->fd_len = line1 - fp->fd_top; - else + } else { fp->fd_len += amount; + } } else { - /* 3. fold contains line1 and line2 */ + // 3. fold contains line1 and line2 fp->fd_len += amount_after; } } else { @@ -1522,7 +1543,7 @@ static void foldMarkAdjustRecurse( } } -/* getDeepestNesting() {{{2 */ +// getDeepestNesting() {{{2 /* * Get the lowest 'foldlevel' value that makes the deepest nested fold in the * current window open. @@ -1537,13 +1558,14 @@ static int getDeepestNestingRecurse(garray_T *gap) { int level; int maxlevel = 0; - fold_T *fp; + fold_T *fp; fp = (fold_T *)gap->ga_data; for (int i = 0; i < gap->ga_len; ++i) { level = getDeepestNestingRecurse(&fp[i].fd_nested) + 1; - if (level > maxlevel) + if (level > maxlevel) { maxlevel = level; + } } return maxlevel; @@ -1558,14 +1580,8 @@ static int getDeepestNestingRecurse(garray_T *gap) /// @param[out] maybe_smallp true: outer this had fd_small == kNone /// @param lnum_off line number offset for fp->fd_top /// @return true if fold is closed -static bool check_closed( - win_T *const wp, - fold_T *const fp, - bool *const use_levelp, - const int level, - bool *const maybe_smallp, - const linenr_T lnum_off -) +static bool check_closed(win_T *const wp, fold_T *const fp, bool *const use_levelp, const int level, + bool *const maybe_smallp, const linenr_T lnum_off) { bool closed = false; @@ -1598,13 +1614,9 @@ static bool check_closed( // checkSmall() {{{2 /// Update fd_small field of fold "fp". -/// @param lnum_off offset for fp->fd_top -static void -checkSmall( - win_T *const wp, - fold_T *const fp, - const linenr_T lnum_off // offset for fp->fd_top -) +/// +/// @param lnum_off offset for fp->fd_top +static void checkSmall(win_T *const wp, fold_T *const fp, const linenr_T lnum_off) { if (fp->fd_small == kNone) { // Mark any nested folds to maybe-small @@ -1636,7 +1648,7 @@ static void setSmallMaybe(garray_T *gap) } } -/* foldCreateMarkers() {{{2 */ +// foldCreateMarkers() {{{2 /* * Create a fold from line "start" to line "end" (inclusive) in the current * window by adding markers. @@ -1665,17 +1677,16 @@ static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end) buf_updates_send_changes(buf, start.lnum, num_changed, num_changed, true); } -/* foldAddMarker() {{{2 */ +// foldAddMarker() {{{2 /* * Add "marker[markerlen]" in 'commentstring' to line "lnum". */ -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_u *marker, size_t markerlen) { - char_u *cms = buf->b_p_cms; - char_u *line; - char_u *newline; - char_u *p = (char_u *)strstr((char *)buf->b_p_cms, "%s"); + char_u *cms = buf->b_p_cms; + char_u *line; + char_u *newline; + char_u *p = (char_u *)strstr((char *)buf->b_p_cms, "%s"); bool line_is_comment = false; linenr_T lnum = pos.lnum; @@ -1707,17 +1718,11 @@ static void foldAddMarker( } } -/* deleteFoldMarkers() {{{2 */ -/* - * Delete the markers for a fold, causing it to be deleted. - */ -static void -deleteFoldMarkers( - win_T *wp, - fold_T *fp, - int recursive, - linenr_T lnum_off // offset for fp->fd_top -) +// deleteFoldMarkers() {{{2 +/// Delete the markers for a fold, causing it to be deleted. +/// +/// @param lnum_off offset for fp->fd_top +static void deleteFoldMarkers(win_T *wp, fold_T *fp, int recursive, linenr_T lnum_off) { if (recursive) { for (int i = 0; i < fp->fd_nested.ga_len; i++) { @@ -1737,13 +1742,11 @@ deleteFoldMarkers( // 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_u *marker, size_t markerlen) { - char_u *newline; - char_u *cms = buf->b_p_cms; - char_u *cms2; + char_u *newline; + char_u *cms = buf->b_p_cms; + char_u *cms2; // end marker may be missing and fold extends below the last line if (lnum > buf->b_ml.ml_line_count) { @@ -1754,12 +1757,13 @@ static void foldDelMarker( if (STRNCMP(p, marker, markerlen) != 0) { continue; } - /* Found the marker, include a digit if it's there. */ + // Found the marker, include a digit if it's there. size_t len = markerlen; - if (ascii_isdigit(p[len])) + if (ascii_isdigit(p[len])) { ++len; + } if (*cms != NUL) { - /* Also delete 'commentstring' if it matches. */ + // Also delete 'commentstring' if it matches. cms2 = (char_u *)strstr((char *)cms, "%s"); if (p - line >= cms2 - cms && STRNCMP(p - (cms2 - cms), cms, cms2 - cms) == 0 @@ -1769,7 +1773,7 @@ static void foldDelMarker( } } if (u_save(lnum - 1, lnum + 1) == OK) { - /* Make new line: text-before-marker + text-after-marker */ + // Make new line: text-before-marker + text-after-marker newline = xmalloc(STRLEN(line) - len + 1); assert(p >= line); memcpy(newline, line, (size_t)(p - line)); @@ -1791,34 +1795,35 @@ static void foldDelMarker( /// @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_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldinfo, char_u *buf) FUNC_ATTR_NONNULL_ARG(1) { - char_u *text = NULL; - /* an error occurred when evaluating 'fdt' setting */ + char_u *text = NULL; + // an error occurred when evaluating 'fdt' setting static int got_fdt_error = FALSE; int save_did_emsg = did_emsg; - static win_T *last_wp = NULL; + static win_T *last_wp = NULL; static linenr_T last_lnum = 0; - if (last_wp == NULL || last_wp != wp || last_lnum > lnum || last_lnum == 0) - /* window changed, try evaluating foldtext setting once again */ + if (last_wp == NULL || last_wp != wp || last_lnum > lnum || last_lnum == 0) { + // window changed, try evaluating foldtext setting once again got_fdt_error = FALSE; + } - if (!got_fdt_error) - /* a previous error should not abort evaluating 'foldexpr' */ + if (!got_fdt_error) { + // a previous error should not abort evaluating 'foldexpr' did_emsg = FALSE; + } if (*wp->w_p_fdt != NUL) { char dashes[MAX_LEVEL + 2]; - win_T *save_curwin; + win_T *save_curwin; int level; - char_u *p; + char_u *p; // Set "v:foldstart" and "v:foldend". - set_vim_var_nr(VV_FOLDSTART, (varnumber_T) lnum); - set_vim_var_nr(VV_FOLDEND, (varnumber_T) lnume); + set_vim_var_nr(VV_FOLDSTART, (varnumber_T)lnum); + set_vim_var_nr(VV_FOLDEND, (varnumber_T)lnume); // Set "v:folddashes" to a string of "level" dashes. // Set "v:foldlevel" to "level". @@ -1829,22 +1834,22 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, memset(dashes, '-', (size_t)level); dashes[level] = NUL; set_vim_var_string(VV_FOLDDASHES, dashes, -1); - set_vim_var_nr(VV_FOLDLEVEL, (varnumber_T) level); + set_vim_var_nr(VV_FOLDLEVEL, (varnumber_T)level); - /* skip evaluating foldtext on errors */ + // skip evaluating foldtext on errors if (!got_fdt_error) { save_curwin = curwin; curwin = wp; curbuf = wp->w_buffer; emsg_silent++; // handle exceptions, but don't display errors - text = eval_to_string_safe( - wp->w_p_fdt, NULL, - was_set_insecurely(wp, (char_u *)"foldtext", OPT_LOCAL)); + text = eval_to_string_safe(wp->w_p_fdt, NULL, + was_set_insecurely(wp, (char_u *)"foldtext", OPT_LOCAL)); emsg_silent--; - if (text == NULL || did_emsg) + if (text == NULL || did_emsg) { got_fdt_error = TRUE; + } curwin = save_curwin; curbuf = curwin->w_buffer; @@ -1853,8 +1858,9 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, last_wp = wp; set_vim_var_string(VV_FOLDDASHES, NULL, -1); - if (!did_emsg && save_did_emsg) + if (!did_emsg && save_did_emsg) { did_emsg = save_did_emsg; + } if (text != NULL) { /* Replace unprintable characters, if there are any. But @@ -1867,10 +1873,11 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, break; } p += len - 1; - } else if (*p == TAB) + } else if (*p == TAB) { *p = ' '; - else if (ptr2cells(p) > 1) + } else if (ptr2cells(p) > 1) { break; + } } if (*p != NUL) { p = (char_u *)transstr((const char *)text); @@ -1891,35 +1898,37 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, return text; } -/* foldtext_cleanup() {{{2 */ +// foldtext_cleanup() {{{2 /* * Remove 'foldmarker' and 'commentstring' from "str" (in-place). */ void foldtext_cleanup(char_u *str) { - char_u *s; - char_u *p; + char_u *s; + char_u *p; int did1 = FALSE; int did2 = FALSE; - /* Ignore leading and trailing white space in 'commentstring'. */ + // Ignore leading and trailing white space in 'commentstring'. char_u *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])) + while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) { --cms_slen; + } - /* locate "%s" in 'commentstring', use the part before and after it. */ + // locate "%s" in 'commentstring', use the part before and after it. char_u *cms_end = (char_u *)strstr((char *)cms_start, "%s"); size_t cms_elen = 0; if (cms_end != NULL) { cms_elen = cms_slen - (size_t)(cms_end - cms_start); cms_slen = (size_t)(cms_end - cms_start); - /* exclude white space before "%s" */ - while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) + // exclude white space before "%s" + while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) { --cms_slen; + } - /* skip "%s" and white space after it */ + // skip "%s" and white space after it s = skipwhite(cms_end + 2); cms_elen -= (size_t)(s - cms_end); cms_end = s; @@ -1928,18 +1937,21 @@ void foldtext_cleanup(char_u *str) for (s = str; *s != NUL; ) { size_t len = 0; - if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0) + if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0) { len = foldstartmarkerlen; - else if (STRNCMP(s, foldendmarker, foldendmarkerlen) == 0) + } else if (STRNCMP(s, foldendmarker, foldendmarkerlen) == 0) { len = foldendmarkerlen; + } if (len > 0) { - if (ascii_isdigit(s[len])) + if (ascii_isdigit(s[len])) { ++len; + } /* May remove 'commentstring' start. Useful when it's a double * quote and we already removed a double quote. */ - for (p = s; p > str && ascii_iswhite(p[-1]); --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) { len += (size_t)(s - p) + cms_slen; @@ -1956,8 +1968,9 @@ void foldtext_cleanup(char_u *str) } } if (len != 0) { - while (ascii_iswhite(s[len])) + while (ascii_iswhite(s[len])) { ++len; + } STRMOVE(s, s + len); } else { MB_PTR_ADV(s); @@ -1965,10 +1978,10 @@ void foldtext_cleanup(char_u *str) } } -/* Folding by indent, expr, marker and syntax. {{{1 */ -/* Function declarations. {{{2 */ +// Folding by indent, expr, marker and syntax. {{{1 +// Function declarations. {{{2 -/* foldUpdateIEMS() {{{2 */ +// foldUpdateIEMS() {{{2 /* * Update the folding for window "wp", at least from lines "top" to "bot". * IEMS = "Indent Expr Marker Syntax" @@ -1977,28 +1990,30 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) { fline_T fline; LevelGetter getlevel = NULL; - fold_T *fp; + fold_T *fp; - /* Avoid problems when being called recursively. */ - if (invalid_top != (linenr_T)0) + // Avoid problems when being called recursively. + if (invalid_top != (linenr_T)0) { return; + } if (wp->w_foldinvalid) { - /* Need to update all folds. */ + // Need to update all folds. top = 1; bot = wp->w_buffer->b_ml.ml_line_count; wp->w_foldinvalid = false; - /* Mark all folds a maybe-small. */ + // Mark all folds a maybe-small. setSmallMaybe(&wp->w_folds); } - /* add the context for "diff" folding */ + // add the context for "diff" folding if (foldmethodIsDiff(wp)) { - if (top > diff_context) + if (top > diff_context) { top -= diff_context; - else + } else { top = 1; + } bot += diff_context; } @@ -2023,7 +2038,7 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) if (foldmethodIsMarker(wp)) { getlevel = foldlevelMarker; - /* Init marker variables to speed up foldlevelMarker(). */ + // Init marker variables to speed up foldlevelMarker(). parseMarker(wp); /* Need to get the level of the line above top, it is used if there is @@ -2032,7 +2047,7 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) // Get the fold level at top - 1. const int level = foldLevelWin(wp, top - 1); - /* The fold may end just above the top, check for that. */ + // The fold may end just above the top, check for that. fline.lnum = top - 1; fline.lvl = level; getlevel(&fline); @@ -2040,10 +2055,11 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) /* If a fold started here, we already had the level, if it stops * here, we need to use lvl_next. Could also start and end a fold * in the same line. */ - if (fline.lvl > level) + if (fline.lvl > level) { fline.lvl = level - (fline.lvl - fline.lvl_next); - else + } else { fline.lvl = fline.lvl_next; + } } fline.lnum = top; getlevel(&fline); @@ -2053,14 +2069,16 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) getlevel = foldlevelExpr; /* start one line back, because a "<1" may indicate the end of a * fold in the topline */ - if (top > 1) + if (top > 1) { --fline.lnum; - } else if (foldmethodIsSyntax(wp)) + } + } else if (foldmethodIsSyntax(wp)) { getlevel = foldlevelSyntax; - else if (foldmethodIsDiff(wp)) + } else if (foldmethodIsDiff(wp)) { getlevel = foldlevelDiff; - else + } else { getlevel = foldlevelIndent; + } /* Backup to a line for which the fold level is defined. Since it's * always defined for line one, we will stop there. */ @@ -2070,8 +2088,9 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) * the next line, but we search backwards here. */ fline.lvl_next = -1; getlevel(&fline); - if (fline.lvl >= 0) + if (fline.lvl >= 0) { break; + } } } @@ -2084,14 +2103,15 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) */ if (foldlevelSyntax == getlevel) { garray_T *gap = &wp->w_folds; - fold_T *fpn = NULL; + fold_T *fpn = NULL; int current_fdl = 0; linenr_T fold_start_lnum = 0; linenr_T lnum_rel = fline.lnum; while (current_fdl < fline.lvl) { - if (!foldFind(gap, lnum_rel, &fpn)) + if (!foldFind(gap, lnum_rel, &fpn)) { break; + } ++current_fdl; fold_start_lnum += fpn->fd_top; @@ -2101,8 +2121,9 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) if (fpn != NULL && current_fdl == fline.lvl) { linenr_T fold_end_lnum = fold_start_lnum + fpn->fd_len; - if (fold_end_lnum > bot) + if (fold_end_lnum > bot) { bot = fold_end_lnum; + } } } @@ -2115,34 +2136,37 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) while (!got_int) { /* Always stop at the end of the file ("end" can be past the end of * the file). */ - if (fline.lnum > wp->w_buffer->b_ml.ml_line_count) + if (fline.lnum > wp->w_buffer->b_ml.ml_line_count) { break; + } if (fline.lnum > end) { /* For "marker", "expr" and "syntax" methods: If a change caused * a fold to be removed, we need to continue at least until where * it ended. */ if (getlevel != foldlevelMarker && getlevel != foldlevelSyntax - && getlevel != foldlevelExpr) + && getlevel != foldlevelExpr) { break; + } if ((start <= end && foldFind(&wp->w_folds, end, &fp) && fp->fd_top + fp->fd_len - 1 > end) || (fline.lvl == 0 && foldFind(&wp->w_folds, fline.lnum, &fp) - && fp->fd_top < fline.lnum)) + && fp->fd_top < fline.lnum)) { end = fp->fd_top + fp->fd_len - 1; - else if (getlevel == foldlevelSyntax - && foldLevelWin(wp, fline.lnum) != fline.lvl) + } else if (getlevel == foldlevelSyntax + && foldLevelWin(wp, fline.lnum) != fline.lvl) { /* For "syntax" method: Compare the foldlevel that the syntax * tells us to the foldlevel from the existing folds. If they * don't match continue updating folds. */ end = fline.lnum; - else + } else { break; + } } - /* A level 1 fold starts at a line with foldlevel > 0. */ + // A level 1 fold starts at a line with foldlevel > 0. if (fline.lvl > 0) { invalid_top = fline.lnum; invalid_bot = end; @@ -2150,8 +2174,9 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) FD_LEVEL); start = fline.lnum; } else { - if (fline.lnum == wp->w_buffer->b_ml.ml_line_count) + if (fline.lnum == wp->w_buffer->b_ml.ml_line_count) { break; + } ++fline.lnum; fline.lvl = fline.lvl_next; getlevel(&fline); @@ -2161,56 +2186,58 @@ static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot) // There can't be any folds from start until end now. foldRemove(wp, &wp->w_folds, start, end); - /* If some fold changed, need to redraw and position cursor. */ - if (fold_changed && wp->w_p_fen) + // If some fold changed, need to redraw and position cursor. + if (fold_changed && wp->w_p_fen) { changed_window_setting_win(wp); + } /* If we updated folds past "bot", need to redraw more lines. Don't do * this in other situations, the changed lines will be redrawn anyway and * this method can cause the whole window to be updated. */ if (end != bot) { - if (wp->w_redraw_top == 0 || wp->w_redraw_top > top) + if (wp->w_redraw_top == 0 || wp->w_redraw_top > top) { wp->w_redraw_top = top; - if (wp->w_redraw_bot < end) + } + if (wp->w_redraw_bot < end) { wp->w_redraw_bot = end; + } } invalid_top = (linenr_T)0; } -/* foldUpdateIEMSRecurse() {{{2 */ -/* - * Update a fold that starts at "flp->lnum". At this line there is always a - * valid foldlevel, and its level >= "level". - * "flp" is valid for "flp->lnum" when called and it's valid when returning. - * "flp->lnum" is set to the lnum just below the fold, if it ends before - * "bot", it's "bot" plus one if the fold continues and it's bigger when using - * the marker method and a text change made following folds to change. - * When returning, "flp->lnum_save" is the line number that was used to get - * the level when the level at "flp->lnum" is invalid. - * Remove any folds from "startlnum" up to here at this level. - * Recursively update nested folds. - * Below line "bot" there are no changes in the text. - * "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the - * outer fold. - * "flp->off" is the offset to the real line number in the buffer. - * - * All this would be a lot simpler if all folds in the range would be deleted - * and then created again. But we would lose all information about the - * folds, even when making changes that don't affect the folding (e.g. "vj~"). - * - * Returns bot, which may have been increased for lines that also need to be - * updated as a result of a detected change in the fold. - */ -static linenr_T foldUpdateIEMSRecurse( - garray_T *const gap, const int level, const linenr_T startlnum, - fline_T *const flp, LevelGetter getlevel, linenr_T bot, - const char topflags // containing fold flags -) +// foldUpdateIEMSRecurse() {{{2 +/// Update a fold that starts at "flp->lnum". At this line there is always a +/// valid foldlevel, and its level >= "level". +/// +/// "flp" is valid for "flp->lnum" when called and it's valid when returning. +/// "flp->lnum" is set to the lnum just below the fold, if it ends before +/// "bot", it's "bot" plus one if the fold continues and it's bigger when using +/// the marker method and a text change made following folds to change. +/// When returning, "flp->lnum_save" is the line number that was used to get +/// the level when the level at "flp->lnum" is invalid. +/// Remove any folds from "startlnum" up to here at this level. +/// Recursively update nested folds. +/// Below line "bot" there are no changes in the text. +/// "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the +/// outer fold. +/// "flp->off" is the offset to the real line number in the buffer. +/// +/// All this would be a lot simpler if all folds in the range would be deleted +/// and then created again. But we would lose all information about the +/// folds, even when making changes that don't affect the folding (e.g. "vj~"). +/// +/// @param topflags containing fold flags +/// +/// @return bot, which may have been increased for lines that also need to be +/// updated as a result of a detected change in the fold. +static linenr_T foldUpdateIEMSRecurse(garray_T *const gap, const int level, + const linenr_T startlnum, fline_T *const flp, + LevelGetter getlevel, linenr_T bot, const char topflags) { linenr_T ll; - fold_T *fp = NULL; - fold_T *fp2; + fold_T *fp = NULL; + fold_T *fp2; int lvl = level; linenr_T startlnum2 = startlnum; const linenr_T firstlnum = flp->lnum; // first lnum we got @@ -2248,7 +2275,7 @@ static linenr_T foldUpdateIEMSRecurse( */ flp->lnum_save = flp->lnum; while (!got_int) { - /* Updating folds can be slow, check for CTRL-C. */ + // Updating folds can be slow, check for CTRL-C. line_breakcheck(); /* Set "lvl" to the level of line "flp->lnum". When flp->start is set @@ -2256,11 +2283,13 @@ static linenr_T foldUpdateIEMSRecurse( * force the fold to end. Do the same when had_end is set: Previous * line was marked as end of a fold. */ lvl = flp->lvl; - if (lvl > MAX_LEVEL) + if (lvl > MAX_LEVEL) { lvl = MAX_LEVEL; + } if (flp->lnum > firstlnum - && (level > lvl - flp->start || level >= flp->had_end)) + && (level > lvl - flp->start || level >= flp->had_end)) { lvl = 0; + } if (flp->lnum > bot && !finish && fp != NULL) { /* For "marker" and "syntax" methods: @@ -2271,8 +2300,9 @@ static linenr_T foldUpdateIEMSRecurse( */ if (getlevel != foldlevelMarker && getlevel != foldlevelExpr - && getlevel != foldlevelSyntax) + && getlevel != foldlevelSyntax) { break; + } i = 0; fp2 = fp; if (lvl >= level) { @@ -2313,10 +2343,11 @@ static linenr_T foldUpdateIEMSRecurse( while (!got_int) { /* set concat to 1 if it's allowed to concatenated this fold * with a previous one that touches it. */ - if (flp->start != 0 || flp->had_end <= MAX_LEVEL) + if (flp->start != 0 || flp->had_end <= MAX_LEVEL) { concat = 0; - else + } else { concat = 1; + } /* Find an existing fold to re-use. Preferably one that * includes startlnum, otherwise one that ends just before @@ -2439,10 +2470,12 @@ static linenr_T foldUpdateIEMSRecurse( fp->fd_flags = FD_OPEN; } else if (i <= 0) { fp->fd_flags = topflags; - if (topflags != FD_LEVEL) + if (topflags != FD_LEVEL) { flp->wp->w_fold_manual = true; - } else + } + } else { fp->fd_flags = (fp - 1)->fd_flags; + } fp->fd_small = kNone; // If using the "marker", "expr" or "syntax" method, we // need to continue until the end of the fold is found. @@ -2491,7 +2524,7 @@ static linenr_T foldUpdateIEMSRecurse( bot += fp->fd_top; startlnum2 = flp->lnum; - /* This fold may end at the same line, don't incr. flp->lnum. */ + // This fold may end at the same line, don't incr. flp->lnum. } else { /* * Get the level of the next line, then continue the loop to check @@ -2502,20 +2535,23 @@ static linenr_T foldUpdateIEMSRecurse( flp->lnum = flp->lnum_save; ll = flp->lnum + 1; while (!got_int) { - /* Make the previous level available to foldlevel(). */ + // Make the previous level available to foldlevel(). prev_lnum = flp->lnum; prev_lnum_lvl = flp->lvl; - if (++flp->lnum > linecount) + if (++flp->lnum > linecount) { break; + } flp->lvl = flp->lvl_next; getlevel(flp); - if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL) + if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL) { break; + } } prev_lnum = 0; - if (flp->lnum > linecount) + if (flp->lnum > linecount) { break; + } /* leave flp->lnum_save to lnum of the line that was used to get * the level, flp->lnum to the lnum of the next line. */ @@ -2524,8 +2560,9 @@ static linenr_T foldUpdateIEMSRecurse( } } - if (fp == NULL) /* only happens when got_int is set */ + if (fp == NULL) { // only happens when got_int is set return bot; + } /* * Get here when: @@ -2574,12 +2611,13 @@ static linenr_T foldUpdateIEMSRecurse( } } - /* delete following folds that end before the current line */ + // delete following folds that end before the current line for (;; ) { fp2 = fp + 1; if (fp2 >= (fold_T *)gap->ga_data + gap->ga_len - || fp2->fd_top > flp->lnum) + || fp2->fd_top > flp->lnum) { break; + } if (fp2->fd_top + fp2->fd_len > flp->lnum) { if (fp2->fd_top < flp->lnum) { // Make fold that includes lnum start at lnum. @@ -2603,19 +2641,20 @@ static linenr_T foldUpdateIEMSRecurse( /* Need to redraw the lines we inspected, which might be further down than * was asked for. */ - if (bot < flp->lnum - 1) + if (bot < flp->lnum - 1) { bot = flp->lnum - 1; + } return bot; } -/* foldInsert() {{{2 */ +// foldInsert() {{{2 /* * Insert a new fold in "gap" at position "i". */ static void foldInsert(garray_T *gap, int i) { - fold_T *fp; + fold_T *fp; ga_grow(gap, 1); @@ -2627,7 +2666,7 @@ static void foldInsert(garray_T *gap, int i) ga_init(&fp->fd_nested, (int)sizeof(fold_T), 10); } -/* foldSplit() {{{2 */ +// foldSplit() {{{2 /* * Split the "i"th fold in "gap", which starts before "top" and ends below * "bot" in two pieces, one ending above "top" and the other starting below @@ -2635,14 +2674,12 @@ static void foldInsert(garray_T *gap, int i) * The caller must first have taken care of any nested folds from "top" to * "bot"! */ -static void foldSplit(buf_T *buf, garray_T *const gap, - const int i, const linenr_T top, - const linenr_T bot - ) +static void foldSplit(buf_T *buf, garray_T *const gap, const int i, const linenr_T top, + const linenr_T bot) { - fold_T *fp2; + fold_T *fp2; - /* The fold continues below bot, need to split it. */ + // The fold continues below bot, need to split it. foldInsert(gap, i + 1); fold_T *const fp = (fold_T *)gap->ga_data + i; @@ -2675,7 +2712,7 @@ static void foldSplit(buf_T *buf, garray_T *const gap, fold_changed = true; } -/* foldRemove() {{{2 */ +// foldRemove() {{{2 /* * Remove folds within the range "top" to and including "bot". * Check for these situations: @@ -2694,11 +2731,9 @@ static void foldSplit(buf_T *buf, garray_T *const gap, * 5: made to start below "bot". * 6: not changed */ -static void foldRemove( - win_T *const wp, garray_T *gap, linenr_T top, linenr_T bot -) +static void foldRemove(win_T *const wp, garray_T *gap, linenr_T top, linenr_T bot) { - fold_T *fp = NULL; + fold_T *fp = NULL; if (bot < top) { return; // nothing to do @@ -2731,10 +2766,9 @@ static void foldRemove( fold_changed = true; if (fp->fd_top + fp->fd_len - 1 > bot) { // 5: Make fold that includes bot start below bot. - foldMarkAdjustRecurse( - wp, &fp->fd_nested, - (linenr_T)0, (long)(bot - fp->fd_top), - (linenr_T)MAXLNUM, (long)(fp->fd_top - bot - 1)); + foldMarkAdjustRecurse(wp, &fp->fd_nested, + (linenr_T)0, (long)(bot - fp->fd_top), + (linenr_T)MAXLNUM, (long)(fp->fd_top - bot - 1)); fp->fd_len -= bot - fp->fd_top + 1; fp->fd_top = bot + 1; break; @@ -2747,10 +2781,7 @@ static void foldRemove( } // foldReverseOrder() {{{2 -static void foldReverseOrder( - garray_T *gap, - const linenr_T start_arg, - const linenr_T end_arg) +static void foldReverseOrder(garray_T *gap, const linenr_T start_arg, const linenr_T end_arg) { linenr_T start = start_arg; linenr_T end = end_arg; @@ -2805,11 +2836,8 @@ static void truncate_fold(win_T *const wp, fold_T *fp, linenr_T end) #define VALID_FOLD(fp, gap) \ ((gap)->ga_len > 0 && (fp) < ((fold_T *)(gap)->ga_data + (gap)->ga_len)) #define FOLD_INDEX(fp, gap) ((size_t)(fp - ((fold_T *)(gap)->ga_data))) -void foldMoveRange( - win_T *const wp, garray_T *gap, - const linenr_T line1, const linenr_T line2, - const linenr_T dest -) +void foldMoveRange(win_T *const wp, garray_T *gap, const linenr_T line1, const linenr_T line2, + const linenr_T dest) { fold_T *fp; const linenr_T range_len = line2 - line1 + 1; @@ -2909,7 +2937,7 @@ void foldMoveRange( #undef VALID_FOLD #undef FOLD_INDEX -/* foldMerge() {{{2 */ +// foldMerge() {{{2 /* * Merge two adjacent folds (and the nested ones in them). * This only works correctly when the folds are really adjacent! Thus "fp1" @@ -2919,11 +2947,11 @@ void foldMoveRange( */ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) { - fold_T *fp3; - fold_T *fp4; + fold_T *fp3; + fold_T *fp4; int idx; - garray_T *gap1 = &fp1->fd_nested; - garray_T *gap2 = &fp2->fd_nested; + garray_T *gap1 = &fp1->fd_nested; + garray_T *gap2 = &fp2->fd_nested; /* If the last nested fold in fp1 touches the first nested fold in fp2, * merge them recursively. */ @@ -2931,7 +2959,7 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) foldMerge(wp, fp3, gap2, fp4); } - /* Move nested folds in fp2 to the end of fp1. */ + // Move nested folds in fp2 to the end of fp1. if (!GA_EMPTY(gap2)) { ga_grow(gap1, gap2->ga_len); for (idx = 0; idx < gap2->ga_len; ++idx) { @@ -2948,7 +2976,7 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) fold_changed = true; } -/* foldlevelIndent() {{{2 */ +// foldlevelIndent() {{{2 /* * Low level function to get the foldlevel for the "indent" method. * Doesn't use any caching. @@ -2956,8 +2984,8 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2) */ static void foldlevelIndent(fline_T *flp) { - char_u *s; - buf_T *buf; + char_u *s; + buf_T *buf; linenr_T lnum = flp->lnum + flp->off; buf = flp->wp->w_buffer; @@ -2966,33 +2994,35 @@ static void foldlevelIndent(fline_T *flp) /* empty line or lines starting with a character in 'foldignore': level * depends on surrounding lines */ if (*s == NUL || vim_strchr(flp->wp->w_p_fdi, *s) != NULL) { - /* first and last line can't be undefined, use level 0 */ - if (lnum == 1 || lnum == buf->b_ml.ml_line_count) + // first and last line can't be undefined, use level 0 + if (lnum == 1 || lnum == buf->b_ml.ml_line_count) { flp->lvl = 0; - else + } else { flp->lvl = -1; + } } else { flp->lvl = get_indent_buf(buf, lnum) / get_sw_value(buf); } if (flp->lvl > flp->wp->w_p_fdn) { - flp->lvl = (int) MAX(0, flp->wp->w_p_fdn); + flp->lvl = (int)MAX(0, flp->wp->w_p_fdn); } } -/* foldlevelDiff() {{{2 */ +// foldlevelDiff() {{{2 /* * Low level function to get the foldlevel for the "diff" method. * Doesn't use any caching. */ static void foldlevelDiff(fline_T *flp) { - if (diff_infold(flp->wp, flp->lnum + flp->off)) + if (diff_infold(flp->wp, flp->lnum + flp->off)) { flp->lvl = 1; - else + } else { flp->lvl = 0; + } } -/* foldlevelExpr() {{{2 */ +// foldlevelExpr() {{{2 /* * Low level function to get the foldlevel for the "expr" method. * Doesn't use any caching. @@ -3000,20 +3030,21 @@ static void foldlevelDiff(fline_T *flp) */ static void foldlevelExpr(fline_T *flp) { - win_T *win; + win_T *win; int c; linenr_T lnum = flp->lnum + flp->off; win = curwin; curwin = flp->wp; curbuf = flp->wp->w_buffer; - set_vim_var_nr(VV_LNUM, (varnumber_T) lnum); + set_vim_var_nr(VV_LNUM, (varnumber_T)lnum); flp->start = 0; flp->had_end = flp->end; flp->end = MAX_LEVEL + 1; - if (lnum <= 1) + if (lnum <= 1) { flp->lvl = 0; + } /* KeyTyped may be reset to 0 when calling a function which invokes * do_cmdline(). To make 'foldopen' work correctly restore KeyTyped. */ @@ -3022,46 +3053,54 @@ static void foldlevelExpr(fline_T *flp) KeyTyped = save_keytyped; switch (c) { - /* "a1", "a2", .. : add to the fold level */ - case 'a': if (flp->lvl >= 0) { + // "a1", "a2", .. : add to the fold level + case 'a': + if (flp->lvl >= 0) { flp->lvl += n; flp->lvl_next = flp->lvl; - } + } flp->start = n; break; - /* "s1", "s2", .. : subtract from the fold level */ - case 's': if (flp->lvl >= 0) { - if (n > flp->lvl) + // "s1", "s2", .. : subtract from the fold level + case 's': + if (flp->lvl >= 0) { + if (n > flp->lvl) { flp->lvl_next = 0; - else + } else { flp->lvl_next = flp->lvl - n; + } flp->end = flp->lvl_next + 1; - } + } break; - /* ">1", ">2", .. : start a fold with a certain level */ - case '>': flp->lvl = n; + // ">1", ">2", .. : start a fold with a certain level + case '>': + flp->lvl = n; flp->lvl_next = n; flp->start = 1; break; - /* "<1", "<2", .. : end a fold with a certain level */ - case '<': flp->lvl_next = n - 1; + // "<1", "<2", .. : end a fold with a certain level + case '<': + flp->lvl_next = n - 1; flp->end = n; break; - /* "=": No change in level */ - case '=': flp->lvl_next = flp->lvl; + // "=": No change in level + case '=': + flp->lvl_next = flp->lvl; break; - /* "-1", "0", "1", ..: set fold level */ - default: if (n < 0) + // "-1", "0", "1", ..: set fold level + default: + if (n < 0) { /* Use the current level for the next line, so that "a1" * will work there. */ flp->lvl_next = flp->lvl; - else + } else { flp->lvl_next = n; + } flp->lvl = n; break; } @@ -3073,15 +3112,16 @@ static void foldlevelExpr(fline_T *flp) flp->lvl = 0; flp->lvl_next = 0; } - if (lnum == curbuf->b_ml.ml_line_count) + if (lnum == curbuf->b_ml.ml_line_count) { flp->lvl_next = 0; + } } curwin = win; curbuf = curwin->w_buffer; } -/* parseMarker() {{{2 */ +// parseMarker() {{{2 /* * Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and * "foldendmarkerlen". @@ -3094,7 +3134,7 @@ static void parseMarker(win_T *wp) foldendmarkerlen = STRLEN(foldendmarker); } -/* foldlevelMarker() {{{2 */ +// foldlevelMarker() {{{2 /* * Low level function to get the foldlevel for the "marker" method. * "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been @@ -3106,20 +3146,20 @@ static void parseMarker(win_T *wp) */ static void foldlevelMarker(fline_T *flp) { - char_u *startmarker; + char_u *startmarker; int cstart; int cend; int start_lvl = flp->lvl; - char_u *s; + char_u *s; int n; - /* cache a few values for speed */ + // cache a few values for speed startmarker = flp->wp->w_p_fmr; cstart = *startmarker; ++startmarker; cend = *foldendmarker; - /* Default: no start found, next level is same as current level */ + // Default: no start found, next level is same as current level flp->start = 0; flp->lvl_next = flp->lvl; @@ -3127,17 +3167,18 @@ static void foldlevelMarker(fline_T *flp) while (*s) { if (*s == cstart && STRNCMP(s + 1, startmarker, foldstartmarkerlen - 1) == 0) { - /* found startmarker: set flp->lvl */ + // found startmarker: set flp->lvl s += foldstartmarkerlen; if (ascii_isdigit(*s)) { n = atoi((char *)s); if (n > 0) { flp->lvl = n; flp->lvl_next = n; - if (n <= start_lvl) + if (n <= start_lvl) { flp->start = 1; - else + } else { flp->start = n - start_lvl; + } } } else { ++flp->lvl; @@ -3146,16 +3187,17 @@ static void foldlevelMarker(fline_T *flp) } } else if (*s == cend && STRNCMP(s + 1, foldendmarker + 1, foldendmarkerlen - 1) == 0) { - /* found endmarker: set flp->lvl_next */ + // found endmarker: set flp->lvl_next s += foldendmarkerlen; if (ascii_isdigit(*s)) { n = atoi((char *)s); if (n > 0) { flp->lvl = n; flp->lvl_next = n - 1; - /* never start a fold with an end marker */ - if (flp->lvl_next > start_lvl) + // never start a fold with an end marker + if (flp->lvl_next > start_lvl) { flp->lvl_next = start_lvl; + } } } else { flp->lvl_next--; @@ -3165,12 +3207,13 @@ static void foldlevelMarker(fline_T *flp) } } - /* The level can't go negative, must be missing a start marker. */ - if (flp->lvl_next < 0) + // The level can't go negative, must be missing a start marker. + if (flp->lvl_next < 0) { flp->lvl_next = 0; + } } -/* foldlevelSyntax() {{{2 */ +// foldlevelSyntax() {{{2 /* * Low level function to get the foldlevel for the "syntax" method. * Doesn't use any caching. @@ -3180,20 +3223,20 @@ static void foldlevelSyntax(fline_T *flp) linenr_T lnum = flp->lnum + flp->off; int n; - /* Use the maximum fold level at the start of this line and the next. */ + // Use the maximum fold level at the start of this line and the next. flp->lvl = syn_get_foldlevel(flp->wp, lnum); flp->start = 0; if (lnum < flp->wp->w_buffer->b_ml.ml_line_count) { n = syn_get_foldlevel(flp->wp, lnum + 1); if (n > flp->lvl) { - flp->start = n - flp->lvl; /* fold(s) start here */ + flp->start = n - flp->lvl; // fold(s) start here flp->lvl = n; } } } -/* functions for storing the fold state in a View {{{1 */ -/* put_folds() {{{2 */ +// functions for storing the fold state in a View {{{1 +// put_folds() {{{2 /* * Write commands to "fd" to restore the manual folds in window "wp". @@ -3209,14 +3252,15 @@ int put_folds(FILE *fd, win_T *wp) } } - /* If some folds are manually opened/closed, need to restore that. */ - if (wp->w_fold_manual) + // If some folds are manually opened/closed, need to restore that. + if (wp->w_fold_manual) { return put_foldopen_recurse(fd, wp, &wp->w_folds, (linenr_T)0); + } return OK; } -/* put_folds_recurse() {{{2 */ +// put_folds_recurse() {{{2 /* * Write commands to "fd" to recreate manually created folds. * Returns FAIL when writing failed. @@ -3225,20 +3269,22 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off) { fold_T *fp = (fold_T *)gap->ga_data; for (int i = 0; i < gap->ga_len; i++) { - /* Do nested folds first, they will be created closed. */ - if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) + // Do nested folds first, they will be created closed. + if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) { return FAIL; + } if (fprintf(fd, "%" PRId64 ",%" PRId64 "fold", (int64_t)(fp->fd_top + off), (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0 - || put_eol(fd) == FAIL) + || put_eol(fd) == FAIL) { return FAIL; + } ++fp; } return OK; } -/* put_foldopen_recurse() {{{2 */ +// put_foldopen_recurse() {{{2 /* * Write commands to "fd" to open and close manually opened/closed folds. * Returns FAIL when writing failed. @@ -3251,19 +3297,22 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off for (int i = 0; i < gap->ga_len; i++) { if (fp->fd_flags != FD_LEVEL) { if (!GA_EMPTY(&fp->fd_nested)) { - /* open nested folds while this fold is open */ + // open nested folds while this fold is open if (fprintf(fd, "%" PRId64, (int64_t)(fp->fd_top + off)) < 0 || put_eol(fd) == FAIL - || put_line(fd, "normal! zo") == FAIL) + || put_line(fd, "normal! zo") == FAIL) { return FAIL; + } if (put_foldopen_recurse(fd, wp, &fp->fd_nested, - off + fp->fd_top) - == FAIL) + off + fp->fd_top) + == FAIL) { return FAIL; - /* close the parent when needed */ + } + // close the parent when needed if (fp->fd_flags == FD_CLOSED) { - if (put_fold_open_close(fd, fp, off) == FAIL) + if (put_fold_open_close(fd, fp, off) == FAIL) { return FAIL; + } } } else { /* Open or close the leaf according to the window foldlevel. @@ -3271,9 +3320,11 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off * the parent. */ level = foldLevelWin(wp, off + fp->fd_top); if ((fp->fd_flags == FD_CLOSED && wp->w_p_fdl >= level) - || (fp->fd_flags != FD_CLOSED && wp->w_p_fdl < level)) - if (put_fold_open_close(fd, fp, off) == FAIL) + || (fp->fd_flags != FD_CLOSED && wp->w_p_fdl < level)) { + if (put_fold_open_close(fd, fp, off) == FAIL) { return FAIL; + } + } } } ++fp; @@ -3282,7 +3333,7 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off return OK; } -/* put_fold_open_close() {{{2 */ +// put_fold_open_close() {{{2 /* * Write the open or close command to "fd". * Returns FAIL when writing failed. @@ -3292,11 +3343,12 @@ static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off) if (fprintf(fd, "%" PRId64, (int64_t)(fp->fd_top + off)) < 0 || put_eol(fd) == FAIL || fprintf(fd, "normal! z%c", - fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 - || put_eol(fd) == FAIL) + fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 + || put_eol(fd) == FAIL) { return FAIL; + } return OK; } -/* }}}1 */ +// }}}1 diff --git a/src/nvim/fold.h b/src/nvim/fold.h index 95c4b0c1dc..37fab4da60 100644 --- a/src/nvim/fold.h +++ b/src/nvim/fold.h @@ -21,6 +21,8 @@ typedef struct foldinfo { long fi_lines; } foldinfo_T; +#define FOLDINFO_INIT { 0, 0, 0, 0 } + #ifdef INCLUDE_GENERATED_DECLARATIONS # include "fold.h.generated.h" diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index 28f58e2c34..11e3b9bc2d 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -1563,8 +1563,8 @@ int vgetc(void) */ may_garbage_collect = false; - // Exec lua callbacks for on_keystroke - nlua_execute_log_keystroke(c); + // Execute Lua on_key callbacks. + nlua_execute_on_key(c); return c; } diff --git a/src/nvim/keymap.c b/src/nvim/keymap.c index 277b9ade89..c6966ff9fa 100644 --- a/src/nvim/keymap.c +++ b/src/nvim/keymap.c @@ -628,7 +628,11 @@ int find_special_key(const char_u **srcp, const size_t src_len, int *const modp, 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); + vim_str2nr(bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true); + if (l == 0) { + EMSG(_(e_invarg)); + return 0; + } bp += l + 5; break; } @@ -654,7 +658,11 @@ int find_special_key(const char_u **srcp, const size_t src_len, int *const modp, if (STRNICMP(last_dash + 1, "char-", 5) == 0 && ascii_isdigit(last_dash[6])) { // <Char-123> or <Char-033> or <Char-0x33> - vim_str2nr(last_dash + 6, NULL, NULL, STR2NR_ALL, NULL, &n, 0); + vim_str2nr(last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true); + if (l == 0) { + EMSG(_(e_invarg)); + return 0; + } key = (int)n; } else { int off = 1; diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 5cd9894f9d..d071203db1 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -33,6 +33,7 @@ #include "nvim/eval/userfunc.h" #include "nvim/event/time.h" #include "nvim/event/loop.h" +#include "mpack/lmpack.h" #include "nvim/os/os.h" @@ -506,6 +507,8 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL lua_setfield(lstate, -2, "__tostring"); lua_setmetatable(lstate, -2); nlua_nil_ref = nlua_ref(lstate, -1); + lua_pushvalue(lstate, -1); + lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.NIL"); lua_setfield(lstate, -2, "NIL"); // vim._empty_dict_mt @@ -513,8 +516,23 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL lua_pushcfunction(lstate, &nlua_empty_dict_tostring); lua_setfield(lstate, -2, "__tostring"); nlua_empty_dict_ref = nlua_ref(lstate, -1); + lua_pushvalue(lstate, -1); + lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.empty_dict"); lua_setfield(lstate, -2, "_empty_dict_mt"); + // vim.mpack + luaopen_mpack(lstate); + lua_pushvalue(lstate, -1); + lua_setfield(lstate, -3, "mpack"); + + // package.loaded.mpack = vim.mpack + // otherwise luv will be reinitialized when require'mpack' + lua_getglobal(lstate, "package"); + lua_getfield(lstate, -1, "loaded"); + lua_pushvalue(lstate, -3); + lua_setfield(lstate, -2, "mpack"); + lua_pop(lstate, 3); + // internal vim._treesitter... API nlua_add_treesitter(lstate); @@ -1499,7 +1517,7 @@ int nlua_expand_pat(expand_T *xp, lua_getfield(lstate, -1, "_expand_pat"); luaL_checktype(lstate, -1, LUA_TFUNCTION); - // [ vim, vim._log_keystroke, buf ] + // [ vim, vim._on_key, buf ] lua_pushlstring(lstate, (const char *)pat, STRLEN(pat)); if (lua_pcall(lstate, 1, 2, 0) != 0) { @@ -1773,7 +1791,7 @@ char_u *nlua_register_table_as_callable(typval_T *const arg) return name; } -void nlua_execute_log_keystroke(int c) +void nlua_execute_on_key(int c) { char_u buf[NUMBUFLEN]; size_t buf_len = special_to_buf(c, mod_mask, false, buf); @@ -1787,17 +1805,17 @@ void nlua_execute_log_keystroke(int c) // [ vim ] lua_getglobal(lstate, "vim"); - // [ vim, vim._log_keystroke ] - lua_getfield(lstate, -1, "_log_keystroke"); + // [ vim, vim._on_key] + lua_getfield(lstate, -1, "_on_key"); luaL_checktype(lstate, -1, LUA_TFUNCTION); - // [ vim, vim._log_keystroke, buf ] + // [ vim, vim._on_key, buf ] lua_pushlstring(lstate, (const char *)buf, buf_len); if (lua_pcall(lstate, 1, 0, 0)) { nlua_error( lstate, - _("Error executing vim.log_keystroke lua callback: %.*s")); + _("Error executing vim.on_key Lua callback: %.*s")); } // [ vim ] diff --git a/src/nvim/lua/vim.lua b/src/nvim/lua/vim.lua index 34b314b40d..c6bbdee7ad 100644 --- a/src/nvim/lua/vim.lua +++ b/src/nvim/lua/vim.lua @@ -4,6 +4,7 @@ -- 1. runtime/lua/vim/ (the runtime): For "nice to have" features, e.g. the -- `inspect` and `lpeg` modules. -- 2. runtime/lua/vim/shared.lua: Code shared between Nvim and tests. +-- (This will go away if we migrate to nvim as the test-runner.) -- 3. src/nvim/lua/: Compiled-into Nvim itself. -- -- Guideline: "If in doubt, put it in the runtime". @@ -426,26 +427,35 @@ function vim.notify(msg, log_level, _opts) end -local on_keystroke_callbacks = {} +function vim.register_keystroke_callback() + error('vim.register_keystroke_callback is deprecated, instead use: vim.on_key') +end + +local on_key_cbs = {} ---- Register a lua {fn} with an {id} to be run after every keystroke. +--- Adds Lua function {fn} with namespace id {ns_id} as a listener to every, +--- yes every, input key. --- ----@param fn function: Function to call. It should take one argument, which is a string. ---- The string will contain the literal keys typed. ---- See |i_CTRL-V| +--- The Nvim command-line option |-w| is related but does not support callbacks +--- and cannot be toggled dynamically. --- +---@param fn function: Callback function. It should take one string argument. +--- On each key press, Nvim passes the key char to fn(). |i_CTRL-V| --- If {fn} is nil, it removes the callback for the associated {ns_id} ----@param ns_id number? Namespace ID. If not passed or 0, will generate and return a new ---- namespace ID from |nvim_create_namesapce()| +---@param ns_id number? Namespace ID. If nil or 0, generates and returns a new +--- |nvim_create_namesapce()| id. --- ----@return number Namespace ID associated with {fn} +---@return number Namespace id associated with {fn}. Or count of all callbacks +---if on_key() is called without arguments. --- ----@note {fn} will be automatically removed if an error occurs while calling. ---- This is to prevent the annoying situation of every keystroke erroring ---- while trying to remove a broken callback. ----@note {fn} will not be cleared from |nvim_buf_clear_namespace()| ----@note {fn} will receive the keystrokes after mappings have been evaluated -function vim.register_keystroke_callback(fn, ns_id) +---@note {fn} will be removed if an error occurs while calling. +---@note {fn} will not be cleared by |nvim_buf_clear_namespace()| +---@note {fn} will receive the keys after mappings have been evaluated +function vim.on_key(fn, ns_id) + if fn == nil and ns_id == nil then + return #on_key_cbs + end + vim.validate { fn = { fn, 'c', true}, ns_id = { ns_id, 'n', true } @@ -455,20 +465,19 @@ function vim.register_keystroke_callback(fn, ns_id) ns_id = vim.api.nvim_create_namespace('') end - on_keystroke_callbacks[ns_id] = fn + on_key_cbs[ns_id] = fn return ns_id end ---- Function that executes the keystroke callbacks. +--- Executes the on_key callbacks. ---@private -function vim._log_keystroke(char) +function vim._on_key(char) local failed_ns_ids = {} local failed_messages = {} - for k, v in pairs(on_keystroke_callbacks) do + for k, v in pairs(on_key_cbs) do local ok, err_msg = pcall(v, char) if not ok then - vim.register_keystroke_callback(nil, k) - + vim.on_key(nil, k) table.insert(failed_ns_ids, k) table.insert(failed_messages, err_msg) end @@ -476,7 +485,7 @@ function vim._log_keystroke(char) if failed_ns_ids[1] then error(string.format( - "Error executing 'on_keystroke' with ns_ids of '%s'\n With messages: %s", + "Error executing 'on_key' with ns_ids '%s'\n Messages: %s", table.concat(failed_ns_ids, ", "), table.concat(failed_messages, "\n"))) end diff --git a/src/nvim/lua/xdiff.c b/src/nvim/lua/xdiff.c index d50f874a82..ae0ea00765 100644 --- a/src/nvim/lua/xdiff.c +++ b/src/nvim/lua/xdiff.c @@ -8,7 +8,7 @@ #include <string.h> #include "nvim/vim.h" -#include "nvim/xdiff/xdiff.h" +#include "xdiff/xdiff.h" #include "nvim/lua/xdiff.h" #include "nvim/lua/converter.h" #include "nvim/lua/executor.h" @@ -294,7 +294,7 @@ int nlua_xdl_diff(lua_State *lstate) case kNluaXdiffModeUnified: luaL_buffinit(lstate, &buf); ecb.priv = &buf; - ecb.outf = write_string; + ecb.out_line = write_string; break; case kNluaXdiffModeOnHunkCB: priv = xmalloc(sizeof(*priv)); diff --git a/src/nvim/main.c b/src/nvim/main.c index 9fc82a75af..716434f32e 100644 --- a/src/nvim/main.c +++ b/src/nvim/main.c @@ -309,9 +309,6 @@ int main(int argc, char **argv) init_highlight(true, false); // Default highlight groups. TIME_MSG("init highlight"); - init_default_mappings(); // Default mappings. - TIME_MSG("init default mappings"); - // Set the break level after the terminal is initialized. debug_break_level = params.use_debug_break_level; @@ -337,24 +334,14 @@ int main(int argc, char **argv) // prepare screen now, so external UIs can display messages starting = NO_BUFFERS; screenclear(); - TIME_MSG("initialized screen early for UI"); - } - - // open terminals when opening files that start with term:// -#define PROTO "term://" - do_cmdline_cmd("augroup nvim_terminal"); - do_cmdline_cmd("autocmd!"); - do_cmdline_cmd("autocmd BufReadCmd " PROTO "* nested " - ":if !exists('b:term_title')|call termopen( " - // Capture the command string - "matchstr(expand(\"<amatch>\"), " - "'\\c\\m" PROTO "\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), " - // capture the working directory - "{'cwd': expand(get(matchlist(expand(\"<amatch>\"), " - "'\\c\\m" PROTO "\\(.\\{-}\\)//'), 1, ''))})" - "|endif"); - do_cmdline_cmd("augroup END"); -#undef PROTO + TIME_MSG("init screen for UI"); + } + + init_default_mappings(); // Default mappings. + TIME_MSG("init default mappings"); + + init_default_autocmds(); + TIME_MSG("init default autocommands"); // Reset 'loadplugins' for "-u NONE" before "--cmd" arguments. // Allows for setting 'loadplugins' there. diff --git a/src/nvim/math.c b/src/nvim/math.c index b51f335ed7..63309b6f7a 100644 --- a/src/nvim/math.c +++ b/src/nvim/math.c @@ -2,6 +2,8 @@ // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include <math.h> +#include <stdint.h> +#include <string.h> #include "nvim/math.h" @@ -9,34 +11,26 @@ # include "math.c.generated.h" #endif -#if defined(__clang__) && __clang__ == 1 && __clang_major__ >= 6 -// Workaround glibc + Clang 6+ bug. #8274 -// https://bugzilla.redhat.com/show_bug.cgi?id=1472437 -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wconversion" -#endif int xfpclassify(double d) { -#if defined(__MINGW32__) - // Workaround mingw warning. #7863 - return __fpclassify(d); -#else - return fpclassify(d); -#endif + uint64_t m; + int e; + + memcpy(&m, &d, sizeof(m)); + e = 0x7ff & (m >> 52); + m = 0xfffffffffffffULL & m; + + switch (e) { + default: return FP_NORMAL; + case 0x000: return m ? FP_SUBNORMAL : FP_ZERO; + case 0x7ff: return m ? FP_NAN : FP_INFINITE; + } } int xisinf(double d) { - return isinf(d); + return FP_INFINITE == xfpclassify(d); } int xisnan(double d) { -#if defined(__MINGW32__) - // Workaround mingw warning. #7863 - return _isnan(d); -#else - return isnan(d); -#endif + return FP_NAN == xfpclassify(d); } -#if defined(__clang__) && __clang__ == 1 && __clang_major__ >= 6 -# pragma clang diagnostic pop -#endif diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c index cba372b9d3..fea1ab77a2 100644 --- a/src/nvim/mbyte.c +++ b/src/nvim/mbyte.c @@ -31,30 +31,30 @@ #include <wchar.h> #include <wctype.h> -#include "nvim/vim.h" #include "nvim/ascii.h" +#include "nvim/vim.h" #ifdef HAVE_LOCALE_H # include <locale.h> #endif -#include "nvim/eval.h" -#include "nvim/path.h" -#include "nvim/iconv.h" -#include "nvim/mbyte.h" +#include "nvim/arabic.h" #include "nvim/charset.h" #include "nvim/cursor.h" +#include "nvim/eval.h" #include "nvim/fileio.h" #include "nvim/func_attr.h" +#include "nvim/iconv.h" +#include "nvim/mark.h" +#include "nvim/mbyte.h" #include "nvim/memline.h" +#include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/memory.h" #include "nvim/option.h" +#include "nvim/os/os.h" +#include "nvim/path.h" #include "nvim/screen.h" #include "nvim/spell.h" #include "nvim/strings.h" -#include "nvim/os/os.h" -#include "nvim/arabic.h" -#include "nvim/mark.h" typedef struct { int rangeStart; @@ -70,6 +70,7 @@ struct interval { #ifdef INCLUDE_GENERATED_DECLARATIONS # include "mbyte.c.generated.h" + # include "unicode_tables.generated.h" #endif @@ -127,131 +128,131 @@ static struct enc_canon_table[] = { #define IDX_LATIN_1 0 - {"latin1", ENC_8BIT + ENC_LATIN1, 1252}, + { "latin1", ENC_8BIT + ENC_LATIN1, 1252 }, #define IDX_ISO_2 1 - {"iso-8859-2", ENC_8BIT, 0}, + { "iso-8859-2", ENC_8BIT, 0 }, #define IDX_ISO_3 2 - {"iso-8859-3", ENC_8BIT, 0}, + { "iso-8859-3", ENC_8BIT, 0 }, #define IDX_ISO_4 3 - {"iso-8859-4", ENC_8BIT, 0}, + { "iso-8859-4", ENC_8BIT, 0 }, #define IDX_ISO_5 4 - {"iso-8859-5", ENC_8BIT, 0}, + { "iso-8859-5", ENC_8BIT, 0 }, #define IDX_ISO_6 5 - {"iso-8859-6", ENC_8BIT, 0}, + { "iso-8859-6", ENC_8BIT, 0 }, #define IDX_ISO_7 6 - {"iso-8859-7", ENC_8BIT, 0}, + { "iso-8859-7", ENC_8BIT, 0 }, #define IDX_ISO_8 7 - {"iso-8859-8", ENC_8BIT, 0}, + { "iso-8859-8", ENC_8BIT, 0 }, #define IDX_ISO_9 8 - {"iso-8859-9", ENC_8BIT, 0}, + { "iso-8859-9", ENC_8BIT, 0 }, #define IDX_ISO_10 9 - {"iso-8859-10", ENC_8BIT, 0}, + { "iso-8859-10", ENC_8BIT, 0 }, #define IDX_ISO_11 10 - {"iso-8859-11", ENC_8BIT, 0}, + { "iso-8859-11", ENC_8BIT, 0 }, #define IDX_ISO_13 11 - {"iso-8859-13", ENC_8BIT, 0}, + { "iso-8859-13", ENC_8BIT, 0 }, #define IDX_ISO_14 12 - {"iso-8859-14", ENC_8BIT, 0}, + { "iso-8859-14", ENC_8BIT, 0 }, #define IDX_ISO_15 13 - {"iso-8859-15", ENC_8BIT + ENC_LATIN9, 0}, + { "iso-8859-15", ENC_8BIT + ENC_LATIN9, 0 }, #define IDX_KOI8_R 14 - {"koi8-r", ENC_8BIT, 0}, + { "koi8-r", ENC_8BIT, 0 }, #define IDX_KOI8_U 15 - {"koi8-u", ENC_8BIT, 0}, + { "koi8-u", ENC_8BIT, 0 }, #define IDX_UTF8 16 - {"utf-8", ENC_UNICODE, 0}, + { "utf-8", ENC_UNICODE, 0 }, #define IDX_UCS2 17 - {"ucs-2", ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0}, + { "ucs-2", ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0 }, #define IDX_UCS2LE 18 - {"ucs-2le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0}, + { "ucs-2le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0 }, #define IDX_UTF16 19 - {"utf-16", ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0}, + { "utf-16", ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0 }, #define IDX_UTF16LE 20 - {"utf-16le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0}, + { "utf-16le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0 }, #define IDX_UCS4 21 - {"ucs-4", ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0}, + { "ucs-4", ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0 }, #define IDX_UCS4LE 22 - {"ucs-4le", ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0}, + { "ucs-4le", ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0 }, - /* For debugging DBCS encoding on Unix. */ + // For debugging DBCS encoding on Unix. #define IDX_DEBUG 23 - {"debug", ENC_DBCS, DBCS_DEBUG}, + { "debug", ENC_DBCS, DBCS_DEBUG }, #define IDX_EUC_JP 24 - {"euc-jp", ENC_DBCS, DBCS_JPNU}, + { "euc-jp", ENC_DBCS, DBCS_JPNU }, #define IDX_SJIS 25 - {"sjis", ENC_DBCS, DBCS_JPN}, + { "sjis", ENC_DBCS, DBCS_JPN }, #define IDX_EUC_KR 26 - {"euc-kr", ENC_DBCS, DBCS_KORU}, + { "euc-kr", ENC_DBCS, DBCS_KORU }, #define IDX_EUC_CN 27 - {"euc-cn", ENC_DBCS, DBCS_CHSU}, + { "euc-cn", ENC_DBCS, DBCS_CHSU }, #define IDX_EUC_TW 28 - {"euc-tw", ENC_DBCS, DBCS_CHTU}, + { "euc-tw", ENC_DBCS, DBCS_CHTU }, #define IDX_BIG5 29 - {"big5", ENC_DBCS, DBCS_CHT}, + { "big5", ENC_DBCS, DBCS_CHT }, /* MS-DOS and MS-Windows codepages are included here, so that they can be * used on Unix too. Most of them are similar to ISO-8859 encodings, but * not exactly the same. */ #define IDX_CP437 30 - {"cp437", ENC_8BIT, 437}, /* like iso-8859-1 */ + { "cp437", ENC_8BIT, 437 }, // like iso-8859-1 #define IDX_CP737 31 - {"cp737", ENC_8BIT, 737}, /* like iso-8859-7 */ + { "cp737", ENC_8BIT, 737 }, // like iso-8859-7 #define IDX_CP775 32 - {"cp775", ENC_8BIT, 775}, /* Baltic */ + { "cp775", ENC_8BIT, 775 }, // Baltic #define IDX_CP850 33 - {"cp850", ENC_8BIT, 850}, /* like iso-8859-4 */ + { "cp850", ENC_8BIT, 850 }, // like iso-8859-4 #define IDX_CP852 34 - {"cp852", ENC_8BIT, 852}, /* like iso-8859-1 */ + { "cp852", ENC_8BIT, 852 }, // like iso-8859-1 #define IDX_CP855 35 - {"cp855", ENC_8BIT, 855}, /* like iso-8859-2 */ + { "cp855", ENC_8BIT, 855 }, // like iso-8859-2 #define IDX_CP857 36 - {"cp857", ENC_8BIT, 857}, /* like iso-8859-5 */ + { "cp857", ENC_8BIT, 857 }, // like iso-8859-5 #define IDX_CP860 37 - {"cp860", ENC_8BIT, 860}, /* like iso-8859-9 */ + { "cp860", ENC_8BIT, 860 }, // like iso-8859-9 #define IDX_CP861 38 - {"cp861", ENC_8BIT, 861}, /* like iso-8859-1 */ + { "cp861", ENC_8BIT, 861 }, // like iso-8859-1 #define IDX_CP862 39 - {"cp862", ENC_8BIT, 862}, /* like iso-8859-1 */ + { "cp862", ENC_8BIT, 862 }, // like iso-8859-1 #define IDX_CP863 40 - {"cp863", ENC_8BIT, 863}, /* like iso-8859-8 */ + { "cp863", ENC_8BIT, 863 }, // like iso-8859-8 #define IDX_CP865 41 - {"cp865", ENC_8BIT, 865}, /* like iso-8859-1 */ + { "cp865", ENC_8BIT, 865 }, // like iso-8859-1 #define IDX_CP866 42 - {"cp866", ENC_8BIT, 866}, /* like iso-8859-5 */ + { "cp866", ENC_8BIT, 866 }, // like iso-8859-5 #define IDX_CP869 43 - {"cp869", ENC_8BIT, 869}, /* like iso-8859-7 */ + { "cp869", ENC_8BIT, 869 }, // like iso-8859-7 #define IDX_CP874 44 - {"cp874", ENC_8BIT, 874}, /* Thai */ + { "cp874", ENC_8BIT, 874 }, // Thai #define IDX_CP932 45 - {"cp932", ENC_DBCS, DBCS_JPN}, + { "cp932", ENC_DBCS, DBCS_JPN }, #define IDX_CP936 46 - {"cp936", ENC_DBCS, DBCS_CHS}, + { "cp936", ENC_DBCS, DBCS_CHS }, #define IDX_CP949 47 - {"cp949", ENC_DBCS, DBCS_KOR}, + { "cp949", ENC_DBCS, DBCS_KOR }, #define IDX_CP950 48 - {"cp950", ENC_DBCS, DBCS_CHT}, + { "cp950", ENC_DBCS, DBCS_CHT }, #define IDX_CP1250 49 - {"cp1250", ENC_8BIT, 1250}, /* Czech, Polish, etc. */ + { "cp1250", ENC_8BIT, 1250 }, // Czech, Polish, etc. #define IDX_CP1251 50 - {"cp1251", ENC_8BIT, 1251}, /* Cyrillic */ - /* cp1252 is considered to be equal to latin1 */ + { "cp1251", ENC_8BIT, 1251 }, // Cyrillic + // cp1252 is considered to be equal to latin1 #define IDX_CP1253 51 - {"cp1253", ENC_8BIT, 1253}, /* Greek */ + { "cp1253", ENC_8BIT, 1253 }, // Greek #define IDX_CP1254 52 - {"cp1254", ENC_8BIT, 1254}, /* Turkish */ + { "cp1254", ENC_8BIT, 1254 }, // Turkish #define IDX_CP1255 53 - {"cp1255", ENC_8BIT, 1255}, /* Hebrew */ + { "cp1255", ENC_8BIT, 1255 }, // Hebrew #define IDX_CP1256 54 - {"cp1256", ENC_8BIT, 1256}, /* Arabic */ + { "cp1256", ENC_8BIT, 1256 }, // Arabic #define IDX_CP1257 55 - {"cp1257", ENC_8BIT, 1257}, /* Baltic */ + { "cp1257", ENC_8BIT, 1257 }, // Baltic #define IDX_CP1258 56 - {"cp1258", ENC_8BIT, 1258}, /* Vietnamese */ + { "cp1258", ENC_8BIT, 1258 }, // Vietnamese #define IDX_MACROMAN 57 - {"macroman", ENC_8BIT + ENC_MACROMAN, 0}, /* Mac OS */ + { "macroman", ENC_8BIT + ENC_MACROMAN, 0 }, // Mac OS #define IDX_HPROMAN8 58 - {"hp-roman8", ENC_8BIT, 0}, /* HP Roman8 */ + { "hp-roman8", ENC_8BIT, 0 }, // HP Roman8 #define IDX_COUNT 59 }; @@ -336,9 +337,11 @@ static int enc_canon_search(const char_u *name) { int i; - for (i = 0; i < IDX_COUNT; ++i) - if (STRCMP(name, enc_canon_table[i].name) == 0) + for (i = 0; i < IDX_COUNT; ++i) { + if (STRCMP(name, enc_canon_table[i].name) == 0) { return i; + } + } return -1; } @@ -353,12 +356,13 @@ int enc_canon_props(const char_u *name) int i; i = enc_canon_search(name); - if (i >= 0) + if (i >= 0) { return enc_canon_table[i].prop; - if (STRNCMP(name, "2byte-", 6) == 0) + } else if (STRNCMP(name, "2byte-", 6) == 0) { return ENC_DBCS; - if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0) + } else if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0) { return ENC_8BIT; + } return 0; } @@ -436,21 +440,23 @@ static bool intable(const struct interval *table, size_t n_items, int c) { int mid, bot, top; - /* first quick check for Latin1 etc. characters */ - if (c < table[0].first) + // first quick check for Latin1 etc. characters + if (c < table[0].first) { return false; + } - /* binary search in table */ + // binary search in table bot = 0; top = (int)(n_items - 1); while (top >= bot) { mid = (bot + top) / 2; - if (table[mid].last < c) + if (table[mid].last < c) { bot = mid + 1; - else if (table[mid].first > c) + } else if (table[mid].first > c) { top = mid - 1; - else + } else { return true; + } } return false; } @@ -512,12 +518,14 @@ int utf_ptr2cells(const char_u *p) // Need to convert to a character number. if (*p >= 0x80) { c = utf_ptr2char(p); - /* An illegal byte is displayed as <xx>. */ - if (utf_ptr2len(p) == 1 || c == NUL) + // An illegal byte is displayed as <xx>. + if (utf_ptr2len(p) == 1 || c == NUL) { return 4; - /* If the char is ASCII it must be an overlong sequence. */ - if (c < 0x80) + } + // If the char is ASCII it must be an overlong sequence. + if (c < 0x80) { return char2cells(c); + } return utf_char2cells(c); } return 1; @@ -529,17 +537,20 @@ int utf_ptr2cells_len(const char_u *p, int size) { int c; - /* Need to convert to a wide character. */ + // Need to convert to a wide character. if (size > 0 && *p >= 0x80) { - if (utf_ptr2len_len(p, size) < utf8len_tab[*p]) - return 1; /* truncated */ + if (utf_ptr2len_len(p, size) < utf8len_tab[*p]) { + return 1; // truncated + } c = utf_ptr2char(p); - /* An illegal byte is displayed as <xx>. */ - if (utf_ptr2len(p) == 1 || c == NUL) + // An illegal byte is displayed as <xx>. + if (utf_ptr2len(p) == 1 || c == NUL) { return 4; - /* If the char is ASCII it must be an overlong sequence. */ - if (c < 0x80) + } + // If the char is ASCII it must be an overlong sequence. + if (c < 0x80) { return char2cells(c); + } return utf_char2cells(c); } return 1; @@ -651,13 +662,14 @@ static int utf_safe_read_char_adv(const char_u **s, size_t *n) { int c; - if (*n == 0) /* end of buffer */ + if (*n == 0) { // end of buffer return 0; + } uint8_t k = utf8len_tab_zero[**s]; if (k == 1) { - /* ASCII character or NUL */ + // ASCII character or NUL (*n)--; return *(*s)++; } @@ -674,14 +686,14 @@ static int utf_safe_read_char_adv(const char_u **s, size_t *n) * U+00C3 (UTF-8: 0xC3 0x83), so need to check that special case too. * It's safe even if n=1, else we would have k=2 > n. */ if (c != (int)(**s) || (c == 0xC3 && (*s)[1] == 0x83)) { - /* byte sequence was successfully decoded */ + // byte sequence was successfully decoded *s += k; *n -= k; return c; } } - /* byte sequence is incomplete or illegal */ + // byte sequence is incomplete or illegal return -1; } @@ -721,10 +733,12 @@ bool utf_composinglike(const char_u *p1, const char_u *p2) int c2; c2 = utf_ptr2char(p2); - if (utf_iscomposing(c2)) + if (utf_iscomposing(c2)) { return true; - if (!arabic_maycombine(c2)) + } + if (!arabic_maycombine(c2)) { return false; + } return arabic_combine(utf_ptr2char(p1), c2); } @@ -746,23 +760,26 @@ int utfc_ptr2char(const char_u *p, int *pcc) c = utf_ptr2char(p); len = utf_ptr2len(p); - /* Only accept a composing char when the first char isn't illegal. */ + // 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(p + len); for (;; ) { pcc[i++] = cc; - if (i == MAX_MCO) + if (i == MAX_MCO) { break; + } len += utf_ptr2len(p + len); - if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len))) + if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len))) { break; + } } } - if (i < MAX_MCO) /* last composing char must be 0 */ + if (i < MAX_MCO) { // last composing char must be 0 pcc[i] = 0; + } return c; } @@ -855,15 +872,19 @@ int utf_ptr2len_len(const char_u *p, int size) int m; len = utf8len_tab[*p]; - if (len == 1) - return 1; /* NUL, ascii or illegal lead byte */ - if (len > size) - m = size; /* incomplete byte sequence. */ - else + if (len == 1) { + return 1; // NUL, ascii or illegal lead byte + } + if (len > size) { + m = size; // incomplete byte sequence. + } else { m = len; - for (i = 1; i < m; ++i) - if ((p[i] & 0xc0) != 0x80) + } + for (i = 1; i < m; ++i) { + if ((p[i] & 0xc0) != 0x80) { return 1; + } + } return len; } @@ -915,17 +936,20 @@ int utfc_ptr2len_len(const char_u *p, int size) int len; int prevlen; - if (size < 1 || *p == NUL) + if (size < 1 || *p == NUL) { return 0; - if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) /* be quick for ASCII */ + } + if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) { // be quick for ASCII return 1; + } - /* Skip over first UTF-8 char, stopping at a NUL byte. */ + // Skip over first UTF-8 char, stopping at a NUL byte. len = utf_ptr2len_len(p, size); - /* Check for illegal byte and incomplete byte sequence. */ - if ((len == 1 && p[0] >= 0x80) || len > size) + // Check for illegal byte and incomplete byte sequence. + if ((len == 1 && p[0] >= 0x80) || len > size) { return 1; + } /* * Check for composing characters. We can handle only the first six, but @@ -935,21 +959,24 @@ int utfc_ptr2len_len(const char_u *p, int size) while (len < size) { int len_next_char; - if (p[len] < 0x80) + if (p[len] < 0x80) { break; + } /* * 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); - if (len_next_char > size - len) + if (len_next_char > size - len) { break; + } - if (!UTF_COMPOSINGLIKE(p + prevlen, p + len)) + if (!UTF_COMPOSINGLIKE(p + prevlen, p + len)) { break; + } - /* Skip over composing char */ + // Skip over composing char prevlen = len; len += len_next_char; } @@ -1043,9 +1070,9 @@ bool utf_printable(int c) * 0xd800-0xdfff is reserved for UTF-16, actually illegal. */ static struct interval nonprint[] = { - {0x070f, 0x070f}, {0x180b, 0x180e}, {0x200b, 0x200f}, {0x202a, 0x202e}, - {0x206a, 0x206f}, {0xd800, 0xdfff}, {0xfeff, 0xfeff}, {0xfff9, 0xfffb}, - {0xfffe, 0xffff} + { 0x070f, 0x070f }, { 0x180b, 0x180e }, { 0x200b, 0x200f }, { 0x202a, 0x202e }, + { 0x206a, 0x206f }, { 0xd800, 0xdfff }, { 0xfeff, 0xfeff }, { 0xfff9, 0xfffb }, + { 0xfffe, 0xffff } }; return !intable(nonprint, ARRAY_SIZE(nonprint), c); @@ -1065,7 +1092,7 @@ int utf_class(const int c) int utf_class_tab(const int c, const uint64_t *const chartab) { - /* sorted list of non-overlapping intervals */ + // sorted list of non-overlapping intervals static struct clinterval { unsigned int first; unsigned int last; @@ -1147,7 +1174,7 @@ int utf_class_tab(const int c, const uint64_t *const chartab) int top = ARRAY_SIZE(classes) - 1; int mid; - /* First quick check for Latin1 characters, use 'iskeyword'. */ + // First quick check for Latin1 characters, use 'iskeyword'. if (c < 0x100) { if (c == ' ' || c == '\t' || c == NUL || c == 0xa0) { return 0; // blank @@ -1158,15 +1185,16 @@ int utf_class_tab(const int c, const uint64_t *const chartab) return 1; // punctuation } - /* binary search in table */ + // binary search in table while (top >= bot) { mid = (bot + top) / 2; - if (classes[mid].last < (unsigned int)c) + if (classes[mid].last < (unsigned int)c) { bot = mid + 1; - else if (classes[mid].first > (unsigned int)c) + } else if (classes[mid].first > (unsigned int)c) { top = mid - 1; - else + } else { return (int)classes[mid].class; + } } // emoji @@ -1174,7 +1202,7 @@ int utf_class_tab(const int c, const uint64_t *const chartab) return 3; } - /* most other characters are "word" characters */ + // most other characters are "word" characters return 2; } @@ -1191,25 +1219,27 @@ bool utf_ambiguous_width(int c) */ static int utf_convert(int a, const convertStruct *const table, size_t n_items) { - size_t start, mid, end; /* indices into table */ + size_t start, mid, end; // indices into table start = 0; end = n_items; while (start < end) { - /* need to search further */ + // need to search further mid = (end + start) / 2; - if (table[mid].rangeEnd < a) + if (table[mid].rangeEnd < a) { start = mid + 1; - else + } else { end = mid; + } } if (start < n_items && table[start].rangeStart <= a && a <= table[start].rangeEnd - && (a - table[start].rangeStart) % table[start].step == 0) + && (a - table[start].rangeStart) % table[start].step == 0) { return a + table[start].offset; - else + } else { return a; + } } /* @@ -1234,21 +1264,24 @@ int utf_fold(int a) /// simple case folding. int mb_toupper(int a) { - /* If 'casemap' contains "keepascii" use ASCII style toupper(). */ - if (a < 128 && (cmp_flags & CMP_KEEPASCII)) + // If 'casemap' contains "keepascii" use ASCII style toupper(). + if (a < 128 && (cmp_flags & CMP_KEEPASCII)) { return TOUPPER_ASC(a); + } #if defined(__STDC_ISO_10646__) - /* If towupper() is available and handles Unicode, use it. */ - if (!(cmp_flags & CMP_INTERNAL)) + // If towupper() is available and handles Unicode, use it. + if (!(cmp_flags & CMP_INTERNAL)) { return towupper(a); + } #endif - /* For characters below 128 use locale sensitive toupper(). */ - if (a < 128) + // For characters below 128 use locale sensitive toupper(). + if (a < 128) { return TOUPPER_LOC(a); + } - /* For any other characters use the above mapping table. */ + // For any other characters use the above mapping table. return utf_convert(a, toUpper, ARRAY_SIZE(toUpper)); } @@ -1262,21 +1295,24 @@ bool mb_islower(int a) /// simple case folding. int mb_tolower(int a) { - /* If 'casemap' contains "keepascii" use ASCII style tolower(). */ - if (a < 128 && (cmp_flags & CMP_KEEPASCII)) + // If 'casemap' contains "keepascii" use ASCII style tolower(). + if (a < 128 && (cmp_flags & CMP_KEEPASCII)) { return TOLOWER_ASC(a); + } #if defined(__STDC_ISO_10646__) - /* If towlower() is available and handles Unicode, use it. */ - if (!(cmp_flags & CMP_INTERNAL)) + // If towlower() is available and handles Unicode, use it. + if (!(cmp_flags & CMP_INTERNAL)) { return towlower(a); + } #endif - /* For characters below 128 use locale sensitive tolower(). */ - if (a < 128) + // For characters below 128 use locale sensitive tolower(). + if (a < 128) { return TOLOWER_LOC(a); + } - /* For any other characters use the above mapping table. */ + // For any other characters use the above mapping table. return utf_convert(a, toLower, ARRAY_SIZE(toLower)); } @@ -1285,8 +1321,7 @@ bool mb_isupper(int a) return mb_tolower(a) != a; } -static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, - size_t n2) +static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, size_t n2) { int c1, c2, cdiff; char_u buffer[6]; @@ -1295,23 +1330,27 @@ static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, c1 = utf_safe_read_char_adv(&s1, &n1); c2 = utf_safe_read_char_adv(&s2, &n2); - if (c1 <= 0 || c2 <= 0) + if (c1 <= 0 || c2 <= 0) { break; + } - if (c1 == c2) + if (c1 == c2) { continue; + } cdiff = utf_fold(c1) - utf_fold(c2); - if (cdiff != 0) + if (cdiff != 0) { return cdiff; + } } - /* some string ended or has an incomplete/illegal character sequence */ + // some string ended or has an incomplete/illegal character sequence if (c1 == 0 || c2 == 0) { - /* some string ended. shorter string is smaller */ - if (c1 == 0 && c2 == 0) + // some string ended. shorter string is smaller + if (c1 == 0 && c2 == 0) { return 0; + } return c1 == 0 ? -1 : 1; } @@ -1332,8 +1371,9 @@ static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, while (n1 > 0 && n2 > 0 && *s1 != NUL && *s2 != NUL) { cdiff = (int)(*s1) - (int)(*s2); - if (cdiff != 0) + if (cdiff != 0) { return cdiff; + } s1++; s2++; @@ -1341,19 +1381,22 @@ static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, n2--; } - if (n1 > 0 && *s1 == NUL) + if (n1 > 0 && *s1 == NUL) { n1 = 0; - if (n2 > 0 && *s2 == NUL) + } + if (n2 > 0 && *s2 == NUL) { n2 = 0; + } - if (n1 == 0 && n2 == 0) + if (n1 == 0 && n2 == 0) { return 0; + } return n1 == 0 ? -1 : 1; } #ifdef WIN32 #ifndef CP_UTF8 -# define CP_UTF8 65001 /* magic number from winnls.h */ +# define CP_UTF8 65001 // magic number from winnls.h #endif /// Converts string from UTF-8 to UTF-16. @@ -1453,8 +1496,7 @@ int utf16_to_utf8(const wchar_t *utf16, int utf16len, char **utf8) /// @param len maximum length (an earlier NUL terminates) /// @param[out] codepoints incremented with UTF-32 code point size /// @param[out] codeunits incremented with UTF-16 code unit size -void mb_utflen(const char_u *s, size_t len, size_t *codepoints, - size_t *codeunits) +void mb_utflen(const char_u *s, size_t len, size_t *codepoints, size_t *codeunits) FUNC_ATTR_NONNULL_ALL { size_t count = 0, extra = 0; @@ -1473,8 +1515,7 @@ void mb_utflen(const char_u *s, size_t len, size_t *codepoints, *codeunits += count + extra; } -ssize_t mb_utf_index_to_bytes(const char_u *s, size_t len, - size_t index, bool use_utf16_units) +ssize_t mb_utf_index_to_bytes(const char_u *s, size_t len, size_t index, bool use_utf16_units) FUNC_ATTR_NONNULL_ALL { size_t count = 0; @@ -1537,7 +1578,7 @@ void show_utf8(void) { int len; int rlen = 0; - char_u *line; + char_u *line; int clen; int i; @@ -1553,7 +1594,7 @@ void show_utf8(void) clen = 0; for (i = 0; i < len; ++i) { if (clen == 0) { - /* start of (composing) character, get its length */ + // start of (composing) character, get its length if (i > 0) { STRCPY(IObuff + rlen, "+ "); rlen += 2; @@ -1561,11 +1602,12 @@ void show_utf8(void) clen = utf_ptr2len(line + i); } sprintf((char *)IObuff + rlen, "%02x ", - (line[i] == NL) ? NUL : line[i]); /* NUL is stored as NL */ + (line[i] == NL) ? NUL : line[i]); // NUL is stored as NL --clen; rlen += (int)STRLEN(IObuff + rlen); - if (rlen > IOSIZE - 20) + if (rlen > IOSIZE - 20) { break; + } } msg(IObuff); @@ -1579,42 +1621,49 @@ int utf_head_off(const char_u *base, const char_u *p) int c; int len; - if (*p < 0x80) /* be quick for ASCII */ + if (*p < 0x80) { // be quick for ASCII return 0; + } /* Skip backwards over trailing bytes: 10xx.xxxx * Skip backwards again if on a composing char. */ const char_u *q; for (q = p;; --q) { - /* Move s to the last byte of this char. */ + // Move s to the last byte of this char. const char_u *s; for (s = q; (s[1] & 0xc0) == 0x80; ++s) {} - /* Move q to the first byte of this char. */ - while (q > base && (*q & 0xc0) == 0x80) + // Move q to the first byte of this char. + while (q > base && (*q & 0xc0) == 0x80) { --q; + } /* Check for illegal sequence. Do allow an illegal byte after where we * started. */ len = utf8len_tab[*q]; - if (len != (int)(s - q + 1) && len != (int)(p - q + 1)) + if (len != (int)(s - q + 1) && len != (int)(p - q + 1)) { return 0; + } - if (q <= base) + if (q <= base) { break; + } c = utf_ptr2char(q); - if (utf_iscomposing(c)) + if (utf_iscomposing(c)) { continue; + } if (arabic_maycombine(c)) { - /* Advance to get a sneak-peak at the next char */ + // Advance to get a sneak-peak at the next char const char_u *j = q; --j; - /* Move j to the first byte of this char. */ - while (j > base && (*j & 0xc0) == 0x80) + // Move j to the first byte of this char. + while (j > base && (*j & 0xc0) == 0x80) { --j; - if (arabic_combine(utf_ptr2char(j), c)) + } + if (arabic_combine(utf_ptr2char(j), c)) { continue; + } } break; } @@ -1627,12 +1676,12 @@ bool utf_eat_space(int cc) FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT { return (cc >= 0x2000 && cc <= 0x206F) // General punctuations - || (cc >= 0x2e00 && cc <= 0x2e7f) // Supplemental punctuations - || (cc >= 0x3000 && cc <= 0x303f) // CJK symbols and punctuations - || (cc >= 0xff01 && cc <= 0xff0f) // Full width ASCII punctuations - || (cc >= 0xff1a && cc <= 0xff20) // .. - || (cc >= 0xff3b && cc <= 0xff40) // .. - || (cc >= 0xff5b && cc <= 0xff65); // .. + || (cc >= 0x2e00 && cc <= 0x2e7f) // Supplemental punctuations + || (cc >= 0x3000 && cc <= 0x303f) // CJK symbols and punctuations + || (cc >= 0xff01 && cc <= 0xff0f) // Full width ASCII punctuations + || (cc >= 0xff1a && cc <= 0xff20) // .. + || (cc >= 0xff3b && cc <= 0xff40) // .. + || (cc >= 0xff5b && cc <= 0xff65); // .. } // Whether line break is allowed before "cc". @@ -1814,8 +1863,9 @@ int mb_tail_off(char_u *base, char_u *p) int i; int j; - if (*p == NUL) + if (*p == NUL) { return 0; + } // Find the last character that is 10xx.xxxx for (i = 0; (p[i + 1] & 0xc0) == 0x80; i++) {} @@ -1839,10 +1889,10 @@ int mb_tail_off(char_u *base, char_u *p) void utf_find_illegal(void) { pos_T pos = curwin->w_cursor; - char_u *p; + char_u *p; int len; vimconv_T vimconv; - char_u *tofree = NULL; + char_u *tofree = NULL; vimconv.vc_type = CONV_NONE; if (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT) { @@ -1858,8 +1908,9 @@ void utf_find_illegal(void) if (vimconv.vc_type != CONV_NONE) { xfree(tofree); tofree = string_convert(&vimconv, p, NULL); - if (tofree == NULL) + if (tofree == NULL) { break; + } p = tofree; } @@ -1868,10 +1919,10 @@ void utf_find_illegal(void) * utf_ptr2len()) or too many of them (overlong sequence). */ len = utf_ptr2len(p); if (*p >= 0x80 && (len == 1 - || utf_char2len(utf_ptr2char(p)) != len)) { - if (vimconv.vc_type == CONV_NONE) + || utf_char2len(utf_ptr2char(p)) != len)) { + if (vimconv.vc_type == CONV_NONE) { curwin->w_cursor.col += (colnr_T)(p - get_cursor_pos_ptr()); - else { + } else { int l; len = (int)(p - tofree); @@ -1884,13 +1935,14 @@ void utf_find_illegal(void) } p += len; } - if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) + if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) { break; + } ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; } - /* didn't find it: don't move and beep */ + // didn't find it: don't move and beep curwin->w_cursor = pos; beep_flush(); @@ -1944,13 +1996,10 @@ void mb_check_adjust_col(void *win_) } } -/* - * Return a pointer to the character before "*p", if there is one. - */ -char_u * mb_prevptr( - char_u *line, /* start of the string */ - char_u *p - ) +/// @param line start of the string +/// +/// @return a pointer to the character before "*p", if there is one. +char_u * mb_prevptr(char_u *line, char_u *p) { if (p > line) { MB_PTR_BACK(line, p); @@ -1964,14 +2013,16 @@ char_u * mb_prevptr( */ int mb_charlen(char_u *str) { - char_u *p = str; + char_u *p = str; int count; - if (p == NULL) + if (p == NULL) { return 0; + } - for (count = 0; *p != NUL; count++) + for (count = 0; *p != NUL; count++) { p += (*mb_ptr2len)(p); + } return count; } @@ -1981,11 +2032,12 @@ int mb_charlen(char_u *str) */ int mb_charlen_len(char_u *str, int len) { - char_u *p = str; + char_u *p = str; int count; - for (count = 0; *p != NUL && p < str + len; count++) + for (count = 0; *p != NUL && p < str + len; count++) { p += (*mb_ptr2len)(p); + } return count; } @@ -2049,10 +2101,12 @@ const char *mb_unescape(const char **const pp) */ char_u * enc_skip(char_u *p) { - if (STRNCMP(p, "2byte-", 6) == 0) + if (STRNCMP(p, "2byte-", 6) == 0) { return p + 6; - if (STRNCMP(p, "8bit-", 5) == 0) + } + if (STRNCMP(p, "8bit-", 5) == 0) { return p + 5; + } return p; } @@ -2064,7 +2118,7 @@ char_u * enc_skip(char_u *p) */ char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET { - char_u *p, *s; + char_u *p, *s; int i; if (STRCMP(enc, "default") == 0) { @@ -2072,47 +2126,51 @@ char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET return vim_strsave(fenc_default); } - /* copy "enc" to allocated memory, with room for two '-' */ + // copy "enc" to allocated memory, with room for two '-' char_u *r = xmalloc(STRLEN(enc) + 3); - /* Make it all lower case and replace '_' with '-'. */ + // Make it all lower case and replace '_' with '-'. p = r; for (s = enc; *s != NUL; ++s) { - if (*s == '_') + if (*s == '_') { *p++ = '-'; - else + } else { *p++ = TOLOWER_ASC(*s); + } } *p = NUL; - /* Skip "2byte-" and "8bit-". */ + // Skip "2byte-" and "8bit-". p = enc_skip(r); - /* Change "microsoft-cp" to "cp". Used in some spell files. */ - if (STRNCMP(p, "microsoft-cp", 12) == 0) + // Change "microsoft-cp" to "cp". Used in some spell files. + if (STRNCMP(p, "microsoft-cp", 12) == 0) { STRMOVE(p, p + 10); + } - /* "iso8859" -> "iso-8859" */ + // "iso8859" -> "iso-8859" if (STRNCMP(p, "iso8859", 7) == 0) { STRMOVE(p + 4, p + 3); p[3] = '-'; } - /* "iso-8859n" -> "iso-8859-n" */ + // "iso-8859n" -> "iso-8859-n" if (STRNCMP(p, "iso-8859", 8) == 0 && p[8] != '-') { STRMOVE(p + 9, p + 8); p[8] = '-'; } - /* "latin-N" -> "latinN" */ - if (STRNCMP(p, "latin-", 6) == 0) + // "latin-N" -> "latinN" + if (STRNCMP(p, "latin-", 6) == 0) { STRMOVE(p + 5, p + 6); + } if (enc_canon_search(p) >= 0) { - /* canonical name can be used unmodified */ - if (p != r) + // canonical name can be used unmodified + if (p != r) { STRMOVE(r, p); + } } else if ((i = enc_alias_search(p)) >= 0) { - /* alias recognized, get canonical name */ + // alias recognized, get canonical name xfree(r); r = vim_strsave((char_u *)enc_canon_table[i].name); } @@ -2127,9 +2185,11 @@ static int enc_alias_search(char_u *name) { int i; - for (i = 0; enc_alias_table[i].name != NULL; ++i) - if (STRCMP(name, enc_alias_table[i].name) == 0) + for (i = 0; enc_alias_table[i].name != NULL; ++i) { + if (STRCMP(name, enc_alias_table[i].name) == 0) { return enc_alias_table[i].canon; + } + } return -1; } @@ -2219,13 +2279,13 @@ void * my_iconv_open(char_u *to, char_u *from) iconv_t fd; #define ICONV_TESTLEN 400 char_u tobuf[ICONV_TESTLEN]; - char *p; + char *p; size_t tolen; static WorkingStatus iconv_working = kUnknown; - if (iconv_working == kBroken) - return (void *)-1; /* detected a broken iconv() previously */ - + if (iconv_working == kBroken) { + return (void *)-1; // detected a broken iconv() previously + } fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from)); if (fd != (iconv_t)-1 && iconv_working == kUnknown) { @@ -2243,8 +2303,9 @@ void * my_iconv_open(char_u *to, char_u *from) iconv_working = kBroken; iconv_close(fd); fd = (iconv_t)-1; - } else + } else { iconv_working = kWorking; + } } return (void *)fd; @@ -2257,17 +2318,17 @@ void * my_iconv_open(char_u *to, char_u *from) * 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) +static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen, + size_t *unconvlenp, size_t *resultlenp) { - const char *from; + const char *from; size_t fromlen; - char *to; + char *to; size_t tolen; size_t len = 0; size_t done = 0; - char_u *result = NULL; - char_u *p; + char_u *result = NULL; + char_u *p; int l; from = (char *)str; @@ -2278,8 +2339,9 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, * increase the buffer size. */ len = len + fromlen * 2 + 40; p = xmalloc(len); - if (done > 0) + if (done > 0) { memmove(p, result, done); + } xfree(result); result = p; } @@ -2327,8 +2389,9 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, done = to - (char *)result; } - if (resultlenp != NULL && result != NULL) + if (resultlenp != NULL && result != NULL) { *resultlenp = (size_t)(to - (char *)result); + } return result; } @@ -2353,8 +2416,8 @@ int convert_setup(vimconv_T *vcp, char_u *from, char_u *to) /// As convert_setup(), but only when from_unicode_is_utf8 is true will all /// "from" unicode charsets be considered utf-8. Same for "to". -int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, - char_u *to, bool to_unicode_is_utf8) +int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, char_u *to, + bool to_unicode_is_utf8) { int from_prop; int to_prop; @@ -2369,51 +2432,54 @@ int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, # endif *vcp = (vimconv_T)MBYTE_NONE_CONV; - /* No conversion when one of the names is empty or they are equal. */ + // No conversion when one of the names is empty or they are equal. if (from == NULL || *from == NUL || to == NULL || *to == NUL - || STRCMP(from, to) == 0) + || STRCMP(from, to) == 0) { return OK; + } from_prop = enc_canon_props(from); to_prop = enc_canon_props(to); - if (from_unicode_is_utf8) + if (from_unicode_is_utf8) { from_is_utf8 = from_prop & ENC_UNICODE; - else + } else { from_is_utf8 = from_prop == ENC_UNICODE; - if (to_unicode_is_utf8) + } + if (to_unicode_is_utf8) { to_is_utf8 = to_prop & ENC_UNICODE; - else + } else { to_is_utf8 = to_prop == ENC_UNICODE; + } if ((from_prop & ENC_LATIN1) && to_is_utf8) { - /* Internal latin1 -> utf-8 conversion. */ + // Internal latin1 -> utf-8 conversion. vcp->vc_type = CONV_TO_UTF8; - vcp->vc_factor = 2; /* up to twice as long */ + vcp->vc_factor = 2; // up to twice as long } else if ((from_prop & ENC_LATIN9) && to_is_utf8) { - /* Internal latin9 -> utf-8 conversion. */ + // Internal latin9 -> utf-8 conversion. vcp->vc_type = CONV_9_TO_UTF8; - vcp->vc_factor = 3; /* up to three as long (euro sign) */ + vcp->vc_factor = 3; // up to three as long (euro sign) } else if (from_is_utf8 && (to_prop & ENC_LATIN1)) { - /* Internal utf-8 -> latin1 conversion. */ + // Internal utf-8 -> latin1 conversion. vcp->vc_type = CONV_TO_LATIN1; } else if (from_is_utf8 && (to_prop & ENC_LATIN9)) { - /* Internal utf-8 -> latin9 conversion. */ + // Internal utf-8 -> latin9 conversion. vcp->vc_type = CONV_TO_LATIN9; } # ifdef HAVE_ICONV else { // NOLINT(readability/braces) // Use iconv() for conversion. - vcp->vc_fd = (iconv_t)my_iconv_open( - to_is_utf8 ? (char_u *)"utf-8" : to, - from_is_utf8 ? (char_u *)"utf-8" : from); + vcp->vc_fd = (iconv_t)my_iconv_open(to_is_utf8 ? (char_u *)"utf-8" : to, + from_is_utf8 ? (char_u *)"utf-8" : from); if (vcp->vc_fd != (iconv_t)-1) { vcp->vc_type = CONV_ICONV; - vcp->vc_factor = 4; /* could be longer too... */ + vcp->vc_factor = 4; // could be longer too... } } # endif - if (vcp->vc_type == CONV_NONE) + if (vcp->vc_type == CONV_NONE) { return FAIL; + } return OK; } @@ -2435,129 +2501,153 @@ char_u *string_convert(const vimconv_T *const vcp, char_u *ptr, size_t *lenp) * 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) +char_u * string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp, + size_t *unconvlenp) { - char_u *retval = NULL; - char_u *d; + char_u *retval = NULL; + char_u *d; int l; int c; size_t len; - if (lenp == NULL) + if (lenp == NULL) { len = STRLEN(ptr); - else + } else { len = *lenp; - if (len == 0) + } + if (len == 0) { return vim_strsave((char_u *)""); + } switch (vcp->vc_type) { - case CONV_TO_UTF8: /* latin1 to utf-8 conversion */ - retval = xmalloc(len * 2 + 1); - d = retval; - for (size_t i = 0; i < len; ++i) { - c = ptr[i]; - if (c < 0x80) - *d++ = c; - else { - *d++ = 0xc0 + ((unsigned)c >> 6); - *d++ = 0x80 + (c & 0x3f); - } + case CONV_TO_UTF8: // latin1 to utf-8 conversion + retval = xmalloc(len * 2 + 1); + d = retval; + for (size_t i = 0; i < len; ++i) { + c = ptr[i]; + if (c < 0x80) { + *d++ = c; + } else { + *d++ = 0xc0 + ((unsigned)c >> 6); + *d++ = 0x80 + (c & 0x3f); } - *d = NUL; - if (lenp != NULL) - *lenp = (size_t)(d - retval); - break; + } + *d = NUL; + if (lenp != NULL) { + *lenp = (size_t)(d - retval); + } + break; - case CONV_9_TO_UTF8: /* latin9 to utf-8 conversion */ - retval = xmalloc(len * 3 + 1); - d = retval; - for (size_t i = 0; i < len; ++i) { - c = ptr[i]; - switch (c) { - case 0xa4: c = 0x20ac; break; /* euro */ - case 0xa6: c = 0x0160; break; /* S hat */ - case 0xa8: c = 0x0161; break; /* S -hat */ - case 0xb4: c = 0x017d; break; /* Z hat */ - case 0xb8: c = 0x017e; break; /* Z -hat */ - case 0xbc: c = 0x0152; break; /* OE */ - case 0xbd: c = 0x0153; break; /* oe */ - case 0xbe: c = 0x0178; break; /* Y */ - } - d += utf_char2bytes(c, d); + case CONV_9_TO_UTF8: // latin9 to utf-8 conversion + retval = xmalloc(len * 3 + 1); + d = retval; + for (size_t i = 0; i < len; ++i) { + c = ptr[i]; + switch (c) { + case 0xa4: + c = 0x20ac; break; // euro + case 0xa6: + c = 0x0160; break; // S hat + case 0xa8: + c = 0x0161; break; // S -hat + case 0xb4: + c = 0x017d; break; // Z hat + case 0xb8: + c = 0x017e; break; // Z -hat + case 0xbc: + c = 0x0152; break; // OE + case 0xbd: + c = 0x0153; break; // oe + case 0xbe: + c = 0x0178; break; // Y } - *d = NUL; - if (lenp != NULL) - *lenp = (size_t)(d - retval); - break; + d += utf_char2bytes(c, d); + } + *d = NUL; + if (lenp != NULL) { + *lenp = (size_t)(d - retval); + } + break; - case CONV_TO_LATIN1: /* utf-8 to latin1 conversion */ - case CONV_TO_LATIN9: /* utf-8 to latin9 conversion */ - retval = xmalloc(len + 1); - d = retval; - for (size_t i = 0; i < len; ++i) { - l = utf_ptr2len_len(ptr + i, len - i); - if (l == 0) - *d++ = NUL; - else if (l == 1) { - uint8_t l_w = utf8len_tab_zero[ptr[i]]; - - if (l_w == 0) { - /* Illegal utf-8 byte cannot be converted */ + case CONV_TO_LATIN1: // utf-8 to latin1 conversion + case CONV_TO_LATIN9: // utf-8 to latin9 conversion + retval = xmalloc(len + 1); + d = retval; + for (size_t i = 0; i < len; ++i) { + l = utf_ptr2len_len(ptr + i, len - i); + if (l == 0) { + *d++ = NUL; + } else if (l == 1) { + uint8_t l_w = utf8len_tab_zero[ptr[i]]; + + if (l_w == 0) { + // Illegal utf-8 byte cannot be converted + xfree(retval); + return NULL; + } + if (unconvlenp != NULL && l_w > len - i) { + // Incomplete sequence at the end. + *unconvlenp = len - i; + break; + } + *d++ = ptr[i]; + } else { + c = utf_ptr2char(ptr + i); + if (vcp->vc_type == CONV_TO_LATIN9) { + switch (c) { + case 0x20ac: + c = 0xa4; break; // euro + case 0x0160: + c = 0xa6; break; // S hat + case 0x0161: + c = 0xa8; break; // S -hat + case 0x017d: + c = 0xb4; break; // Z hat + case 0x017e: + c = 0xb8; break; // Z -hat + case 0x0152: + c = 0xbc; break; // OE + case 0x0153: + c = 0xbd; break; // oe + case 0x0178: + c = 0xbe; break; // Y + case 0xa4: + case 0xa6: + case 0xa8: + case 0xb4: + case 0xb8: + case 0xbc: + case 0xbd: + case 0xbe: + c = 0x100; break; // not in latin9 + } + } + if (!utf_iscomposing(c)) { // skip composing chars + if (c < 0x100) { + *d++ = c; + } else if (vcp->vc_fail) { xfree(retval); return NULL; - } - if (unconvlenp != NULL && l_w > len - i) { - /* Incomplete sequence at the end. */ - *unconvlenp = len - i; - break; - } - *d++ = ptr[i]; - } else { - c = utf_ptr2char(ptr + i); - if (vcp->vc_type == CONV_TO_LATIN9) - switch (c) { - case 0x20ac: c = 0xa4; break; /* euro */ - case 0x0160: c = 0xa6; break; /* S hat */ - case 0x0161: c = 0xa8; break; /* S -hat */ - case 0x017d: c = 0xb4; break; /* Z hat */ - case 0x017e: c = 0xb8; break; /* Z -hat */ - case 0x0152: c = 0xbc; break; /* OE */ - case 0x0153: c = 0xbd; break; /* oe */ - case 0x0178: c = 0xbe; break; /* Y */ - case 0xa4: - case 0xa6: - case 0xa8: - case 0xb4: - case 0xb8: - case 0xbc: - case 0xbd: - case 0xbe: c = 0x100; break; /* not in latin9 */ - } - if (!utf_iscomposing(c)) { /* skip composing chars */ - if (c < 0x100) - *d++ = c; - else if (vcp->vc_fail) { - xfree(retval); - return NULL; - } else { - *d++ = 0xbf; - if (utf_char2cells(c) > 1) - *d++ = '?'; + } else { + *d++ = 0xbf; + if (utf_char2cells(c) > 1) { + *d++ = '?'; } } - i += l - 1; } + i += l - 1; } - *d = NUL; - if (lenp != NULL) - *lenp = (size_t)(d - retval); - break; + } + *d = NUL; + if (lenp != NULL) { + *lenp = (size_t)(d - retval); + } + break; # ifdef HAVE_ICONV - case CONV_ICONV: // conversion with vcp->vc_fd - retval = iconv_string(vcp, ptr, len, unconvlenp, lenp); - break; + case CONV_ICONV: // conversion with vcp->vc_fd + retval = iconv_string(vcp, ptr, len, unconvlenp, lenp); + break; # endif } diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index 6c25525936..c4fa269851 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -228,10 +228,6 @@ retnomove: redraw_curbuf_later(INVERTED); // delete the inversion } - - row -= curwin->w_winrow; - col -= curwin->w_wincol; - // When clicking beyond the end of the window, scroll the screen. // Scroll by however many rows outside the window we are. if (row < 0) { @@ -723,14 +719,20 @@ int mouse_check_fold(void) int click_row = mouse_row; int click_col = mouse_col; int mouse_char = ' '; + int max_row = Rows; + int max_col = Columns; + int multigrid = ui_has(kUIMultigrid); win_T *wp; wp = mouse_find_win(&click_grid, &click_row, &click_col); + if (wp && multigrid) { + max_row = wp->w_grid_alloc.Rows; + max_col = wp->w_grid_alloc.Columns; + } - if (wp && mouse_row >= 0 && mouse_row < Rows - && mouse_col >= 0 && mouse_col <= Columns) { - int multigrid = ui_has(kUIMultigrid); + if (wp && mouse_row >= 0 && mouse_row < max_row + && mouse_col >= 0 && mouse_col < max_col) { ScreenGrid *gp = multigrid ? &wp->w_grid_alloc : &default_grid; int fdc = win_fdccol_count(wp); int row = multigrid && mouse_grid == 0 ? click_row : mouse_row; diff --git a/src/nvim/move.c b/src/nvim/move.c index 09815d1e6a..21cbac4d79 100644 --- a/src/nvim/move.c +++ b/src/nvim/move.c @@ -788,11 +788,12 @@ void curs_columns( wp->w_wcol -= n * width; wp->w_wrow += n; - /* When cursor wraps to first char of next line in Insert - * mode, the 'showbreak' string isn't shown, backup to first - * column */ - if (*p_sbr && *get_cursor_pos_ptr() == NUL - && wp->w_wcol == (int)vim_strsize(p_sbr)) { + // When cursor wraps to first char of next line in Insert + // mode, the 'showbreak' string isn't shown, backup to first + // column + char_u *const sbr = get_showbreak_value(wp); + if (*sbr && *get_cursor_pos_ptr() == NUL + && wp->w_wcol == (int)vim_strsize(sbr)) { wp->w_wcol = 0; } } diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 4c3d7d58de..74aaed87c1 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -9,14 +9,12 @@ #include <assert.h> #include <inttypes.h> -#include <string.h> #include <stdbool.h> #include <stdlib.h> +#include <string.h> -#include "nvim/log.h" -#include "nvim/vim.h" +#include "nvim/api/private/helpers.h" #include "nvim/ascii.h" -#include "nvim/normal.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" @@ -25,6 +23,7 @@ #include "nvim/digraph.h" #include "nvim/edit.h" #include "nvim/eval/userfunc.h" +#include "nvim/event/loop.h" #include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" @@ -34,35 +33,35 @@ #include "nvim/getchar.h" #include "nvim/indent.h" #include "nvim/indent_c.h" +#include "nvim/keymap.h" +#include "nvim/log.h" #include "nvim/main.h" #include "nvim/mark.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/keymap.h" -#include "nvim/move.h" #include "nvim/mouse.h" +#include "nvim/move.h" +#include "nvim/normal.h" #include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/time.h" #include "nvim/plines.h" #include "nvim/quickfix.h" #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/spell.h" #include "nvim/spellfile.h" +#include "nvim/state.h" #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/tag.h" #include "nvim/ui.h" -#include "nvim/mouse.h" #include "nvim/undo.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/state.h" -#include "nvim/event/loop.h" -#include "nvim/os/time.h" -#include "nvim/os/input.h" -#include "nvim/api/private/helpers.h" typedef struct normal_state { VimState state; @@ -88,10 +87,10 @@ typedef struct normal_state { /* * The Visual area is remembered for reselection. */ -static int resel_VIsual_mode = NUL; /* 'v', 'V', or Ctrl-V */ -static linenr_T resel_VIsual_line_count; /* number of lines */ -static colnr_T resel_VIsual_vcol; /* nr of cols or end col */ -static int VIsual_mode_orig = NUL; /* saved Visual mode */ +static int resel_VIsual_mode = NUL; // 'v', 'V', or Ctrl-V +static linenr_T resel_VIsual_line_count; // number of lines +static colnr_T resel_VIsual_vcol; // nr of cols or end col +static int VIsual_mode_orig = NUL; // saved Visual mode #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -119,18 +118,18 @@ static char *e_noident = N_("E349: No identifier under cursor"); */ typedef void (*nv_func_T)(cmdarg_T *cap); -/* Values for cmd_flags. */ -#define NV_NCH 0x01 /* may need to get a second char */ -#define NV_NCH_NOP (0x02|NV_NCH) /* get second char when no operator pending */ -#define NV_NCH_ALW (0x04|NV_NCH) /* always get a second char */ -#define NV_LANG 0x08 /* second char needs language adjustment */ +// Values for cmd_flags. +#define NV_NCH 0x01 // may need to get a second char +#define NV_NCH_NOP (0x02|NV_NCH) // get second char when no operator pending +#define NV_NCH_ALW (0x04|NV_NCH) // always get a second char +#define NV_LANG 0x08 // second char needs language adjustment -#define NV_SS 0x10 /* may start selection */ -#define NV_SSS 0x20 /* may start selection with shift modifier */ -#define NV_STS 0x40 /* may stop selection without shift modif. */ -#define NV_RL 0x80 /* 'rightleft' modifies command */ -#define NV_KEEPREG 0x100 /* don't clear regname */ -#define NV_NCW 0x200 /* not allowed in command-line window */ +#define NV_SS 0x10 // may start selection +#define NV_SSS 0x20 // may start selection with shift modifier +#define NV_STS 0x40 // may stop selection without shift modif. +#define NV_RL 0x80 // 'rightleft' modifies command +#define NV_KEEPREG 0x100 // don't clear regname +#define NV_NCW 0x200 // not allowed in command-line window /* * Generally speaking, every Normal mode command should either clear any @@ -148,10 +147,10 @@ typedef void (*nv_func_T)(cmdarg_T *cap); * It is faster when all keys from zero to '~' are present. */ static const struct nv_cmd { - int cmd_char; /* (first) command character */ - nv_func_T cmd_func; /* function for this command */ - uint16_t cmd_flags; /* NV_ flags */ - short cmd_arg; /* value for ca.arg */ + int cmd_char; // (first) command character + nv_func_T cmd_func; // function for this command + uint16_t cmd_flags; // NV_ flags + short cmd_arg; // value for ca.arg } nv_cmds[] = { { NUL, nv_error, 0, 0 }, @@ -344,10 +343,10 @@ static const struct nv_cmd { { K_COMMAND, nv_colon, 0, 0 }, }; -/* Number of commands in nv_cmds[]. */ +// Number of commands in nv_cmds[]. #define NV_CMDS_SIZE ARRAY_SIZE(nv_cmds) -/* Sorted index of commands in nv_cmds[]. */ +// Sorted index of commands in nv_cmds[]. static short nv_cmd_idx[NV_CMDS_SIZE]; /* The highest index for which @@ -362,13 +361,15 @@ static int nv_compare(const void *s1, const void *s2) { int c1, c2; - /* The commands are sorted on absolute value. */ + // The commands are sorted on absolute value. c1 = nv_cmds[*(const short *)s1].cmd_char; c2 = nv_cmds[*(const short *)s2].cmd_char; - if (c1 < 0) + if (c1 < 0) { c1 = -c1; - if (c2 < 0) + } + if (c2 < 0) { c2 = -c2; + } return c1 - c2; } @@ -379,15 +380,15 @@ void init_normal_cmds(void) { assert(NV_CMDS_SIZE <= SHRT_MAX); - /* Fill the index table with a one to one relation. */ + // Fill the index table with a one to one relation. for (short int i = 0; i < (short int)NV_CMDS_SIZE; ++i) { nv_cmd_idx[i] = i; } - /* Sort the commands by the command character. */ + // Sort the commands by the command character. qsort(&nv_cmd_idx, NV_CMDS_SIZE, sizeof(short), nv_compare); - /* Find the first entry that can't be indexed by the command character. */ + // Find the first entry that can't be indexed by the command character. short int i; for (i = 0; i < (short int)NV_CMDS_SIZE; ++i) { if (i != nv_cmds[nv_cmd_idx[i]].cmd_char) { @@ -408,38 +409,43 @@ static int find_command(int cmdchar) int top, bot; int c; - /* A multi-byte character is never a command. */ - if (cmdchar >= 0x100) + // A multi-byte character is never a command. + if (cmdchar >= 0x100) { return -1; + } /* We use the absolute value of the character. Special keys have a * negative value, but are sorted on their absolute value. */ - if (cmdchar < 0) + if (cmdchar < 0) { cmdchar = -cmdchar; + } /* If the character is in the first part: The character is the index into * nv_cmd_idx[]. */ assert(nv_max_linear < (int)NV_CMDS_SIZE); - if (cmdchar <= nv_max_linear) + if (cmdchar <= nv_max_linear) { return nv_cmd_idx[cmdchar]; + } - /* Perform a binary search. */ + // Perform a binary search. bot = nv_max_linear + 1; top = NV_CMDS_SIZE - 1; idx = -1; while (bot <= top) { i = (top + bot) / 2; c = nv_cmds[nv_cmd_idx[i]].cmd_char; - if (c < 0) + if (c < 0) { c = -c; + } if (cmdchar == c) { idx = nv_cmd_idx[i]; break; } - if (cmdchar > c) + if (cmdchar > c) { bot = i + 1; - else + } else { top = i - 1; + } } return idx; } @@ -544,59 +550,60 @@ static bool normal_need_additional_char(NormalState *s) int cmdchar = s->ca.cmdchar; // without NV_NCH we never need to check for an additional char return flags & NV_NCH && ( - // NV_NCH_NOP is set and no operator is pending, get a second char - ((flags & NV_NCH_NOP) == NV_NCH_NOP && !pending_op) - // NV_NCH_ALW is set, always get a second char - || (flags & NV_NCH_ALW) == NV_NCH_ALW - // 'q' without a pending operator, recording or executing a register, - // needs to be followed by a second char, examples: - // - qc => record using register c - // - q: => open command-line window - || (cmdchar == 'q' - && !pending_op - && reg_recording == 0 - && reg_executing == 0) - // 'a' or 'i' after an operator is a text object, examples: - // - ciw => change inside word - // - da( => delete parenthesis and everything inside. - // Also, don't do anything when these keys are received in visual mode - // so just get another char. - // - // TODO(tarruda): Visual state needs to be refactored into a - // separate state that "inherits" from normal state. - || ((cmdchar == 'a' || cmdchar == 'i') && (pending_op || VIsual_active))); + // NV_NCH_NOP is set and no operator is pending, get a second char + ((flags & NV_NCH_NOP) == NV_NCH_NOP && !pending_op) + // NV_NCH_ALW is set, always get a second char + || (flags & NV_NCH_ALW) == NV_NCH_ALW + // 'q' without a pending operator, recording or executing a register, + // needs to be followed by a second char, examples: + // - qc => record using register c + // - q: => open command-line window + || (cmdchar == 'q' + && !pending_op + && reg_recording == 0 + && reg_executing == 0) + // 'a' or 'i' after an operator is a text object, examples: + // - ciw => change inside word + // - da( => delete parenthesis and everything inside. + // Also, don't do anything when these keys are received in visual mode + // so just get another char. + // + // TODO(tarruda): Visual state needs to be refactored into a + // separate state that "inherits" from normal state. + || ((cmdchar == 'a' || cmdchar == 'i') && + (pending_op || VIsual_active))); } static bool normal_need_redraw_mode_message(NormalState *s) { return ( - // 'showmode' is set and messages can be printed - ((p_smd && msg_silent == 0 - // must restart insert mode(ctrl+o or ctrl+l) or we just entered visual - // mode - && (restart_edit != 0 || (VIsual_active - && s->old_pos.lnum == curwin->w_cursor.lnum - && s->old_pos.col == curwin->w_cursor.col)) - // command-line must be cleared or redrawn - && (clear_cmdline || redraw_cmdline) - // some message was printed or scrolled - && (msg_didout || (msg_didany && msg_scroll)) - // it is fine to remove the current message - && !msg_nowait - // the command was the result of direct user input and not a mapping - && KeyTyped) - // must restart insert mode, not in visual mode and error message is - // being shown - || (restart_edit != 0 && !VIsual_active && msg_scroll - && emsg_on_display)) - // no register was used - && s->oa.regname == 0 - && !(s->ca.retval & CA_COMMAND_BUSY) - && stuff_empty() - && typebuf_typed() - && emsg_silent == 0 - && !did_wait_return - && s->oa.op_type == OP_NOP); + // 'showmode' is set and messages can be printed + ((p_smd && msg_silent == 0 + // must restart insert mode(ctrl+o or ctrl+l) or we just entered visual + // mode + && (restart_edit != 0 || (VIsual_active + && s->old_pos.lnum == curwin->w_cursor.lnum + && s->old_pos.col == curwin->w_cursor.col)) + // command-line must be cleared or redrawn + && (clear_cmdline || redraw_cmdline) + // some message was printed or scrolled + && (msg_didout || (msg_didany && msg_scroll)) + // it is fine to remove the current message + && !msg_nowait + // the command was the result of direct user input and not a mapping + && KeyTyped) + // must restart insert mode, not in visual mode and error message is + // being shown + || (restart_edit != 0 && !VIsual_active && msg_scroll + && emsg_on_display)) + // no register was used + && s->oa.regname == 0 + && !(s->ca.retval & CA_COMMAND_BUSY) + && stuff_empty() + && typebuf_typed() + && emsg_silent == 0 + && !did_wait_return + && s->oa.op_type == OP_NOP); } static void normal_redraw_mode_message(NormalState *s) @@ -611,7 +618,7 @@ static void normal_redraw_mode_message(NormalState *s) // If need to redraw, and there is a "keep_msg", redraw before the // delay if (must_redraw && keep_msg != NULL && !emsg_on_display) { - char_u *kmsg; + char_u *kmsg; kmsg = keep_msg; keep_msg = NULL; @@ -707,7 +714,7 @@ static void normal_get_additional_char(NormalState *s) if (!lit) { // Typing CTRL-K gets a digraph. if (*cp == Ctrl_K && ((nv_cmds[s->idx].cmd_flags & NV_LANG) - || cp == &s->ca.extra_char) + || cp == &s->ca.extra_char) && vim_strchr(p_cpo, CPO_DIGRAPH) == NULL) { s->c = get_digraph(false); if (s->c > 0) { @@ -735,7 +742,7 @@ static void normal_get_additional_char(NormalState *s) s->ca.nchar = s->ca.extra_char; s->idx = find_command(s->ca.cmdchar); } else if ((s->ca.nchar == 'n' || s->ca.nchar == 'N') - && s->ca.cmdchar == 'g') { + && s->ca.cmdchar == 'g') { s->ca.oap->op_type = get_op_type(*cp, NUL); } else if (*cp == Ctrl_BSL) { long towait = (p_ttm >= 0 ? p_ttm : p_tm); @@ -769,7 +776,7 @@ static void normal_get_additional_char(NormalState *s) && (s->c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1)) { s->c = plain_vgetc(); if (!utf_iscomposing(s->c)) { - vungetc(s->c); /* it wasn't, put it back */ + vungetc(s->c); // it wasn't, put it back break; } else if (s->ca.ncharC1 == 0) { s->ca.ncharC1 = s->c; @@ -785,16 +792,26 @@ static void normal_get_additional_char(NormalState *s) static void normal_invert_horizontal(NormalState *s) { switch (s->ca.cmdchar) { - case 'l': s->ca.cmdchar = 'h'; break; - case K_RIGHT: s->ca.cmdchar = K_LEFT; break; - case K_S_RIGHT: s->ca.cmdchar = K_S_LEFT; break; - case K_C_RIGHT: s->ca.cmdchar = K_C_LEFT; break; - case 'h': s->ca.cmdchar = 'l'; break; - case K_LEFT: s->ca.cmdchar = K_RIGHT; break; - case K_S_LEFT: s->ca.cmdchar = K_S_RIGHT; break; - case K_C_LEFT: s->ca.cmdchar = K_C_RIGHT; break; - case '>': s->ca.cmdchar = '<'; break; - case '<': s->ca.cmdchar = '>'; break; + case 'l': + s->ca.cmdchar = 'h'; break; + case K_RIGHT: + s->ca.cmdchar = K_LEFT; break; + case K_S_RIGHT: + s->ca.cmdchar = K_S_LEFT; break; + case K_C_RIGHT: + s->ca.cmdchar = K_C_LEFT; break; + case 'h': + s->ca.cmdchar = 'l'; break; + case K_LEFT: + s->ca.cmdchar = K_RIGHT; break; + case K_S_LEFT: + s->ca.cmdchar = K_S_RIGHT; break; + case K_C_LEFT: + s->ca.cmdchar = K_C_RIGHT; break; + case '>': + s->ca.cmdchar = '<'; break; + case '<': + s->ca.cmdchar = '>'; break; } s->idx = find_command(s->ca.cmdchar); } @@ -808,7 +825,7 @@ static bool normal_get_command_count(NormalState *s) // Note that '0' is a command and not the start of a count, but it's // part of a count after other digits. while ((s->c >= '1' && s->c <= '9') || (s->ca.count0 != 0 - && (s->c == K_DEL || s->c == K_KDEL || s->c == '0'))) { + && (s->c == K_DEL || s->c == K_KDEL || s->c == '0'))) { if (s->c == K_DEL || s->c == K_KDEL) { s->ca.count0 /= 10; del_from_showcmd(4); // delete the digit and ~@% @@ -941,11 +958,11 @@ normal_end: // if still inside a mapping that started in Visual mode). // May switch from Visual to Select mode after CTRL-O command. if (s->oa.op_type == OP_NOP - && ((restart_edit != 0 && !VIsual_active && s->old_mapped_len == 0) - || restart_VIsual_select == 1) - && !(s->ca.retval & CA_COMMAND_BUSY) - && stuff_empty() - && s->oa.regname == 0) { + && ((restart_edit != 0 && !VIsual_active && s->old_mapped_len == 0) + || restart_VIsual_select == 1) + && !(s->ca.retval & CA_COMMAND_BUSY) + && stuff_empty() + && s->oa.regname == 0) { if (restart_VIsual_select == 1) { VIsual_select = true; showmode(); @@ -968,7 +985,7 @@ static int normal_execute(VimState *state, int key) { NormalState *s = (NormalState *)state; s->command_finished = false; - s->ctrl_w = false; /* got CTRL-W command */ + s->ctrl_w = false; // got CTRL-W command s->old_col = curwin->w_curswant; s->c = key; @@ -980,7 +997,7 @@ static int normal_execute(VimState *state, int key) if (restart_edit == 0) { s->old_mapped_len = 0; } else if (s->old_mapped_len || (VIsual_active && s->mapped_len == 0 - && typebuf_maplen() > 0)) { + && typebuf_maplen() > 0)) { s->old_mapped_len = typebuf_maplen(); } @@ -990,7 +1007,7 @@ static int normal_execute(VimState *state, int key) // In Select mode, typed text replaces the selection. if (VIsual_active && VIsual_select && (vim_isprintc(s->c) - || s->c == NL || s->c == CAR || s->c == K_KENTER)) { + || s->c == NL || s->c == CAR || s->c == K_KENTER)) { // Fake a "c"hange command. When "restart_edit" is set (e.g., because // 'insertmode' is set) fake a "d"elete command, Insert mode will // restart automatically. @@ -1008,14 +1025,14 @@ static int normal_execute(VimState *state, int key) s->need_flushbuf = add_to_showcmd(s->c); - while (normal_get_command_count(s)) continue; + while (normal_get_command_count(s)) { continue; } if (s->c == K_EVENT) { // Save the count values so that ca.opcount and ca.count0 are exactly // the same when coming back here after handling K_EVENT. s->oa.prev_opcount = s->ca.opcount; s->oa.prev_count0 = s->ca.count0; - } else if (s->ca.opcount != 0) { + } else if (s->ca.opcount != 0) { // If we're in the middle of an operator (including after entering a // yank buffer with '"') AND we had a count before the operator, then // that count overrides the current value of ca.count0. @@ -1427,18 +1444,19 @@ static void set_vcount_ca(cmdarg_T *cap, bool *set_prevcount) { long count = cap->count0; - /* multiply with cap->opcount the same way as above */ - if (cap->opcount != 0) + // multiply with cap->opcount the same way as above + if (cap->opcount != 0) { count = cap->opcount * (count == 0 ? 1 : count); + } set_vcount(count, count == 0 ? 1 : count, *set_prevcount); - *set_prevcount = false; /* only set v:prevcount once */ + *set_prevcount = false; // only set v:prevcount once } // Handle an operator after Visual mode or when the movement is finished. // "gui_yank" is true when yanking text for the clipboard. void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) { - oparg_T *oap = cap->oap; + oparg_T *oap = cap->oap; pos_T old_cursor; bool empty_region_error; int restart_edit_save; @@ -1508,12 +1526,11 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) && oap->op_type != OP_FOLDCLOSE && oap->op_type != OP_FOLDCLOSEREC && oap->op_type != OP_FOLDDEL - && oap->op_type != OP_FOLDDELREC - ) { + && oap->op_type != OP_FOLDDELREC) { prep_redo(oap->regname, cap->count0, - get_op_char(oap->op_type), get_extra_op_char(oap->op_type), - oap->motion_force, cap->cmdchar, cap->nchar); - if (cap->cmdchar == '/' || cap->cmdchar == '?') { /* was a search */ + get_op_char(oap->op_type), get_extra_op_char(oap->op_type), + oap->motion_force, cap->cmdchar, cap->nchar); + if (cap->cmdchar == '/' || cap->cmdchar == '?') { // was a search /* * If 'cpoptions' does not contain 'r', insert the search * pattern to really repeat the same command. @@ -1541,8 +1558,9 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) * redo_VIsual_line_count and redo_VIsual_vcol. */ oap->start = curwin->w_cursor; curwin->w_cursor.lnum += redo_VIsual_line_count - 1; - if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) + if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; + } VIsual_mode = redo_VIsual_mode; if (redo_VIsual_vcol == MAXCOL || VIsual_mode == 'v') { if (VIsual_mode == 'v') { @@ -1550,8 +1568,9 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) validate_virtcol(); curwin->w_curswant = curwin->w_virtcol + redo_VIsual_vcol - 1; - } else + } else { curwin->w_curswant = redo_VIsual_vcol; + } } else { curwin->w_curswant = MAXCOL; } @@ -1561,7 +1580,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) cap->count1 = (cap->count0 == 0 ? 1 : cap->count0); } else if (VIsual_active) { if (!gui_yank) { - /* Save the current VIsual area for '< and '> marks, and "gv" */ + // Save the current VIsual area for '< and '> marks, and "gv" curbuf->b_visual.vi_start = VIsual; curbuf->b_visual.vi_end = curwin->w_cursor; curbuf->b_visual.vi_mode = VIsual_mode; @@ -1607,10 +1626,11 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) * to the end of the operated text. w_cursor is equal to oap->start. */ if (lt(oap->start, curwin->w_cursor)) { - /* Include folded lines completely. */ + // Include folded lines completely. if (!VIsual_active) { - if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL)) + if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL)) { oap->start.col = 0; + } if ((curwin->w_cursor.col > 0 || oap->inclusive || oap->motion_type == kMTLineWise) @@ -1645,7 +1665,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) check_pos(curwin->w_buffer, &oap->end); oap->line_count = oap->end.lnum - oap->start.lnum + 1; - /* Set "virtual_op" before resetting VIsual_active. */ + // Set "virtual_op" before resetting VIsual_active. virtual_op = virtual_active(); if (VIsual_active || redo_VIsual_busy) { @@ -1657,19 +1677,22 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) * size of the Visual text */ resel_VIsual_mode = VIsual_mode; - if (curwin->w_curswant == MAXCOL) + if (curwin->w_curswant == MAXCOL) { resel_VIsual_vcol = MAXCOL; - else { - if (VIsual_mode != Ctrl_V) + } else { + if (VIsual_mode != Ctrl_V) { getvvcol(curwin, &(oap->end), - NULL, NULL, &oap->end_vcol); + NULL, NULL, &oap->end_vcol); + } if (VIsual_mode == Ctrl_V || oap->line_count <= 1) { - if (VIsual_mode != Ctrl_V) + if (VIsual_mode != Ctrl_V) { getvvcol(curwin, &(oap->start), - &oap->start_vcol, NULL, NULL); + &oap->start_vcol, NULL, NULL); + } resel_VIsual_vcol = oap->end_vcol - oap->start_vcol + 1; - } else + } else { resel_VIsual_vcol = oap->end_vcol; + } } resel_VIsual_line_count = oap->line_count; } @@ -1684,8 +1707,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) && oap->op_type != OP_FOLDCLOSEREC && oap->op_type != OP_FOLDDEL && oap->op_type != OP_FOLDDELREC - && oap->motion_force == NUL - ) { + && oap->motion_force == NUL) { /* Prepare for redoing. Only use the nchar field for "r", * otherwise it might be the second char of the operator. */ if (cap->cmdchar == 'g' && (cap->nchar == 'n' @@ -1725,8 +1747,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) } else if (VIsual_mode == 'v') { oap->motion_type = kMTCharWise; if (*ml_get_pos(&(oap->end)) == NUL - && (include_line_break || !virtual_op) - ) { + && (include_line_break || !virtual_op)) { oap->inclusive = false; // Try to include the newline, unless it's an operator // that works on lines only. @@ -1828,22 +1849,24 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) oap->inclusive = true; } } - } else + } else { oap->end_adjusted = false; + } switch (oap->op_type) { case OP_LSHIFT: case OP_RSHIFT: op_shift(oap, true, - oap->is_VIsual ? (int)cap->count1 : - 1); + oap->is_VIsual ? (int)cap->count1 : + 1); auto_format(false, true); break; case OP_JOIN_NS: case OP_JOIN: - if (oap->line_count < 2) + if (oap->line_count < 2) { oap->line_count = 2; + } if (curwin->w_cursor.lnum + oap->line_count - 1 > curbuf->b_ml.ml_line_count) { beep_flush(); @@ -1855,7 +1878,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) break; case OP_DELETE: - VIsual_reselect = false; /* don't reselect now */ + VIsual_reselect = false; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); @@ -1885,7 +1908,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) break; case OP_CHANGE: - VIsual_reselect = false; /* don't reselect now */ + VIsual_reselect = false; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); @@ -1894,10 +1917,11 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) * remember it to make 'insertmode' work with mappings for * Visual mode. But do this only once and not when typed and * 'insertmode' isn't set. */ - if (p_im || !KeyTyped) + if (p_im || !KeyTyped) { restart_edit_save = restart_edit; - else + } else { restart_edit_save = 0; + } restart_edit = 0; // Restore linebreak, so that when the user edits it looks as before. @@ -1905,10 +1929,12 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) // Reset finish_op now, don't want it set inside edit(). finish_op = false; - if (op_change(oap)) /* will call edit() */ + if (op_change(oap)) { // will call edit() cap->retval |= CA_COMMAND_BUSY; - if (restart_edit == 0) + } + if (restart_edit == 0) { restart_edit = restart_edit_save; + } } break; @@ -1932,8 +1958,8 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) break; } op_reindent(oap, - *curbuf->b_p_inde != NUL ? get_expr_indent : - get_c_indent); + *curbuf->b_p_inde != NUL ? get_expr_indent : + get_c_indent); break; } @@ -1947,8 +1973,9 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); - } else + } else { op_tilde(oap); + } check_cursor_col(); break; @@ -1965,7 +1992,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) break; case OP_FORMAT2: - op_format(oap, true); /* use internal function */ + op_format(oap, true); // use internal function break; case OP_FUNCTION: @@ -1977,7 +2004,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) case OP_INSERT: case OP_APPEND: - VIsual_reselect = false; /* don't reselect now */ + VIsual_reselect = false; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); @@ -2009,7 +2036,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank) break; case OP_REPLACE: - VIsual_reselect = false; /* don't reselect now */ + VIsual_reselect = false; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); @@ -2141,10 +2168,10 @@ static void op_function(const oparg_T *oap) { const TriState save_virtual_op = virtual_op; - if (*p_opfunc == NUL) + if (*p_opfunc == NUL) { EMSG(_("E774: 'operatorfunc' is empty")); - else { - /* Set '[ and '] marks to text to be operated on. */ + } else { + // Set '[ and '] marks to text to be operated on. curbuf->b_op_start = oap->start; curbuf->b_op_end = oap->end; if (oap->motion_type != kMTLineWise && !oap->inclusive) { @@ -2157,10 +2184,10 @@ static void op_function(const oparg_T *oap) argv[1].v_type = VAR_UNKNOWN; argv[0].vval.v_string = (char_u *)(((const char *const[]) { - [kMTBlockWise] = "block", - [kMTLineWise] = "line", - [kMTCharWise] = "char", - })[oap->motion_type]); + [kMTBlockWise] = "block", + [kMTLineWise] = "line", + [kMTCharWise] = "char", + })[oap->motion_type]); // Reset virtual_op so that 'virtualedit' can be changed in the // function. @@ -2178,73 +2205,69 @@ static void move_tab_to_mouse(void) { int tabnr = tab_page_click_defs[mouse_col].tabnr; if (tabnr <= 0) { - tabpage_move(9999); + tabpage_move(9999); } else if (tabnr < tabpage_index(curtab)) { - tabpage_move(tabnr - 1); + tabpage_move(tabnr - 1); } else { - tabpage_move(tabnr); - } -} - -/* - * Do the appropriate action for the current mouse click in the current mode. - * Not used for Command-line mode. - * - * Normal Mode: - * event modi- position visual change action - * fier cursor window - * left press - yes end yes - * left press C yes end yes "^]" (2) - * left press S yes end yes "*" (2) - * left drag - yes start if moved no - * left relse - yes start if moved no - * middle press - yes if not active no put register - * middle press - yes if active no yank and put - * right press - yes start or extend yes - * right press S yes no change yes "#" (2) - * right drag - yes extend no - * right relse - yes extend no - * - * Insert or Replace Mode: - * event modi- position visual change action - * fier cursor window - * left press - yes (cannot be active) yes - * left press C yes (cannot be active) yes "CTRL-O^]" (2) - * left press S yes (cannot be active) yes "CTRL-O*" (2) - * left drag - yes start or extend (1) no CTRL-O (1) - * left relse - yes start or extend (1) no CTRL-O (1) - * middle press - no (cannot be active) no put register - * right press - yes start or extend yes CTRL-O - * right press S yes (cannot be active) yes "CTRL-O#" (2) - * - * (1) only if mouse pointer moved since press - * (2) only if click is in same buffer - * - * Return true if start_arrow() should be called for edit mode. - */ -bool -do_mouse ( - oparg_T *oap, /* operator argument, can be NULL */ - int c, /* K_LEFTMOUSE, etc */ - int dir, /* Direction to 'put' if necessary */ - long count, - bool fixindent /* PUT_FIXINDENT if fixing indent necessary */ -) -{ - static bool got_click = false; /* got a click some time back */ - - int which_button; /* MOUSE_LEFT, _MIDDLE or _RIGHT */ - bool is_click; /* If false it's a drag or release event */ - bool is_drag; /* If true it's a drag event */ - int jump_flags = 0; /* flags for jump_to_mouse() */ + tabpage_move(tabnr); + } +} + +/// Do the appropriate action for the current mouse click in the current mode. +/// Not used for Command-line mode. +/// +/// Normal Mode: +/// event modi- position visual change action +/// fier cursor window +/// left press - yes end yes +/// left press C yes end yes "^]" (2) +/// left press S yes end yes "*" (2) +/// left drag - yes start if moved no +/// left relse - yes start if moved no +/// middle press - yes if not active no put register +/// middle press - yes if active no yank and put +/// right press - yes start or extend yes +/// right press S yes no change yes "#" (2) +/// right drag - yes extend no +/// right relse - yes extend no +/// +/// Insert or Replace Mode: +/// event modi- position visual change action +/// fier cursor window +/// left press - yes (cannot be active) yes +/// left press C yes (cannot be active) yes "CTRL-O^]" (2) +/// left press S yes (cannot be active) yes "CTRL-O*" (2) +/// left drag - yes start or extend (1) no CTRL-O (1) +/// left relse - yes start or extend (1) no CTRL-O (1) +/// middle press - no (cannot be active) no put register +/// right press - yes start or extend yes CTRL-O +/// right press S yes (cannot be active) yes "CTRL-O#" (2) +/// +/// (1) only if mouse pointer moved since press +/// (2) only if click is in same buffer +/// +/// @param oap operator argument, can be NULL +/// @param c K_LEFTMOUSE, etc +/// @param dir Direction to 'put' if necessary +/// @param fixindent PUT_FIXINDENT if fixing indent necessary +/// +/// @return true if start_arrow() should be called for edit mode. +bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent) +{ + static bool got_click = false; // got a click some time back + + int which_button; // MOUSE_LEFT, _MIDDLE or _RIGHT + bool is_click; // If false it's a drag or release event + bool is_drag; // If true it's a drag event + int jump_flags = 0; // flags for jump_to_mouse() pos_T start_visual; - bool moved; /* Has cursor moved? */ - bool in_status_line; /* mouse in status line */ - static bool in_tab_line = false; /* mouse clicked in tab line */ - bool in_sep_line; /* mouse in vertical separator line */ + bool moved; // Has cursor moved? + bool in_status_line; // mouse in status line + static bool in_tab_line = false; // mouse clicked in tab line + bool in_sep_line; // mouse in vertical separator line int c1, c2; pos_T save_cursor; - win_T *old_curwin = curwin; + win_T *old_curwin = curwin; static pos_T orig_cursor; colnr_T leftcol, rightcol; pos_T end_visual; @@ -2269,8 +2292,9 @@ do_mouse ( /* Need to get the character, peeking doesn't get the actual * one. */ nc = safe_vgetc(); - if (c == nc) + if (c == nc) { continue; + } vungetc(nc); mouse_grid = save_mouse_grid; mouse_row = save_mouse_row; @@ -2288,12 +2312,13 @@ do_mouse ( /* * Ignore drag and release events if we didn't get a click. */ - if (is_click) + if (is_click) { got_click = true; - else { - if (!got_click) /* didn't get click, ignore */ + } else { + if (!got_click) { // didn't get click, ignore return false; - if (!is_drag) { /* release, reset got_click */ + } + if (!is_drag) { // release, reset got_click got_click = false; if (in_tab_line) { in_tab_line = false; @@ -2307,20 +2332,23 @@ do_mouse ( * CTRL right mouse button does CTRL-T */ if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT) { - if (State & INSERT) + if (State & INSERT) { stuffcharReadbuff(Ctrl_O); - if (count > 1) + } + if (count > 1) { stuffnumReadbuff(count); + } stuffcharReadbuff(Ctrl_T); - got_click = false; /* ignore drag&release now */ + got_click = false; // ignore drag&release now return false; } /* * CTRL only works with left mouse button */ - if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT) + if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT) { return false; + } /* * When a modifier is down, ignore drag and release events, as well as @@ -2337,22 +2365,24 @@ do_mouse ( && which_button == MOUSE_LEFT) && !((mod_mask & MOD_MASK_ALT) && !mouse_model_popup() - && which_button == MOUSE_RIGHT) - ) + && which_button == MOUSE_RIGHT)) { return false; + } /* * If the button press was used as the movement command for an operator * (eg "d<MOUSE>"), or it is the middle button that is held down, ignore * drag/release events. */ - if (!is_click && which_button == MOUSE_MIDDLE) + if (!is_click && which_button == MOUSE_MIDDLE) { return false; + } - if (oap != NULL) + if (oap != NULL) { regname = oap->regname; - else + } else { regname = 0; + } /* * Middle mouse button does a 'put' of the selected text @@ -2386,8 +2416,9 @@ do_mouse ( /* * The rest is below jump_to_mouse() */ - } else if ((State & INSERT) == 0) + } else if ((State & INSERT) == 0) { return false; + } /* * Middle click in insert mode doesn't move the mouse, just insert the @@ -2409,7 +2440,7 @@ do_mouse ( do_put(regname, NULL, BACKWARD, 1L, (fixindent ? PUT_FIXINDENT : 0) | PUT_CURSEND); - /* Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r */ + // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r AppendCharToRedobuff(Ctrl_R); AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O); AppendCharToRedobuff(regname == 0 ? '"' : regname); @@ -2419,9 +2450,10 @@ do_mouse ( } } - /* When dragging or button-up stay in the same window. */ - if (!is_click) + // When dragging or button-up stay in the same window. + if (!is_click) { jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE; + } start_visual.lnum = 0; @@ -2434,17 +2466,17 @@ do_mouse ( return false; } - /* click in a tab selects that tab page */ + // click in a tab selects that tab page if (is_click && cmdwin_type == 0 && mouse_col < Columns) { in_tab_line = true; c1 = tab_page_click_defs[mouse_col].tabnr; switch (tab_page_click_defs[mouse_col].type) { - case kStlClickDisabled: { + case kStlClickDisabled: { break; } - case kStlClickTabClose: { + case kStlClickTabClose: { tabpage_T *tp; // Close the current or specified tab page. @@ -2462,7 +2494,7 @@ do_mouse ( } break; } - case kStlClickTabSwitch: { + case kStlClickTabSwitch: { if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) { // double click opens new page end_visual_mode(); @@ -2480,13 +2512,13 @@ do_mouse ( } break; } - case kStlClickFuncRun: { + case kStlClickFuncRun: { typval_T argv[] = { { .v_lock = VAR_FIXED, .v_type = VAR_NUMBER, .vval = { - .v_number = (varnumber_T) tab_page_click_defs[mouse_col].tabnr + .v_number = (varnumber_T)tab_page_click_defs[mouse_col].tabnr }, }, { @@ -2508,7 +2540,7 @@ do_mouse ( { .v_lock = VAR_FIXED, .v_type = VAR_STRING, - .vval = { .v_string = (char_u *) (which_button == MOUSE_LEFT + .vval = { .v_string = (char_u *)(which_button == MOUSE_LEFT ? "l" : which_button == MOUSE_RIGHT ? "r" @@ -2521,10 +2553,10 @@ do_mouse ( .v_type = VAR_STRING, .vval = { .v_string = (char_u[]) { - (char_u) (mod_mask & MOD_MASK_SHIFT ? 's' : ' '), - (char_u) (mod_mask & MOD_MASK_CTRL ? 'c' : ' '), - (char_u) (mod_mask & MOD_MASK_ALT ? 'a' : ' '), - (char_u) (mod_mask & MOD_MASK_META ? 'm' : ' '), + (char_u)(mod_mask & MOD_MASK_SHIFT ? 's' : ' '), + (char_u)(mod_mask & MOD_MASK_CTRL ? 'c' : ' '), + (char_u)(mod_mask & MOD_MASK_ALT ? 'a' : ' '), + (char_u)(mod_mask & MOD_MASK_META ? 'm' : ' '), NUL } }, @@ -2577,8 +2609,9 @@ do_mouse ( if (is_click) { /* stop Visual mode for a left click in a window, but not when * on a status line */ - if (VIsual_active) + if (VIsual_active) { jump_flags |= MOUSE_MAY_STOP_VIS; + } } else { jump_flags |= MOUSE_MAY_VIS; } @@ -2610,9 +2643,10 @@ do_mouse ( oap->motion_type = kMTCharWise; } - /* When releasing the button let jump_to_mouse() know. */ - if (!is_click && !is_drag) + // When releasing the button let jump_to_mouse() know. + if (!is_click && !is_drag) { jump_flags |= MOUSE_RELEASED; + } /* * JUMP! @@ -2628,8 +2662,9 @@ do_mouse ( /* When jumping to another window, clear a pending operator. That's a bit * friendlier than beeping and not jumping to that window. */ - if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP) + if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP) { clearop(oap); + } if (mod_mask == 0 && !is_drag @@ -2659,16 +2694,17 @@ do_mouse ( } } - /* When dragging the mouse above the window, scroll down. */ + // When dragging the mouse above the window, scroll down. if (is_drag && mouse_row < 0 && !in_status_line) { scroll_redraw(false, 1L); mouse_row = 0; } - if (start_visual.lnum) { /* right click in visual mode */ - /* When ALT is pressed make Visual mode blockwise. */ - if (mod_mask & MOD_MASK_ALT) + if (start_visual.lnum) { // right click in visual mode + // When ALT is pressed make Visual mode blockwise. + if (mod_mask & MOD_MASK_ALT) { VIsual_mode = Ctrl_V; + } /* * In Visual-block mode, divide the area in four, pick up the corner @@ -2676,55 +2712,58 @@ do_mouse ( */ if (VIsual_mode == Ctrl_V) { getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol); - if (curwin->w_curswant > (leftcol + rightcol) / 2) + if (curwin->w_curswant > (leftcol + rightcol) / 2) { end_visual.col = leftcol; - else + } else { end_visual.col = rightcol; + } if (curwin->w_cursor.lnum >= (start_visual.lnum + end_visual.lnum) / 2) { end_visual.lnum = start_visual.lnum; } - /* move VIsual to the right column */ - start_visual = curwin->w_cursor; /* save the cursor pos */ + // move VIsual to the right column + start_visual = curwin->w_cursor; // save the cursor pos curwin->w_cursor = end_visual; coladvance(end_visual.col); VIsual = curwin->w_cursor; - curwin->w_cursor = start_visual; /* restore the cursor */ + curwin->w_cursor = start_visual; // restore the cursor } else { /* * If the click is before the start of visual, change the start. * If the click is after the end of visual, change the end. If * the click is inside the visual, change the closest side. */ - if (lt(curwin->w_cursor, start_visual)) + if (lt(curwin->w_cursor, start_visual)) { VIsual = end_visual; - else if (lt(end_visual, curwin->w_cursor)) + } else if (lt(end_visual, curwin->w_cursor)) { VIsual = start_visual; - else { - /* In the same line, compare column number */ + } else { + // In the same line, compare column number if (end_visual.lnum == start_visual.lnum) { if (curwin->w_cursor.col - start_visual.col > - end_visual.col - curwin->w_cursor.col) + end_visual.col - curwin->w_cursor.col) { VIsual = start_visual; - else + } else { VIsual = end_visual; + } } - /* In different lines, compare line number */ + // In different lines, compare line number else { diff = (curwin->w_cursor.lnum - start_visual.lnum) - (end_visual.lnum - curwin->w_cursor.lnum); - if (diff > 0) /* closest to end */ + if (diff > 0) { // closest to end VIsual = start_visual; - else if (diff < 0) /* closest to start */ + } else if (diff < 0) { // closest to start VIsual = end_visual; - else { /* in the middle line */ + } else { // in the middle line if (curwin->w_cursor.col < - (start_visual.col + end_visual.col) / 2) + (start_visual.col + end_visual.col) / 2) { VIsual = end_visual; - else + } else { VIsual = start_visual; + } } } } @@ -2733,8 +2772,9 @@ do_mouse ( /* * If Visual mode started in insert mode, execute "CTRL-O" */ - else if ((State & INSERT) && VIsual_active) + else if ((State & INSERT) && VIsual_active) { stuffcharReadbuff(Ctrl_O); + } /* * Middle mouse click: Put text before cursor. @@ -2744,10 +2784,12 @@ do_mouse ( regname = '*'; } if (yank_register_mline(regname)) { - if (mouse_past_bottom) + if (mouse_past_bottom) { dir = FORWARD; - } else if (mouse_past_eol) + } + } else if (mouse_past_eol) { dir = FORWARD; + } if (fixindent) { c1 = (dir == BACKWARD) ? '[' : ']'; @@ -2762,8 +2804,9 @@ do_mouse ( * Remember where the paste started, so in edit() Insstart can be set * to this position */ - if (restart_edit != 0) + if (restart_edit != 0) { where_paste_started = curwin->w_cursor; + } do_put(regname, NULL, dir, count, (fixindent ? PUT_FIXINDENT : 0)| PUT_CURSEND); } @@ -2789,10 +2832,11 @@ do_mouse ( && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)) { - if (State & INSERT) + if (State & INSERT) { stuffcharReadbuff(Ctrl_O); + } stuffcharReadbuff(Ctrl_RSB); - got_click = false; /* ignore drag&release now */ + got_click = false; // ignore drag&release now } /* * Shift-Mouse click searches for the next occurrence of the word under @@ -2800,15 +2844,16 @@ do_mouse ( */ else if ((mod_mask & MOD_MASK_SHIFT)) { if (State & INSERT - || (VIsual_active && VIsual_select) - ) + || (VIsual_active && VIsual_select)) { stuffcharReadbuff(Ctrl_O); - if (which_button == MOUSE_LEFT) + } + if (which_button == MOUSE_LEFT) { stuffcharReadbuff('*'); - else /* MOUSE_RIGHT */ + } else { // MOUSE_RIGHT stuffcharReadbuff('#'); + } } - /* Handle double clicks, unless on status line */ + // Handle double clicks, unless on status line else if (in_status_line) { } else if (in_sep_line) { } else if ((mod_mask & MOD_MASK_MULTI_CLICK) && (State & (NORMAL | INSERT))) { @@ -2820,26 +2865,28 @@ do_mouse ( orig_cursor = VIsual; VIsual_active = true; VIsual_reselect = true; - /* start Select mode if 'selectmode' contains "mouse" */ + // start Select mode if 'selectmode' contains "mouse" may_start_select('o'); setmouse(); } if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) { - /* Double click with ALT pressed makes it blockwise. */ - if (mod_mask & MOD_MASK_ALT) + // Double click with ALT pressed makes it blockwise. + if (mod_mask & MOD_MASK_ALT) { VIsual_mode = Ctrl_V; - else + } else { VIsual_mode = 'v'; - } else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK) + } + } else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK) { VIsual_mode = 'V'; - else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK) + } else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK) { VIsual_mode = Ctrl_V; + } } /* * A double click selects a word or a block. */ if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) { - pos_T *pos = NULL; + pos_T *pos = NULL; int gc; if (is_click) { @@ -2847,8 +2894,9 @@ do_mouse ( * not a word character, try finding a match and select a (), * {}, [], #if/#endif, etc. block. */ end_visual = curwin->w_cursor; - while (gc = gchar_pos(&end_visual), ascii_iswhite(gc)) + while (gc = gchar_pos(&end_visual), ascii_iswhite(gc)) { inc(&end_visual); + } if (oap != NULL) { oap->motion_type = kMTCharWise; } @@ -2878,28 +2926,32 @@ do_mouse ( find_end_of_word(&VIsual); } else { find_start_of_word(&VIsual); - if (*p_sel == 'e' && *get_cursor_pos_ptr() != NUL) + if (*p_sel == 'e' && *get_cursor_pos_ptr() != NUL) { curwin->w_cursor.col += (*mb_ptr2len)(get_cursor_pos_ptr()); + } find_end_of_word(&curwin->w_cursor); } } curwin->w_set_curswant = true; } - if (is_click) - redraw_curbuf_later(INVERTED); /* update the inversion */ + if (is_click) { + redraw_curbuf_later(INVERTED); // update the inversion + } } else if (VIsual_active && !old_active) { - if (mod_mask & MOD_MASK_ALT) + if (mod_mask & MOD_MASK_ALT) { VIsual_mode = Ctrl_V; - else + } else { VIsual_mode = 'v'; + } } - /* If Visual mode changed show it later. */ + // If Visual mode changed show it later. if ((!VIsual_active && old_active && mode_displayed) || (VIsual_active && p_smd && msg_silent == 0 - && (!old_active || VIsual_mode != old_mode))) + && (!old_active || VIsual_mode != old_mode))) { redraw_cmdline = true; + } return moved; } @@ -2909,7 +2961,7 @@ do_mouse ( */ static void find_start_of_word(pos_T *pos) { - char_u *line; + char_u *line; int cclass; int col; @@ -2932,7 +2984,7 @@ static void find_start_of_word(pos_T *pos) */ static void find_end_of_word(pos_T *pos) { - char_u *line; + char_u *line; int cclass; int col; @@ -2945,8 +2997,9 @@ static void find_end_of_word(pos_T *pos) while (line[pos->col] != NUL) { col = pos->col + (*mb_ptr2len)(line + pos->col); if (get_mouse_class(line + col) != cclass) { - if (*p_sel == 'e') + if (*p_sel == 'e') { pos->col = col; + } break; } pos->col = col; @@ -2980,8 +3033,9 @@ static int get_mouse_class(char_u *p) * "->", "/ *", "*=", "+=", "&=", "<=", ">=", "!=" etc. Otherwise, each * character is in its own class. */ - if (c != NUL && vim_strchr((char_u *)"-+*/%<>&|^!=", c) != NULL) + if (c != NUL && vim_strchr((char_u *)"-+*/%<>&|^!=", c) != NULL) { return 1; + } return c; } @@ -2992,19 +3046,19 @@ static int get_mouse_class(char_u *p) */ void end_visual_mode(void) { - VIsual_active = false; setmouse(); mouse_dragging = 0; - /* Save the current VIsual area for '< and '> marks, and "gv" */ + // Save the current VIsual area for '< and '> marks, and "gv" curbuf->b_visual.vi_mode = VIsual_mode; curbuf->b_visual.vi_start = VIsual; curbuf->b_visual.vi_end = curwin->w_cursor; curbuf->b_visual.vi_curswant = curwin->w_curswant; curbuf->b_visual_mode_eval = VIsual_mode; - if (!virtual_active()) + if (!virtual_active()) { curwin->w_cursor.coladd = 0; + } may_clear_cmdline(); @@ -3018,7 +3072,7 @@ void reset_VIsual_and_resel(void) { if (VIsual_active) { end_visual_mode(); - redraw_curbuf_later(INVERTED); /* delete the inversion later */ + redraw_curbuf_later(INVERTED); // delete the inversion later } VIsual_reselect = false; } @@ -3030,7 +3084,7 @@ void reset_VIsual(void) { if (VIsual_active) { end_visual_mode(); - redraw_curbuf_later(INVERTED); /* delete the inversion later */ + redraw_curbuf_later(INVERTED); // delete the inversion later VIsual_reselect = false; } } @@ -3041,11 +3095,8 @@ void reset_VIsual(void) // "dir" is FORWARD or BACKWARD, the direction of searching. // "*colp" is in/decremented if "ptr[-dir]" should also be included. // "bnp" points to a counter for square brackets. -static bool find_is_eval_item( - const char_u *const ptr, - int *const colp, - int *const bnp, - const int dir) +static bool find_is_eval_item(const char_u *const ptr, int *const colp, int *const bnp, + const int dir) { // Accept everything inside []. if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD)) { @@ -3098,17 +3149,12 @@ size_t find_ident_under_cursor(char_u **text, int find_type) curwin->w_cursor.col, text, NULL, find_type); } -/* - * Like find_ident_under_cursor(), but for any window and any position. - * However: Uses 'iskeyword' from the current window!. - */ -size_t find_ident_at_pos( - win_T *wp, - linenr_T lnum, - colnr_T startcol, - char_u **text, - int *textcol, // column where "text" starts, can be NULL - int find_type) +/// Like find_ident_under_cursor(), but for any window and any position. +/// However: Uses 'iskeyword' from the current window!. +/// +/// @param textcol column where "text" starts, can be NULL +size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char_u **text, int *textcol, + int find_type) FUNC_ATTR_NONNULL_ARG(1, 4) { int col = 0; // init to shut up GCC @@ -3214,7 +3260,7 @@ size_t find_ident_at_pos( static void prep_redo_cmd(cmdarg_T *cap) { prep_redo(cap->oap->regname, cap->count0, - NUL, cap->cmdchar, NUL, NUL, cap->nchar); + NUL, cap->cmdchar, NUL, NUL, cap->nchar); } /* @@ -3224,23 +3270,29 @@ static void prep_redo_cmd(cmdarg_T *cap) static void prep_redo(int regname, long num, int cmd1, int cmd2, int cmd3, int cmd4, int cmd5) { ResetRedobuff(); - if (regname != 0) { /* yank from specified buffer */ + if (regname != 0) { // yank from specified buffer AppendCharToRedobuff('"'); AppendCharToRedobuff(regname); } - if (num) + if (num) { AppendNumberToRedobuff(num); + } - if (cmd1 != NUL) + if (cmd1 != NUL) { AppendCharToRedobuff(cmd1); - if (cmd2 != NUL) + } + if (cmd2 != NUL) { AppendCharToRedobuff(cmd2); - if (cmd3 != NUL) + } + if (cmd3 != NUL) { AppendCharToRedobuff(cmd3); - if (cmd4 != NUL) + } + if (cmd4 != NUL) { AppendCharToRedobuff(cmd4); - if (cmd5 != NUL) + } + if (cmd5 != NUL) { AppendCharToRedobuff(cmd5); + } } /* @@ -3250,8 +3302,9 @@ static void prep_redo(int regname, long num, int cmd1, int cmd2, int cmd3, int c */ static bool checkclearop(oparg_T *oap) { - if (oap->op_type == OP_NOP) + if (oap->op_type == OP_NOP) { return false; + } clearopbeep(oap); return true; } @@ -3264,9 +3317,9 @@ static bool checkclearop(oparg_T *oap) static bool checkclearopq(oparg_T *oap) { if (oap->op_type == OP_NOP - && !VIsual_active - ) + && !VIsual_active) { return false; + } clearopbeep(oap); return true; } @@ -3292,12 +3345,18 @@ static void clearopbeep(oparg_T *oap) static void unshift_special(cmdarg_T *cap) { switch (cap->cmdchar) { - case K_S_RIGHT: cap->cmdchar = K_RIGHT; break; - case K_S_LEFT: cap->cmdchar = K_LEFT; break; - case K_S_UP: cap->cmdchar = K_UP; break; - case K_S_DOWN: cap->cmdchar = K_DOWN; break; - case K_S_HOME: cap->cmdchar = K_HOME; break; - case K_S_END: cap->cmdchar = K_END; break; + case K_S_RIGHT: + cap->cmdchar = K_RIGHT; break; + case K_S_LEFT: + cap->cmdchar = K_LEFT; break; + case K_S_UP: + cap->cmdchar = K_UP; break; + case K_S_DOWN: + cap->cmdchar = K_DOWN; break; + case K_S_HOME: + cap->cmdchar = K_HOME; break; + case K_S_END: + cap->cmdchar = K_END; break; } cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask); } @@ -3317,15 +3376,16 @@ static void may_clear_cmdline(void) // Routines for displaying a partly typed command # define SHOWCMD_BUFLEN SHOWCMD_COLS + 1 + 30 static char_u showcmd_buf[SHOWCMD_BUFLEN]; -static char_u old_showcmd_buf[SHOWCMD_BUFLEN]; /* For push_showcmd() */ +static char_u old_showcmd_buf[SHOWCMD_BUFLEN]; // For push_showcmd() static bool showcmd_is_clear = true; static bool showcmd_visual = false; void clear_showcmd(void) { - if (!p_sc) + if (!p_sc) { return; + } if (VIsual_active && !char_avail()) { int cursor_bot = lt(VIsual, curwin->w_cursor); @@ -3333,7 +3393,7 @@ void clear_showcmd(void) colnr_T leftcol, rightcol; linenr_T top, bot; - /* Show the size of the Visual area. */ + // Show the size of the Visual area. if (cursor_bot) { top = VIsual.lnum; bot = curwin->w_cursor.lnum; @@ -3347,18 +3407,21 @@ void clear_showcmd(void) lines = bot - top + 1; if (VIsual_mode == Ctrl_V) { - char_u *saved_sbr = p_sbr; + char_u *const saved_sbr = p_sbr; + char_u *const saved_w_sbr = curwin->w_p_sbr; - /* Make 'sbr' empty for a moment to get the correct size. */ + // Make 'sbr' empty for a moment to get the correct size. p_sbr = empty_option; + curwin->w_p_sbr = empty_option; getvcols(curwin, &curwin->w_cursor, &VIsual, &leftcol, &rightcol); p_sbr = saved_sbr; + curwin->w_p_sbr = saved_w_sbr; snprintf((char *)showcmd_buf, SHOWCMD_BUFLEN, "%" PRId64 "x%" PRId64, (int64_t)lines, (int64_t)rightcol - leftcol + 1); } else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum) { snprintf((char *)showcmd_buf, SHOWCMD_BUFLEN, "%" PRId64, (int64_t)lines); } else { - char_u *s, *e; + char_u *s, *e; int l; int bytes = 0; int chars = 0; @@ -3375,16 +3438,17 @@ void clear_showcmd(void) if (l == 0) { ++bytes; ++chars; - break; /* end of line */ + break; // end of line } bytes += l; ++chars; s += l; } - if (bytes == chars) + if (bytes == chars) { sprintf((char *)showcmd_buf, "%d", chars); - else + } else { sprintf((char *)showcmd_buf, "%d-%d", chars, bytes); + } } int limit = ui_has(kUIMessages) ? SHOWCMD_BUFLEN-1 : SHOWCMD_COLS; showcmd_buf[limit] = NUL; // truncate @@ -3393,9 +3457,10 @@ void clear_showcmd(void) showcmd_buf[0] = NUL; showcmd_visual = false; - /* Don't actually display something if there is nothing to clear. */ - if (showcmd_is_clear) + // Don't actually display something if there is nothing to clear. + if (showcmd_is_clear) { return; + } } display_showcmd(); @@ -3407,7 +3472,7 @@ void clear_showcmd(void) */ bool add_to_showcmd(int c) { - char_u *p; + char_u *p; int i; static int ignore[] = { @@ -3421,23 +3486,28 @@ bool add_to_showcmd(int c) 0 }; - if (!p_sc || msg_silent != 0) + if (!p_sc || msg_silent != 0) { return false; + } if (showcmd_visual) { showcmd_buf[0] = NUL; showcmd_visual = false; } - /* Ignore keys that are scrollbar updates and mouse clicks */ - if (IS_SPECIAL(c)) - for (i = 0; ignore[i] != 0; ++i) - if (ignore[i] == c) + // Ignore keys that are scrollbar updates and mouse clicks + if (IS_SPECIAL(c)) { + for (i = 0; ignore[i] != 0; ++i) { + if (ignore[i] == c) { return false; + } + } + } p = transchar(c); - if (*p == ' ') + if (*p == ' ') { STRCPY(p, "<20>"); + } size_t old_len = STRLEN(showcmd_buf); size_t extra_len = STRLEN(p); size_t limit = ui_has(kUIMessages) ? SHOWCMD_BUFLEN-1 : SHOWCMD_COLS; @@ -3447,8 +3517,9 @@ bool add_to_showcmd(int c) } STRCAT(showcmd_buf, p); - if (char_avail()) + if (char_avail()) { return false; + } display_showcmd(); @@ -3468,16 +3539,19 @@ static void del_from_showcmd(int len) { int old_len; - if (!p_sc) + if (!p_sc) { return; + } old_len = (int)STRLEN(showcmd_buf); - if (len > old_len) + if (len > old_len) { len = old_len; + } showcmd_buf[old_len - len] = NUL; - if (!char_avail()) + if (!char_avail()) { display_showcmd(); + } } /* @@ -3486,14 +3560,16 @@ static void del_from_showcmd(int len) */ void push_showcmd(void) { - if (p_sc) + if (p_sc) { STRCPY(old_showcmd_buf, showcmd_buf); + } } void pop_showcmd(void) { - if (!p_sc) + if (!p_sc) { return; + } STRCPY(showcmd_buf, old_showcmd_buf); @@ -3542,18 +3618,18 @@ static void display_showcmd(void) */ void do_check_scrollbind(bool check) { - static win_T *old_curwin = NULL; + static win_T *old_curwin = NULL; static linenr_T old_topline = 0; static int old_topfill = 0; - static buf_T *old_buf = NULL; + static buf_T *old_buf = NULL; static colnr_T old_leftcol = 0; if (check && curwin->w_p_scb) { /* If a ":syncbind" command was just used, don't scroll, only reset * the values. */ - if (did_syncbind) + if (did_syncbind) { did_syncbind = false; - else if (curwin == old_curwin) { + } else if (curwin == old_curwin) { /* * Synchronize other windows, as necessary according to * 'scrollbind'. Don't do this after an ":edit" command, except @@ -3566,9 +3642,9 @@ void do_check_scrollbind(bool check) || curwin->w_topfill != old_topfill || curwin->w_leftcol != old_leftcol)) { check_scrollbind(curwin->w_topline - old_topline, - (long)(curwin->w_leftcol - old_leftcol)); + (long)(curwin->w_leftcol - old_leftcol)); } - } else if (vim_strchr(p_sbo, 'j')) { /* jump flag set in 'scrollopt' */ + } else if (vim_strchr(p_sbo, 'j')) { // jump flag set in 'scrollopt' /* * When switching between windows, make sure that the relative * vertical offset is valid for the new window. The relative @@ -3600,8 +3676,8 @@ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) { bool want_ver; bool want_hor; - win_T *old_curwin = curwin; - buf_T *old_curbuf = curbuf; + win_T *old_curwin = curwin; + buf_T *old_curbuf = curbuf; int old_VIsual_select = VIsual_select; int old_VIsual_active = VIsual_active; colnr_T tgt_leftcol = curwin->w_leftcol; @@ -3622,7 +3698,7 @@ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { curwin = wp; curbuf = curwin->w_buffer; - /* skip original window and windows with 'noscrollbind' */ + // skip original window and windows with 'noscrollbind' if (curwin == old_curwin || !curwin->w_p_scb) { continue; } @@ -3635,16 +3711,19 @@ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) } else { curwin->w_scbind_pos += topline_diff; topline = curwin->w_scbind_pos; - if (topline > curbuf->b_ml.ml_line_count) + if (topline > curbuf->b_ml.ml_line_count) { topline = curbuf->b_ml.ml_line_count; - if (topline < 1) + } + if (topline < 1) { topline = 1; + } y = topline - curwin->w_topline; - if (y > 0) + if (y > 0) { scrollup(y, false); - else + } else { scrolldown(-y, false); + } } redraw_later(curwin, VALID); @@ -3677,7 +3756,7 @@ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) */ static void nv_ignore(cmdarg_T *cap) { - cap->retval |= CA_COMMAND_BUSY; /* don't call edit() now */ + cap->retval |= CA_COMMAND_BUSY; // don't call edit() now } /* @@ -3701,8 +3780,9 @@ static void nv_error(cmdarg_T *cap) */ static void nv_help(cmdarg_T *cap) { - if (!checkclearopq(cap->oap)) + if (!checkclearopq(cap->oap)) { ex_help(NULL); + } } /* @@ -3731,25 +3811,22 @@ static void nv_page(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { if (mod_mask & MOD_MASK_CTRL) { - /* <C-PageUp>: tab page back; <C-PageDown>: tab page forward */ - if (cap->arg == BACKWARD) + // <C-PageUp>: tab page back; <C-PageDown>: tab page forward + if (cap->arg == BACKWARD) { goto_tabpage(-(int)cap->count1); - else + } else { goto_tabpage((int)cap->count0); - } else + } + } else { (void)onepage(cap->arg, cap->count1); + } } } -/* - * Implementation of "gd" and "gD" command. - */ -static void -nv_gd ( - oparg_T *oap, - int nchar, - int thisblock /* 1 for "1gd" and "1gD" */ -) +/// Implementation of "gd" and "gD" command. +/// +/// @param thisblock 1 for "1gd" and "1gD" +static void nv_gd(oparg_T *oap, int nchar, int thisblock) { size_t len; char_u *ptr; @@ -3794,23 +3871,17 @@ static bool is_ident(char_u *line, int offset) return incomment == false && instring == 0; } -/* - * Search for variable declaration of "ptr[len]". - * When "locally" is true in the current function ("gd"), otherwise in the - * current file ("gD"). - * When "thisblock" is true check the {} block scope. - * Return fail when not found. - */ -bool -find_decl ( - char_u *ptr, - size_t len, - bool locally, - bool thisblock, - int flags_arg // flags passed to searchit() -) -{ - char_u *pat; +/// Search for variable declaration of "ptr[len]". +/// When "locally" is true in the current function ("gd"), otherwise in the +/// current file ("gD"). +/// +/// @param thisblock when true check the {} block scope. +/// @param flags_arg flags passed to searchit() +/// +/// @return fail when not found. +bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_arg) +{ + char_u *pat; pos_T old_pos; pos_T par_pos; pos_T found_pos; @@ -3831,8 +3902,8 @@ find_decl ( old_pos = curwin->w_cursor; save_p_ws = p_ws; save_p_scs = p_scs; - p_ws = false; /* don't wrap around end of file now */ - p_scs = false; /* don't switch ignorecase off now */ + p_ws = false; // don't wrap around end of file now + p_scs = false; // don't switch ignorecase off now /* * With "gD" go to line 1. @@ -3840,18 +3911,19 @@ find_decl ( * back until a blank line. If this fails go to line 1. */ if (!locally || !findpar(&incll, BACKWARD, 1L, '{', false)) { - setpcmark(); /* Set in findpar() otherwise */ + setpcmark(); // Set in findpar() otherwise curwin->w_cursor.lnum = 1; par_pos = curwin->w_cursor; } else { par_pos = curwin->w_cursor; while (curwin->w_cursor.lnum > 1 - && *skipwhite(get_cursor_line_ptr()) != NUL) + && *skipwhite(get_cursor_line_ptr()) != NUL) { --curwin->w_cursor.lnum; + } } curwin->w_cursor.col = 0; - /* Search forward for the identifier, ignore comment lines. */ + // Search forward for the identifier, ignore comment lines. clearpos(&found_pos); for (;; ) { t = searchit(curwin, curbuf, &curwin->w_cursor, NULL, FORWARD, @@ -3875,7 +3947,7 @@ find_decl ( } if (t == false) { - /* If we previously found a valid position, use it. */ + // If we previously found a valid position, use it. if (found_pos.lnum != 0) { curwin->w_cursor = found_pos; t = true; @@ -3883,7 +3955,7 @@ find_decl ( break; } if (get_leader_len(get_cursor_line_ptr(), NULL, false, true) > 0) { - /* Ignore this line, continue at start of next line. */ + // Ignore this line, continue at start of next line. ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; continue; @@ -3925,7 +3997,7 @@ find_decl ( curwin->w_cursor = old_pos; } else { curwin->w_set_curswant = true; - /* "n" searches forward now */ + // "n" searches forward now reset_search_dir(); } @@ -3949,10 +4021,10 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) bool retval = true; bool atend = false; int n; - int col_off1; /* margin offset for first screen line */ - int col_off2; /* margin offset for wrapped screen line */ - int width1; /* text width for first screen line */ - int width2; /* test width for wrapped screen line */ + int col_off1; // margin offset for first screen line + int col_off2; // margin offset for wrapped screen line + int width1; // text width for first screen line + int width2; // test width for wrapped screen line oap->motion_type = kMTCharWise; oap->inclusive = (curwin->w_curswant == MAXCOL); @@ -3972,20 +4044,22 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) if (curwin->w_curswant == MAXCOL) { atend = true; validate_virtcol(); - if (width1 <= 0) + if (width1 <= 0) { curwin->w_curswant = 0; - else { + } else { curwin->w_curswant = width1 - 1; - if (curwin->w_virtcol > curwin->w_curswant) + if (curwin->w_virtcol > curwin->w_curswant) { curwin->w_curswant += ((curwin->w_virtcol - curwin->w_curswant - 1) / width2 + 1) * width2; + } } } else { - if (linelen > width1) + if (linelen > width1) { n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1; - else + } else { n = width1; + } if (curwin->w_curswant >= n) { curwin->w_curswant = n - 1; } @@ -4021,11 +4095,12 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) curwin->w_curswant += w; } } - } else { /* dir == FORWARD */ - if (linelen > width1) + } else { // dir == FORWARD + if (linelen > width1) { n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1; - else + } else { n = width1; + } if (curwin->w_curswant + width2 < (colnr_T)n && !hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { // move forward within line @@ -4055,10 +4130,11 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) } } - if (virtual_active() && atend) + if (virtual_active() && atend) { coladvance(MAXCOL); - else + } else { coladvance(curwin->w_curswant); + } if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { /* @@ -4068,20 +4144,22 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist) */ validate_virtcol(); colnr_T virtcol = curwin->w_virtcol; - if (virtcol > (colnr_T)width1 && *p_sbr != NUL) - virtcol -= vim_strsize(p_sbr); + if (virtcol > (colnr_T)width1 && *get_showbreak_value(curwin) != NUL) { + virtcol -= vim_strsize(get_showbreak_value(curwin)); + } if (virtcol > curwin->w_curswant && (curwin->w_curswant < (colnr_T)width1 ? (curwin->w_curswant > (colnr_T)width1 / 2) : ((curwin->w_curswant - width1) % width2 - > (colnr_T)width2 / 2))) + > (colnr_T)width2 / 2))) { --curwin->w_cursor.col; + } } - if (atend) - curwin->w_curswant = MAXCOL; /* stick in the last column */ - + if (atend) { + curwin->w_curswant = MAXCOL; // stick in the last column + } return retval; } @@ -4146,8 +4224,9 @@ static void nv_mouse(cmdarg_T *cap) */ static void nv_scroll_line(cmdarg_T *cap) { - if (!checkclearop(cap->oap)) + if (!checkclearop(cap->oap)) { scroll_redraw(cap->arg, cap->count1); + } } /* @@ -4160,8 +4239,8 @@ void scroll_redraw(int up, long count) linenr_T prev_lnum = curwin->w_cursor.lnum; bool moved = up ? - scrollup(count, true) : - scrolldown(count, true); + scrollup(count, true) : + scrolldown(count, true); if (get_scrolloff_value(curwin)) { // Adjust the cursor position for 'scrolloff'. Mark w_topline as @@ -4174,17 +4253,18 @@ void scroll_redraw(int up, long count) * we get stuck at one position. Don't move the cursor up if the * first line of the buffer is already on the screen */ while (curwin->w_topline == prev_topline - && curwin->w_topfill == prev_topfill - ) { + && curwin->w_topfill == prev_topfill) { if (up) { if (curwin->w_cursor.lnum > prev_lnum - || cursor_down(1L, false) == false) + || cursor_down(1L, false) == false) { break; + } } else { if (curwin->w_cursor.lnum < prev_lnum || prev_topline == 1L - || cursor_up(1L, false) == false) + || cursor_up(1L, false) == false) { break; + } } /* Mark w_topline as valid, otherwise the screen jumps back at the * end of the file. */ @@ -4220,8 +4300,9 @@ static void nv_zet(cmdarg_T *cap) /* * "z123{nchar}": edit the count before obtaining {nchar} */ - if (checkclearop(cap->oap)) + if (checkclearop(cap->oap)) { return; + } n = nchar - '0'; for (;; ) { no_mapping++; @@ -4229,11 +4310,11 @@ static void nv_zet(cmdarg_T *cap) LANGMAP_ADJUST(nchar, true); no_mapping--; (void)add_to_showcmd(nchar); - if (nchar == K_DEL || nchar == K_KDEL) + if (nchar == K_DEL || nchar == K_KDEL) { n /= 10; - else if (ascii_isdigit(nchar)) + } else if (ascii_isdigit(nchar)) { n = n * 10 + (nchar - '0'); - else if (nchar == CAR) { + } else if (nchar == CAR) { win_setheight(n); break; } else if (nchar == 'l' @@ -4270,15 +4351,16 @@ dozet: && cap->count0 && cap->count0 != curwin->w_cursor.lnum) { setpcmark(); - if (cap->count0 > curbuf->b_ml.ml_line_count) + if (cap->count0 > curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; - else + } else { curwin->w_cursor.lnum = cap->count0; + } check_cursor_col(); } switch (nchar) { - /* "z+", "z<CR>" and "zt": put cursor at top of screen */ + // "z+", "z<CR>" and "zt": put cursor at top of screen case '+': if (cap->count0 == 0) { // No count given: put cursor at the line below screen @@ -4296,16 +4378,19 @@ dozet: beginline(BL_WHITE | BL_FIX); FALLTHROUGH; - case 't': scroll_cursor_top(0, true); + case 't': + scroll_cursor_top(0, true); redraw_later(curwin, VALID); set_fraction(curwin); break; - /* "z." and "zz": put cursor in middle of screen */ - case '.': beginline(BL_WHITE | BL_FIX); - FALLTHROUGH; + // "z." and "zz": put cursor in middle of screen + case '.': + beginline(BL_WHITE | BL_FIX); + FALLTHROUGH; - case 'z': scroll_cursor_halfway(true); + case 'z': + scroll_cursor_halfway(true); redraw_later(curwin, VALID); set_fraction(curwin); break; @@ -4317,74 +4402,83 @@ dozet: if (cap->count0 != 0) { scroll_cursor_bot(0, true); curwin->w_cursor.lnum = curwin->w_topline; - } else if (curwin->w_topline == 1) + } else if (curwin->w_topline == 1) { curwin->w_cursor.lnum = 1; - else + } else { curwin->w_cursor.lnum = curwin->w_topline - 1; + } FALLTHROUGH; case '-': beginline(BL_WHITE | BL_FIX); FALLTHROUGH; - case 'b': scroll_cursor_bot(0, true); + case 'b': + scroll_cursor_bot(0, true); redraw_later(curwin, VALID); set_fraction(curwin); break; - /* "zH" - scroll screen right half-page */ + // "zH" - scroll screen right half-page case 'H': cap->count1 *= curwin->w_width_inner / 2; FALLTHROUGH; - /* "zh" - scroll screen to the right */ + // "zh" - scroll screen to the right case 'h': case K_LEFT: if (!curwin->w_p_wrap) { - if ((colnr_T)cap->count1 > curwin->w_leftcol) + if ((colnr_T)cap->count1 > curwin->w_leftcol) { curwin->w_leftcol = 0; - else + } else { curwin->w_leftcol -= (colnr_T)cap->count1; + } leftcol_changed(); } break; // "zL" - scroll screen left half-page - case 'L': cap->count1 *= curwin->w_width_inner / 2; + case 'L': + cap->count1 *= curwin->w_width_inner / 2; FALLTHROUGH; - /* "zl" - scroll screen to the left */ + // "zl" - scroll screen to the left case 'l': case K_RIGHT: if (!curwin->w_p_wrap) { - /* scroll the window left */ + // scroll the window left curwin->w_leftcol += (colnr_T)cap->count1; leftcol_changed(); } break; - /* "zs" - scroll screen, cursor at the start */ - case 's': if (!curwin->w_p_wrap) { - if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) - col = 0; /* like the cursor is in col 0 */ - else + // "zs" - scroll screen, cursor at the start + case 's': + if (!curwin->w_p_wrap) { + if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { + col = 0; // like the cursor is in col 0 + } else { getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL); - if (col > l_p_siso) + } + if (col > l_p_siso) { col -= l_p_siso; - else + } else { col = 0; + } if (curwin->w_leftcol != col) { curwin->w_leftcol = col; redraw_later(curwin, NOT_VALID); } - } + } break; - /* "ze" - scroll screen, cursor at the end */ - case 'e': if (!curwin->w_p_wrap) { - if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) - col = 0; /* like the cursor is in col 0 */ - else + // "ze" - scroll screen, cursor at the end + case 'e': + if (!curwin->w_p_wrap) { + if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { + col = 0; // like the cursor is in col 0 + } else { getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col); + } n = curwin->w_width_inner - curwin_col_off(); if (col + l_p_siso < n) { col = 0; @@ -4395,7 +4489,7 @@ dozet: curwin->w_leftcol = col; redraw_later(curwin, NOT_VALID); } - } + } break; // "zp", "zP" in block mode put without addind trailing spaces @@ -4404,41 +4498,46 @@ dozet: nv_put(cap); break; // "zy" Yank without trailing spaces - case 'y': nv_operator(cap); - break; + case 'y': + nv_operator(cap); + break; - /* "zF": create fold command */ - /* "zf": create fold operator */ + // "zF": create fold command + // "zf": create fold operator case 'F': - case 'f': if (foldManualAllowed(true)) { + case 'f': + if (foldManualAllowed(true)) { cap->nchar = 'f'; nv_operator(cap); curwin->w_p_fen = true; - /* "zF" is like "zfzf" */ + // "zF" is like "zfzf" if (nchar == 'F' && cap->oap->op_type == OP_FOLD) { nv_operator(cap); finish_op = true; } - } else + } else { clearopbeep(cap->oap); + } break; - /* "zd": delete fold at cursor */ - /* "zD": delete fold at cursor recursively */ + // "zd": delete fold at cursor + // "zD": delete fold at cursor recursively case 'd': - case 'D': if (foldManualAllowed(false)) { + case 'D': + if (foldManualAllowed(false)) { if (VIsual_active) { nv_operator(cap); } else { deleteFold(curwin, curwin->w_cursor.lnum, curwin->w_cursor.lnum, nchar == 'D', false); } - } + } break; - /* "zE": erase all folds */ - case 'E': if (foldmethodIsManual(curwin)) { + // "zE": erase all folds + case 'E': + if (foldmethodIsManual(curwin)) { clearFolding(curwin); changed_window_setting(); } else if (foldmethodIsMarker(curwin)) { @@ -4448,20 +4547,24 @@ dozet: } break; - /* "zn": fold none: reset 'foldenable' */ - case 'n': curwin->w_p_fen = false; + // "zn": fold none: reset 'foldenable' + case 'n': + curwin->w_p_fen = false; break; - /* "zN": fold Normal: set 'foldenable' */ - case 'N': curwin->w_p_fen = true; + // "zN": fold Normal: set 'foldenable' + case 'N': + curwin->w_p_fen = true; break; - /* "zi": invert folding: toggle 'foldenable' */ - case 'i': curwin->w_p_fen = !curwin->w_p_fen; + // "zi": invert folding: toggle 'foldenable' + case 'i': + curwin->w_p_fen = !curwin->w_p_fen; break; // "za": open closed fold or close open fold at cursor - case 'a': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { + case 'a': + if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { openFold(curwin->w_cursor, cap->count1); } else { closeFold(curwin->w_cursor, cap->count1); @@ -4470,7 +4573,8 @@ dozet: break; // "zA": open fold at cursor recursively - case 'A': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { + case 'A': + if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) { openFoldRecurse(curwin->w_cursor); } else { closeFoldRecurse(curwin->w_cursor); @@ -4479,7 +4583,8 @@ dozet: break; // "zo": open fold at cursor or Visual area - case 'o': if (VIsual_active) { + case 'o': + if (VIsual_active) { nv_operator(cap); } else { openFold(curwin->w_cursor, cap->count1); @@ -4487,7 +4592,8 @@ dozet: break; // "zO": open fold recursively - case 'O': if (VIsual_active) { + case 'O': + if (VIsual_active) { nv_operator(cap); } else { openFoldRecurse(curwin->w_cursor); @@ -4495,16 +4601,18 @@ dozet: break; // "zc": close fold at cursor or Visual area - case 'c': if (VIsual_active) { + case 'c': + if (VIsual_active) { nv_operator(cap); - } else { + } else { closeFold(curwin->w_cursor, cap->count1); } curwin->w_p_fen = true; break; // "zC": close fold recursively - case 'C': if (VIsual_active) { + case 'C': + if (VIsual_active) { nv_operator(cap); } else { closeFoldRecurse(curwin->w_cursor); @@ -4512,24 +4620,27 @@ dozet: curwin->w_p_fen = true; break; - /* "zv": open folds at the cursor */ - case 'v': foldOpenCursor(); + // "zv": open folds at the cursor + case 'v': + foldOpenCursor(); break; - /* "zx": re-apply 'foldlevel' and open folds at the cursor */ - case 'x': curwin->w_p_fen = true; - curwin->w_foldinvalid = true; /* recompute folds */ - newFoldLevel(); /* update right now */ + // "zx": re-apply 'foldlevel' and open folds at the cursor + case 'x': + curwin->w_p_fen = true; + curwin->w_foldinvalid = true; // recompute folds + newFoldLevel(); // update right now foldOpenCursor(); break; - /* "zX": undo manual opens/closes, re-apply 'foldlevel' */ - case 'X': curwin->w_p_fen = true; - curwin->w_foldinvalid = true; /* recompute folds */ - old_fdl = -1; /* force an update */ + // "zX": undo manual opens/closes, re-apply 'foldlevel' + case 'X': + curwin->w_p_fen = true; + curwin->w_foldinvalid = true; // recompute folds + old_fdl = -1; // force an update break; - /* "zm": fold more */ + // "zm": fold more case 'm': if (curwin->w_p_fdl > 0) { curwin->w_p_fdl -= cap->count1; @@ -4537,17 +4648,18 @@ dozet: curwin->w_p_fdl = 0; } } - old_fdl = -1; /* force an update */ + old_fdl = -1; // force an update curwin->w_p_fen = true; break; - /* "zM": close all folds */ - case 'M': curwin->w_p_fdl = 0; - old_fdl = -1; /* force an update */ + // "zM": close all folds + case 'M': + curwin->w_p_fdl = 0; + old_fdl = -1; // force an update curwin->w_p_fen = true; break; - /* "zr": reduce folding */ + // "zr": reduce folding case 'r': curwin->w_p_fdl += cap->count1; { @@ -4563,11 +4675,12 @@ dozet: old_fdl = -1; // force an update break; - case 'j': /* "zj" move to next fold downwards */ - case 'k': /* "zk" move to next fold upwards */ + case 'j': // "zj" move to next fold downwards + case 'k': // "zk" move to next fold upwards if (foldMoveTo(true, nchar == 'j' ? FORWARD : BACKWARD, - cap->count1) == false) + cap->count1) == false) { clearopbeep(cap->oap); + } break; @@ -4584,55 +4697,61 @@ dozet: undo = true; FALLTHROUGH; - case 'g': /* "zg": add good word to word list */ - case 'w': /* "zw": add wrong word to word list */ - case 'G': /* "zG": add good word to temp word list */ - case 'W': /* "zW": add wrong word to temp word list */ - { - char_u *ptr = NULL; - size_t len; - - if (checkclearop(cap->oap)) - break; - if (VIsual_active && !get_visual_text(cap, &ptr, &len)) - return; - if (ptr == NULL) { - pos_T pos = curwin->w_cursor; + case 'g': // "zg": add good word to word list + case 'w': // "zw": add wrong word to word list + case 'G': // "zG": add good word to temp word list + case 'W': // "zW": add wrong word to temp word list + { + char_u *ptr = NULL; + size_t len; - /* Find bad word under the cursor. When 'spell' is - * off this fails and find_ident_under_cursor() is - * used below. */ - emsg_off++; - len = spell_move_to(curwin, FORWARD, true, true, NULL); - emsg_off--; - if (len != 0 && curwin->w_cursor.col <= pos.col) - ptr = ml_get_pos(&curwin->w_cursor); - curwin->w_cursor = pos; - } + if (checkclearop(cap->oap)) { + break; + } + if (VIsual_active && !get_visual_text(cap, &ptr, &len)) { + return; + } + if (ptr == NULL) { + pos_T pos = curwin->w_cursor; + + /* Find bad word under the cursor. When 'spell' is + * off this fails and find_ident_under_cursor() is + * used below. */ + emsg_off++; + len = spell_move_to(curwin, FORWARD, true, true, NULL); + emsg_off--; + if (len != 0 && curwin->w_cursor.col <= pos.col) { + ptr = ml_get_pos(&curwin->w_cursor); + } + curwin->w_cursor = pos; + } - if (ptr == NULL && (len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) - return; - assert(len <= INT_MAX); - spell_add_word(ptr, (int)len, - nchar == 'w' || nchar == 'W' + if (ptr == NULL && (len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) { + return; + } + assert(len <= INT_MAX); + spell_add_word(ptr, (int)len, + nchar == 'w' || nchar == 'W' ? SPELL_ADD_BAD : SPELL_ADD_GOOD, - (nchar == 'G' || nchar == 'W') ? 0 : (int)cap->count1, - undo); - } - break; + (nchar == 'G' || nchar == 'W') ? 0 : (int)cap->count1, + undo); + } + break; - case '=': /* "z=": suggestions for a badly spelled word */ - if (!checkclearop(cap->oap)) + case '=': // "z=": suggestions for a badly spelled word + if (!checkclearop(cap->oap)) { spell_suggest((int)cap->count0); + } break; - default: clearopbeep(cap->oap); + default: + clearopbeep(cap->oap); } - /* Redraw when 'foldenable' changed */ + // Redraw when 'foldenable' changed if (old_fen != curwin->w_p_fen) { if (foldmethodIsDiff(curwin) && curwin->w_p_scb) { - /* Adjust 'foldenable' in diff-synced windows. */ + // Adjust 'foldenable' in diff-synced windows. FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb) { wp->w_p_fen = curwin->w_p_fen; @@ -4643,9 +4762,10 @@ dozet: changed_window_setting(); } - /* Redraw when 'foldlevel' changed. */ - if (old_fdl != curwin->w_p_fdl) + // Redraw when 'foldlevel' changed. + if (old_fdl != curwin->w_p_fdl) { newFoldLevel(); + } } @@ -4688,9 +4808,10 @@ static void nv_colon(cmdarg_T *cap) } } - /* When typing, don't type below an old message */ - if (KeyTyped) + // When typing, don't type below an old message + if (KeyTyped) { compute_cmdrow(); + } old_p_im = p_im; @@ -4698,26 +4819,28 @@ static void nv_colon(cmdarg_T *cap) cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL, cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0); - /* If 'insertmode' changed, enter or exit Insert mode */ + // If 'insertmode' changed, enter or exit Insert mode if (p_im != old_p_im) { - if (p_im) + if (p_im) { restart_edit = 'i'; - else + } else { restart_edit = 0; + } } - if (cmd_result == false) - /* The Ex command failed, do not execute the operator. */ + if (cmd_result == false) { + // The Ex command failed, do not execute the operator. clearop(cap->oap); - else if (cap->oap->op_type != OP_NOP - && (cap->oap->start.lnum > curbuf->b_ml.ml_line_count - || cap->oap->start.col > - (colnr_T)STRLEN(ml_get(cap->oap->start.lnum)) - || did_emsg - )) + } else if (cap->oap->op_type != OP_NOP + && (cap->oap->start.lnum > curbuf->b_ml.ml_line_count + || cap->oap->start.col > + (colnr_T)STRLEN(ml_get(cap->oap->start.lnum)) + || did_emsg + )) { /* The start of the operator has become invalid by the Ex command. */ clearopbeep(cap->oap); + } } } @@ -4726,12 +4849,13 @@ static void nv_colon(cmdarg_T *cap) */ static void nv_ctrlg(cmdarg_T *cap) { - if (VIsual_active) { /* toggle Selection/Visual mode */ + if (VIsual_active) { // toggle Selection/Visual mode VIsual_select = !VIsual_select; showmode(); - } else if (!checkclearop(cap->oap)) - /* print full name if count given or :cd used */ + } else if (!checkclearop(cap->oap)) { + // print full name if count given or :cd used fileinfo((int)cap->count0, false, true); + } } /* @@ -4740,10 +4864,11 @@ static void nv_ctrlg(cmdarg_T *cap) static void nv_ctrlh(cmdarg_T *cap) { if (VIsual_active && VIsual_select) { - cap->cmdchar = 'x'; /* BS key behaves like 'x' in Select mode */ + cap->cmdchar = 'x'; // BS key behaves like 'x' in Select mode v_visop(cap); - } else + } else { nv_left(cap); + } } /* @@ -4752,7 +4877,7 @@ static void nv_ctrlh(cmdarg_T *cap) static void nv_clear(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { - /* Clear all syntax states to force resyncing. */ + // Clear all syntax states to force resyncing. syn_stack_free_all(curwin->w_s); FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { wp->w_s->b_syn_slow = false; @@ -4770,7 +4895,7 @@ static void nv_ctrlo(cmdarg_T *cap) if (VIsual_active && VIsual_select) { VIsual_select = false; showmode(); - restart_VIsual_select = 2; /* restart Select mode later */ + restart_VIsual_select = 2; // restart Select mode later } else { cap->count1 = -cap->count1; nv_pcmark(cap); @@ -4781,9 +4906,10 @@ static void nv_ctrlo(cmdarg_T *cap) // not named. static void nv_hat(cmdarg_T *cap) { - if (!checkclearopq(cap->oap)) + if (!checkclearopq(cap->oap)) { (void)buflist_getfile((int)cap->count0, (linenr_T)0, - GETF_SETMARK|GETF_ALT, false); + GETF_SETMARK|GETF_ALT, false); + } } /* @@ -4793,15 +4919,18 @@ static void nv_Zet(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { switch (cap->nchar) { - /* "ZZ": equivalent to ":x". */ - case 'Z': do_cmdline_cmd("x"); + // "ZZ": equivalent to ":x". + case 'Z': + do_cmdline_cmd("x"); break; - /* "ZQ": equivalent to ":q!" (Elvis compatible). */ - case 'Q': do_cmdline_cmd("q!"); + // "ZQ": equivalent to ":q!" (Elvis compatible). + case 'Q': + do_cmdline_cmd("q!"); break; - default: clearopbeep(cap->oap); + default: + clearopbeep(cap->oap); } } } @@ -4824,23 +4953,23 @@ void do_nv_ident(int c1, int c2) /* * Handle the commands that use the word under the cursor. - * [g] CTRL-] :ta to current identifier - * [g] 'K' run program for current identifier - * [g] '*' / to current identifier or string - * [g] '#' ? to current identifier or string - * g ']' :tselect for current identifier + * [g] CTRL-] :ta to current identifier + * [g] 'K' run program for current identifier + * [g] '*' / to current identifier or string + * [g] '#' ? to current identifier or string + * g ']' :tselect for current identifier */ static void nv_ident(cmdarg_T *cap) { - char_u *ptr = NULL; - char_u *p; - size_t n = 0; /* init for GCC */ + char_u *ptr = NULL; + char_u *p; + size_t n = 0; // init for GCC int cmdchar; - bool g_cmd; /* "g" command */ + bool g_cmd; // "g" command bool tag_cmd = false; - char_u *aux_ptr; + char_u *aux_ptr; - if (cap->cmdchar == 'g') { /* "g*", "g#", "g]" and "gCTRL-]" */ + if (cap->cmdchar == 'g') { // "g*", "g#", "g]" and "gCTRL-]" cmdchar = cap->nchar; g_cmd = true; } else { @@ -4848,17 +4977,20 @@ static void nv_ident(cmdarg_T *cap) g_cmd = false; } - if (cmdchar == POUND) /* the pound sign, '#' for English keyboards */ + if (cmdchar == POUND) { // the pound sign, '#' for English keyboards cmdchar = '#'; + } /* * The "]", "CTRL-]" and "K" commands accept an argument in Visual mode. */ if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K') { - if (VIsual_active && get_visual_text(cap, &ptr, &n) == false) + if (VIsual_active && get_visual_text(cap, &ptr, &n) == false) { return; - if (checkclearopq(cap->oap)) + } + if (checkclearopq(cap->oap)) { return; + } } if (ptr == NULL && (n = find_ident_under_cursor(&ptr, @@ -4895,11 +5027,12 @@ static void nv_ident(cmdarg_T *cap) * it was. */ setpcmark(); - curwin->w_cursor.col = (colnr_T) (ptr - get_cursor_line_ptr()); + curwin->w_cursor.col = (colnr_T)(ptr - get_cursor_line_ptr()); - if (!g_cmd && vim_iswordp(ptr)) + if (!g_cmd && vim_iswordp(ptr)) { STRCPY(buf, "\\<"); - no_smartcase = true; /* don't use 'smartcase' now */ + } + no_smartcase = true; // don't use 'smartcase' now break; case 'K': @@ -4919,7 +5052,7 @@ static void nv_ident(cmdarg_T *cap) --n; } if (n == 0) { - EMSG(_(e_noident)); /* found dashes only */ + EMSG(_(e_noident)); // found dashes only xfree(buf); return; } @@ -4942,7 +5075,7 @@ static void nv_ident(cmdarg_T *cap) STRCAT(buf, " "); if (cap->count0 != 0 && (isman || isman_s)) { snprintf(buf + STRLEN(buf), buf_size - STRLEN(buf), "%" PRId64, - (int64_t)cap->count0); + (int64_t)cap->count0); STRCAT(buf, " "); } } @@ -4950,21 +5083,23 @@ static void nv_ident(cmdarg_T *cap) case ']': tag_cmd = true; - if (p_cst) + if (p_cst) { STRCPY(buf, "cstag "); - else + } else { STRCPY(buf, "ts "); + } break; default: tag_cmd = true; - if (curbuf->b_help) + if (curbuf->b_help) { STRCPY(buf, "he! "); - else { - if (g_cmd) + } else { + if (g_cmd) { STRCPY(buf, "tj "); - else + } else { snprintf(buf, buf_size, "%" PRId64 "ta ", (int64_t)cap->count0); + } } } @@ -4984,24 +5119,27 @@ static void nv_ident(cmdarg_T *cap) STRCAT(buf, p); xfree(p); } else { - if (cmdchar == '*') + if (cmdchar == '*') { aux_ptr = (char_u *)(p_magic ? "/.*~[^$\\" : "/^$\\"); - else if (cmdchar == '#') + } else if (cmdchar == '#') { aux_ptr = (char_u *)(p_magic ? "/?.*~[^$\\" : "/?^$\\"); - else if (tag_cmd) { - if (curbuf->b_help) - /* ":help" handles unescaped argument */ + } else if (tag_cmd) { + if (curbuf->b_help) { + // ":help" handles unescaped argument aux_ptr = (char_u *)""; - else + } else { aux_ptr = (char_u *)"\\|\"\n["; - } else + } + } else { aux_ptr = (char_u *)"\\|\"\n*?["; + } p = (char_u *)buf + STRLEN(buf); while (n-- > 0) { - /* put a backslash before \ and some others */ - if (vim_strchr(aux_ptr, *ptr) != NULL) + // put a backslash before \ and some others + if (vim_strchr(aux_ptr, *ptr) != NULL) { *p++ = '\\'; + } /* When current byte is a part of multibyte character, copy all * bytes of that character. */ const size_t len = (size_t)(utfc_ptr2len(ptr) - 1); @@ -5046,22 +5184,21 @@ static void nv_ident(cmdarg_T *cap) xfree(buf); } -/* - * Get visually selected text, within one line only. - * Returns false if more than one line selected. - */ -bool -get_visual_text ( - cmdarg_T *cap, - char_u **pp, /* return: start of selected text */ - size_t *lenp /* return: length of selected text */ -) -{ - if (VIsual_mode != 'V') +/// Get visually selected text, within one line only. +/// +/// @param pp return: start of selected text +/// @param lenp return: length of selected text +/// +/// @return false if more than one line selected. +bool get_visual_text(cmdarg_T *cap, char_u **pp, size_t *lenp) +{ + if (VIsual_mode != 'V') { unadjust_for_sel(); + } if (VIsual.lnum != curwin->w_cursor.lnum) { - if (cap != NULL) + if (cap != NULL) { clearopbeep(cap->oap); + } return false; } if (VIsual_mode == 'V') { @@ -5087,8 +5224,9 @@ get_visual_text ( */ static void nv_tagpop(cmdarg_T *cap) { - if (!checkclearopq(cap->oap)) + if (!checkclearopq(cap->oap)) { do_tag((char_u *)"", DT_POP, (int)cap->count1, false, true); + } } /* @@ -5107,23 +5245,24 @@ static void nv_scroll(cmdarg_T *cap) if (cap->cmdchar == 'L') { validate_botline(curwin); // make sure curwin->w_botline is valid curwin->w_cursor.lnum = curwin->w_botline - 1; - if (cap->count1 - 1 >= curwin->w_cursor.lnum) + if (cap->count1 - 1 >= curwin->w_cursor.lnum) { curwin->w_cursor.lnum = 1; - else { + } else { if (hasAnyFolding(curwin)) { - /* Count a fold for one screen line. */ + // Count a fold for one screen line. for (n = cap->count1 - 1; n > 0 && curwin->w_cursor.lnum > curwin->w_topline; --n) { (void)hasFolding(curwin->w_cursor.lnum, - &curwin->w_cursor.lnum, NULL); + &curwin->w_cursor.lnum, NULL); --curwin->w_cursor.lnum; } - } else + } else { curwin->w_cursor.lnum -= cap->count1 - 1; + } } } else { if (cap->cmdchar == 'M') { - /* Don't count filler lines above the window. */ + // Don't count filler lines above the window. used -= diff_check_fill(curwin, curwin->w_topline) - curwin->w_topfill; validate_botline(curwin); // make sure w_empty_rows is valid @@ -5132,7 +5271,7 @@ static void nv_scroll(cmdarg_T *cap) // Count half he number of filler lines to be "below this // line" and half to be "above the next line". if (n > 0 && used + diff_check_fill(curwin, curwin->w_topline - + n) / 2 >= half) { + + n) / 2 >= half) { --n; break; } @@ -5150,7 +5289,7 @@ static void nv_scroll(cmdarg_T *cap) } else { // (cap->cmdchar == 'H') n = cap->count1 - 1; if (hasAnyFolding(curwin)) { - /* Count a fold for one screen line. */ + // Count a fold for one screen line. lnum = curwin->w_topline; while (n-- > 0 && lnum < curwin->w_botline - 1) { (void)hasFolding(lnum, NULL, &lnum); @@ -5160,8 +5299,9 @@ static void nv_scroll(cmdarg_T *cap) } } curwin->w_cursor.lnum = curwin->w_topline + n; - if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) + if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; + } } // Correct for 'so', except when an operator is pending. @@ -5180,9 +5320,10 @@ static void nv_right(cmdarg_T *cap) int PAST_LINE; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { - /* <C-Right> and <S-Right> move a word or WORD right */ - if (mod_mask & MOD_MASK_CTRL) + // <C-Right> and <S-Right> move a word or WORD right + if (mod_mask & MOD_MASK_CTRL) { cap->arg = true; + } nv_wordcmd(cap); return; } @@ -5195,13 +5336,14 @@ static void nv_right(cmdarg_T *cap) * In virtual mode, there's no such thing as "PAST_LINE", as lines are * (theoretically) infinitely long. */ - if (virtual_active()) + if (virtual_active()) { PAST_LINE = 0; + } for (n = cap->count1; n > 0; --n) { if ((!PAST_LINE && oneright() == false) - || (PAST_LINE && *get_cursor_pos_ptr() == NUL) - ) { + || (PAST_LINE && + *get_cursor_pos_ptr() == NUL)) { // <Space> wraps to next line if 'whichwrap' has 's'. // 'l' wraps to next line if 'whichwrap' has 'l'. // CURS_RIGHT wraps to next line if 'whichwrap' has '>'. @@ -5246,8 +5388,9 @@ static void nv_right(cmdarg_T *cap) } } if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped - && cap->oap->op_type == OP_NOP) + && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } /* @@ -5260,9 +5403,10 @@ static void nv_left(cmdarg_T *cap) long n; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { - /* <C-Left> and <S-Left> move a word or WORD left */ - if (mod_mask & MOD_MASK_CTRL) + // <C-Left> and <S-Left> move a word or WORD left + if (mod_mask & MOD_MASK_CTRL) { cap->arg = 1; + } nv_bck_word(cap); return; } @@ -5272,8 +5416,8 @@ static void nv_left(cmdarg_T *cap) for (n = cap->count1; n > 0; --n) { if (oneleft() == false) { /* <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'. - * 'h' wraps to previous line if 'whichwrap' has 'h'. - * CURS_LEFT wraps to previous line if 'whichwrap' has '<'. + * 'h' wraps to previous line if 'whichwrap' has 'h'. + * CURS_LEFT wraps to previous line if 'whichwrap' has '<'. */ if ((((cap->cmdchar == K_BS || cap->cmdchar == Ctrl_H) && vim_strchr(p_ww, 'b') != NULL) @@ -5299,15 +5443,17 @@ static void nv_left(cmdarg_T *cap) } continue; } - /* Only beep and flush if not moved at all */ - else if (cap->oap->op_type == OP_NOP && n == cap->count1) + // Only beep and flush if not moved at all + else if (cap->oap->op_type == OP_NOP && n == cap->count1) { beep_flush(); + } break; } } if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped - && cap->oap->op_type == OP_NOP) + && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } /* @@ -5317,7 +5463,7 @@ static void nv_left(cmdarg_T *cap) static void nv_up(cmdarg_T *cap) { if (mod_mask & MOD_MASK_SHIFT) { - /* <S-Up> is page up */ + // <S-Up> is page up cap->arg = BACKWARD; nv_page(cap); } else { @@ -5337,7 +5483,7 @@ static void nv_up(cmdarg_T *cap) static void nv_down(cmdarg_T *cap) { if (mod_mask & MOD_MASK_SHIFT) { - /* <S-Down> is page down */ + // <S-Down> is page down cap->arg = FORWARD; nv_page(cap); } else if (bt_quickfix(curbuf) && cap->cmdchar == CAR) { @@ -5370,7 +5516,7 @@ static void nv_down(cmdarg_T *cap) */ static void nv_gotofile(cmdarg_T *cap) { - char_u *ptr; + char_u *ptr; linenr_T lnum = -1; if (text_locked()) { @@ -5399,8 +5545,9 @@ static void nv_gotofile(cmdarg_T *cap) beginline(BL_SOL | BL_FIX); } xfree(ptr); - } else + } else { clearop(cap->oap); + } } /* @@ -5408,10 +5555,10 @@ static void nv_gotofile(cmdarg_T *cap) */ static void nv_end(cmdarg_T *cap) { - if (cap->arg || (mod_mask & MOD_MASK_CTRL)) { /* CTRL-END = goto last line */ + if (cap->arg || (mod_mask & MOD_MASK_CTRL)) { // CTRL-END = goto last line cap->arg = true; nv_goto(cap); - cap->count1 = 1; /* to end of current line */ + cap->count1 = 1; // to end of current line } nv_dollar(cap); } @@ -5427,13 +5574,15 @@ static void nv_dollar(cmdarg_T *cap) * is pending (whew!) keep the cursor where it is. * Otherwise, send it to the end of the line. */ if (!virtual_active() || gchar_cursor() != NUL - || cap->oap->op_type == OP_NOP) - curwin->w_curswant = MAXCOL; /* so we stay at the end */ + || cap->oap->op_type == OP_NOP) { + curwin->w_curswant = MAXCOL; // so we stay at the end + } if (cursor_down(cap->count1 - 1, - cap->oap->op_type == OP_NOP) == false) + cap->oap->op_type == OP_NOP) == false) { clearopbeep(cap->oap); - else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) + } else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } /* @@ -5442,11 +5591,11 @@ static void nv_dollar(cmdarg_T *cap) */ static void nv_search(cmdarg_T *cap) { - oparg_T *oap = cap->oap; + oparg_T *oap = cap->oap; pos_T save_cursor = curwin->w_cursor; if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13) { - /* Translate "g??" to "g?g?" */ + // Translate "g??" to "g?g?" cap->cmdchar = 'g'; cap->nchar = '?'; nv_operator(cap); @@ -5487,18 +5636,13 @@ static void nv_next(cmdarg_T *cap) } } -/* - * Search for "pat" in direction "dir" ('/' or '?', 0 for repeat). - * Uses only cap->count1 and cap->oap from "cap". - * 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, // extra flags for do_search() - int *wrapped -) +/// Search for "pat" in direction "dir" ('/' or '?', 0 for repeat). +/// Uses only cap->count1 and cap->oap from "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) { int i; searchit_arg_T sia; @@ -5521,8 +5665,9 @@ static int normal_search( cap->oap->motion_type = kMTLineWise; } curwin->w_cursor.coladd = 0; - if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) + if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) { foldOpenCursor(); + } } /* "/$" will put the cursor after the end of the line, may need to @@ -5541,28 +5686,31 @@ static void nv_csearch(cmdarg_T *cap) { bool t_cmd; - if (cap->cmdchar == 't' || cap->cmdchar == 'T') + if (cap->cmdchar == 't' || cap->cmdchar == 'T') { t_cmd = true; - else + } else { t_cmd = false; + } cap->oap->motion_type = kMTCharWise; if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == false) { clearopbeep(cap->oap); } else { curwin->w_set_curswant = true; - /* Include a Tab for "tx" and for "dfx". */ + // Include a Tab for "tx" and for "dfx". if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD && (t_cmd || cap->oap->op_type != OP_NOP)) { colnr_T scol, ecol; getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol); curwin->w_cursor.coladd = ecol - scol; - } else + } else { curwin->w_cursor.coladd = 0; + } adjust_for_sel(cap); - if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) + if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } } @@ -5574,8 +5722,8 @@ static void nv_brackets(cmdarg_T *cap) { pos_T new_pos = { 0, 0, 0 }; pos_T prev_pos; - pos_T *pos = NULL; /* init for GCC */ - pos_T old_pos; /* cursor position before command */ + pos_T *pos = NULL; // init for GCC + pos_T old_pos; // cursor position before command int flag; long n; int findc; @@ -5584,32 +5732,32 @@ static void nv_brackets(cmdarg_T *cap) cap->oap->motion_type = kMTCharWise; cap->oap->inclusive = false; old_pos = curwin->w_cursor; - curwin->w_cursor.coladd = 0; /* TODO: don't do this for an error. */ + curwin->w_cursor.coladd = 0; // TODO: don't do this for an error. /* * "[f" or "]f" : Edit file under the cursor (same as "gf") */ - if (cap->nchar == 'f') + if (cap->nchar == 'f') { nv_gotofile(cap); - else + } else /* * Find the occurrence(s) of the identifier or define under cursor * in current and included files or jump to the first occurrence. * - * search list jump - * fwd bwd fwd bwd fwd bwd - * identifier "]i" "[i" "]I" "[I" "]^I" "[^I" - * define "]d" "[d" "]D" "[D" "]^D" "[^D" + * search list jump + * fwd bwd fwd bwd fwd bwd + * identifier "]i" "[i" "]I" "[I" "]^I" "[^I" + * define "]d" "[d" "]D" "[D" "]^D" "[^D" */ if (vim_strchr((char_u *) - "iI\011dD\004", - cap->nchar) != NULL) { - char_u *ptr; + "iI\011dD\004", + cap->nchar) != NULL) { + char_u *ptr; size_t len; - if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) + if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) { clearop(cap->oap); - else { + } else { find_pattern_in_path(ptr, 0, len, true, cap->count0 == 0 ? !isupper(cap->nchar) : false, (((cap->nchar & 0xf) == ('d' & 0xf)) @@ -5637,14 +5785,16 @@ static void nv_brackets(cmdarg_T *cap) && vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL) || (cap->cmdchar == ']' && vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL)) { - if (cap->nchar == '*') + if (cap->nchar == '*') { cap->nchar = '/'; + } prev_pos.lnum = 0; if (cap->nchar == 'm' || cap->nchar == 'M') { - if (cap->cmdchar == '[') + if (cap->cmdchar == '[') { findc = '{'; - else + } else { findc = '}'; + } n = 9999; } else { findc = cap->nchar; @@ -5652,12 +5802,14 @@ static void nv_brackets(cmdarg_T *cap) } for (; n > 0; --n) { if ((pos = findmatchlimit(cap->oap, findc, - (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) { - if (new_pos.lnum == 0) { /* nothing found */ - if (cap->nchar != 'm' && cap->nchar != 'M') + (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) { + if (new_pos.lnum == 0) { // nothing found + if (cap->nchar != 'm' && cap->nchar != 'M') { clearopbeep(cap->oap); - } else - pos = &new_pos; /* use last one found */ + } + } else { + pos = &new_pos; // use last one found + } break; } prev_pos = new_pos; @@ -5673,24 +5825,27 @@ static void nv_brackets(cmdarg_T *cap) * Also repeat for the given count. */ if (cap->nchar == 'm' || cap->nchar == 'M') { - /* norm is true for "]M" and "[m" */ + // norm is true for "]M" and "[m" int norm = ((findc == '{') == (cap->nchar == 'm')); n = cap->count1; - /* found a match: we were inside a method */ + // found a match: we were inside a method if (prev_pos.lnum != 0) { pos = &prev_pos; curwin->w_cursor = prev_pos; - if (norm) + if (norm) { --n; - } else + } + } else { pos = NULL; + } while (n > 0) { for (;; ) { if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0) { - /* if not found anything, that's an error */ - if (pos == NULL) + // if not found anything, that's an error + if (pos == NULL) { clearopbeep(cap->oap); + } n = 0; break; } @@ -5709,54 +5864,59 @@ static void nv_brackets(cmdarg_T *cap) new_pos = curwin->w_cursor; pos = &new_pos; } - /* found start/end of other method: go to match */ + // found start/end of other method: go to match else if ((pos = findmatchlimit(cap->oap, findc, - (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, - 0)) == NULL) + (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, + 0)) == NULL) { n = 0; - else + } else { curwin->w_cursor = *pos; + } break; } } --n; } curwin->w_cursor = old_pos; - if (pos == NULL && new_pos.lnum != 0) + if (pos == NULL && new_pos.lnum != 0) { clearopbeep(cap->oap); + } } if (pos != NULL) { setpcmark(); curwin->w_cursor = *pos; curwin->w_set_curswant = true; if ((fdo_flags & FDO_BLOCK) && KeyTyped - && cap->oap->op_type == OP_NOP) + && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } } /* * "[[", "[]", "]]" and "][": move to start or end of function */ else if (cap->nchar == '[' || cap->nchar == ']') { - if (cap->nchar == cap->cmdchar) /* "]]" or "[[" */ + if (cap->nchar == cap->cmdchar) { // "]]" or "[[" flag = '{'; - else - flag = '}'; /* "][" or "[]" */ - + } else { + flag = '}'; // "][" or "[]" + } curwin->w_set_curswant = true; /* * Imitate strange Vi behaviour: When using "]]" with an operator * we also stop at '}'. */ if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag, - (cap->oap->op_type != OP_NOP - && cap->arg == FORWARD && flag == '{'))) + (cap->oap->op_type != OP_NOP + && cap->arg == FORWARD && flag == '{'))) { clearopbeep(cap->oap); - else { - if (cap->oap->op_type == OP_NOP) + } else { + if (cap->oap->op_type == OP_NOP) { beginline(BL_WHITE | BL_FIX); - if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) + } + if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } } else if (cap->nchar == 'p' || cap->nchar == 'P') { // "[p", "[P", "]P" and "]p": put with indent adjustment @@ -5770,12 +5930,14 @@ static void nv_brackets(cmdarg_T *cap) for (n = cap->count1; n > 0; --n) { prev_pos = *pos; pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD, - cap->nchar == '\''); - if (pos == NULL) + cap->nchar == '\''); + if (pos == NULL) { break; + } } - if (pos == NULL) + if (pos == NULL) { pos = &prev_pos; + } nv_cursormark(cap, cap->nchar == '\'', pos); } /* @@ -5784,31 +5946,33 @@ static void nv_brackets(cmdarg_T *cap) */ else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE) { (void)do_mouse(cap->oap, cap->nchar, - (cap->cmdchar == ']') ? FORWARD : BACKWARD, - cap->count1, PUT_FIXINDENT); + (cap->cmdchar == ']') ? FORWARD : BACKWARD, + cap->count1, PUT_FIXINDENT); } /* * "[z" and "]z": move to start or end of open fold. */ else if (cap->nchar == 'z') { if (foldMoveTo(false, cap->cmdchar == ']' ? FORWARD : BACKWARD, - cap->count1) == false) + cap->count1) == false) { clearopbeep(cap->oap); + } } /* * "[c" and "]c": move to next or previous diff-change. */ else if (cap->nchar == 'c') { if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD, - cap->count1) == false) + cap->count1) == false) { clearopbeep(cap->oap); + } } /* * "[s", "[S", "]s" and "]S": move to next spell error. */ else if (cap->nchar == 's' || cap->nchar == 'S') { setpcmark(); - for (n = 0; n < cap->count1; ++n) + for (n = 0; n < cap->count1; ++n) { if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->nchar == 's', false, NULL) == 0) { clearopbeep(cap->oap); @@ -5816,12 +5980,15 @@ static void nv_brackets(cmdarg_T *cap) } else { curwin->w_set_curswant = true; } - if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) + } + if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) { foldOpenCursor(); + } } - /* Not a valid cap->nchar. */ - else + // Not a valid cap->nchar. + else { clearopbeep(cap->oap); + } } /* @@ -5829,7 +5996,7 @@ static void nv_brackets(cmdarg_T *cap) */ static void nv_percent(cmdarg_T *cap) { - pos_T *pos; + pos_T *pos; linenr_T lnum = curwin->w_cursor.lnum; cap->oap->inclusive = true; @@ -5861,9 +6028,9 @@ static void nv_percent(cmdarg_T *cap) } else { // "%" : go to matching paren cap->oap->motion_type = kMTCharWise; cap->oap->use_reg_one = true; - if ((pos = findmatch(cap->oap, NUL)) == NULL) + if ((pos = findmatch(cap->oap, NUL)) == NULL) { clearopbeep(cap->oap); - else { + } else { setpcmark(); curwin->w_cursor = *pos; curwin->w_set_curswant = true; @@ -5874,8 +6041,9 @@ static void nv_percent(cmdarg_T *cap) if (cap->oap->op_type == OP_NOP && lnum != curwin->w_cursor.lnum && (fdo_flags & FDO_PERCENT) - && KeyTyped) + && KeyTyped) { foldOpenCursor(); + } } /* @@ -5886,18 +6054,19 @@ static void nv_brace(cmdarg_T *cap) { cap->oap->motion_type = kMTCharWise; cap->oap->use_reg_one = true; - /* The motion used to be inclusive for "(", but that is not what Vi does. */ + // The motion used to be inclusive for "(", but that is not what Vi does. cap->oap->inclusive = false; curwin->w_set_curswant = true; - if (findsent(cap->arg, cap->count1) == false) + if (findsent(cap->arg, cap->count1) == false) { clearopbeep(cap->oap); - else { - /* Don't leave the cursor on the NUL past end of line. */ + } else { + // Don't leave the cursor on the NUL past end of line. adjust_cursor(cap->oap); curwin->w_cursor.coladd = 0; - if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) + if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } } @@ -5907,8 +6076,9 @@ static void nv_brace(cmdarg_T *cap) static void nv_mark(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { - if (setmark(cap->nchar) == false) + if (setmark(cap->nchar) == false) { clearopbeep(cap->oap); + } } } @@ -5922,12 +6092,13 @@ static void nv_findpar(cmdarg_T *cap) cap->oap->inclusive = false; cap->oap->use_reg_one = true; curwin->w_set_curswant = true; - if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, false)) + if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, false)) { clearopbeep(cap->oap); - else { + } else { curwin->w_cursor.coladd = 0; - if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) + if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } } @@ -5937,14 +6108,14 @@ static void nv_findpar(cmdarg_T *cap) static void nv_undo(cmdarg_T *cap) { if (cap->oap->op_type == OP_LOWER - || VIsual_active - ) { - /* translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" */ + || VIsual_active) { + // translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" cap->cmdchar = 'g'; cap->nchar = 'u'; nv_operator(cap); - } else + } else { nv_kundo(cap); + } } /* @@ -5967,7 +6138,7 @@ static void nv_kundo(cmdarg_T *cap) */ static void nv_replace(cmdarg_T *cap) { - char_u *ptr; + char_u *ptr; int had_ctrl_v; if (checkclearop(cap->oap)) { @@ -5978,26 +6149,29 @@ static void nv_replace(cmdarg_T *cap) return; } - /* get another character */ + // get another character if (cap->nchar == Ctrl_V) { had_ctrl_v = Ctrl_V; cap->nchar = get_literal(); - /* Don't redo a multibyte character with CTRL-V. */ - if (cap->nchar > DEL) + // Don't redo a multibyte character with CTRL-V. + if (cap->nchar > DEL) { had_ctrl_v = NUL; - } else + } + } else { had_ctrl_v = NUL; + } - /* Abort if the character is a special key. */ + // Abort if the character is a special key. if (IS_SPECIAL(cap->nchar)) { clearopbeep(cap->oap); return; } - /* Visual mode "r" */ + // Visual mode "r" if (VIsual_active) { - if (got_int) + if (got_int) { reset_VIsual(); + } if (had_ctrl_v) { // Use a special (negative) number to make a difference between a // literal CR or NL and a line break. @@ -6011,24 +6185,25 @@ static void nv_replace(cmdarg_T *cap) return; } - /* Break tabs, etc. */ + // Break tabs, etc. if (virtual_active()) { - if (u_save_cursor() == false) + if (u_save_cursor() == false) { return; + } if (gchar_cursor() == NUL) { - /* Add extra space and put the cursor on the first one. */ + // Add extra space and put the cursor on the first one. coladvance_force((colnr_T)(getviscol() + cap->count1)); assert(cap->count1 <= INT_MAX); curwin->w_cursor.col -= (colnr_T)cap->count1; - } else if (gchar_cursor() == TAB) + } else if (gchar_cursor() == TAB) { coladvance_force(getviscol()); + } } - /* Abort if not enough characters to replace. */ + // Abort if not enough characters to replace. ptr = get_cursor_pos_ptr(); if (STRLEN(ptr) < (unsigned)cap->count1 - || (mb_charlen(ptr) < cap->count1) - ) { + || (mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } @@ -6045,9 +6220,10 @@ static void nv_replace(cmdarg_T *cap) return; } - /* save line for undo */ - if (u_save_cursor() == false) + // save line for undo + if (u_save_cursor() == false) { return; + } if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) { /* @@ -6055,18 +6231,18 @@ static void nv_replace(cmdarg_T *cap) * Strange vi behaviour: Only one newline is inserted. * Delete the characters here. * Insert the newline with an insert command, takes care of - * autoindent. The insert command depends on being on the last + * autoindent. The insert command depends on being on the last * character of a line or not. */ - (void)del_chars(cap->count1, false); /* delete the characters */ + (void)del_chars(cap->count1, false); // delete the characters stuffcharReadbuff('\r'); stuffcharReadbuff(ESC); - /* Give 'r' to edit(), to get the redo command right. */ + // Give 'r' to edit(), to get the redo command right. invoke_edit(cap, true, 'r', false); } else { prep_redo(cap->oap->regname, cap->count1, - NUL, 'r', NUL, had_ctrl_v, cap->nchar); + NUL, 'r', NUL, had_ctrl_v, cap->nchar); curbuf->b_op_start = curwin->w_cursor; const int old_State = State; @@ -6103,7 +6279,7 @@ static void nv_replace(cmdarg_T *cap) ins_char(cap->ncharC2); } } - --curwin->w_cursor.col; /* cursor on the last replaced char */ + --curwin->w_cursor.col; // cursor on the last replaced char /* if the character on the left of the current cursor is a multi-byte * character, move two characters left */ mb_adjust_cursor(); @@ -6135,16 +6311,18 @@ static void v_swap_corners(int cmdchar) curwin->w_curswant = right; /* 'selection "exclusive" and cursor at right-bottom corner: move it * right one column */ - if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e') + if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e') { ++curwin->w_curswant; + } coladvance(curwin->w_curswant); if (curwin->w_cursor.col == old_cursor.col && (!virtual_active() - || curwin->w_cursor.coladd == old_cursor.coladd) - ) { + || curwin->w_cursor.coladd == + old_cursor.coladd)) { curwin->w_cursor.lnum = VIsual.lnum; - if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e') + if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e') { ++right; + } coladvance(right); VIsual = curwin->w_cursor; @@ -6165,18 +6343,19 @@ static void v_swap_corners(int cmdchar) */ static void nv_Replace(cmdarg_T *cap) { - if (VIsual_active) { /* "R" is replace lines */ + if (VIsual_active) { // "R" is replace lines cap->cmdchar = 'c'; cap->nchar = NUL; - VIsual_mode_orig = VIsual_mode; /* remember original area for gv */ + VIsual_mode_orig = VIsual_mode; // remember original area for gv VIsual_mode = 'V'; nv_operator(cap); } else if (!checkclearopq(cap->oap)) { if (!MODIFIABLE(curbuf)) { EMSG(_(e_modifiable)); } else { - if (virtual_active()) + if (virtual_active()) { coladvance(getviscol()); + } invoke_edit(cap, false, cap->arg ? 'V' : 'R', false); } } @@ -6190,17 +6369,19 @@ static void nv_vreplace(cmdarg_T *cap) if (VIsual_active) { cap->cmdchar = 'r'; cap->nchar = cap->extra_char; - nv_replace(cap); /* Do same as "r" in Visual mode for now */ + nv_replace(cap); // Do same as "r" in Visual mode for now } else if (!checkclearopq(cap->oap)) { if (!MODIFIABLE(curbuf)) { EMSG(_(e_modifiable)); } else { - if (cap->extra_char == Ctrl_V) /* get another character */ + if (cap->extra_char == Ctrl_V) { // get another character cap->extra_char = get_literal(); + } stuffcharReadbuff(cap->extra_char); stuffcharReadbuff(ESC); - if (virtual_active()) + if (virtual_active()) { coladvance(getviscol()); + } invoke_edit(cap, true, 'v', false); } } @@ -6226,8 +6407,9 @@ static void n_swapchar(cmdarg_T *cap) prep_redo_cmd(cap); - if (u_save_cursor() == false) + if (u_save_cursor() == false) { return; + } startpos = curwin->w_cursor; for (n = cap->count1; n > 0; --n) { @@ -6239,12 +6421,14 @@ static void n_swapchar(cmdarg_T *cap) ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; if (n > 1) { - if (u_savesub(curwin->w_cursor.lnum) == false) + if (u_savesub(curwin->w_cursor.lnum) == false) { break; + } u_clearline(); } - } else + } else { break; + } } } @@ -6256,8 +6440,9 @@ static void n_swapchar(cmdarg_T *cap) 0L, true); curbuf->b_op_start = startpos; curbuf->b_op_end = curwin->w_cursor; - if (curbuf->b_op_end.col > 0) + if (curbuf->b_op_end.col > 0) { --curbuf->b_op_end.col; + } } } @@ -6266,19 +6451,21 @@ static void n_swapchar(cmdarg_T *cap) */ static void nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos) { - if (check_mark(pos) == false) + if (check_mark(pos) == false) { clearop(cap->oap); - else { + } else { if (cap->cmdchar == '\'' || cap->cmdchar == '`' || cap->cmdchar == '[' - || cap->cmdchar == ']') + || cap->cmdchar == ']') { setpcmark(); + } curwin->w_cursor = *pos; - if (flag) + if (flag) { beginline(BL_WHITE | BL_FIX); - else + } else { check_cursor(); + } } cap->oap->motion_type = flag ? kMTLineWise : kMTCharWise; if (cap->cmdchar == '`') { @@ -6301,8 +6488,9 @@ static void v_visop(cmdarg_T *cap) if (VIsual_mode != Ctrl_V) { VIsual_mode_orig = VIsual_mode; VIsual_mode = 'V'; - } else if (cap->cmdchar == 'C' || cap->cmdchar == 'D') + } else if (cap->cmdchar == 'C' || cap->cmdchar == 'D') { curwin->w_curswant = MAXCOL; + } } cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1); nv_operator(cap); @@ -6324,8 +6512,9 @@ static void nv_subst(cmdarg_T *cap) } cap->cmdchar = 'c'; nv_operator(cap); - } else + } else { nv_optrans(cap); + } } /* @@ -6333,14 +6522,15 @@ static void nv_subst(cmdarg_T *cap) */ static void nv_abbrev(cmdarg_T *cap) { - if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL) - cap->cmdchar = 'x'; /* DEL key behaves like 'x' */ - - /* in Visual mode these commands are operators */ - if (VIsual_active) + if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL) { + cap->cmdchar = 'x'; // DEL key behaves like 'x' + } + // in Visual mode these commands are operators + if (VIsual_active) { v_visop(cap); - else + } else { nv_optrans(cap); + } } /* @@ -6367,24 +6557,27 @@ static void nv_optrans(cmdarg_T *cap) */ static void nv_gomark(cmdarg_T *cap) { - pos_T *pos; + pos_T *pos; int c; pos_T old_cursor = curwin->w_cursor; const bool old_KeyTyped = KeyTyped; // getting file may reset it - if (cap->cmdchar == 'g') + if (cap->cmdchar == 'g') { c = cap->extra_char; - else + } else { c = cap->nchar; + } pos = getmark(c, (cap->oap->op_type == OP_NOP)); - if (pos == (pos_T *)-1) { /* jumped to other file */ + if (pos == (pos_T *)-1) { // jumped to other file if (cap->arg) { check_cursor_lnum(); beginline(BL_WHITE | BL_FIX); - } else + } else { check_cursor(); - } else + } + } else { nv_cursormark(cap, cap->arg, pos); + } // May need to clear the coladd that a mark includes. if (!virtual_active()) { @@ -6403,7 +6596,7 @@ static void nv_gomark(cmdarg_T *cap) // Handle CTRL-O, CTRL-I, "g;", "g,", and "CTRL-Tab" commands. static void nv_pcmark(cmdarg_T *cap) { - pos_T *pos; + pos_T *pos; linenr_T lnum = curwin->w_cursor.lnum; const bool old_KeyTyped = KeyTyped; // getting file may reset it @@ -6420,22 +6613,25 @@ static void nv_pcmark(cmdarg_T *cap) if (pos == (pos_T *)-1) { // jump to other file curwin->w_set_curswant = true; check_cursor(); - } else if (pos != NULL) /* can jump */ + } else if (pos != NULL) { // can jump nv_cursormark(cap, false, pos); - else if (cap->cmdchar == 'g') { - if (curbuf->b_changelistlen == 0) + } else if (cap->cmdchar == 'g') { + if (curbuf->b_changelistlen == 0) { EMSG(_("E664: changelist is empty")); - else if (cap->count1 < 0) + } else if (cap->count1 < 0) { EMSG(_("E662: At start of changelist")); - else + } else { EMSG(_("E663: At end of changelist")); - } else + } + } else { clearopbeep(cap->oap); + } if (cap->oap->op_type == OP_NOP && (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum) && (fdo_flags & FDO_MARK) - && old_KeyTyped) + && old_KeyTyped) { foldOpenCursor(); + } } } @@ -6444,16 +6640,19 @@ static void nv_pcmark(cmdarg_T *cap) */ static void nv_regname(cmdarg_T *cap) { - if (checkclearop(cap->oap)) + if (checkclearop(cap->oap)) { return; - if (cap->nchar == '=') + } + if (cap->nchar == '=') { cap->nchar = get_expr_register(); + } if (cap->nchar != NUL && valid_yank_reg(cap->nchar, false)) { cap->oap->regname = cap->nchar; - cap->opcount = cap->count0; /* remember count before '"' */ + cap->opcount = cap->count0; // remember count before '"' set_reg_var(cap->oap->regname); - } else + } else { clearopbeep(cap->oap); + } } /* @@ -6464,8 +6663,9 @@ static void nv_regname(cmdarg_T *cap) */ static void nv_visual(cmdarg_T *cap) { - if (cap->cmdchar == Ctrl_Q) + if (cap->cmdchar == Ctrl_Q) { cap->cmdchar = Ctrl_V; + } // 'v', 'V' and CTRL-V can be used while an operator is pending to make it // charwise, linewise, or blockwise. @@ -6476,28 +6676,30 @@ static void nv_visual(cmdarg_T *cap) } VIsual_select = cap->arg; - if (VIsual_active) { /* change Visual mode */ - if (VIsual_mode == cap->cmdchar) /* stop visual mode */ + if (VIsual_active) { // change Visual mode + if (VIsual_mode == cap->cmdchar) { // stop visual mode end_visual_mode(); - else { /* toggle char/block mode */ - /* or char/line mode */ + } else { // toggle char/block mode + // or char/line mode VIsual_mode = cap->cmdchar; showmode(); } redraw_curbuf_later(INVERTED); // update the inversion } else { // start Visual mode if (cap->count0 > 0 && resel_VIsual_mode != NUL) { - /* use previously selected part */ + // use previously selected part VIsual = curwin->w_cursor; VIsual_active = true; VIsual_reselect = true; - if (!cap->arg) - /* start Select mode when 'selectmode' contains "cmd" */ + if (!cap->arg) { + // start Select mode when 'selectmode' contains "cmd" may_start_select('c'); + } setmouse(); - if (p_smd && msg_silent == 0) - redraw_cmdline = true; /* show visual mode later */ + if (p_smd && msg_silent == 0) { + redraw_cmdline = true; // show visual mode later + } /* * For V and ^V, we multiply the number of lines even if there * was only one -- webb @@ -6505,8 +6707,9 @@ static void nv_visual(cmdarg_T *cap) if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1) { curwin->w_cursor.lnum += resel_VIsual_line_count * cap->count0 - 1; - if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) + if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; + } } VIsual_mode = resel_VIsual_mode; if (VIsual_mode == 'v') { @@ -6515,8 +6718,9 @@ static void nv_visual(cmdarg_T *cap) assert(cap->count0 >= INT_MIN && cap->count0 <= INT_MAX); curwin->w_curswant = (curwin->w_virtcol + resel_VIsual_vcol * (int)cap->count0 - 1); - } else + } else { curwin->w_curswant = resel_VIsual_vcol; + } coladvance(curwin->w_curswant); } if (resel_VIsual_vcol == MAXCOL) { @@ -6528,22 +6732,26 @@ static void nv_visual(cmdarg_T *cap) curwin->w_curswant = (curwin->w_virtcol + resel_VIsual_vcol * (int)cap->count0 - 1); coladvance(curwin->w_curswant); - } else + } else { curwin->w_set_curswant = true; - redraw_curbuf_later(INVERTED); /* show the inversion */ + } + redraw_curbuf_later(INVERTED); // show the inversion } else { - if (!cap->arg) - /* start Select mode when 'selectmode' contains "cmd" */ + if (!cap->arg) { + // start Select mode when 'selectmode' contains "cmd" may_start_select('c'); + } n_start_visual_mode(cap->cmdchar); - if (VIsual_mode != 'V' && *p_sel == 'e') - ++cap->count1; /* include one more char */ + if (VIsual_mode != 'V' && *p_sel == 'e') { + ++cap->count1; // include one more char + } if (cap->count0 > 0 && --cap->count1 > 0) { - /* With a count select that many characters or lines. */ - if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V) + // With a count select that many characters or lines. + if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V) { nv_right(cap); - else if (VIsual_mode == 'V') + } else if (VIsual_mode == 'V') { nv_down(cap); + } } } } @@ -6554,7 +6762,7 @@ static void nv_visual(cmdarg_T *cap) */ void start_selection(void) { - /* if 'selectmode' contains "key", start Select mode */ + // if 'selectmode' contains "key", start Select mode may_start_select('k'); n_start_visual_mode('v'); } @@ -6592,9 +6800,9 @@ static void n_start_visual_mode(int c) // Check for redraw after changing the state. conceal_check_cursor_line(); - if (p_smd && msg_silent == 0) - redraw_cmdline = true; /* show visual mode later */ - + if (p_smd && msg_silent == 0) { + redraw_cmdline = true; // show visual mode later + } /* Only need to redraw this line, unless still need to redraw an old * Visual area (when 'lazyredraw' is set). */ if (curwin->w_redr_type < INVERTED) { @@ -6625,8 +6833,9 @@ static void nv_window(cmdarg_T *cap) static void nv_suspend(cmdarg_T *cap) { clearop(cap->oap); - if (VIsual_active) - end_visual_mode(); /* stop Visual mode */ + if (VIsual_active) { + end_visual_mode(); // stop Visual mode + } do_cmdline_cmd("st"); } @@ -6635,7 +6844,7 @@ static void nv_suspend(cmdarg_T *cap) */ static void nv_g_cmd(cmdarg_T *cap) { - oparg_T *oap = cap->oap; + oparg_T *oap = cap->oap; pos_T tpos; int i; bool flag = false; @@ -6670,18 +6879,19 @@ static void nv_g_cmd(cmdarg_T *cap) /* * "gv": Reselect the previous Visual area. If Visual already active, - * exchange previous and current Visual area. + * exchange previous and current Visual area. */ case 'v': - if (checkclearop(oap)) + if (checkclearop(oap)) { break; + } - if ( curbuf->b_visual.vi_start.lnum == 0 - || curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count - || curbuf->b_visual.vi_end.lnum == 0) + if (curbuf->b_visual.vi_start.lnum == 0 + || curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count + || curbuf->b_visual.vi_end.lnum == 0) { beep_flush(); - else { - /* set w_cursor to the start of the Visual area, tpos to the end */ + } else { + // set w_cursor to the start of the Visual area, tpos to the end if (VIsual_active) { i = VIsual_mode; VIsual_mode = curbuf->b_visual.vi_mode; @@ -6727,7 +6937,7 @@ static void nv_g_cmd(cmdarg_T *cap) break; /* * "gV": Don't reselect the previous Visual area after a Select mode - * mapping of menu. + * mapping of menu. */ case 'V': VIsual_reselect = false; @@ -6755,8 +6965,9 @@ static void nv_g_cmd(cmdarg_T *cap) */ case 'N': case 'n': - if (!current_search(cap->count1, cap->nchar == 'n')) + if (!current_search(cap->count1, cap->nchar == 'n')) { clearopbeep(oap); + } break; /* @@ -6769,10 +6980,12 @@ static void nv_g_cmd(cmdarg_T *cap) if (!curwin->w_p_wrap) { oap->motion_type = kMTLineWise; i = cursor_down(cap->count1, oap->op_type == OP_NOP); - } else + } else { i = nv_screengo(oap, FORWARD, cap->count1); - if (!i) + } + if (!i) { clearopbeep(oap); + } break; case 'k': @@ -6781,10 +6994,12 @@ static void nv_g_cmd(cmdarg_T *cap) if (!curwin->w_p_wrap) { oap->motion_type = kMTLineWise; i = cursor_up(cap->count1, oap->op_type == OP_NOP); - } else + } else { i = nv_screengo(oap, BACKWARD, cap->count1); - if (!i) + } + if (!i) { clearopbeep(oap); + } break; /* @@ -6809,17 +7024,18 @@ static void nv_g_cmd(cmdarg_T *cap) oap->motion_type = kMTCharWise; oap->inclusive = false; if (curwin->w_p_wrap - && curwin->w_width_inner != 0 - ) { + && curwin->w_width_inner != 0) { int width1 = curwin->w_width_inner - curwin_col_off(); int width2 = width1 + curwin_col_off2(); validate_virtcol(); i = 0; - if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0) + if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0) { i = (curwin->w_virtcol - width1) / width2 * width2 + width1; - } else + } + } else { i = curwin->w_leftcol; + } /* Go to the middle of the screen line. When 'number' or * 'relativenumber' is on and lines are wrapping the middle can be more * to the left. */ @@ -6838,8 +7054,7 @@ static void nv_g_cmd(cmdarg_T *cap) curwin->w_set_curswant = true; break; - case 'M': - { + case 'M': { const char_u *const ptr = get_cursor_line_ptr(); oap->motion_type = kMTCharWise; @@ -6861,19 +7076,21 @@ static void nv_g_cmd(cmdarg_T *cap) cap->oap->inclusive = true; curwin->w_curswant = MAXCOL; if (cursor_down(cap->count1 - 1, - cap->oap->op_type == OP_NOP) == false) + cap->oap->op_type == OP_NOP) == false) { clearopbeep(cap->oap); - else { - char_u *ptr = get_cursor_line_ptr(); + } else { + char_u *ptr = 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) + // In Visual mode we may end up after the line. + if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) { --curwin->w_cursor.col; + } - /* Decrease the cursor column until it's on a non-blank. */ + // Decrease the cursor column until it's on a non-blank. while (curwin->w_cursor.col > 0 - && ascii_iswhite(ptr[curwin->w_cursor.col])) + && ascii_iswhite(ptr[curwin->w_cursor.col])) { --curwin->w_cursor.col; + } curwin->w_set_curswant = true; adjust_for_sel(cap); } @@ -6881,57 +7098,58 @@ static void nv_g_cmd(cmdarg_T *cap) case '$': case K_END: - case K_KEND: - { - int col_off = curwin_col_off(); + case K_KEND: { + int col_off = curwin_col_off(); - oap->motion_type = kMTCharWise; - oap->inclusive = true; - if (curwin->w_p_wrap - && curwin->w_width_inner != 0 - ) { - curwin->w_curswant = MAXCOL; /* so we stay at the end */ - if (cap->count1 == 1) { - int width1 = curwin->w_width_inner - col_off; - int width2 = width1 + curwin_col_off2(); + oap->motion_type = kMTCharWise; + oap->inclusive = true; + if (curwin->w_p_wrap + && curwin->w_width_inner != 0) { + curwin->w_curswant = MAXCOL; // so we stay at the end + if (cap->count1 == 1) { + int width1 = curwin->w_width_inner - col_off; + int width2 = width1 + curwin_col_off2(); - validate_virtcol(); - i = width1 - 1; - if (curwin->w_virtcol >= (colnr_T)width1) - i += ((curwin->w_virtcol - width1) / width2 + 1) - * width2; + validate_virtcol(); + i = width1 - 1; + if (curwin->w_virtcol >= (colnr_T)width1) { + i += ((curwin->w_virtcol - width1) / width2 + 1) + * width2; + } + coladvance((colnr_T)i); + + // Make sure we stick in this column. + validate_virtcol(); + curwin->w_curswant = curwin->w_virtcol; + curwin->w_set_curswant = false; + if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { + /* + * Check for landing on a character that got split at + * the end of the line. We do not want to advance to + * the next screen line. + */ + if (curwin->w_virtcol > (colnr_T)i) { + --curwin->w_cursor.col; + } + } + } else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == false) { + clearopbeep(oap); + } + } else { + if (cap->count1 > 1) { + // if it fails, let the cursor still move to the last char + (void)cursor_down(cap->count1 - 1, false); + } + i = curwin->w_leftcol + curwin->w_width_inner - col_off - 1; coladvance((colnr_T)i); - /* Make sure we stick in this column. */ + // Make sure we stick in this column. validate_virtcol(); curwin->w_curswant = curwin->w_virtcol; curwin->w_set_curswant = false; - if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { - /* - * Check for landing on a character that got split at - * the end of the line. We do not want to advance to - * the next screen line. - */ - if (curwin->w_virtcol > (colnr_T)i) - --curwin->w_cursor.col; - } - } else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == false) - clearopbeep(oap); - } else { - if (cap->count1 > 1) { - // if it fails, let the cursor still move to the last char - (void)cursor_down(cap->count1 - 1, false); } - i = curwin->w_leftcol + curwin->w_width_inner - col_off - 1; - coladvance((colnr_T)i); - - // Make sure we stick in this column. - validate_virtcol(); - curwin->w_curswant = curwin->w_virtcol; - curwin->w_set_curswant = false; } - } - break; + break; /* * "g*" and "g#", like "*" and "#" but without using "\<" and "\>" @@ -6939,10 +7157,10 @@ static void nv_g_cmd(cmdarg_T *cap) case '*': case '#': #if POUND != '#' - case POUND: /* pound sign (sometimes equal to '#') */ + case POUND: // pound sign (sometimes equal to '#') #endif - case Ctrl_RSB: /* :tag or :tselect for current identifier */ - case ']': /* :tselect for current identifier */ + case Ctrl_RSB: // :tag or :tselect for current identifier + case ']': // :tselect for current identifier nv_ident(cap); break; @@ -6954,8 +7172,9 @@ static void nv_g_cmd(cmdarg_T *cap) oap->motion_type = kMTCharWise; curwin->w_set_curswant = true; oap->inclusive = true; - if (bckend_word(cap->count1, cap->nchar == 'E', false) == false) + if (bckend_word(cap->count1, cap->nchar == 'E', false) == false) { clearopbeep(oap); + } break; // "g CTRL-G": display info about cursor position @@ -6970,8 +7189,9 @@ static void nv_g_cmd(cmdarg_T *cap) check_cursor_lnum(); i = (int)STRLEN(get_cursor_line_ptr()); if (curwin->w_cursor.col > (colnr_T)i) { - if (virtual_active()) + if (virtual_active()) { curwin->w_cursor.coladd += curwin->w_cursor.col - i; + } curwin->w_cursor.col = i; } } @@ -6984,8 +7204,9 @@ static void nv_g_cmd(cmdarg_T *cap) */ case 'I': beginline(0); - if (!checkclearopq(oap)) + if (!checkclearopq(oap)) { invoke_edit(cap, false, 'g', false); + } break; /* @@ -6997,7 +7218,7 @@ static void nv_g_cmd(cmdarg_T *cap) nv_gotofile(cap); break; - /* "g'm" and "g`m": jump to mark without setting pcmark */ + // "g'm" and "g`m": jump to mark without setting pcmark case '\'': cap->arg = true; FALLTHROUGH; @@ -7014,7 +7235,7 @@ static void nv_g_cmd(cmdarg_T *cap) /* * "ga": Display the ascii value of the character under the - * cursor. It is displayed in decimal, hex, and octal. -- webb + * cursor. It is displayed in decimal, hex, and octal. -- webb */ case 'a': do_ascii(NULL); @@ -7022,14 +7243,15 @@ static void nv_g_cmd(cmdarg_T *cap) /* * "g8": Display the bytes used for the UTF-8 character under the - * cursor. It is displayed in hex. + * cursor. It is displayed in hex. * "8g8" finds illegal byte sequence. */ case '8': - if (cap->count0 == 8) + if (cap->count0 == 8) { utf_find_illegal(); - else + } else { show_utf8(); + } break; // "g<": show scrollback text case '<': @@ -7046,14 +7268,14 @@ static void nv_g_cmd(cmdarg_T *cap) break; /* - * Two-character operators: - * "gq" Format text - * "gw" Format text and keep cursor position - * "g~" Toggle the case of the text. - * "gu" Change text to lower case. - * "gU" Change text to upper case. - * "g?" rot13 encoding - * "g@" call 'operatorfunc' + * Two-character operators: + * "gq" Format text + * "gw" Format text and keep cursor position + * "g~" Toggle the case of the text. + * "gu" Change text to lower case. + * "gU" Change text to upper case. + * "g?" rot13 encoding + * "g@" call 'operatorfunc' */ case 'q': case 'w': @@ -7069,7 +7291,7 @@ static void nv_g_cmd(cmdarg_T *cap) /* * "gd": Find first occurrence of pattern under the cursor in the - * current function + * current function * "gD": idem, but in the current file. */ case 'd': @@ -7111,12 +7333,12 @@ static void nv_g_cmd(cmdarg_T *cap) nv_put(cap); break; - /* "go": goto byte count from start of buffer */ + // "go": goto byte count from start of buffer case 'o': goto_byte(cap->count0); break; - /* "gQ": improved Ex mode */ + // "gQ": improved Ex mode case 'Q': if (text_locked()) { clearopbeep(cap->oap); @@ -7139,12 +7361,14 @@ static void nv_g_cmd(cmdarg_T *cap) break; case 't': - if (!checkclearop(oap)) + if (!checkclearop(oap)) { goto_tabpage((int)cap->count0); + } break; case 'T': - if (!checkclearop(oap)) + if (!checkclearop(oap)) { goto_tabpage(-(int)cap->count1); + } break; case TAB: if (!checkclearop(oap)) { @@ -7153,10 +7377,11 @@ static void nv_g_cmd(cmdarg_T *cap) break; case '+': - case '-': /* "g+" and "g-": undo or redo along the timeline */ - if (!checkclearopq(oap)) + case '-': // "g+" and "g-": undo or redo along the timeline + if (!checkclearopq(oap)) { undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1, - false, false, false); + false, false, false); + } break; default: @@ -7171,19 +7396,20 @@ static void nv_g_cmd(cmdarg_T *cap) static void n_opencmd(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { - if (cap->cmdchar == 'O') - /* Open above the first line of a folded sequence of lines */ + if (cap->cmdchar == 'O') { + // Open above the first line of a folded sequence of lines (void)hasFolding(curwin->w_cursor.lnum, - &curwin->w_cursor.lnum, NULL); - else - /* Open below the last line of a folded sequence of lines */ + &curwin->w_cursor.lnum, NULL); + } else { + // Open below the last line of a folded sequence of lines (void)hasFolding(curwin->w_cursor.lnum, - NULL, &curwin->w_cursor.lnum); + NULL, &curwin->w_cursor.lnum); + } if (u_save((linenr_T)(curwin->w_cursor.lnum - (cap->cmdchar == 'O' ? 1 : 0)), - (linenr_T)(curwin->w_cursor.lnum + - (cap->cmdchar == 'o' ? 1 : 0)) - ) + (linenr_T)(curwin->w_cursor.lnum + + (cap->cmdchar == 'o' ? 1 : 0)) + ) && open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD, has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM : 0, @@ -7208,8 +7434,9 @@ static void nv_dot(cmdarg_T *cap) * instead of the last command (inserting text). This is used for * CTRL-O <.> in insert mode. */ - if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == false) + if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == false) { clearopbeep(cap->oap); + } } } @@ -7229,11 +7456,10 @@ static void nv_redo(cmdarg_T *cap) */ static void nv_Undo(cmdarg_T *cap) { - /* In Visual mode and typing "gUU" triggers an operator */ + // In Visual mode and typing "gUU" triggers an operator if (cap->oap->op_type == OP_UPPER - || VIsual_active - ) { - /* translate "gUU" to "gUgU" */ + || VIsual_active) { + // translate "gUU" to "gUgU" cap->cmdchar = 'g'; cap->nchar = 'U'; nv_operator(cap); @@ -7278,9 +7504,9 @@ static void nv_operator(cmdarg_T *cap) return; } - if (op_type == cap->oap->op_type) /* double operator works on lines */ + if (op_type == cap->oap->op_type) { // double operator works on lines nv_lineop(cap); - else if (!checkclearop(cap->oap)) { + } else if (!checkclearop(cap->oap)) { cap->oap->start = curwin->w_cursor; cap->oap->op_type = op_type; set_op_var(op_type); @@ -7298,11 +7524,11 @@ static void set_op_var(int optype) char opchars[3]; int opchar0 = get_op_char(optype); assert(opchar0 >= 0 && opchar0 <= UCHAR_MAX); - opchars[0] = (char) opchar0; + opchars[0] = (char)opchar0; int opchar1 = get_extra_op_char(optype); assert(opchar1 >= 0 && opchar1 <= UCHAR_MAX); - opchars[1] = (char) opchar1; + opchars[1] = (char)opchar1; opchars[2] = NUL; set_vim_var_string(VV_OP, opchars, -1); @@ -7340,10 +7566,10 @@ static void nv_lineop(cmdarg_T *cap) */ static void nv_home(cmdarg_T *cap) { - /* CTRL-HOME is like "gg" */ - if (mod_mask & MOD_MASK_CTRL) + // CTRL-HOME is like "gg" + if (mod_mask & MOD_MASK_CTRL) { nv_goto(cap); - else { + } else { cap->count0 = 1; nv_pipe(cap); } @@ -7362,8 +7588,9 @@ static void nv_pipe(cmdarg_T *cap) if (cap->count0 > 0) { coladvance((colnr_T)(cap->count0 - 1)); curwin->w_curswant = (colnr_T)(cap->count0 - 1); - } else + } else { curwin->w_curswant = 0; + } /* keep curswant at the column where we wanted to go, not where * we ended; differs if line is too short */ curwin->w_set_curswant = false; @@ -7378,10 +7605,11 @@ static void nv_bck_word(cmdarg_T *cap) cap->oap->motion_type = kMTCharWise; cap->oap->inclusive = false; curwin->w_set_curswant = true; - if (bck_word(cap->count1, cap->arg, false) == false) + if (bck_word(cap->count1, cap->arg, false) == false) { clearopbeep(cap->oap); - else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) + } else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } /* @@ -7398,10 +7626,11 @@ static void nv_wordcmd(cmdarg_T *cap) /* * Set inclusive for the "E" and "e" command. */ - if (cap->cmdchar == 'e' || cap->cmdchar == 'E') + if (cap->cmdchar == 'e' || cap->cmdchar == 'E') { word_end = true; - else + } else { word_end = false; + } cap->oap->inclusive = word_end; /* @@ -7428,22 +7657,25 @@ static void nv_wordcmd(cmdarg_T *cap) cap->oap->motion_type = kMTCharWise; curwin->w_set_curswant = true; - if (word_end) + if (word_end) { n = end_word(cap->count1, cap->arg, flag, false); - else + } else { n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP); + } /* Don't leave the cursor on the NUL past the end of line. Unless we * didn't move it forward. */ - if (lt(startpos, curwin->w_cursor)) + if (lt(startpos, curwin->w_cursor)) { adjust_cursor(cap->oap); + } - if (n == false && cap->oap->op_type == OP_NOP) + if (n == false && cap->oap->op_type == OP_NOP) { clearopbeep(cap->oap); - else { + } else { adjust_for_sel(cap); - if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) + if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } } @@ -7461,8 +7693,8 @@ static void adjust_cursor(oparg_T *oap) */ if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL && (!VIsual_active || *p_sel == 'o') - && !virtual_active() && (ve_flags & VE_ONEMORE) == 0 - ) { + && !virtual_active() && + (ve_flags & VE_ONEMORE) == 0) { curwin->w_cursor.col--; // prevent cursor from moving on the trail byte mb_adjust_cursor(); @@ -7479,8 +7711,9 @@ static void nv_beginline(cmdarg_T *cap) cap->oap->motion_type = kMTCharWise; cap->oap->inclusive = false; beginline(cap->arg); - if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) + if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } ins_at_eol = false; /* Don't move cursor past eol (only necessary in a one-character line). */ } @@ -7504,13 +7737,14 @@ static void adjust_for_sel(cmdarg_T *cap) */ static bool unadjust_for_sel(void) { - pos_T *pp; + pos_T *pp; if (*p_sel == 'e' && !equalpos(VIsual, curwin->w_cursor)) { - if (lt(VIsual, curwin->w_cursor)) + if (lt(VIsual, curwin->w_cursor)) { pp = &curwin->w_cursor; - else + } else { pp = &VIsual; + } if (pp->coladd > 0) { pp->coladd--; } else if (pp->col > 0) { @@ -7530,10 +7764,10 @@ static bool unadjust_for_sel(void) */ static void nv_select(cmdarg_T *cap) { - if (VIsual_active) + if (VIsual_active) { VIsual_select = true; - else if (VIsual_reselect) { - cap->nchar = 'v'; /* fake "gv" command */ + } else if (VIsual_reselect) { + cap->nchar = 'v'; // fake "gv" command cap->arg = true; nv_g_cmd(cap); } @@ -7548,24 +7782,28 @@ static void nv_goto(cmdarg_T *cap) { linenr_T lnum; - if (cap->arg) + if (cap->arg) { lnum = curbuf->b_ml.ml_line_count; - else + } else { lnum = 1L; + } cap->oap->motion_type = kMTLineWise; setpcmark(); - /* When a count is given, use it instead of the default lnum */ - if (cap->count0 != 0) + // When a count is given, use it instead of the default lnum + if (cap->count0 != 0) { lnum = cap->count0; - if (lnum < 1L) + } + if (lnum < 1L) { lnum = 1L; - else if (lnum > curbuf->b_ml.ml_line_count) + } else if (lnum > curbuf->b_ml.ml_line_count) { lnum = curbuf->b_ml.ml_line_count; + } curwin->w_cursor.lnum = lnum; beginline(BL_SOL | BL_FIX); - if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP) + if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP) { foldOpenCursor(); + } } /* @@ -7575,20 +7813,24 @@ static void nv_normal(cmdarg_T *cap) { if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G) { clearop(cap->oap); - if (restart_edit != 0 && mode_displayed) - clear_cmdline = true; /* unshow mode later */ + if (restart_edit != 0 && mode_displayed) { + clear_cmdline = true; // unshow mode later + } restart_edit = 0; - if (cmdwin_type != 0) + if (cmdwin_type != 0) { cmdwin_result = Ctrl_C; + } if (VIsual_active) { - end_visual_mode(); /* stop Visual */ + end_visual_mode(); // stop Visual redraw_curbuf_later(INVERTED); } - /* CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. */ - if (cap->nchar == Ctrl_G && p_im) + // CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. + if (cap->nchar == Ctrl_G && p_im) { restart_edit = 'a'; - } else + } + } else { clearopbeep(cap->oap); + } } /* @@ -7605,7 +7847,7 @@ static void nv_esc(cmdarg_T *cap) && cap->oap->regname == 0 && !p_im); - if (cap->arg) { /* true for CTRL-C */ + if (cap->arg) { // true for CTRL-C if (restart_edit == 0 && cmdwin_type == 0 && !VIsual_active @@ -7620,11 +7862,12 @@ static void nv_esc(cmdarg_T *cap) /* Don't reset "restart_edit" when 'insertmode' is set, it won't be * set again below when halfway through a mapping. */ - if (!p_im) + if (!p_im) { restart_edit = 0; + } if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; - got_int = false; /* don't stop executing autocommands et al. */ + got_int = false; // don't stop executing autocommands et al. return; } } else if (cmdwin_type != 0 && ex_normal_busy) { @@ -7636,8 +7879,8 @@ static void nv_esc(cmdarg_T *cap) } if (VIsual_active) { - end_visual_mode(); /* stop Visual */ - check_cursor_col(); /* make sure cursor is not beyond EOL */ + end_visual_mode(); // stop Visual + check_cursor_col(); // make sure cursor is not beyond EOL curwin->w_set_curswant = true; redraw_curbuf_later(INVERTED); } else if (no_reason) { @@ -7648,9 +7891,9 @@ static void nv_esc(cmdarg_T *cap) /* A CTRL-C is often used at the start of a menu. When 'insertmode' is * set return to Insert mode afterwards. */ if (restart_edit == 0 && goto_im() - && ex_normal_busy == 0 - ) + && ex_normal_busy == 0) { restart_edit = 'a'; + } } // Move the cursor for the "A" command. @@ -7681,7 +7924,7 @@ static void nv_edit(cmdarg_T *cap) // in Visual mode "A" and "I" are an operator if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I')) { v_visop(cap); - // in Visual mode and after an operator "a" and "i" are for text objects + // in Visual mode and after an operator "a" and "i" are for text objects } else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i') && (cap->oap->op_type != OP_NOP || VIsual_active)) { nv_object(cap); @@ -7695,20 +7938,21 @@ static void nv_edit(cmdarg_T *cap) set_cursor_for_append_to_line(); break; - case 'I': /* "I"nsert before the first non-blank */ + case 'I': // "I"nsert before the first non-blank beginline(BL_WHITE); break; - case 'a': /* "a"ppend is like "i"nsert on the next character. */ + case 'a': // "a"ppend is like "i"nsert on the next character. /* increment coladd when in virtual space, increment the * column otherwise, also to append after an unprintable char */ if (virtual_active() && (curwin->w_cursor.coladd > 0 || *get_cursor_pos_ptr() == NUL - || *get_cursor_pos_ptr() == TAB)) + || *get_cursor_pos_ptr() == TAB)) { curwin->w_cursor.coladd++; - else if (*get_cursor_pos_ptr() != NUL) + } else if (*get_cursor_pos_ptr() != NUL) { inc_cursor(); + } break; } @@ -7726,35 +7970,32 @@ static void nv_edit(cmdarg_T *cap) } } -/* - * Invoke edit() and take care of "restart_edit" and the return value. - */ -static void -invoke_edit ( - cmdarg_T *cap, - int repl, /* "r" or "gr" command */ - int cmd, - int startln -) +/// Invoke edit() and take care of "restart_edit" and the return value. +/// +/// @param repl "r" or "gr" command +static void invoke_edit(cmdarg_T *cap, int repl, int cmd, int startln) { int restart_edit_save = 0; /* Complicated: When the user types "a<C-O>a" we don't want to do Insert * mode recursively. But when doing "a<C-O>." or "a<C-O>rx" we do allow * it. */ - if (repl || !stuff_empty()) + if (repl || !stuff_empty()) { restart_edit_save = restart_edit; - else + } else { restart_edit_save = 0; + } - /* Always reset "restart_edit", this is not a restarted edit. */ + // Always reset "restart_edit", this is not a restarted edit. restart_edit = 0; - if (edit(cmd, startln, cap->count1)) + if (edit(cmd, startln, cap->count1)) { cap->retval |= CA_COMMAND_BUSY; + } - if (restart_edit == 0) + if (restart_edit == 0) { restart_edit = restart_edit_save; + } } /* @@ -7764,43 +8005,43 @@ static void nv_object(cmdarg_T *cap) { bool flag; bool include; - char_u *mps_save; + char_u *mps_save; - if (cap->cmdchar == 'i') - include = false; /* "ix" = inner object: exclude white space */ - else - include = true; /* "ax" = an object: include white space */ - - /* Make sure (), [], {} and <> are in 'matchpairs' */ + if (cap->cmdchar == 'i') { + include = false; // "ix" = inner object: exclude white space + } else { + include = true; // "ax" = an object: include white space + } + // Make sure (), [], {} and <> are in 'matchpairs' mps_save = curbuf->b_p_mps; curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>"; switch (cap->nchar) { - case 'w': /* "aw" = a word */ + case 'w': // "aw" = a word flag = current_word(cap->oap, cap->count1, include, false); break; - case 'W': /* "aW" = a WORD */ + case 'W': // "aW" = a WORD flag = current_word(cap->oap, cap->count1, include, true); break; - case 'b': /* "ab" = a braces block */ + case 'b': // "ab" = a braces block case '(': case ')': flag = current_block(cap->oap, cap->count1, include, '(', ')'); break; - case 'B': /* "aB" = a Brackets block */ + case 'B': // "aB" = a Brackets block case '{': case '}': flag = current_block(cap->oap, cap->count1, include, '{', '}'); break; - case '[': /* "a[" = a [] block */ + case '[': // "a[" = a [] block case ']': flag = current_block(cap->oap, cap->count1, include, '[', ']'); break; - case '<': /* "a<" = a <> block */ + case '<': // "a<" = a <> block case '>': flag = current_block(cap->oap, cap->count1, include, '<', '>'); break; - case 't': /* "at" = a tag block (xml and html) */ + case 't': // "at" = a tag block (xml and html) // Do not adjust oap->end in do_pending_operator() // otherwise there are different results for 'dit' // (note leading whitespace in last line): @@ -7810,17 +8051,17 @@ static void nv_object(cmdarg_T *cap) cap->retval |= CA_NO_ADJ_OP_END; flag = current_tagblock(cap->oap, cap->count1, include); break; - case 'p': /* "ap" = a paragraph */ + case 'p': // "ap" = a paragraph flag = current_par(cap->oap, cap->count1, include, 'p'); break; - case 's': /* "as" = a sentence */ + case 's': // "as" = a sentence flag = current_sent(cap->oap, cap->count1, include); break; - case '"': /* "a"" = a double quoted string */ - case '\'': /* "a'" = a single quoted string */ - case '`': /* "a`" = a backtick quoted string */ + case '"': // "a"" = a double quoted string + case '\'': // "a'" = a single quoted string + case '`': // "a`" = a backtick quoted string flag = current_quote(cap->oap, cap->count1, include, - cap->nchar); + cap->nchar); break; default: flag = false; @@ -7828,8 +8069,9 @@ static void nv_object(cmdarg_T *cap) } curbuf->b_p_mps = mps_save; - if (!flag) + if (!flag) { clearopbeep(cap->oap); + } adjust_cursor_col(); curwin->w_set_curswant = true; } @@ -7841,7 +8083,7 @@ static void nv_object(cmdarg_T *cap) static void nv_record(cmdarg_T *cap) { if (cap->oap->op_type == OP_FORMAT) { - /* "gqq" is the same as "gqgq": format line */ + // "gqq" is the same as "gqgq": format line cap->cmdchar = 'g'; cap->nchar = 'q'; nv_operator(cap); @@ -7864,11 +8106,13 @@ static void nv_record(cmdarg_T *cap) */ static void nv_at(cmdarg_T *cap) { - if (checkclearop(cap->oap)) + if (checkclearop(cap->oap)) { return; + } if (cap->nchar == '=') { - if (get_expr_register() == NUL) + if (get_expr_register() == NUL) { return; + } } while (cap->count1-- && !got_int) { if (do_execreg(cap->nchar, false, false, false) == false) { @@ -7886,10 +8130,11 @@ static void nv_halfpage(cmdarg_T *cap) { if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1) || (cap->cmdchar == Ctrl_D - && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)) + && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)) { clearopbeep(cap->oap); - else if (!checkclearop(cap->oap)) + } else if (!checkclearop(cap->oap)) { halfpage(cap->cmdchar == Ctrl_D, cap->count0); + } } /* @@ -7939,7 +8184,7 @@ static void nv_put_opt(cmdarg_T *cap, bool fix_indent) int flags = 0; if (cap->oap->op_type != OP_NOP) { - /* "dp" is ":diffput" */ + // "dp" is ":diffput" if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p') { clearop(cap->oap); assert(cap->opcount >= 0); @@ -7976,7 +8221,7 @@ static void nv_put_opt(cmdarg_T *cap, bool fix_indent) regname = cap->oap->regname; // '+' and '*' could be the same selection bool clipoverwrite = (regname == '+' || regname == '*') - && (cb_flags & CB_UNNAMEDMASK); + && (cb_flags & CB_UNNAMEDMASK); if (regname == 0 || regname == '"' || clipoverwrite || ascii_isdigit(regname) || regname == '-') { // The delete might overwrite the register we want to put, save it first @@ -8017,11 +8262,12 @@ static void nv_put_opt(cmdarg_T *cap, bool fix_indent) if ((VIsual_mode != 'V' && curwin->w_cursor.col < curbuf->b_op_start.col) || (VIsual_mode == 'V' - && curwin->w_cursor.lnum < curbuf->b_op_start.lnum)) + && curwin->w_cursor.lnum < curbuf->b_op_start.lnum)) { /* cursor is at the end of the line or end of file, put * forward. */ dir = FORWARD; - /* May have been reset in do_put(). */ + } + // May have been reset in do_put(). VIsual_active = true; } do_put(cap->oap->regname, savereg, dir, cap->count1, flags); @@ -8065,7 +8311,7 @@ static void nv_put_opt(cmdarg_T *cap, bool fix_indent) */ static void nv_open(cmdarg_T *cap) { - /* "do" is ":diffget" */ + // "do" is ":diffget" if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o') { clearop(cap->oap); assert(cap->opcount >= 0); @@ -8080,12 +8326,10 @@ static void nv_open(cmdarg_T *cap) } } -// Calculate start/end virtual columns for operating in block mode. -static void get_op_vcol( - oparg_T *oap, - colnr_T redo_VIsual_vcol, - bool initial // when true: adjust position for 'selectmode' -) +/// Calculate start/end virtual columns for operating in block mode. +/// +/// @param initial when true: adjust position for 'selectmode' +static void get_op_vcol(oparg_T *oap, colnr_T redo_VIsual_vcol, bool initial) { colnr_T start; colnr_T end; diff --git a/src/nvim/ops.c b/src/nvim/ops.c index a06db4a551..77432149ce 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -11,27 +11,27 @@ #include <stdbool.h> #include <string.h> -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/ops.h" +#include "nvim/assert.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" -#include "nvim/assert.h" #include "nvim/edit.h" #include "nvim/eval.h" #include "nvim/eval/typval.h" #include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_getln.h" +#include "nvim/extmark.h" #include "nvim/fileio.h" #include "nvim/fold.h" #include "nvim/getchar.h" #include "nvim/indent.h" +#include "nvim/lib/kvec.h" #include "nvim/log.h" +#include "nvim/macros.h" #include "nvim/mark.h" -#include "nvim/extmark.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" @@ -39,7 +39,10 @@ #include "nvim/misc1.h" #include "nvim/move.h" #include "nvim/normal.h" +#include "nvim/ops.h" #include "nvim/option.h" +#include "nvim/os/input.h" +#include "nvim/os/time.h" #include "nvim/path.h" #include "nvim/plines.h" #include "nvim/screen.h" @@ -49,15 +52,12 @@ #include "nvim/terminal.h" #include "nvim/ui.h" #include "nvim/undo.h" -#include "nvim/macros.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/lib/kvec.h" -#include "nvim/os/input.h" -#include "nvim/os/time.h" static yankreg_T y_regs[NUM_REGISTERS]; -static yankreg_T *y_previous = NULL; /* ptr to last written yankreg */ +static yankreg_T *y_previous = NULL; // ptr to last written yankreg // for behavior between start_batch_changes() and end_batch_changes()) static int batch_change_count = 0; // inside a script @@ -70,20 +70,20 @@ static bool clipboard_didwarn = false; * 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 */ - int textlen; /* chars in block */ - char_u *textstart; /* pointer to 1st char (partially) in block */ - colnr_T textcol; /* index of chars (partially) in block */ - colnr_T start_vcol; /* start col of 1st char wholly inside block */ - colnr_T end_vcol; /* start col of 1st char wholly after block */ - int is_short; /* TRUE if line is too short to fit in block */ - int is_MAX; /* TRUE if curswant==MAXCOL when starting */ - int is_oneChar; /* TRUE if block within one character */ - int pre_whitesp; /* screen cols of ws before block */ - int pre_whitesp_c; /* chars of ws before block */ - colnr_T end_char_vcols; /* number of vcols of post-block char */ - colnr_T start_char_vcols; /* number of vcols of pre-block char */ + int startspaces; // 'extra' cols before first char + int endspaces; // 'extra' cols after last char + int textlen; // chars in block + char_u *textstart; // pointer to 1st char (partially) in block + colnr_T textcol; // index of chars (partially) in block + colnr_T start_vcol; // start col of 1st char wholly inside block + colnr_T end_vcol; // start col of 1st char wholly after block + int is_short; // TRUE if line is too short to fit in block + int is_MAX; // TRUE if curswant==MAXCOL when starting + int is_oneChar; // TRUE if block within one character + int pre_whitesp; // screen cols of ws before block + int pre_whitesp_c; // chars of ws before block + colnr_T end_char_vcols; // number of vcols of post-block char + colnr_T start_char_vcols; // number of vcols of pre-block char }; #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -183,7 +183,7 @@ int op_on_lines(int op) // Return TRUE if operator "op" changes text. int op_is_change(int op) { - return opchars[op][2] & OPF_CHANGE; + return opchars[op][2] & OPF_CHANGE; } /* @@ -210,12 +210,13 @@ void op_shift(oparg_T *oap, int curs_top, int amount) { long i; int first_char; - char_u *s; + char_u *s; int block_col = 0; if (u_save((linenr_T)(oap->start.lnum - 1), - (linenr_T)(oap->end.lnum + 1)) == FAIL) + (linenr_T)(oap->end.lnum + 1)) == FAIL) { return; + } if (oap->motion_type == kMTBlockWise) { block_col = curwin->w_cursor.col; @@ -238,32 +239,35 @@ void op_shift(oparg_T *oap, int curs_top, int amount) if (oap->motion_type == kMTBlockWise) { curwin->w_cursor.lnum = oap->start.lnum; curwin->w_cursor.col = block_col; - } else if (curs_top) { /* put cursor on first line, for ">>" */ + } else if (curs_top) { // put cursor on first line, for ">>" curwin->w_cursor.lnum = oap->start.lnum; - beginline(BL_SOL | BL_FIX); /* shift_line() may have set cursor.col */ - } else - --curwin->w_cursor.lnum; /* put cursor on last line, for ":>" */ - + beginline(BL_SOL | BL_FIX); // shift_line() may have set cursor.col + } else { + --curwin->w_cursor.lnum; // put cursor on last line, for ":>" + } // The cursor line is not in a closed fold foldOpenCursor(); if (oap->line_count > p_report) { - if (oap->op_type == OP_RSHIFT) + if (oap->op_type == OP_RSHIFT) { s = (char_u *)">"; - else + } else { s = (char_u *)"<"; + } if (oap->line_count == 1) { - if (amount == 1) + if (amount == 1) { sprintf((char *)IObuff, _("1 line %sed 1 time"), s); - else + } else { sprintf((char *)IObuff, _("1 line %sed %d times"), s, amount); + } } else { - if (amount == 1) + if (amount == 1) { sprintf((char *)IObuff, _("%" PRId64 " lines %sed 1 time"), - (int64_t)oap->line_count, s); - else + (int64_t)oap->line_count, s); + } else { sprintf((char *)IObuff, _("%" PRId64 " lines %sed %d times"), - (int64_t)oap->line_count, s, amount); + (int64_t)oap->line_count, s, amount); + } } msg_attr_keep(IObuff, 0, true, false); } @@ -281,14 +285,11 @@ void op_shift(oparg_T *oap, int curs_top, int amount) changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L, true); } -// Shift the current line one shiftwidth left (if left != 0) or right -// leaves cursor on first blank in the line. -void shift_line( - int left, - int round, - int amount, - int call_changed_bytes // call changed_bytes() -) +/// Shift the current line one shiftwidth left (if left != 0) or right +/// leaves cursor on first blank in the line. +/// +/// @param call_changed_bytes call changed_bytes() +void shift_line(int left, int round, int amount, int call_changed_bytes) { int count; int i, j; @@ -304,18 +305,22 @@ void shift_line( } if (left) { i -= amount; - if (i < 0) + if (i < 0) { i = 0; - } else + } + } else { i += amount; + } count = i * p_sw; } else { // original vi indent if (left) { count -= p_sw * amount; - if (count < 0) + if (count < 0) { count = 0; - } else + } + } else { count += p_sw * amount; + } } // Set new indent @@ -344,7 +349,7 @@ static void shift_block(oparg_T *oap, int amount) int i = 0, j = 0; const int old_p_ri = p_ri; - p_ri = 0; /* don't want revins in indent */ + p_ri = 0; // don't want revins in indent State = INSERT; // don't want REPLACE for State block_prep(oap, &bd, curwin->w_cursor.lnum, true); @@ -408,7 +413,7 @@ static void shift_block(oparg_T *oap, int amount) newlen = i+j; memset(newp + bd.textcol, TAB, (size_t)i); memset(newp + bd.textcol + i, ' ', (size_t)j); - /* the end */ + // the end memmove(newp + bd.textcol + i + j, bd.textstart, (size_t)len); } else { // left colnr_T destination_col; // column to which text in block will @@ -420,7 +425,7 @@ static void shift_block(oparg_T *oap, int amount) size_t fill; // nr of spaces that replace a TAB size_t new_line_len; // the length of the line after the // block shift - char_u *non_white = bd.textstart; + char_u *non_white = bd.textstart; /* * Firstly, let's find the first non-whitespace character that is @@ -462,15 +467,17 @@ static void shift_block(oparg_T *oap, int amount) /* If "bd.startspaces" is set, "bd.textstart" points to the character * preceding the block. We have to subtract its width to obtain its * column number. */ - if (bd.startspaces) + 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) + if (verbatim_copy_width + incr > destination_col) { break; + } verbatim_copy_width += incr; MB_PTR_ADV(verbatim_copy_end); } @@ -519,7 +526,7 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def int spaces = 0; // non-zero if cutting a TAB colnr_T offset; // pointer along new line size_t s_len = STRLEN(s); - char_u *newp, *oldp; // new, old lines + char_u *newp, *oldp; // new, old lines linenr_T lnum; // loop var int oldstate = State; State = INSERT; // don't want REPLACE for State @@ -535,20 +542,23 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def if (b_insert) { p_ts = bdp->start_char_vcols; spaces = bdp->startspaces; - if (spaces != 0) - count = p_ts - 1; /* we're cutting a TAB */ + if (spaces != 0) { + count = p_ts - 1; // we're cutting a TAB + } offset = bdp->textcol; - } else { /* append */ + } else { // append p_ts = bdp->end_char_vcols; - if (!bdp->is_short) { /* spaces = padding after block */ + if (!bdp->is_short) { // spaces = padding after block spaces = (bdp->endspaces ? p_ts - bdp->endspaces : 0); - if (spaces != 0) - count = p_ts - 1; /* we're cutting a TAB */ + if (spaces != 0) { + count = p_ts - 1; // we're cutting a TAB + } offset = bdp->textcol + bdp->textlen - (spaces != 0); - } else { /* spaces = padding to block edge */ - /* if $ used, just append to EOL (ie spaces==0) */ - if (!bdp->is_MAX) + } else { // spaces = padding to block edge + // if $ used, just append to EOL (ie spaces==0) + if (!bdp->is_MAX) { spaces = (oap->end_vcol - bdp->end_vcol) + 1; + } count = spaces; offset = bdp->textcol + bdp->textlen; } @@ -594,8 +604,9 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def skipped = 1; } - if (spaces > 0) + if (spaces > 0) { offset += count; + } STRMOVE(newp + offset, oldp); ml_replace(lnum, newp, false); @@ -608,7 +619,7 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def curbuf->b_op_end.lnum = oap->end.lnum; curbuf->b_op_end.col = offset; } - } /* for all lnum */ + } // for all lnum changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L, true); @@ -621,13 +632,13 @@ static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def void op_reindent(oparg_T *oap, Indenter how) { long i; - char_u *l; + char_u *l; int amount; linenr_T first_changed = 0; linenr_T last_changed = 0; linenr_T start_lnum = curwin->w_cursor.lnum; - /* Don't even try when 'modifiable' is off. */ + // Don't even try when 'modifiable' is off. if (!MODIFIABLE(curbuf)) { EMSG(_(e_modifiable)); return; @@ -639,8 +650,9 @@ void op_reindent(oparg_T *oap, Indenter how) if (i > 1 && (i % 50 == 0 || i == oap->line_count - 1) - && oap->line_count > p_report) + && oap->line_count > p_report) { smsg(_("%" PRId64 " lines to indent... "), (int64_t)i); + } /* * Be vi-compatible: For lisp indenting the first line is not @@ -649,11 +661,11 @@ void op_reindent(oparg_T *oap, Indenter how) if (i != oap->line_count - 1 || oap->line_count == 1 || how != get_lisp_indent) { l = skipwhite(get_cursor_line_ptr()); - if (*l == NUL) /* empty or blank line */ + if (*l == NUL) { // empty or blank line amount = 0; - else - amount = how(); /* get the indent for this line */ - + } else { + amount = how(); // get the indent for this line + } if (amount >= 0 && set_indent(amount, SIN_UNDO)) { // did change the indent, call changed_lines() later if (first_changed == 0) { @@ -663,10 +675,10 @@ void op_reindent(oparg_T *oap, Indenter how) } } ++curwin->w_cursor.lnum; - curwin->w_cursor.col = 0; /* make sure it's valid */ + curwin->w_cursor.col = 0; // make sure it's valid } - /* put cursor on first non-blank of indented line */ + // put cursor on first non-blank of indented line curwin->w_cursor.lnum = start_lnum; beginline(BL_SOL | BL_FIX); @@ -683,12 +695,13 @@ void op_reindent(oparg_T *oap, Indenter how) if (oap->line_count > p_report) { i = oap->line_count - (i + 1); - if (i == 1) + if (i == 1) { MSG(_("1 line indented ")); - else + } else { smsg(_("%" PRId64 " lines indented "), (int64_t)i); + } } - /* set '[ and '] marks */ + // set '[ and '] marks curbuf->b_op_start = oap->start; curbuf->b_op_end = oap->end; } @@ -696,7 +709,7 @@ void op_reindent(oparg_T *oap, Indenter how) /* * Keep the last expression line here, for repeating. */ -static char_u *expr_line = NULL; +static char_u *expr_line = NULL; /* * Get an expression for the "\"=expr1" or "CTRL-R =expr1" @@ -704,7 +717,7 @@ static char_u *expr_line = NULL; */ int get_expr_register(void) { - char_u *new_line; + char_u *new_line; new_line = getcmdline('=', 0L, 0, true); if (new_line == NULL) { @@ -734,12 +747,13 @@ void set_expr_line(char_u *new_line) */ char_u *get_expr_line(void) { - char_u *expr_copy; - char_u *rv; + char_u *expr_copy; + char_u *rv; static int nested = 0; - if (expr_line == NULL) + if (expr_line == NULL) { return NULL; + } /* Make a copy of the expression, because evaluating it may cause it to be * changed. */ @@ -747,8 +761,9 @@ char_u *get_expr_line(void) /* When we are invoked recursively limit the evaluation to 10 levels. * Then return the string as-is. */ - if (nested >= 10) + if (nested >= 10) { return expr_copy; + } ++nested; rv = eval_to_string(expr_copy, NULL, TRUE); @@ -762,8 +777,9 @@ char_u *get_expr_line(void) */ char_u *get_expr_line_src(void) { - if (expr_line == NULL) + if (expr_line == NULL) { return NULL; + } return vim_strsave(expr_line); } @@ -776,7 +792,7 @@ char_u *get_expr_line_src(void) bool valid_yank_reg(int regname, bool writing) { if ((regname > 0 && ASCII_ISALNUM(regname)) - || (!writing && vim_strchr((char_u *) "/.%:=" , regname) != NULL) + || (!writing && vim_strchr((char_u *)"/.%:=", regname) != NULL) || regname == '#' || regname == '"' || regname == '-' @@ -820,8 +836,8 @@ yankreg_T *get_yank_register(int regname, int mode) // reg is set to clipboard contents. return reg; } else if (mode != YREG_YANK - && (regname == 0 || regname == '"' || regname == '*' || regname == '+') - && y_previous != NULL) { + && (regname == 0 || regname == '"' || regname == '*' || regname == '+') + && y_previous != NULL) { // in case clipboard not available, paste from previous used register return y_previous; } @@ -894,9 +910,9 @@ bool yank_register_mline(int regname) */ int do_record(int c) { - char_u *p; + char_u *p; static int regname; - yankreg_T *old_y_previous; + yankreg_T *old_y_previous; int retval; if (reg_recording == 0) { @@ -910,7 +926,7 @@ int do_record(int c) regname = c; retval = OK; } - } else { /* stop recording */ + } else { // stop recording /* * Get the recorded key hits. K_SPECIAL and CSI will be escaped, this * needs to be removed again to put it in a register. exec_reg then @@ -923,10 +939,10 @@ int do_record(int c) MSG(""); } p = get_recorded(); - if (p == NULL) + if (p == NULL) { retval = FAIL; - else { - /* Remove escaping for CSI and K_SPECIAL in multi-byte chars. */ + } else { + // Remove escaping for CSI and K_SPECIAL in multi-byte chars. vim_unescape_csi(p); /* @@ -961,12 +977,12 @@ static void set_yreg_additional_data(yankreg_T *reg, dict_T *additional_data) */ static int stuff_yank(int regname, char_u *p) { - /* check for read-only register */ + // check for read-only register if (regname != 0 && !valid_yank_reg(regname, true)) { xfree(p); return FAIL; } - if (regname == '_') { /* black hole: don't do anything */ + if (regname == '_') { // black hole: don't do anything xfree(p); return OK; } @@ -996,36 +1012,35 @@ static int execreg_lastc = NUL; /// Execute a yank register: copy it into the stuff buffer /// -/// Return FAIL for failure, OK otherwise -int -do_execreg( - int regname, - int colon, /* insert ':' before each line */ - int addcr, /* always add '\n' to end of line */ - int silent /* set "silent" flag in typeahead buffer */ -) +/// @param colon insert ':' before each line +/// @param addcr always add '\n' to end of line +/// @param silent set "silent" flag in typeahead buffer +/// +/// @return FAIL for failure, OK otherwise +int do_execreg(int regname, int colon, int addcr, int silent) { char_u *p; int retval = OK; - if (regname == '@') { /* repeat previous one */ + if (regname == '@') { // repeat previous one if (execreg_lastc == NUL) { EMSG(_("E748: No previously used register")); return FAIL; } regname = execreg_lastc; } - /* check for valid regname */ + // check for valid regname if (regname == '%' || regname == '#' || !valid_yank_reg(regname, false)) { emsg_invreg(regname); return FAIL; } execreg_lastc = regname; - if (regname == '_') /* black hole: don't stuff anything */ + if (regname == '_') { // black hole: don't stuff anything return OK; + } - if (regname == ':') { /* use last command line */ + if (regname == ':') { // use last command line if (last_cmdline == NULL) { EMSG(_(e_nolastcmd)); return FAIL; @@ -1033,13 +1048,12 @@ do_execreg( // 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, - (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" - "\030\031\032\033\034\035\036\037", - Ctrl_V, false); + p = vim_strsave_escaped_ext(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" + "\030\031\032\033\034\035\036\037", + Ctrl_V, false); // When in Visual mode "'<,'>" will be prepended to the command. // Remove it when it's already there. if (VIsual_active && STRNCMP(p, "'<,'>", 5) == 0) { @@ -1050,11 +1064,12 @@ do_execreg( xfree(p); } else if (regname == '=') { p = get_expr_line(); - if (p == NULL) + if (p == NULL) { return FAIL; + } retval = put_in_typebuf(p, true, colon, silent); xfree(p); - } else if (regname == '.') { /* use last inserted text */ + } else if (regname == '.') { // use last inserted text p = get_last_insert_save(); if (p == NULL) { EMSG(_(e_noinstext)); @@ -1064,8 +1079,9 @@ do_execreg( xfree(p); } else { yankreg_T *reg = get_yank_register(regname, YREG_PASTE); - if (reg->y_array == NULL) + if (reg->y_array == NULL) { return FAIL; + } // Disallow remapping for ":@r". int remap = colon ? REMAP_NONE : REMAP_YES; @@ -1136,7 +1152,7 @@ static int put_in_typebuf(char_u *s, bool esc, bool colon, int silent) retval = ins_typebuf((char_u *)"\n", REMAP_NONE, 0, true, silent); } if (retval == OK) { - char_u *p; + char_u *p; if (esc) { p = vim_strsave_escape_csi(s); @@ -1158,16 +1174,13 @@ static int put_in_typebuf(char_u *s, bool esc, bool colon, int silent) return retval; } -/* - * Insert a yank register: copy it into the Read buffer. - * Used by CTRL-R command and middle mouse button in insert mode. - * - * return FAIL for failure, OK otherwise - */ -int insert_reg( - int regname, - bool literally_arg // insert literally, not as if typed -) +/// Insert a yank register: copy it into the Read buffer. +/// Used by CTRL-R command and middle mouse button in insert mode. +/// +/// @param literally_arg insert literally, not as if typed +/// +/// @return FAIL for failure, OK otherwise +int insert_reg(int regname, bool literally_arg) { int retval = OK; bool allocated; @@ -1179,12 +1192,14 @@ int insert_reg( * If you hit CTRL-C, the loop will be broken here. */ os_breakcheck(); - if (got_int) + if (got_int) { return FAIL; + } - /* check for valid regname */ - if (regname != NUL && !valid_yank_reg(regname, false)) + // check for valid regname + if (regname != NUL && !valid_yank_reg(regname, false)) { return FAIL; + } char_u *arg; if (regname == '.') { // Insert last inserted text. @@ -1241,7 +1256,7 @@ static void stuffescaped(const char *arg, int literally) stuffReadbuffLen(start, (long)(arg - start)); } - /* stuff a single special character */ + // stuff a single special character if (*arg != NUL) { const int c = mb_cptr2char_adv((const char_u **)&arg); if (literally && ((c < ' ' && c != TAB) || c == DEL)) { @@ -1252,23 +1267,24 @@ static void stuffescaped(const char *arg, int literally) } } -// If "regname" is a special register, return true and store a pointer to its -// value in "argp". -bool get_spec_reg( - int regname, - char_u **argp, - bool *allocated, // return: true when value was allocated - bool errmsg // give error message when failing -) +/// If "regname" is a special register, return true and store a pointer to its +/// value in "argp". +/// +/// @param allocated return: true when value was allocated +/// @param errmsg give error message when failing +/// +/// @return true if "regname" is a special register, +bool get_spec_reg(int regname, char_u **argp, bool *allocated, bool errmsg) { size_t cnt; *argp = NULL; *allocated = false; switch (regname) { - case '%': /* file name */ - if (errmsg) - check_fname(); /* will give emsg if not set */ + case '%': // file name + if (errmsg) { + check_fname(); // will give emsg if not set + } *argp = curbuf->b_fname; return true; @@ -1276,24 +1292,26 @@ bool get_spec_reg( *argp = getaltfname(errmsg); // may give emsg if not set return true; - case '=': /* result of expression */ + case '=': // result of expression *argp = get_expr_line(); *allocated = true; return true; - case ':': /* last command line */ - if (last_cmdline == NULL && errmsg) + case ':': // last command line + if (last_cmdline == NULL && errmsg) { EMSG(_(e_nolastcmd)); + } *argp = last_cmdline; return true; - case '/': /* last search-pattern */ - if (last_search_pat() == NULL && errmsg) + case '/': // last search-pattern + if (last_search_pat() == NULL && errmsg) { EMSG(_(e_noprevre)); + } *argp = last_search_pat(); return true; - case '.': /* last inserted text */ + case '.': // last inserted text *argp = get_last_insert_save(); *allocated = true; if (*argp == NULL && errmsg) { @@ -1306,9 +1324,8 @@ bool get_spec_reg( if (!errmsg) { return false; } - *argp = file_name_at_cursor( - FNAME_MESS | FNAME_HYP | (regname == Ctrl_P ? FNAME_EXP : 0), - 1L, NULL); + *argp = file_name_at_cursor(FNAME_MESS | FNAME_HYP | (regname == Ctrl_P ? FNAME_EXP : 0), + 1L, NULL); *allocated = true; return true; @@ -1332,7 +1349,7 @@ bool get_spec_reg( *argp = ml_get_buf(curwin->w_buffer, curwin->w_cursor.lnum, false); return true; - case '_': /* black hole: always empty */ + case '_': // black hole: always empty *argp = (char_u *)""; return true; } @@ -1356,8 +1373,9 @@ bool cmdline_paste_reg(int regname, bool literally_arg, bool remcr) const bool literally = literally_arg || is_literal_register(regname); yankreg_T *reg = get_yank_register(regname, YREG_PASTE); - if (reg->y_array == NULL) + if (reg->y_array == NULL) { return FAIL; + } for (size_t i = 0; i < reg->y_size; i++) { cmdline_paste_str(reg->y_array[i], literally); @@ -1370,8 +1388,9 @@ bool cmdline_paste_reg(int regname, bool literally_arg, bool remcr) /* Check for CTRL-C, in case someone tries to paste a few thousand * lines and gets bored. */ os_breakcheck(); - if (got_int) + if (got_int) { return FAIL; + } } return OK; } @@ -1398,8 +1417,8 @@ int op_delete(oparg_T *oap) { int n; linenr_T lnum; - char_u *ptr; - char_u *newp, *oldp; + char_u *ptr; + char_u *newp, *oldp; struct block_def bd = { 0 }; linenr_T old_lcount = curbuf->b_ml.ml_line_count; @@ -1430,8 +1449,9 @@ int op_delete(oparg_T *oap) && oap->motion_force == NUL && oap->op_type == OP_DELETE) { ptr = ml_get(oap->end.lnum) + oap->end.col; - if (*ptr != NUL) + if (*ptr != NUL) { ptr += oap->inclusive; + } ptr = skipwhite(ptr); if (*ptr == NUL && inindent(0)) { oap->motion_type = kMTLineWise; @@ -1504,7 +1524,6 @@ int op_delete(oparg_T *oap) set_clipboard(oap->regname, reg); do_autocmd_textyankpost(oap, reg); } - } /* @@ -1522,7 +1541,7 @@ int op_delete(oparg_T *oap) continue; } - /* Adjust cursor position for tab replaced by spaces and 'lbr'. */ + // Adjust cursor position for tab replaced by spaces and 'lbr'. if (lnum == curwin->w_cursor.lnum) { curwin->w_cursor.col = bd.textcol + bd.startspaces; curwin->w_cursor.coladd = 0; @@ -1566,8 +1585,9 @@ int op_delete(oparg_T *oap) del_lines(oap->line_count - 1, true); curwin->w_cursor.lnum = lnum; } - if (u_save_cursor() == FAIL) + if (u_save_cursor() == FAIL) { return FAIL; + } if (curbuf->b_p_ai) { // don't delete indent beginline(BL_WHITE); // cursor on first non-white did_ai = true; // delete the indent when ESC hit @@ -1583,25 +1603,27 @@ int op_delete(oparg_T *oap) (int)curwin->w_cursor.lnum-1, curwin->w_cursor.col, old_len - curwin->w_cursor.col, 0, kExtmarkUndo); - // leave cursor past last char in line + // leave cursor past last char in line if (oap->line_count > 1) { u_clearline(); // "U" command not possible after "2cc" } } else { del_lines(oap->line_count, true); beginline(BL_WHITE | BL_FIX); - u_clearline(); /* "U" command not possible after "dd" */ + u_clearline(); // "U" command not possible after "dd" } } else { if (virtual_op) { int endcol = 0; - /* For virtualedit: break the tabs that are partly included. */ + // For virtualedit: break the tabs that are partly included. if (gchar_pos(&oap->start) == '\t') { - if (u_save_cursor() == FAIL) /* save first line for undo */ + if (u_save_cursor() == FAIL) { // save first line for undo return FAIL; - if (oap->line_count == 1) + } + if (oap->line_count == 1) { endcol = getviscol2(oap->end.col, oap->end.coladd); + } coladvance_force(getviscol2(oap->start.col, oap->start.coladd)); oap->start = curwin->w_cursor; if (oap->line_count == 1) { @@ -1612,14 +1634,15 @@ int op_delete(oparg_T *oap) } } - /* Break a tab only when it's included in the area. */ + // Break a tab only when it's included in the area. if (gchar_pos(&oap->end) == '\t' && oap->end.coladd == 0 && oap->inclusive) { - /* save last line for undo */ + // save last line for undo if (u_save((linenr_T)(oap->end.lnum - 1), - (linenr_T)(oap->end.lnum + 1)) == FAIL) + (linenr_T)(oap->end.lnum + 1)) == FAIL) { return FAIL; + } curwin->w_cursor = oap->end; coladvance_force(getviscol2(oap->end.col, oap->end.coladd)); oap->end = curwin->w_cursor; @@ -1628,17 +1651,18 @@ int op_delete(oparg_T *oap) mb_adjust_opend(oap); } - if (oap->line_count == 1) { /* delete characters within one line */ - if (u_save_cursor() == FAIL) /* save line for undo */ + if (oap->line_count == 1) { // delete characters within one line + if (u_save_cursor() == FAIL) { // save line for undo return FAIL; + } - /* if 'cpoptions' contains '$', display '$' at end of change */ - if ( vim_strchr(p_cpo, CPO_DOLLAR) != NULL - && oap->op_type == OP_CHANGE - && oap->end.lnum == curwin->w_cursor.lnum - && !oap->is_VIsual - ) + // if 'cpoptions' contains '$', display '$' at end of change + if (vim_strchr(p_cpo, CPO_DOLLAR) != NULL + && oap->op_type == OP_CHANGE + && oap->end.lnum == curwin->w_cursor.lnum + && !oap->is_VIsual) { display_dollar(oap->end.col - !oap->inclusive); + } n = oap->end.col - oap->start.col + 1 - !oap->inclusive; @@ -1646,20 +1670,23 @@ int op_delete(oparg_T *oap) /* 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 = get_cursor_line_ptr(); int len = (int)STRLEN(curline); if (oap->end.coladd != 0 && (int)oap->end.col >= len - 1 - && !(oap->start.coladd && (int)oap->end.col >= len - 1)) + && !(oap->start.coladd && (int)oap->end.col >= len - 1)) { n++; - /* Delete at least one char (e.g, when on a control char). */ - if (n == 0 && oap->start.coladd != oap->end.coladd) + } + // Delete at least one char (e.g, when on a control char). + if (n == 0 && oap->start.coladd != oap->end.coladd) { n = 1; + } - /* When deleted a char in the line, reset coladd. */ - if (gchar_cursor() != NUL) + // When deleted a char in the line, reset coladd. + if (gchar_cursor() != NUL) { curwin->w_cursor.coladd = 0; + } } (void)del_bytes((colnr_T)n, !virtual_op, @@ -1668,16 +1695,17 @@ int op_delete(oparg_T *oap) // delete characters between lines pos_T curpos; - /* save deleted and changed lines for undo */ + // save deleted and changed lines for undo if (u_save((linenr_T)(curwin->w_cursor.lnum - 1), - (linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL) + (linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL) { return FAIL; + } curbuf_splice_pending++; pos_T startpos = curwin->w_cursor; // start position for delete - bcount_t deleted_bytes = get_region_bytecount( - curbuf, startpos.lnum, oap->end.lnum, startpos.col, - oap->end.col) + oap->inclusive; + bcount_t deleted_bytes = get_region_bytecount(curbuf, startpos.lnum, oap->end.lnum, + startpos.col, + oap->end.col) + oap->inclusive; truncate_line(true); // delete from cursor to end of line curpos = curwin->w_cursor; // remember curwin->w_cursor @@ -1720,7 +1748,7 @@ setmarks: */ static void mb_adjust_opend(oparg_T *oap) { - char_u *p; + char_u *p; if (oap->inclusive) { p = ml_get(oap->end.lnum); @@ -1760,15 +1788,15 @@ int op_replace(oparg_T *oap, int c) { int n, numc; int num_chars; - char_u *newp, *oldp; + char_u *newp, *oldp; colnr_T oldlen; struct block_def bd; - char_u *after_p = NULL; + char_u *after_p = NULL; int had_ctrl_v_cr = false; - if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty) - return OK; /* nothing to do */ - + if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty) { + return OK; // nothing to do + } if (c == REPLACE_CR_NCHAR) { had_ctrl_v_cr = true; c = CAR; @@ -1780,8 +1808,9 @@ int op_replace(oparg_T *oap, int c) mb_adjust_opend(oap); if (u_save((linenr_T)(oap->start.lnum - 1), - (linenr_T)(oap->end.lnum + 1)) == FAIL) + (linenr_T)(oap->end.lnum + 1)) == FAIL) { return FAIL; + } /* * block mode replace @@ -1808,18 +1837,20 @@ int op_replace(oparg_T *oap, int c) getvpos(&vpos, oap->start_vcol); bd.startspaces += vpos.coladd; n = bd.startspaces; - } else - /* allow for pre spaces */ + } else { + // allow for pre spaces n = (bd.startspaces ? bd.start_char_vcols - 1 : 0); + } - /* allow for post spp */ + // allow for post spp n += (bd.endspaces && !bd.is_oneChar && bd.end_char_vcols > 0) ? bd.end_char_vcols - 1 : 0; - /* Figure out how many characters to replace. */ + // Figure out how many characters to replace. numc = oap->end_vcol - oap->start_vcol + 1; - if (bd.is_short && (!virtual_op || bd.is_MAX)) + if (bd.is_short && (!virtual_op || bd.is_MAX)) { numc -= (oap->end_vcol - bd.end_vcol) + 1; + } /* A double-wide character can be replaced only up to half the * times. */ @@ -1831,7 +1862,7 @@ int op_replace(oparg_T *oap, int c) numc = numc / 2; } - /* Compute bytes needed, move character count to num_chars. */ + // Compute bytes needed, move character count to num_chars. num_chars = numc; numc *= (*mb_char2len)(c); @@ -1859,19 +1890,19 @@ int op_replace(oparg_T *oap, int c) assert(col >= 0); int newrows = 0, newcols = 0; if (had_ctrl_v_cr || (c != '\r' && c != '\n')) { - // strlen(newp) at this point - int newp_len = bd.textcol + bd.startspaces; - while (--num_chars >= 0) { - newp_len += utf_char2bytes(c, newp + newp_len); - } - if (!bd.is_short) { - // insert post-spaces - memset(newp + newp_len, ' ', (size_t)bd.endspaces); - newp_len += bd.endspaces; - // copy the part after the changed part - memmove(newp + newp_len, oldp, (size_t)col); - } - newcols = newp_len - bd.textcol; + // strlen(newp) at this point + int newp_len = bd.textcol + bd.startspaces; + while (--num_chars >= 0) { + newp_len += utf_char2bytes(c, newp + newp_len); + } + if (!bd.is_short) { + // insert post-spaces + memset(newp + newp_len, ' ', (size_t)bd.endspaces); + newp_len += bd.endspaces; + // copy the part after the changed part + memmove(newp + newp_len, oldp, (size_t)col); + } + newcols = newp_len - bd.textcol; } else { // Replacing with \r or \n means splitting the line. after_p_len = (size_t)col; @@ -1900,10 +1931,12 @@ int op_replace(oparg_T *oap, int c) oap->start.col = 0; curwin->w_cursor.col = 0; oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); - if (oap->end.col) + if (oap->end.col) { --oap->end.col; - } else if (!oap->inclusive) + } + } else if (!oap->inclusive) { dec(&(oap->end)); + } // TODO(bfredl): we could batch all the splicing // done on the same line, at least @@ -1913,8 +1946,9 @@ int op_replace(oparg_T *oap, int c) if ((*mb_char2len)(c) > 1 || (*mb_char2len)(n) > 1) { /* This is slow, but it handles replacing a single-byte * with a multi-byte and the other way around. */ - if (curwin->w_cursor.lnum == oap->end.lnum) + if (curwin->w_cursor.lnum == oap->end.lnum) { oap->end.col += (*mb_char2len)(c) - (*mb_char2len)(n); + } replace_character(c); } else { if (n == TAB) { @@ -1924,11 +1958,12 @@ int op_replace(oparg_T *oap, int c) /* oap->end has to be recalculated when * the tab breaks */ end_vcol = getviscol2(oap->end.col, - oap->end.coladd); + oap->end.coladd); } coladvance_force(getviscol()); - if (curwin->w_cursor.lnum == oap->end.lnum) + if (curwin->w_cursor.lnum == oap->end.lnum) { getvpos(&oap->end, end_vcol); + } } pbyte(curwin->w_cursor, c); } @@ -1936,8 +1971,9 @@ int op_replace(oparg_T *oap, int c) int virtcols = oap->end.coladd; if (curwin->w_cursor.lnum == oap->start.lnum - && oap->start.col == oap->end.col && oap->start.coladd) + && oap->start.col == oap->end.col && oap->start.coladd) { virtcols -= oap->start.coladd; + } /* oap->end has been trimmed so it's effectively inclusive; * as a result an extra +1 must be counted so we don't @@ -1956,9 +1992,10 @@ int op_replace(oparg_T *oap, int c) } } - /* Advance to next character, stop at the end of the file. */ - if (inc_cursor() == -1) + // Advance to next character, stop at the end of the file. + if (inc_cursor() == -1) { break; + } } } @@ -1966,7 +2003,7 @@ int op_replace(oparg_T *oap, int c) check_cursor(); changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L, true); - /* Set "'[" and "']" marks. */ + // Set "'[" and "']" marks. curbuf->b_op_start = oap->start; curbuf->b_op_end = oap->end; @@ -1984,8 +2021,9 @@ void op_tilde(oparg_T *oap) int did_change = FALSE; if (u_save((linenr_T)(oap->start.lnum - 1), - (linenr_T)(oap->end.lnum + 1)) == FAIL) + (linenr_T)(oap->end.lnum + 1)) == FAIL) { return; + } pos = oap->start; if (oap->motion_type == kMTBlockWise) { // Visual block mode @@ -1996,7 +2034,6 @@ void op_tilde(oparg_T *oap) pos.col = bd.textcol; one_change = swapchars(oap->op_type, &pos, bd.textlen); did_change |= one_change; - } if (did_change) { changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L, true); @@ -2006,31 +2043,36 @@ void op_tilde(oparg_T *oap) oap->start.col = 0; pos.col = 0; oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); - if (oap->end.col) + if (oap->end.col) { --oap->end.col; - } else if (!oap->inclusive) + } + } else if (!oap->inclusive) { dec(&(oap->end)); + } - if (pos.lnum == oap->end.lnum) + if (pos.lnum == oap->end.lnum) { did_change = swapchars(oap->op_type, &pos, - oap->end.col - pos.col + 1); - else + oap->end.col - pos.col + 1); + } else { for (;; ) { did_change |= swapchars(oap->op_type, &pos, - pos.lnum == oap->end.lnum ? oap->end.col + 1 : - (int)STRLEN(ml_get_pos(&pos))); - if (ltoreq(oap->end, pos) || inc(&pos) == -1) + pos.lnum == oap->end.lnum ? oap->end.col + 1 : + (int)STRLEN(ml_get_pos(&pos))); + if (ltoreq(oap->end, pos) || inc(&pos) == -1) { break; + } } + } if (did_change) { changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L, true); } } - if (!did_change && oap->is_VIsual) - /* No change: need to remove the Visual selection */ + if (!did_change && oap->is_VIsual) { + // No change: need to remove the Visual selection redraw_curbuf_later(INVERTED); + } /* * Set '[ and '] marks. @@ -2039,10 +2081,11 @@ void op_tilde(oparg_T *oap) curbuf->b_op_end = oap->end; if (oap->line_count > p_report) { - if (oap->line_count == 1) + if (oap->line_count == 1) { MSG(_("1 line changed")); - else + } else { smsg(_("%" PRId64 " lines changed"), (int64_t)oap->line_count); + } } } @@ -2066,8 +2109,9 @@ static int swapchars(int op_type, pos_T *pos, int length) todo -= len - 1; } did_change |= swapchar(op_type, pos); - if (inc(pos) == -1) /* at end of file */ + if (inc(pos) == -1) { // at end of file break; + } } return did_change; } @@ -2090,7 +2134,7 @@ bool swapchar(int op_type, pos_T *pos) if (op_type == OP_UPPER && c == 0xdf) { pos_T sp = curwin->w_cursor; - /* Special handling of German sharp s: change to "SS". */ + // Special handling of German sharp s: change to "SS". curwin->w_cursor = *pos; del_char(false); ins_char('S'); @@ -2136,16 +2180,16 @@ 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_u *firstline, *ins_text; colnr_T ind_pre = 0; struct block_def bd; int i; pos_T t1; - /* edit() changes this - record it for OP_APPEND */ + // edit() changes this - record it for OP_APPEND bd.is_MAX = (curwin->w_curswant == MAXCOL); - /* vis block is still marked. Get rid of it now. */ + // vis block is still marked. Get rid of it now. curwin->w_cursor.lnum = oap->start.lnum; update_screen(INVERTED); @@ -2158,12 +2202,14 @@ void op_insert(oparg_T *oap, long count1) unsigned old_ve_flags = ve_flags; ve_flags = VE_ALL; - if (u_save_cursor() == FAIL) + if (u_save_cursor() == FAIL) { return; + } coladvance_force(oap->op_type == OP_APPEND ? oap->end_vcol + 1 : getviscol()); - if (oap->op_type == OP_APPEND) + if (oap->op_type == OP_APPEND) { --curwin->w_cursor.col; + } ve_flags = old_ve_flags; } // Get the info about the block before entering the text @@ -2180,18 +2226,19 @@ void op_insert(oparg_T *oap, long count1) if (oap->op_type == OP_APPEND) { if (oap->motion_type == kMTBlockWise - && curwin->w_cursor.coladd == 0 - ) { - /* Move the cursor to the character right of the block. */ + && curwin->w_cursor.coladd == 0) { + // Move the cursor to the character right of the block. curwin->w_set_curswant = TRUE; while (*get_cursor_pos_ptr() != NUL - && (curwin->w_cursor.col < bd.textcol + bd.textlen)) + && (curwin->w_cursor.col < bd.textcol + bd.textlen)) { ++curwin->w_cursor.col; + } if (bd.is_short && !bd.is_MAX) { /* First line was too short, make it longer and adjust the * values in "bd". */ - if (u_save_cursor() == FAIL) + if (u_save_cursor() == FAIL) { return; + } for (i = 0; i < bd.endspaces; i++) { ins_char(' '); } @@ -2223,8 +2270,9 @@ void op_insert(oparg_T *oap, long count1) /* If user has moved off this line, we don't know what to do, so do * nothing. * Also don't repeat the insert when Insert mode ended with CTRL-C. */ - if (curwin->w_cursor.lnum != oap->start.lnum || got_int) + if (curwin->w_cursor.lnum != oap->start.lnum || got_int) { return; + } if (oap->motion_type == kMTBlockWise) { struct block_def bd2; @@ -2260,7 +2308,7 @@ void op_insert(oparg_T *oap, long count1) int t = getviscol2(curbuf->b_op_start_orig.col, curbuf->b_op_start_orig.coladd); oap->start.col = curbuf->b_op_start_orig.col; - /* reset pre_textlen to the value of OP_INSERT */ + // reset pre_textlen to the value of OP_INSERT pre_textlen += bd.textlen; pre_textlen -= t - oap->start_vcol; oap->start_vcol = t; @@ -2277,8 +2325,9 @@ void op_insert(oparg_T *oap, long count1) if (!bd.is_MAX || bd2.textlen < bd.textlen) { if (oap->op_type == OP_APPEND) { pre_textlen += bd2.textlen - bd.textlen; - if (bd2.endspaces) + if (bd2.endspaces) { --bd2.textlen; + } } bd.textcol = bd2.textcol; bd.textlen = bd2.textlen; @@ -2338,18 +2387,20 @@ int op_change(oparg_T *oap) if (oap->motion_type == kMTLineWise) { l = 0; if (!p_paste && curbuf->b_p_si - && !curbuf->b_p_cin - ) + && !curbuf->b_p_cin) { can_si = true; // It's like opening a new line, do si + } } /* First delete the text in the region. In an empty buffer only need to * save for undo */ if (curbuf->b_ml.ml_flags & ML_EMPTY) { - if (u_save_cursor() == FAIL) + if (u_save_cursor() == FAIL) { return FALSE; - } else if (op_delete(oap) == FAIL) + } + } else if (op_delete(oap) == FAIL) { return FALSE; + } if ((l > curwin->w_cursor.col) && !LINEEMPTY(curwin->w_cursor.lnum) && !virtual_op) { @@ -2460,9 +2511,9 @@ void clear_registers(void) #endif - /// Free contents of yankreg `reg`. - /// Called for normal freeing and in case of error. - /// `reg` must not be NULL (but `reg->y_array` might be) +/// Free contents of yankreg `reg`. +/// Called for normal freeing and in case of error. +/// `reg` must not be NULL (but `reg->y_array` might be) void free_register(yankreg_T *reg) FUNC_ATTR_NONNULL_ALL { @@ -2492,7 +2543,7 @@ bool op_yank(oparg_T *oap, bool message, int deleting) return false; } if (oap->regname == '_') { - return true; // black hole: nothing to do + return true; // black hole: nothing to do } yankreg_T *reg = get_yank_register(oap->regname, YREG_YANK); @@ -2554,8 +2605,9 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) // Visual block mode reg->y_width = oap->end_vcol - oap->start_vcol; - if (curwin->w_curswant == MAXCOL && reg->y_width > 0) + if (curwin->w_curswant == MAXCOL && reg->y_width > 0) { reg->y_width--; + } } for (; lnum <= yankendlnum; lnum++, y_idx++) { @@ -2569,76 +2621,76 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) reg->y_array[y_idx] = vim_strsave(ml_get(lnum)); break; - case kMTCharWise: - { - colnr_T startcol = 0, endcol = MAXCOL; - int is_oneChar = false; - colnr_T cs, ce; - p = ml_get(lnum); - bd.startspaces = 0; - bd.endspaces = 0; - - if (lnum == oap->start.lnum) { - startcol = oap->start.col; - if (virtual_op) { - getvcol(curwin, &oap->start, &cs, NULL, &ce); - if (ce != cs && oap->start.coladd > 0) { - /* Part of a tab selected -- but don't - * double-count it. */ - bd.startspaces = (ce - cs + 1) - - oap->start.coladd; - startcol++; + case kMTCharWise: { + colnr_T startcol = 0, endcol = MAXCOL; + int is_oneChar = false; + colnr_T cs, ce; + p = ml_get(lnum); + bd.startspaces = 0; + bd.endspaces = 0; + + if (lnum == oap->start.lnum) { + startcol = oap->start.col; + if (virtual_op) { + getvcol(curwin, &oap->start, &cs, NULL, &ce); + if (ce != cs && oap->start.coladd > 0) { + /* Part of a tab selected -- but don't + * double-count it. */ + bd.startspaces = (ce - cs + 1) + - oap->start.coladd; + startcol++; + } } } - } - if (lnum == oap->end.lnum) { - endcol = oap->end.col; - if (virtual_op) { - getvcol(curwin, &oap->end, &cs, NULL, &ce); - if (p[endcol] == NUL || (cs + oap->end.coladd < ce - // 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)) { - if (oap->start.lnum == oap->end.lnum - && oap->start.col == oap->end.col) { - // Special case: inside a single char - is_oneChar = true; - bd.startspaces = oap->end.coladd - - oap->start.coladd + oap->inclusive; - endcol = startcol; - } else { - bd.endspaces = oap->end.coladd - + oap->inclusive; - endcol -= oap->inclusive; + if (lnum == oap->end.lnum) { + endcol = oap->end.col; + if (virtual_op) { + getvcol(curwin, &oap->end, &cs, NULL, &ce); + if (p[endcol] == NUL || (cs + oap->end.coladd < ce + // 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)) { + if (oap->start.lnum == oap->end.lnum + && oap->start.col == oap->end.col) { + // Special case: inside a single char + is_oneChar = true; + bd.startspaces = oap->end.coladd + - oap->start.coladd + oap->inclusive; + endcol = startcol; + } else { + bd.endspaces = oap->end.coladd + + oap->inclusive; + endcol -= oap->inclusive; + } } } } + if (endcol == MAXCOL) { + endcol = (colnr_T)STRLEN(p); + } + if (startcol > endcol + || is_oneChar) { + bd.textlen = 0; + } else { + bd.textlen = endcol - startcol + oap->inclusive; + } + bd.textstart = p + startcol; + yank_copy_line(reg, &bd, y_idx, false); + break; } - if (endcol == MAXCOL) - endcol = (colnr_T)STRLEN(p); - if (startcol > endcol - || is_oneChar - ) { - bd.textlen = 0; - } else { - bd.textlen = endcol - startcol + oap->inclusive; - } - bd.textstart = p + startcol; - yank_copy_line(reg, &bd, y_idx, false); - break; - } // NOTREACHED case kMTUnknown: - abort(); + abort(); } } - if (curr != reg) { /* append the new block to the old block */ + if (curr != reg) { // append the new block to the old block new_ptr = xmalloc(sizeof(char_u *) * (curr->y_size + reg->y_size)); - for (j = 0; j < curr->y_size; ++j) + for (j = 0; j < curr->y_size; ++j) { new_ptr[j] = curr->y_array[j]; + } xfree(curr->y_array); curr->y_array = new_ptr; @@ -2659,10 +2711,12 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) xfree(reg->y_array[0]); curr->y_array[j++] = pnew; y_idx = 1; - } else + } else { y_idx = 0; - while (y_idx < reg->y_size) + } + while (y_idx < reg->y_size) { curr->y_array[j++] = reg->y_array[y_idx++]; + } curr->y_size = j; xfree(reg->y_array); } @@ -2715,8 +2769,8 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append) // Copy a block range into a register. // If "exclude_trailing_space" is set, do not copy trailing whitespaces. -static void yank_copy_line(yankreg_T *reg, struct block_def *bd, - size_t y_idx, bool exclude_trailing_space) +static void yank_copy_line(yankreg_T *reg, struct block_def *bd, size_t y_idx, + bool exclude_trailing_space) FUNC_ATTR_NONNULL_ALL { if (exclude_trailing_space) { @@ -2827,24 +2881,25 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) int delcount; int incr = 0; struct block_def bd; - char_u **y_array = NULL; + char_u **y_array = NULL; long nr_lines = 0; pos_T new_cursor; int indent; - int orig_indent = 0; /* init for gcc */ - int indent_diff = 0; /* init for gcc */ + int orig_indent = 0; // init for gcc + int indent_diff = 0; // init for gcc int first_indent = TRUE; int lendiff = 0; pos_T old_pos; - char_u *insert_string = NULL; + char_u *insert_string = NULL; bool allocated = false; long cnt; - if (flags & PUT_FIXINDENT) + if (flags & PUT_FIXINDENT) { orig_indent = get_indent(); + } - curbuf->b_op_start = curwin->w_cursor; /* default for '[ mark */ - curbuf->b_op_end = curwin->w_cursor; /* default for '] mark */ + 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 @@ -2855,7 +2910,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) // PUT_LINE has special handling below which means we use 'i' to start. char command_start_char = non_linewise_vis ? 'c' : - (flags & PUT_LINE ? 'i' : (dir == FORWARD ? 'a' : 'i')); + (flags & PUT_LINE ? 'i' : (dir == FORWARD ? 'a' : 'i')); // To avoid 'autoindent' on linewise puts, create a new line with `:put _`. if (flags & PUT_LINE) { @@ -2957,27 +3012,30 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) y_size = 0; ptr = insert_string; while (ptr != NULL) { - if (y_array != NULL) + if (y_array != NULL) { y_array[y_size] = ptr; + } ++y_size; ptr = vim_strchr(ptr, '\n'); if (ptr != NULL) { - if (y_array != NULL) + if (y_array != NULL) { *ptr = NUL; + } ++ptr; - /* A trailing '\n' makes the register linewise. */ + // A trailing '\n' makes the register linewise. if (*ptr == NUL) { y_type = kMTLineWise; break; } } } - if (y_array != NULL) + if (y_array != NULL) { break; + } y_array = (char_u **)xmalloc(y_size * sizeof(char_u *)); } } else { - y_size = 1; /* use fake one-line yank register */ + y_size = 1; // use fake one-line yank register y_array = &insert_string; } } else { @@ -3025,12 +3083,12 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) dir = FORWARD; } if (flags & PUT_LINE_FORWARD) { - /* Must be "p" for a Visual block, put lines below the block. */ + // Must be "p" for a Visual block, put lines below the block. curwin->w_cursor = curbuf->b_visual.vi_end; dir = FORWARD; } - curbuf->b_op_start = curwin->w_cursor; /* default for '[ mark */ - curbuf->b_op_end = curwin->w_cursor; /* default for '] mark */ + curbuf->b_op_start = curwin->w_cursor; // default for '[ mark + curbuf->b_op_end = curwin->w_cursor; // default for '] mark } if (flags & PUT_LINE) { // :put command or "p" in Visual line mode. @@ -3039,7 +3097,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) if (y_size == 0 || y_array == NULL) { EMSG2(_("E353: Nothing in register %s"), - regname == 0 ? (char_u *)"\"" : transchar(regname)); + regname == 0 ? (char_u *)"\"" : transchar(regname)); goto end; } @@ -3109,10 +3167,11 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) colnr_T endcol2 = 0; if (dir == FORWARD && c != NUL) { - if (ve_flags == VE_ALL) + if (ve_flags == VE_ALL) { getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2); - else + } else { getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col); + } // move to start of next multi-byte character curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr()); @@ -3132,10 +3191,12 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) curwin->w_cursor.col++; } if (c == TAB) { - if (dir == BACKWARD && curwin->w_cursor.col) + if (dir == BACKWARD && curwin->w_cursor.col) { curwin->w_cursor.col--; - if (dir == FORWARD && col - 1 == endcol2) + } + if (dir == FORWARD && col - 1 == endcol2) { curwin->w_cursor.col++; + } } } curwin->w_cursor.coladd = 0; @@ -3152,7 +3213,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) vcol = 0; delcount = 0; - /* add a new line */ + // add a new line if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"", (colnr_T)1, false) == FAIL) { @@ -3161,11 +3222,11 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) nr_lines++; lines_appended = 1; } - /* get the old line and advance to the position to insert at */ + // 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; ) { - /* Count a tab for what it's worth (if list mode not on) */ + // Count a tab for what it's worth (if list mode not on) incr = lbr_chartabsize_adv(oldp, &ptr, (colnr_T)vcol); vcol += incr; } @@ -3173,9 +3234,9 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) shortline = (vcol < col) || (vcol == col && !*ptr); - if (vcol < col) /* line too short, padd with spaces */ + if (vcol < col) { // line too short, padd with spaces bd.startspaces = col - vcol; - else if (vcol > col) { + } else if (vcol > col) { bd.endspaces = vcol - col; bd.startspaces = incr - bd.endspaces; --bd.textcol; @@ -3241,18 +3302,19 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) delcount, addcount, kExtmarkUndo); ++curwin->w_cursor.lnum; - if (i == 0) + if (i == 0) { curwin->w_cursor.col += bd.startspaces; + } } changed_lines(lnum, 0, curbuf->b_op_start.lnum + (linenr_T)y_size - - (linenr_T)nr_lines , nr_lines, true); + - (linenr_T)nr_lines, nr_lines, true); - /* Set '[ mark. */ + // Set '[ mark. curbuf->b_op_start = curwin->w_cursor; curbuf->b_op_start.lnum = lnum; - /* adjust '] mark */ + // adjust '] mark curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1; curbuf->b_op_end.col = bd.textcol + (colnr_T)totlen - 1; curbuf->b_op_end.coladd = 0; @@ -3262,12 +3324,14 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) curwin->w_cursor = curbuf->b_op_end; curwin->w_cursor.col++; - /* in Insert mode we might be after the NUL, correct for that */ + // in Insert mode we might be after the NUL, correct for that len = (colnr_T)STRLEN(get_cursor_line_ptr()); - if (curwin->w_cursor.col > len) + if (curwin->w_cursor.col > len) { curwin->w_cursor.col = len; - } else + } + } else { curwin->w_cursor.lnum = lnum; + } } else { // Character or Line mode if (y_type == kMTCharWise) { @@ -3288,8 +3352,9 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) /* * Line mode: BACKWARD is the same as FORWARD on the previous line */ - else if (dir == BACKWARD) + else if (dir == BACKWARD) { --lnum; + } new_cursor = curwin->w_cursor; // simple case: insert into one line at a time @@ -3300,7 +3365,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) if (VIsual_active) { end_lnum = curbuf->b_visual.vi_end.lnum; if (end_lnum < curbuf->b_visual.vi_start.lnum) { - end_lnum = curbuf->b_visual.vi_start.lnum; + end_lnum = curbuf->b_visual.vi_start.lnum; } if (end_lnum > start_lnum) { // "col" is valid for the first line, in following lines @@ -3357,7 +3422,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) } } while (VIsual_active && lnum <= end_lnum); - if (VIsual_active) { /* reset lnum to the last visual line */ + if (VIsual_active) { // reset lnum to the last visual line lnum--; } @@ -3378,7 +3443,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) lnum = new_cursor.lnum; ptr = ml_get(lnum) + col; totlen = STRLEN(y_array[y_size - 1]); - newp = (char_u *) xmalloc((size_t)(STRLEN(ptr) + totlen + 1)); + newp = (char_u *)xmalloc((size_t)(STRLEN(ptr) + totlen + 1)); STRCPY(newp, y_array[y_size - 1]); STRCAT(newp, ptr); // insert second line @@ -3409,23 +3474,26 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags) old_pos = curwin->w_cursor; curwin->w_cursor.lnum = lnum; ptr = ml_get(lnum); - if (cnt == count && i == y_size - 1) + if (cnt == count && i == y_size - 1) { lendiff = (int)STRLEN(ptr); - if (*ptr == '#' && preprocs_left()) - indent = 0; /* Leave # lines at start */ - else if (*ptr == NUL) - indent = 0; /* Ignore empty lines */ - else if (first_indent) { + } + if (*ptr == '#' && preprocs_left()) { + indent = 0; // Leave # lines at start + } else if (*ptr == NUL) { + indent = 0; // Ignore empty lines + } else if (first_indent) { indent_diff = orig_indent - get_indent(); indent = orig_indent; first_indent = FALSE; - } else if ((indent = get_indent() + indent_diff) < 0) + } else if ((indent = get_indent() + indent_diff) < 0) { indent = 0; + } (void)set_indent(indent, SIN_NOMARK); curwin->w_cursor = old_pos; - /* remember how many chars were removed */ - if (cnt == count && i == y_size - 1) + // remember how many chars were removed + if (cnt == count && i == y_size - 1) { lendiff -= (int)STRLEN(ml_get(lnum)); + } } } @@ -3454,8 +3522,9 @@ error: // Adjust marks. if (y_type == kMTLineWise) { curbuf->b_op_start.col = 0; - if (dir == FORWARD) + if (dir == FORWARD) { curbuf->b_op_start.lnum++; + } } ExtmarkOp kind = (y_type == kMTLineWise && !(flags & PUT_LINE_SPLIT)) @@ -3472,17 +3541,18 @@ error: curbuf->b_op_start.lnum, nr_lines, true); } - /* put '] mark at last inserted character */ + // put '] mark at last inserted character curbuf->b_op_end.lnum = lnum; - /* correct length for change in indent */ + // correct length for change in indent col = (colnr_T)STRLEN(y_array[y_size - 1]) - lendiff; - if (col > 1) + if (col > 1) { curbuf->b_op_end.col = col - 1; - else + } else { curbuf->b_op_end.col = 0; + } if (flags & PUT_CURSLINE) { - /* ":put": put cursor on last inserted line */ + // ":put": put cursor on last inserted line curwin->w_cursor.lnum = lnum; beginline(BL_WHITE | BL_FIX); } else if (flags & PUT_CURSEND) { @@ -3501,11 +3571,13 @@ error: } else if (y_type == kMTLineWise) { // put cursor on first non-blank in first inserted line curwin->w_cursor.col = 0; - if (dir == FORWARD) + if (dir == FORWARD) { ++curwin->w_cursor.lnum; + } beginline(BL_WHITE | BL_FIX); - } else /* put cursor on first inserted character */ + } else { // put cursor on first inserted character curwin->w_cursor = new_cursor; + } } } @@ -3513,14 +3585,16 @@ error: curwin->w_set_curswant = TRUE; end: - if (allocated) + if (allocated) { xfree(insert_string); - if (regname == '=') + } + if (regname == '=') { xfree(y_array); + } VIsual_active = FALSE; - /* If the cursor is past the end of the line put it at the end. */ + // If the cursor is past the end of the line put it at the end. adjust_cursor_eol(); } // NOLINT(readability/fn_size) @@ -3534,13 +3608,13 @@ void adjust_cursor_eol(void) && gchar_cursor() == NUL && (ve_flags & VE_ONEMORE) == 0 && !(restart_edit || (State & INSERT))) { - /* Put the cursor on the last character in the line. */ + // Put the cursor on the last character in the line. dec_cursor(); if (ve_flags == VE_ALL) { colnr_T scol, ecol; - /* Coladd is set to the width of the last character. */ + // Coladd is set to the width of the last character. getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol); curwin->w_cursor.coladd = ecol - scol + 1; } @@ -3557,20 +3631,20 @@ int preprocs_left(void) && curbuf->b_ind_hash_comment == 0)); } -/* Return the character name of the register with the given number */ +// Return the character name of the register with the given number int get_register_name(int num) { - if (num == -1) + if (num == -1) { return '"'; - else if (num < 10) + } else if (num < 10) { return num + '0'; - else if (num == DELETION_REGISTER) + } else if (num == DELETION_REGISTER) { return '-'; - else if (num == STAR_REGISTER) + } else if (num == STAR_REGISTER) { return '*'; - else if (num == PLUS_REGISTER) + } else if (num == PLUS_REGISTER) { return '+'; - else { + } else { return num + 'a' - 10; } } @@ -3587,8 +3661,9 @@ void ex_display(exarg_T *eap) int clen; char_u type[2]; - if (arg != NULL && *arg == NUL) + if (arg != NULL && *arg == NUL) { arg = NULL; + } int attr = HL_ATTR(HLF_8); // Highlight title @@ -3596,23 +3671,28 @@ void ex_display(exarg_T *eap) for (int i = -1; i < NUM_REGISTERS && !got_int; i++) { name = get_register_name(i); switch (get_reg_type(name, NULL)) { - case kMTLineWise: type[0] = 'l'; break; - case kMTCharWise: type[0] = 'c'; break; - default: type[0] = 'b'; break; + case kMTLineWise: + type[0] = 'l'; break; + case kMTCharWise: + type[0] = 'c'; break; + default: + type[0] = 'b'; break; } if (arg != NULL && vim_strchr(arg, name) == NULL) { - continue; /* did not ask for this register */ + continue; // did not ask for this register } if (i == -1) { - if (y_previous != NULL) + if (y_previous != NULL) { yb = y_previous; - else + } else { yb = &(y_regs[0]); - } else + } + } else { yb = &(y_regs[i]); + } get_clipboard(name, &yb, true); @@ -3682,7 +3762,7 @@ void ex_display(exarg_T *eap) * display alternate file name */ if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int) { - char_u *fname; + char_u *fname; linenr_T dummy; if (buflist_name_nr(0, &fname, &dummy) != FAIL) { @@ -3710,15 +3790,11 @@ void ex_display(exarg_T *eap) } } -/* - * display a string for do_dis() - * truncate at end of screen line - */ -static void -dis_msg( - const char_u *p, - bool skip_esc // if true, ignore trailing ESC -) +/// display a string for do_dis() +/// 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) FUNC_ATTR_NONNULL_ALL { int n; @@ -3731,8 +3807,9 @@ dis_msg( if ((l = utfc_ptr2len(p)) > 1) { msg_outtrans_len(p, l); p += l; - } else + } else { msg_outtrans_len(p++, 1); + } } os_breakcheck(); } @@ -3748,9 +3825,7 @@ dis_msg( /// @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_u *skip_comment(char_u *line, bool process, bool include_space, bool *is_comment) { char_u *comment_flags = NULL; int lead_len; @@ -3779,8 +3854,9 @@ char_u *skip_comment( lead_len = get_leader_len(line, &comment_flags, false, include_space); - if (lead_len == 0) + if (lead_len == 0) { return line; + } /* Find: * - COM_END, @@ -3814,25 +3890,21 @@ char_u *skip_comment( // to set those marks. // // return FAIL for failure, OK otherwise -int do_join(size_t count, - int insert_space, - int save_undo, - int use_formatoptions, - bool setmark) +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_u *curr = NULL; + char_u *curr_start = NULL; + char_u *cend; + char_u *newp; + char_u *spaces; // number of spaces inserted before a line int endcurr1 = NUL; int endcurr2 = NUL; - int currsize = 0; /* size of the current line */ - int sumsize = 0; /* size of the long new line */ + int currsize = 0; // size of the current line + int sumsize = 0; // size of the long new line linenr_T t; colnr_T col = 0; int ret = OK; - int *comments = NULL; + int *comments = NULL; int remove_comments = (use_formatoptions == TRUE) && has_format_option(FO_REMOVE_COMS); bool prev_was_comment = false; @@ -3882,13 +3954,14 @@ int do_join(size_t count, || (utf_ptr2char(curr) < 0x100 && endcurr1 < 0x100)) && (!has_format_option(FO_MBYTE_JOIN2) || (utf_ptr2char(curr) < 0x100 && !utf_eat_space(endcurr1)) - || (endcurr1 < 0x100 && !utf_eat_space(utf_ptr2char(curr)))) - ) { - /* don't add a space if the line is ending in a space */ - if (endcurr1 == ' ') + || (endcurr1 < 0x100 && + !utf_eat_space(utf_ptr2char(curr))))) { + // don't add a space if the line is ending in a space + if (endcurr1 == ' ') { endcurr1 = endcurr2; - else + } else { ++spaces[t]; + } // Extra space when 'joinspaces' set and line ends in '.', '?', or '!'. if (p_js && (endcurr1 == '.' || endcurr1 == '?' || endcurr1 == '!')) { ++spaces[t]; @@ -3963,10 +4036,12 @@ int do_join(size_t count, } curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1)); - if (remove_comments) + if (remove_comments) { curr += comments[t - 1]; - if (insert_space && t > 1) + } + if (insert_space && t > 1) { curr = skipwhite(curr); + } currsize = (int)STRLEN(curr); } @@ -3998,7 +4073,7 @@ int do_join(size_t count, /* * Set the cursor column: * Vi compatible: use the column of the first join - * vim: use the column of the last join + * vim: use the column of the last join */ curwin->w_cursor.col = (vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col); @@ -4009,8 +4084,9 @@ int do_join(size_t count, theend: xfree(spaces); - if (remove_comments) + if (remove_comments) { xfree(comments); + } return ret; } @@ -4019,15 +4095,17 @@ theend: * the first line. White-space is ignored. Note that the whole of * 'leader1' must match 'leader2_len' characters from 'leader2' -- webb */ -static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, int leader2_len, char_u *leader2_flags) +static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, int leader2_len, + char_u *leader2_flags) { int idx1 = 0, idx2 = 0; - char_u *p; - char_u *line1; - char_u *line2; + char_u *p; + char_u *line1; + char_u *line2; - if (leader1_len == 0) + if (leader1_len == 0) { return leader2_len == 0; + } /* * If first leader has 'f' flag, the lines can be joined only if the @@ -4038,18 +4116,24 @@ static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, in */ if (leader1_flags != NULL) { for (p = leader1_flags; *p && *p != ':'; ++p) { - if (*p == COM_FIRST) + if (*p == COM_FIRST) { return leader2_len == 0; - if (*p == COM_END) + } + if (*p == COM_END) { return FALSE; + } if (*p == COM_START) { - if (*(ml_get(lnum) + leader1_len) == NUL) + if (*(ml_get(lnum) + leader1_len) == NUL) { return FALSE; - if (leader2_flags == NULL || leader2_len == 0) + } + if (leader2_flags == NULL || leader2_len == 0) { return FALSE; - for (p = leader2_flags; *p && *p != ':'; ++p) - if (*p == COM_MIDDLE) + } + for (p = leader2_flags; *p && *p != ':'; ++p) { + if (*p == COM_MIDDLE) { return TRUE; + } + } return FALSE; } } @@ -4060,30 +4144,30 @@ static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, in * The first line has to be saved, only one line can be locked at a time. */ line1 = vim_strsave(ml_get(lnum)); - for (idx1 = 0; ascii_iswhite(line1[idx1]); ++idx1) + for (idx1 = 0; ascii_iswhite(line1[idx1]); ++idx1) { ; + } line2 = ml_get(lnum + 1); for (idx2 = 0; idx2 < leader2_len; ++idx2) { if (!ascii_iswhite(line2[idx2])) { - if (line1[idx1++] != line2[idx2]) + if (line1[idx1++] != line2[idx2]) { break; - } else - while (ascii_iswhite(line1[idx1])) + } + } else { + while (ascii_iswhite(line1[idx1])) { ++idx1; + } + } } xfree(line1); return idx2 == leader2_len && idx1 == leader1_len; } -/* - * Implementation of the format operator 'gq'. - */ -void -op_format( - oparg_T *oap, - int keep_cursor /* keep cursor on same text char */ -) +/// Implementation of the format operator 'gq'. +/// +/// @param keep_cursor keep cursor on same text char +void op_format(oparg_T *oap, int keep_cursor) { long old_line_count = curbuf->b_ml.ml_line_count; @@ -4092,21 +4176,24 @@ op_format( curwin->w_cursor = oap->cursor_start; if (u_save((linenr_T)(oap->start.lnum - 1), - (linenr_T)(oap->end.lnum + 1)) == FAIL) + (linenr_T)(oap->end.lnum + 1)) == FAIL) { return; + } curwin->w_cursor = oap->start; - if (oap->is_VIsual) - /* When there is no change: need to remove the Visual selection */ + if (oap->is_VIsual) { + // When there is no change: need to remove the Visual selection redraw_curbuf_later(INVERTED); + } - /* Set '[ mark at the start of the formatted area */ + // Set '[ mark at the start of the formatted area curbuf->b_op_start = oap->start; /* For "gw" remember the cursor position and put it back below (adjusted * for joined and split lines). */ - if (keep_cursor) + if (keep_cursor) { saved_cursor = oap->cursor_start; + } format_lines(oap->line_count, keep_cursor); @@ -4115,13 +4202,14 @@ op_format( * If the cursor was moved one line back (e.g. with "Q}") go to the next * line, so "." will do the next lines. */ - if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) + if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { ++curwin->w_cursor.lnum; + } beginline(BL_WHITE | BL_FIX); old_line_count = curbuf->b_ml.ml_line_count - old_line_count; msgmore(old_line_count); - /* put '] mark on the end of the formatted area */ + // put '] mark on the end of the formatted area curbuf->b_op_end = curwin->w_cursor; if (keep_cursor) { @@ -4149,25 +4237,22 @@ op_format( */ void op_formatexpr(oparg_T *oap) { - if (oap->is_VIsual) - /* When there is no change: need to remove the Visual selection */ + if (oap->is_VIsual) { + // When there is no change: need to remove the Visual selection redraw_curbuf_later(INVERTED); + } - if (fex_format(oap->start.lnum, oap->line_count, NUL) != 0) + if (fex_format(oap->start.lnum, oap->line_count, NUL) != 0) { /* As documented: when 'formatexpr' returns non-zero fall back to * internal formatting. */ op_format(oap, FALSE); + } } -int -fex_format( - linenr_T lnum, - long count, - int c /* character to be inserted */ -) +/// @param c character to be inserted +int fex_format(linenr_T lnum, long count, int c) { - int use_sandbox = was_set_insecurely( - curwin, (char_u *)"formatexpr", OPT_LOCAL); + int use_sandbox = was_set_insecurely(curwin, (char_u *)"formatexpr", OPT_LOCAL); int r; char_u *fex; @@ -4196,17 +4281,13 @@ fex_format( return r; } -/* - * Format "line_count" lines, starting at the cursor position. - * When "line_count" is negative, format until the end of the paragraph. - * Lines after the cursor line are saved for undo, caller must have saved the - * first line. - */ -void -format_lines( - linenr_T line_count, - int avoid_fex /* don't use 'formatexpr' */ -) +/// Format "line_count" lines, starting at the cursor position. +/// When "line_count" is negative, format until the end of the paragraph. +/// Lines after the cursor line are saved for undo, caller must have saved the +/// first line. +/// +/// @param avoid_fex don't use 'formatexpr' +void format_lines(linenr_T line_count, int avoid_fex) { bool is_not_par; // current line not part of parag. bool next_is_not_par; // next line not part of paragraph @@ -4244,11 +4325,12 @@ format_lines( is_not_par = true; } next_is_not_par = fmt_check_par(curwin->w_cursor.lnum - , &next_leader_len, &next_leader_flags, do_comments - ); + , &next_leader_len, &next_leader_flags, do_comments + ); is_end_par = (is_not_par || next_is_not_par); - if (!is_end_par && do_trail_white) + if (!is_end_par && do_trail_white) { is_end_par = !ends_in_white(curwin->w_cursor.lnum - 1); + } curwin->w_cursor.lnum--; for (count = line_count; count != 0 && !got_int; --count) { @@ -4272,23 +4354,26 @@ format_lines( next_leader_flags = NULL; } else { next_is_not_par = fmt_check_par(curwin->w_cursor.lnum + 1 - , &next_leader_len, &next_leader_flags, do_comments - ); - if (do_number_indent) + , &next_leader_len, &next_leader_flags, do_comments + ); + if (do_number_indent) { next_is_start_par = (get_number_indent(curwin->w_cursor.lnum + 1) > 0); + } } advance = true; is_end_par = (is_not_par || next_is_not_par || next_is_start_par); - if (!is_end_par && do_trail_white) + if (!is_end_par && do_trail_white) { is_end_par = !ends_in_white(curwin->w_cursor.lnum); + } /* * Skip lines that are not in a paragraph. */ if (is_not_par) { - if (line_count < 0) + if (line_count < 0) { break; + } } else { /* * For the first line of a paragraph, check indent of second line. @@ -4300,7 +4385,7 @@ format_lines( && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { if (do_second_indent && !LINEEMPTY(curwin->w_cursor.lnum + 1)) { if (leader_len == 0 && next_leader_len == 0) { - /* no comment found */ + // no comment found second_indent = get_indent_lnum(curwin->w_cursor.lnum + 1); } else { @@ -4309,11 +4394,11 @@ format_lines( } } else if (do_number_indent) { if (leader_len == 0 && next_leader_len == 0) { - /* no comment found */ + // no comment found second_indent = get_number_indent(curwin->w_cursor.lnum); } else { - /* get_number_indent() is now "comment aware"... */ + // get_number_indent() is now "comment aware"... second_indent = get_number_indent(curwin->w_cursor.lnum); do_comments_list = 1; @@ -4326,20 +4411,22 @@ format_lines( */ if (curwin->w_cursor.lnum >= curbuf->b_ml.ml_line_count || !same_leader(curwin->w_cursor.lnum, - leader_len, leader_flags, - next_leader_len, next_leader_flags) - ) + leader_len, leader_flags, + next_leader_len, + next_leader_flags)) { is_end_par = true; + } /* * If we have got to the end of a paragraph, or the line is * getting long, format it. */ if (is_end_par || force_format) { - if (need_set_indent) + if (need_set_indent) { /* replace indent in first line with minimal number of * tabs and spaces, according to current options */ (void)set_indent(get_indent(), SIN_CHANGED); + } // put cursor on last non-space State = NORMAL; // don't go past end-of-line @@ -4348,25 +4435,26 @@ format_lines( dec_cursor(); } - /* do the formatting, without 'showmode' */ - State = INSERT; /* for open_line() */ + // do the formatting, without 'showmode' + State = INSERT; // for open_line() smd_save = p_smd; p_smd = FALSE; insertchar(NUL, INSCHAR_FORMAT - + (do_comments ? INSCHAR_DO_COM : 0) - + (do_comments && do_comments_list + + (do_comments ? INSCHAR_DO_COM : 0) + + (do_comments && do_comments_list ? INSCHAR_COM_LIST : 0) - + (avoid_fex ? INSCHAR_NO_FEX : 0), second_indent); + + (avoid_fex ? INSCHAR_NO_FEX : 0), second_indent); State = old_State; p_smd = smd_save; second_indent = -1; - /* at end of par.: need to set indent of next par. */ + // at end of par.: need to set indent of next par. need_set_indent = is_end_par; if (is_end_par) { /* When called with a negative line count, break at the * end of the paragraph. */ - if (line_count < 0) + if (line_count < 0) { break; + } first_par_line = true; } force_format = false; @@ -4380,8 +4468,9 @@ format_lines( advance = false; curwin->w_cursor.lnum++; curwin->w_cursor.col = 0; - if (line_count < 0 && u_save_cursor() == FAIL) + if (line_count < 0 && u_save_cursor() == FAIL) { break; + } if (next_leader_len > 0) { (void)del_bytes(next_leader_len, false, false); mark_col_adjust(curwin->w_cursor.lnum, (colnr_T)0, 0L, @@ -4418,11 +4507,12 @@ format_lines( */ static int ends_in_white(linenr_T lnum) { - char_u *s = ml_get(lnum); + char_u *s = ml_get(lnum); size_t l; - if (*s == NUL) + if (*s == NUL) { return FALSE; + } l = STRLEN(s) - 1; return ascii_iswhite(s[l]); } @@ -4437,22 +4527,24 @@ static int ends_in_white(linenr_T lnum) */ static int fmt_check_par(linenr_T lnum, int *leader_len, char_u **leader_flags, int do_comments) { - char_u *flags = NULL; /* init for GCC */ - char_u *ptr; + char_u *flags = NULL; // init for GCC + char_u *ptr; ptr = ml_get(lnum); - if (do_comments) + if (do_comments) { *leader_len = get_leader_len(ptr, leader_flags, FALSE, TRUE); - else + } else { *leader_len = 0; + } if (*leader_len > 0) { /* * Search for 'e' flag in comment leader flags. */ flags = *leader_flags; - while (*flags && *flags != ':' && *flags != COM_END) + while (*flags && *flags != ':' && *flags != COM_END) { ++flags; + } } return *skipwhite(ptr + *leader_len) == NUL @@ -4472,13 +4564,13 @@ int paragraph_start(linenr_T lnum) int next_leader_len = 0; // leader len of next line char_u *next_leader_flags = NULL; // flags for leader of next line - if (lnum <= 1) - return TRUE; /* start of the file */ - + if (lnum <= 1) { + return TRUE; // start of the file + } p = ml_get(lnum - 1); - if (*p == NUL) - return TRUE; /* after empty line */ - + if (*p == NUL) { + return TRUE; // after empty line + } const bool do_comments = has_format_option(FO_Q_COMS); // format comments if (fmt_check_par(lnum - 1, &leader_len, &leader_flags, do_comments)) { return true; // after non-paragraph line @@ -4488,16 +4580,16 @@ int paragraph_start(linenr_T lnum) return true; // "lnum" is not a paragraph line } - if (has_format_option(FO_WHITE_PAR) && !ends_in_white(lnum - 1)) - return TRUE; /* missing trailing space in previous line. */ - - if (has_format_option(FO_Q_NUMBER) && (get_number_indent(lnum) > 0)) - return TRUE; /* numbered item starts in "lnum". */ - + if (has_format_option(FO_WHITE_PAR) && !ends_in_white(lnum - 1)) { + return TRUE; // missing trailing space in previous line. + } + if (has_format_option(FO_Q_NUMBER) && (get_number_indent(lnum) > 0)) { + return TRUE; // numbered item starts in "lnum". + } if (!same_leader(lnum - 1, leader_len, leader_flags, - next_leader_len, next_leader_flags)) - return TRUE; /* change of comment leader. */ - + next_leader_len, next_leader_flags)) { + return TRUE; // change of comment leader. + } return FALSE; } @@ -4514,15 +4606,14 @@ int paragraph_start(linenr_T lnum) * - start/endspaces is the number of columns of the first/last yanked char * that are to be yanked. */ -static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, - bool is_del) +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_u *pend; + char_u *pstart; + char_u *line; + char_u *prev_pstart; + char_u *prev_pend; const int lbr_saved = curwin->w_p_lbr; // Avoid a problem with unwanted linebreaks in block mode. @@ -4543,7 +4634,7 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, pstart = line; prev_pstart = line; while (bdp->start_vcol < oap->start_vcol && *pstart) { - /* Count a tab for what it's worth (if list mode not on) */ + // Count a tab for what it's worth (if list mode not on) incr = lbr_chartabsize(line, pstart, (colnr_T)bdp->start_vcol); bdp->start_vcol += incr; if (ascii_iswhite(*pstart)) { @@ -4557,7 +4648,7 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, MB_PTR_ADV(pstart); } bdp->start_char_vcols = incr; - if (bdp->start_vcol < oap->start_vcol) { /* line too short */ + if (bdp->start_vcol < oap->start_vcol) { // line too short bdp->end_vcol = bdp->start_vcol; bdp->is_short = true; if (!is_del || oap->op_type == OP_APPEND) { @@ -4567,8 +4658,9 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, /* notice: this converts partly selected Multibyte characters to * spaces, too. */ bdp->startspaces = bdp->start_vcol - oap->start_vcol; - if (is_del && bdp->startspaces) + if (is_del && bdp->startspaces) { bdp->startspaces = bdp->start_char_vcols - bdp->startspaces; + } pend = pstart; bdp->end_vcol = bdp->start_vcol; if (bdp->end_vcol > oap->end_vcol) { // it's all in one character @@ -4592,7 +4684,7 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, } else { prev_pend = pend; while (bdp->end_vcol <= oap->end_vcol && *pend != NUL) { - /* Count a tab for what it's worth (if list mode not on) */ + // Count a tab for what it's worth (if list mode not on) prev_pend = pend; incr = lbr_chartabsize_adv(line, &pend, (colnr_T)bdp->end_vcol); bdp->end_vcol += incr; @@ -4614,17 +4706,19 @@ static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum, bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1; if (!is_del && bdp->endspaces) { bdp->endspaces = incr - bdp->endspaces; - if (pend != pstart) + if (pend != pstart) { pend = prev_pend; + } } } } bdp->end_char_vcols = incr; - if (is_del && bdp->startspaces) + if (is_del && bdp->startspaces) { pstart = prev_pstart; + } bdp->textlen = (int)(pend - pstart); } - bdp->textcol = (colnr_T) (pstart - line); + bdp->textcol = (colnr_T)(pstart - line); bdp->textstart = pstart; curwin->w_p_lbr = lbr_saved; } @@ -4739,13 +4833,13 @@ void op_addsub(oparg_T *oap, linenr_T Prenum1, bool g_cmd) int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) { int col; - char_u *buf1 = NULL; + char_u *buf1 = NULL; char_u buf2[NUMBUFLEN]; int pre; // 'X' or 'x': hex; '0': octal; 'B' or 'b': bin static bool hexupper = false; // 0xABC uvarnumber_T n; uvarnumber_T oldn; - char_u *ptr; + char_u *ptr; int c; int todel; int firstdigit; @@ -4801,14 +4895,14 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) && ptr[col - 1] == '0' && !utf_head_off(ptr, ptr + col - 1) && ascii_isxdigit(ptr[col + 1])))) { - // In case of binary/hexadecimal pattern overlap match, rescan + // In case of binary/hexadecimal pattern overlap match, rescan - col = curwin->w_cursor.col; + col = curwin->w_cursor.col; - while (col > 0 && ascii_isdigit(ptr[col])) { - col--; - col -= utf_head_off(ptr, ptr + col); - } + while (col > 0 && ascii_isdigit(ptr[col])) { + col--; + col -= utf_head_off(ptr, ptr + col); + } } if ((do_hex @@ -4824,8 +4918,8 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) && !utf_head_off(ptr, 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--; + col -= utf_head_off(ptr, ptr + col); } else { // Search forward and then backward to find the start of number. col = pos->col; @@ -4923,7 +5017,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) 0 + (do_bin ? STR2NR_BIN : 0) + (do_oct ? STR2NR_OCT : 0) + (do_hex ? STR2NR_HEX : 0), - NULL, &n, maxlen); + NULL, &n, maxlen, false); // ignore leading '-' for hex, octal and bin numbers if (pre && negative) { @@ -5031,17 +5125,16 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1) // leading zeros for (bits = 8 * sizeof(n); bits > 0; bits--) { - if ((n >> (bits - 1)) & 0x1) { - break; - } + if ((n >> (bits - 1)) & 0x1) { + break; + } } while (bits > 0) { - buf2[i++] = ((n >> --bits) & 0x1) ? '1' : '0'; + buf2[i++] = ((n >> --bits) & 0x1) ? '1' : '0'; } buf2[i] = '\0'; - } else if (pre == 0) { vim_snprintf((char *)buf2, ARRAY_SIZE(buf2), "%" PRIu64, (uint64_t)n); } else if (pre == '0') { @@ -5099,18 +5192,18 @@ theend: MotionType get_reg_type(int regname, colnr_T *reg_width) { switch (regname) { - case '%': // file name - case '#': // alternate file name - case '=': // expression - case ':': // last command line - case '/': // last search-pattern - case '.': // last inserted text - case Ctrl_F: // Filename under cursor - case Ctrl_P: // Path under cursor, expand via "path" - case Ctrl_W: // word under cursor - case Ctrl_A: // WORD (mnemonic All) under cursor - case '_': // black hole: always empty - return kMTCharWise; + case '%': // file name + case '#': // alternate file name + case '=': // expression + case ':': // last command line + case '/': // last search-pattern + case '.': // last inserted text + case Ctrl_F: // Filename under cursor + case Ctrl_P: // Path under cursor, expand via "path" + case Ctrl_W: // word under cursor + case Ctrl_A: // WORD (mnemonic All) under cursor + case '_': // black hole: always empty + return kMTCharWise; } if (regname != NUL && !valid_yank_reg(regname, false)) { @@ -5135,26 +5228,25 @@ MotionType get_reg_type(int regname, colnr_T *reg_width) /// @param[out] buf Buffer to store formatted string. The allocated size should /// be at least NUMBUFLEN+2 to always fit the value. /// @param buf_len The allocated size of the buffer. -void format_reg_type(MotionType reg_type, colnr_T reg_width, - char *buf, size_t buf_len) +void format_reg_type(MotionType reg_type, colnr_T reg_width, char *buf, size_t buf_len) FUNC_ATTR_NONNULL_ALL { assert(buf_len > 1); switch (reg_type) { - case kMTLineWise: - buf[0] = 'V'; - buf[1] = NUL; - break; - case kMTCharWise: - buf[0] = 'v'; - buf[1] = NUL; - break; - case kMTBlockWise: - snprintf(buf, buf_len, CTRL_V_STR "%" PRIdCOLNR, reg_width + 1); - break; - case kMTUnknown: - buf[0] = NUL; - break; + case kMTLineWise: + buf[0] = 'V'; + buf[1] = NUL; + break; + case kMTCharWise: + buf[0] = 'v'; + buf[1] = NUL; + break; + case kMTBlockWise: + snprintf(buf, buf_len, CTRL_V_STR "%" PRIdCOLNR, reg_width + 1); + break; + case kMTUnknown: + buf[0] = NUL; + break; } } @@ -5195,12 +5287,14 @@ void *get_reg_contents(int regname, int flags) return get_reg_wrap_one_line(get_expr_line(), flags); } - if (regname == '@') /* "@@" is used for unnamed register */ + if (regname == '@') { // "@@" is used for unnamed register regname = '"'; + } - /* check for valid regname */ - if (regname != NUL && !valid_yank_reg(regname, false)) + // check for valid regname + if (regname != NUL && !valid_yank_reg(regname, false)) { return NULL; + } char_u *retval; bool allocated; @@ -5215,8 +5309,9 @@ void *get_reg_contents(int regname, int flags) } yankreg_T *reg = get_yank_register(regname, YREG_PASTE); - if (reg->y_array == NULL) + if (reg->y_array == NULL) { return NULL; + } if (flags & kGRegList) { list_T *const list = tv_list_alloc((ptrdiff_t)reg->y_size); @@ -5277,7 +5372,7 @@ static yankreg_T *init_write_reg(int name, yankreg_T **old_y_previous, bool must yankreg_T *reg = get_yank_register(name, YREG_YANK); if (!is_append_register(name) && !must_append) { - free_register(reg); + free_register(reg); } return reg; } @@ -5296,18 +5391,16 @@ static void finish_write_reg(int name, yankreg_T *reg, yankreg_T *old_y_previous /// write_reg_contents - 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_u *str, ssize_t len, int must_append) { write_reg_contents_ex(name, str, len, must_append, kMTUnknown, 0L); } -void write_reg_contents_lst(int name, char_u **strings, - bool must_append, MotionType yank_type, +void write_reg_contents_lst(int name, char_u **strings, bool must_append, MotionType yank_type, colnr_T block_len) { if (name == '/' || name == '=') { - char_u *s = strings[0]; + char_u *s = strings[0]; if (strings[0] == NULL) { s = (char_u *)""; } else if (strings[1] != NULL) { @@ -5324,7 +5417,7 @@ void write_reg_contents_lst(int name, char_u **strings, return; } - yankreg_T *old_y_previous, *reg; + yankreg_T *old_y_previous, *reg; if (!(reg = init_write_reg(name, &old_y_previous, must_append))) { return; } @@ -5352,18 +5445,14 @@ void write_reg_contents_lst(int name, char_u **strings, /// 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, - MotionType yank_type, - colnr_T block_len) +void write_reg_contents_ex(int name, const char_u *str, ssize_t len, bool must_append, + MotionType yank_type, colnr_T block_len) { if (len < 0) { - len = (ssize_t) STRLEN(str); + len = (ssize_t)STRLEN(str); } - /* Special case: '/' search pattern */ + // Special case: '/' search pattern if (name == '/') { set_last_search_pat(str, RE_SEARCH, TRUE, TRUE); return; @@ -5392,7 +5481,7 @@ void write_reg_contents_ex(int name, if (name == '=') { size_t offset = 0; - size_t totlen = (size_t) len; + size_t totlen = (size_t)len; if (must_append && expr_line) { // append has been specified and expr_line already exists, so we'll @@ -5417,7 +5506,7 @@ void write_reg_contents_ex(int name, return; } - yankreg_T *old_y_previous, *reg; + yankreg_T *old_y_previous, *reg; if (!(reg = init_write_reg(name, &old_y_previous, must_append))) { return; } @@ -5435,9 +5524,8 @@ void write_reg_contents_ex(int name, /// @param len length of the string (Ignored when str_list=true.) /// @param blocklen width of visual block, or -1 for "I don't know." /// @param str_list True if str is `char_u **`. -static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type, - const char_u *str, size_t len, colnr_T blocklen, - bool str_list) +static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type, const char_u *str, size_t len, + colnr_T blocklen, bool str_list) FUNC_ATTR_NONNULL_ALL { if (y_ptr->y_array == NULL) { // NULL means empty register @@ -5456,7 +5544,7 @@ static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type, // Count the number of lines within the string if (str_list) { - for (char_u **ss = (char_u **) str; *ss != NULL; ++ss) { + for (char_u **ss = (char_u **)str; *ss != NULL; ++ss) { newlines++; } } else { @@ -5484,7 +5572,7 @@ static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type, // Find the end of each line and save it into the array. if (str_list) { - for (char_u **ss = (char_u **) str; *ss != NULL; ++ss, ++lnum) { + for (char_u **ss = (char_u **)str; *ss != NULL; ++ss, ++lnum) { size_t ss_len = STRLEN(*ss); pp[lnum] = xmemdupz(*ss, ss_len); if (ss_len > maxlen) { @@ -5525,7 +5613,7 @@ static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type, set_yreg_additional_data(y_ptr, NULL); y_ptr->timestamp = os_time(); if (yank_type == kMTBlockWise) { - y_ptr->y_width = (blocklen == -1 ? (colnr_T) maxlen - 1 : blocklen); + y_ptr->y_width = (blocklen == -1 ? (colnr_T)maxlen - 1 : blocklen); } else { y_ptr->y_width = 0; } @@ -5551,9 +5639,8 @@ void clear_oparg(oparg_T *oap) * case, eol_size will be added to the character count to account for * the size of the EOL character. */ -static varnumber_T line_count_info(char_u *line, varnumber_T *wc, - varnumber_T *cc, varnumber_T limit, - int eol_size) +static varnumber_T line_count_info(char_u *line, varnumber_T *wc, varnumber_T *cc, + varnumber_T limit, int eol_size) { varnumber_T i; varnumber_T words = 0; @@ -5566,17 +5653,19 @@ static varnumber_T line_count_info(char_u *line, varnumber_T *wc, words++; is_word = 0; } - } else if (!ascii_isspace(line[i])) + } else if (!ascii_isspace(line[i])) { is_word = 1; + } ++chars; i += (*mb_ptr2len)(line + i); } - if (is_word) + if (is_word) { words++; + } *wc += words; - /* Add eol_size if the end of line was reached before hitting limit. */ + // Add eol_size if the end of line was reached before hitting limit. if (i < limit && line[i] == NUL) { i += eol_size; chars += eol_size; @@ -5591,7 +5680,7 @@ static varnumber_T line_count_info(char_u *line, varnumber_T *wc, /// When "dict" is not NULL store the info there instead of showing it. void cursor_pos_info(dict_T *dict) { - char_u *p; + char_u *p; char_u buf1[50]; char_u buf2[40]; linenr_T lnum; @@ -5618,10 +5707,11 @@ void cursor_pos_info(dict_T *dict) return; } } else { - if (get_fileformat(curbuf) == EOL_DOS) + if (get_fileformat(curbuf) == EOL_DOS) { eol_size = 2; - else + } else { eol_size = 1; + } if (l_VIsual_active) { if (lt(VIsual, curwin->w_cursor)) { @@ -5631,23 +5721,28 @@ void cursor_pos_info(dict_T *dict) min_pos = curwin->w_cursor; max_pos = VIsual; } - if (*p_sel == 'e' && max_pos.col > 0) + if (*p_sel == 'e' && max_pos.col > 0) { --max_pos.col; + } if (l_VIsual_mode == Ctrl_V) { - char_u * saved_sbr = p_sbr; + char_u *const saved_sbr = p_sbr; + char_u *const saved_w_sbr = curwin->w_p_sbr; - /* Make 'sbr' empty for a moment to get the correct size. */ + // Make 'sbr' empty for a moment to get the correct size. p_sbr = empty_option; + curwin->w_p_sbr = empty_option; oparg.is_VIsual = true; oparg.motion_type = kMTBlockWise; oparg.op_type = OP_NOP; getvcols(curwin, &min_pos, &max_pos, - &oparg.start_vcol, &oparg.end_vcol); + &oparg.start_vcol, &oparg.end_vcol); p_sbr = saved_sbr; - if (curwin->w_curswant == MAXCOL) + curwin->w_p_sbr = saved_w_sbr; + if (curwin->w_curswant == MAXCOL) { oparg.end_vcol = MAXCOL; - /* Swap the start, end vcol if needed */ + } + // Swap the start, end vcol if needed if (oparg.end_vcol < oparg.start_vcol) { oparg.end_vcol += oparg.start_vcol; oparg.start_vcol = oparg.end_vcol - oparg.start_vcol; @@ -5658,18 +5753,19 @@ void cursor_pos_info(dict_T *dict) } for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { - /* Check for a CTRL-C every 100000 characters. */ + // Check for a CTRL-C every 100000 characters. if (byte_count > last_check) { os_breakcheck(); - if (got_int) + if (got_int) { return; + } last_check = byte_count + 100000L; } - /* Do extra processing for VIsual mode. */ + // Do extra processing for VIsual mode. if (l_VIsual_active && lnum >= min_pos.lnum && lnum <= max_pos.lnum) { - char_u *s = NULL; + char_u *s = NULL; long len = 0L; switch (l_VIsual_mode) { @@ -5684,37 +5780,37 @@ void cursor_pos_info(dict_T *dict) s = ml_get(lnum); len = MAXCOL; break; - case 'v': - { - colnr_T start_col = (lnum == min_pos.lnum) + case 'v': { + colnr_T start_col = (lnum == min_pos.lnum) ? min_pos.col : 0; - colnr_T end_col = (lnum == max_pos.lnum) + colnr_T end_col = (lnum == max_pos.lnum) ? max_pos.col - start_col + 1 : MAXCOL; - s = ml_get(lnum) + start_col; - len = end_col; - } - break; + s = ml_get(lnum) + start_col; + len = end_col; + } + break; } if (s != NULL) { byte_count_cursor += line_count_info(s, &word_count_cursor, - &char_count_cursor, len, eol_size); + &char_count_cursor, len, eol_size); if (lnum == curbuf->b_ml.ml_line_count && !curbuf->b_p_eol && (curbuf->b_p_bin || !curbuf->b_p_fixeol) - && (long)STRLEN(s) < len) + && (long)STRLEN(s) < len) { byte_count_cursor -= eol_size; + } } } else { - /* In non-visual mode, check for the line the cursor is on */ + // In non-visual mode, check for the line the cursor is on if (lnum == curwin->w_cursor.lnum) { word_count_cursor += word_count; char_count_cursor += char_count; byte_count_cursor = byte_count - + line_count_info(ml_get(lnum), &word_count_cursor, - &char_count_cursor, - (varnumber_T)curwin->w_cursor.col + 1, - eol_size); + + line_count_info(ml_get(lnum), &word_count_cursor, + &char_count_cursor, + (varnumber_T)curwin->w_cursor.col + 1, + eol_size); } } // Add to the running totals @@ -5912,13 +6008,16 @@ bool prepare_yankreg_from_object(yankreg_T *reg, String regtype, size_t lines) case 0: reg->y_type = kMTUnknown; break; - case 'v': case 'c': + case 'v': + case 'c': reg->y_type = kMTCharWise; break; - case 'V': case 'l': + case 'V': + case 'l': reg->y_type = kMTLineWise; break; - case 'b': case Ctrl_V: + case 'b': + case Ctrl_V: reg->y_type = kMTBlockWise; break; default: @@ -6023,13 +6122,16 @@ static bool get_clipboard(int name, yankreg_T **target, bool quiet) case 0: reg->y_type = kMTUnknown; break; - case 'v': case 'c': + case 'v': + case 'c': reg->y_type = kMTCharWise; break; - case 'V': case 'l': + case 'V': + case 'l': reg->y_type = kMTLineWise; break; - case 'b': case Ctrl_V: + case 'b': + case Ctrl_V: reg->y_type = kMTBlockWise; break; default: @@ -6053,11 +6155,10 @@ static bool get_clipboard(int name, yankreg_T **target, bool quiet) if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING) { goto err; } - reg->y_array[tv_idx++] = (char_u *)xstrdupnul( - (const char *)TV_LIST_ITEM_TV(li)->vval.v_string); + reg->y_array[tv_idx++] = (char_u *)xstrdupnul((const char *)TV_LIST_ITEM_TV(li)->vval.v_string); }); - if (reg->y_size > 0 && strlen((char*)reg->y_array[reg->y_size-1]) == 0) { + if (reg->y_size > 0 && strlen((char *)reg->y_array[reg->y_size-1]) == 0) { // a known-to-be charwise yank might have a final linebreak // but otherwise there is no line after the final newline if (reg->y_type != kMTCharWise) { @@ -6112,8 +6213,7 @@ static void set_clipboard(int name, yankreg_T *reg) return; } - list_T *const lines = tv_list_alloc( - (ptrdiff_t)reg->y_size + (reg->y_type != kMTCharWise)); + list_T *const lines = tv_list_alloc((ptrdiff_t)reg->y_size + (reg->y_type != kMTCharWise)); for (size_t i = 0; i < reg->y_size; i++) { tv_list_append_string(lines, (const char *)reg->y_array[i], -1); @@ -6121,21 +6221,21 @@ static void set_clipboard(int name, yankreg_T *reg) char regtype; switch (reg->y_type) { - case kMTLineWise: { + case kMTLineWise: { regtype = 'V'; tv_list_append_string(lines, NULL, 0); break; } - case kMTCharWise: { + case kMTCharWise: { regtype = 'v'; break; } - case kMTBlockWise: { + case kMTBlockWise: { regtype = 'b'; tv_list_append_string(lines, NULL, 0); break; } - case kMTUnknown: { + case kMTUnknown: { abort(); } } @@ -6211,8 +6311,8 @@ static inline bool reg_empty(const yankreg_T *const reg) /// Iterate over global registers. /// /// @see op_register_iter -const void *op_global_reg_iter(const void *const iter, char *const name, - yankreg_T *const reg, bool *is_unnamed) +const void *op_global_reg_iter(const void *const iter, char *const name, yankreg_T *const reg, + bool *is_unnamed) FUNC_ATTR_NONNULL_ARG(2, 3, 4) FUNC_ATTR_WARN_UNUSED_RESULT { return op_reg_iter(iter, y_regs, name, reg, is_unnamed); @@ -6227,9 +6327,8 @@ const void *op_global_reg_iter(const void *const iter, char *const name, /// /// @return Pointer that must be passed to next `op_register_iter` call or /// NULL if iteration is over. -const void *op_reg_iter(const void *const iter, const yankreg_T *const regs, - char *const name, yankreg_T *const reg, - bool *is_unnamed) +const void *op_reg_iter(const void *const iter, const yankreg_T *const regs, char *const name, + yankreg_T *const reg, bool *is_unnamed) FUNC_ATTR_NONNULL_ARG(3, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT { *name = NUL; @@ -6248,7 +6347,7 @@ const void *op_reg_iter(const void *const iter, const yankreg_T *const regs, *is_unnamed = (iter_reg == y_previous); while (++iter_reg - &(regs[0]) < NUM_SAVED_REGISTERS) { if (!reg_empty(iter_reg)) { - return (void *) iter_reg; + return (void *)iter_reg; } } return NULL; @@ -6323,8 +6422,7 @@ bool op_reg_set_previous(const char name) /// Get the byte count of buffer region. End-exclusive. /// /// @return number of bytes -bcount_t get_region_bytecount(buf_T *buf, linenr_T start_lnum, - linenr_T end_lnum, colnr_T start_col, +bcount_t get_region_bytecount(buf_T *buf, linenr_T start_lnum, linenr_T end_lnum, colnr_T start_col, colnr_T end_col) { linenr_T max_lnum = buf->b_ml.ml_line_count; @@ -6341,8 +6439,7 @@ bcount_t get_region_bytecount(buf_T *buf, linenr_T start_lnum, if (start_lnum + i > max_lnum) { return deleted_bytes; } - deleted_bytes += (bcount_t)STRLEN( - ml_get_buf(buf, start_lnum + i, false)) + 1; + deleted_bytes += (bcount_t)STRLEN(ml_get_buf(buf, start_lnum + i, false)) + 1; } if (end_lnum > max_lnum) { return deleted_bytes; diff --git a/src/nvim/option.c b/src/nvim/option.c index fbf19ab9ff..fb7a0446b6 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1276,9 +1276,9 @@ int do_set( } } else if (*arg == '-' || ascii_isdigit(*arg)) { // Allow negative, octal and hex numbers. - vim_str2nr(arg, NULL, &i, STR2NR_ALL, &value, NULL, 0); - if (arg[i] != NUL && !ascii_iswhite(arg[i])) { - errmsg = e_invarg; + vim_str2nr(arg, NULL, &i, STR2NR_ALL, &value, NULL, 0, true); + if (i == 0 || (arg[i] != NUL && !ascii_iswhite(arg[i]))) { + errmsg = (char_u *)N_("E521: Number required after ="); goto skip; } } else { @@ -2740,10 +2740,11 @@ ambw_end: if (*p_shada && errmsg == NULL && get_shada_parameter('\'') < 0) { errmsg = (char_u *)N_("E528: Must specify a ' value"); } - } else if (varp == &p_sbr) { // 'showbreak' - for (s = p_sbr; *s; ) { + } else if (gvarp == &p_sbr) { // 'showbreak' + for (s = *varp; *s; ) { if (ptr2cells(s) != 1) { - errmsg = (char_u *)N_("E595: contains unprintable or wide character"); + errmsg = (char_u *)N_( + "E595: 'showbreak' contains unprintable or wide character"); } MB_PTR_ADV(s); } @@ -5523,6 +5524,9 @@ void unset_global_local_option(char *name, void *from) case PV_MP: clear_string_option(&buf->b_p_mp); break; + case PV_SBR: + clear_string_option(&((win_T *)from)->w_p_sbr); + break; case PV_STL: clear_string_option(&((win_T *)from)->w_p_stl); break; @@ -5576,6 +5580,7 @@ static char_u *get_varp_scope(vimoption_T *p, int opt_flags) case PV_DICT: return (char_u *)&(curbuf->b_p_dict); case PV_TSR: return (char_u *)&(curbuf->b_p_tsr); case PV_TFU: return (char_u *)&(curbuf->b_p_tfu); + case PV_SBR: return (char_u *)&(curwin->w_p_sbr); case PV_STL: return (char_u *)&(curwin->w_p_stl); case PV_UL: return (char_u *)&(curbuf->b_p_ul); case PV_LW: return (char_u *)&(curbuf->b_p_lw); @@ -5635,6 +5640,8 @@ static char_u *get_varp(vimoption_T *p) ? (char_u *)&(curbuf->b_p_gp) : p->var; case PV_MP: return *curbuf->b_p_mp != NUL ? (char_u *)&(curbuf->b_p_mp) : p->var; + case PV_SBR: return *curwin->w_p_sbr != NUL + ? (char_u *)&(curwin->w_p_sbr) : p->var; case PV_STL: return *curwin->w_p_stl != NUL ? (char_u *)&(curwin->w_p_stl) : p->var; case PV_UL: return curbuf->b_p_ul != NO_LOCAL_UNDOLEVEL @@ -5788,6 +5795,7 @@ void copy_winopt(winopt_T *from, winopt_T *to) to->wo_nuw = from->wo_nuw; to->wo_rl = from->wo_rl; to->wo_rlc = vim_strsave(from->wo_rlc); + to->wo_sbr = vim_strsave(from->wo_sbr); to->wo_stl = vim_strsave(from->wo_stl); to->wo_wrap = from->wo_wrap; to->wo_wrap_save = from->wo_wrap_save; @@ -5851,6 +5859,7 @@ static void check_winopt(winopt_T *wop) check_string_option(&wop->wo_fmr); check_string_option(&wop->wo_scl); check_string_option(&wop->wo_rlc); + check_string_option(&wop->wo_sbr); check_string_option(&wop->wo_stl); check_string_option(&wop->wo_culopt); check_string_option(&wop->wo_cc); @@ -5874,6 +5883,7 @@ void clear_winopt(winopt_T *wop) clear_string_option(&wop->wo_fmr); clear_string_option(&wop->wo_scl); clear_string_option(&wop->wo_rlc); + clear_string_option(&wop->wo_sbr); clear_string_option(&wop->wo_stl); clear_string_option(&wop->wo_culopt); clear_string_option(&wop->wo_cc); @@ -7472,6 +7482,22 @@ unsigned int get_bkc_value(buf_T *buf) return buf->b_bkc_flags ? buf->b_bkc_flags : bkc_flags; } +/// Get the local or global value of 'showbreak'. +/// +/// @param win If not NULL, the window to get the local option from; global +/// otherwise. +char_u *get_showbreak_value(win_T *const win) + FUNC_ATTR_WARN_UNUSED_RESULT +{ + if (win->w_p_sbr == NULL || *win->w_p_sbr == NUL) { + return p_sbr; + } + if (STRCMP(win->w_p_sbr, "NONE") == 0) { + return empty_option; + } + return win->w_p_sbr; +} + /// Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC. int get_fileformat(const buf_T *buf) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL @@ -7678,12 +7704,6 @@ int win_signcol_configured(win_T *wp, int *is_fixed) return ret; } -// Get the local or global value of 'showbreak'. -char_u *get_showbreak_value(win_T *win FUNC_ATTR_UNUSED) -{ - return p_sbr; -} - /// Get window or buffer local options dict_T *get_winbuf_options(const int bufopt) FUNC_ATTR_WARN_UNUSED_RESULT diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h index 97ada9eb25..e588d3f373 100644 --- a/src/nvim/option_defs.h +++ b/src/nvim/option_defs.h @@ -877,6 +877,7 @@ enum { , WV_CUL , WV_CULOPT , WV_CC + , WV_SBR , WV_STL , WV_WFH , WV_WFW diff --git a/src/nvim/options.lua b/src/nvim/options.lua index df2a8edc04..8b9cdefd57 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -2175,7 +2175,7 @@ return { { full_name='showbreak', abbreviation='sbr', short_desc=N_("string to use at the start of wrapped lines"), - type='string', scope={'global'}, + type='string', scope={'global', 'window'}, redraw={'all_windows'}, varname='p_sbr', defaults={if_true=""} diff --git a/src/nvim/plines.c b/src/nvim/plines.c index 6718b7f7a4..a656686a95 100644 --- a/src/nvim/plines.c +++ b/src/nvim/plines.c @@ -263,7 +263,8 @@ unsigned int win_linetabsize(win_T *wp, char_u *line, colnr_T len) /// @return The number of characters taken up on the screen. int lbr_chartabsize(char_u *line, unsigned char *s, colnr_T col) { - if (!curwin->w_p_lbr && (*p_sbr == NUL) && !curwin->w_p_bri) { + if (!curwin->w_p_lbr && *get_showbreak_value(curwin) == NUL + && !curwin->w_p_bri) { if (curwin->w_p_wrap) { return win_nolbr_chartabsize(curwin, s, col, NULL); } @@ -314,7 +315,7 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, int n; // No 'linebreak', 'showbreak' and 'breakindent': return quickly. - if (!wp->w_p_lbr && !wp->w_p_bri && (*p_sbr == NUL)) { + if (!wp->w_p_lbr && !wp->w_p_bri && *get_showbreak_value(wp) == NUL) { if (wp->w_p_wrap) { return win_nolbr_chartabsize(wp, s, col, headp); } @@ -381,7 +382,8 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, // Set *headp to the size of what we add. added = 0; - if ((*p_sbr != NUL || wp->w_p_bri) && wp->w_p_wrap && (col != 0)) { + char_u *const sbr = get_showbreak_value(wp); + if ((*sbr != NUL || wp->w_p_bri) && wp->w_p_wrap && col != 0) { colnr_T sbrlen = 0; int numberwidth = win_col_off(wp); @@ -394,8 +396,8 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, if (col >= numberextra && numberextra > 0) { col %= numberextra; } - if (*p_sbr != NUL) { - sbrlen = (colnr_T)MB_CHARLEN(p_sbr); + if (*sbr != NUL) { + sbrlen = (colnr_T)MB_CHARLEN(sbr); if (col >= sbrlen) { col -= sbrlen; } @@ -410,7 +412,7 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, } if (col == 0 || (col + size + sbrlen > (colnr_T)wp->w_width_inner)) { - if (*p_sbr != NUL) { + 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; @@ -420,13 +422,13 @@ int win_lbr_chartabsize(win_T *wp, char_u *line, char_u *s, if (width <= 0) { width = 1; } - added += ((size - prev_width) / width) * vim_strsize(p_sbr); + added += ((size - prev_width) / width) * vim_strsize(sbr); if ((size - prev_width) % width) { // Wrapped, add another length of 'sbr'. - added += vim_strsize(p_sbr); + added += vim_strsize(sbr); } } else { - added += vim_strsize(p_sbr); + added += vim_strsize(sbr); } } diff --git a/src/nvim/po/sr.po b/src/nvim/po/sr.po index 1450ab5164..d34c1c3100 100644 --- a/src/nvim/po/sr.po +++ b/src/nvim/po/sr.po @@ -2,7 +2,7 @@ # # Do ":help uganda" in Vim to read copying and usage conditions. # Do ":help credits" in Vim to see a list of people who contributed. -# Copyright (C) 2017 +# Copyright (C) 2021 # This file is distributed under the same license as the Vim package. # FIRST AUTHOR Ivan Pešić <ivan.pesic@gmail.com>, 2017. # @@ -10,8 +10,8 @@ msgid "" msgstr "" "Project-Id-Version: Vim(Serbian)\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2021-02-14 01:49+0400\n" -"PO-Revision-Date: 2021-02-14 01:54+0400\n" +"POT-Creation-Date: 2021-06-13 13:16+0400\n" +"PO-Revision-Date: 2021-06-13 13:50+0400\n" "Last-Translator: Ivan Pešić <ivan.pesic@gmail.com>\n" "Language-Team: Serbian\n" "Language: sr\n" @@ -97,6 +97,9 @@ msgstr "Извршавање %s" msgid "autocommand %s" msgstr "аутокоманда %s" +msgid "E972: Blob value does not have the right number of bytes" +msgstr "E972: Блоб вредност нема одговарајући број бајтова" + msgid "E831: bf_key_init() called with empty password" msgstr "E831: bf_key_init() је позвана са празном лозинком" @@ -866,7 +869,7 @@ msgid "E976: using Blob as a String" msgstr "E976: коришћење Blob као String" msgid "E908: using an invalid value as a String" -msgstr "E908: користи се недозвољена вредност као String" +msgstr "E908: Користи се неважећа вредност као Стринг: %s" msgid "E698: variable nested too deep for making a copy" msgstr "E698: променљива је предубоко угњеждена да би се направила копија" @@ -913,7 +916,7 @@ msgid "E928: String required" msgstr "E928: Захтева се String" msgid "E808: Number or Float required" -msgstr "E808: Захтева се Number или Float" +msgstr "E808: Захтева се Број или Покретни" msgid "add() argument" msgstr "add() аргумент" @@ -1130,6 +1133,9 @@ msgstr "" "\n" "# Преградне линије, копиране дословно:\n" +msgid "E503: \"%s\" is not a file or writable device" +msgstr "E503: „%s” није фајл или уређај на који може да се уписује" + msgid "Save As" msgstr "Сачувај као" @@ -4635,12 +4641,12 @@ msgstr "E531: Користите \":gui\" да покренете GUI" msgid "E589: 'backupext' and 'patchmode' are equal" msgstr "E589: 'backupext' и 'patchmode' су истоветни" -msgid "E834: Conflicts with value of 'listchars'" -msgstr "E834: У конфликту са вредношћу 'listchars'" - msgid "E835: Conflicts with value of 'fillchars'" msgstr "E835: У конфликту са вредношћу 'fillchars'" +msgid "E834: Conflicts with value of 'listchars'" +msgstr "E834: У конфликту са вредношћу 'listchars'" + msgid "E617: Cannot be changed in the GTK+ 2 GUI" msgstr "E617: Не може да се промени у GTK+ 2 GUI" @@ -5064,7 +5070,7 @@ msgstr "E554: Синтаксна грешка у %s{...}" #, c-format msgid "E888: (NFA regexp) cannot repeat %s" -msgstr "E888: (NFA regexp) не може да се понови %s" +msgstr "E888: (НКА регуларни израз) не може да се понови %s" msgid "" "E864: \\%#= can only be followed by 0, 1, or 2. The automatic engine will be " @@ -5130,15 +5136,15 @@ msgid "External submatches:\n" msgstr "Спољна подпоклапања:\n" msgid "E865: (NFA) Regexp end encountered prematurely" -msgstr "E865: Крај (NFA) Regexp израза је достигнут прерано" +msgstr "E865: (НКА) прерано је достигнут крај регуларног израза" #, c-format msgid "E866: (NFA regexp) Misplaced %c" -msgstr "E866: (NFA regexp) %c је на погрешном месту" +msgstr "E866: (НКА регуларни израз) %c је на погрешном месту" #, c-format msgid "E877: (NFA regexp) Invalid character class: %d" -msgstr "E877: (NFA regexp) Неважећа карактер класа: %d" +msgstr "E877: (НКА регуларни израз) Неважећа карактер класа: %d" #, c-format msgid "E867: (NFA) Unknown operator '\\z%c'" @@ -6422,6 +6428,13 @@ msgstr "E853: Име аргумента је дуплирано: %s" msgid "E989: Non-default argument follows default argument" msgstr "E989: Неподразумевани аргумент следи иза подразумеваног аргумента" +msgid "E126: Missing :endfunction" +msgstr "E126: Недостаје :endfunction" + +#, c-format +msgid "W22: Text found after :endfunction: %s" +msgstr "W22: Пронађен текст након :endfunction: %s" + #, c-format msgid "E451: Expected }: %s" msgstr "E451: Очекује се }: %s" @@ -6497,17 +6510,6 @@ msgstr "E862: Овде не може да се користи g:" msgid "E932: Closure function should not be at top level: %s" msgstr "E932: Затварајућа функција не би требало да буде на највишем нивоу: %s" -msgid "E126: Missing :endfunction" -msgstr "E126: Недостаје :endfunction" - -#, c-format -msgid "W1001: Text found after :enddef: %s" -msgstr "W1001: Пронађен је текст након :enddef: %s" - -#, c-format -msgid "W22: Text found after :endfunction: %s" -msgstr "W22: Пронађен текст након :endfunction: %s" - #, c-format msgid "E707: Function name conflicts with variable: %s" msgstr "E707: Име функције је у конфликту са променљивом: %s" @@ -6983,8 +6985,8 @@ msgid "E475: Invalid value for argument %s: %s" msgstr "E475: Неважећа вредност за аргумент %s: %s" #, c-format -msgid "E15: Invalid expression: %s" -msgstr "E15: Неважећи израз: %s" +msgid "E15: Invalid expression: \"%s\"" +msgstr "E15: Неважећи израз: „%s”" msgid "E16: Invalid range" msgstr "E16: Неважећи опсег" diff --git a/src/nvim/po/tr.po b/src/nvim/po/tr.po index 3db3cbfef0..e1fef00863 100644 --- a/src/nvim/po/tr.po +++ b/src/nvim/po/tr.po @@ -1,16 +1,16 @@ # Turkish translations for Vim # Vim Türkçe çevirileri -# Copyright (C) 2020 Emir SARI <bitigchi@me.com> +# Copyright (C) 2021 Emir SARI <emir_sari@msn.com> # This file is distributed under the same license as the Vim package. -# Emir SARI <bitigchi@me.com>, 2019-2020 +# Emir SARI <emir_sari@msn.com>, 2019-2021 # msgid "" msgstr "" "Project-Id-Version: Vim Turkish Localization Project\n" -"Report-Msgid-Bugs-To: Emir SARI <bitigchi@me.com>\n" -"POT-Creation-Date: 2020-11-29 00:20+0300\n" -"PO-Revision-Date: 2020-11-29 20:00+0300\n" -"Last-Translator: Emir SARI <bitigchi@me.com>\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2021-07-16 17:56+0300\n" +"PO-Revision-Date: 2021-07-16 20:00+0300\n" +"Last-Translator: Emir SARI <emir_sari@msn.com>\n" "Language-Team: Turkish <https://github.com/bitigchi/vim>\n" "Language: tr\n" "MIME-Version: 1.0\n" @@ -28,7 +28,7 @@ msgid "E165: Cannot go beyond last file" msgstr "E165: Son dosyadan öteye gidilemez" msgid "E610: No argument to delete" -msgstr "E610: Silinecek bir değişken yok" +msgstr "E610: Silinecek bir argüman yok" msgid "E249: window layout changed unexpectedly" msgstr "E249: Pencere yerleşimi beklenmedik bir biçimde değişti" @@ -94,6 +94,9 @@ msgstr "%s çalıştırılıyor" msgid "autocommand %s" msgstr "%s otokomutu" +msgid "E972: Blob value does not have the right number of bytes" +msgstr "E972: İkili geniş nesne değeri doğru bayt sayısına sahip değil" + msgid "E831: bf_key_init() called with empty password" msgstr "E831: bf_key_init() boş bir şifre ile çağrıldı" @@ -131,6 +134,27 @@ msgstr "E931: Arabellek kaydedilemedi" msgid "E937: Attempt to delete a buffer that is in use: %s" msgstr "E937: Kullanımda olan bir arabellek silinmeye çalışılıyor: %s" +msgid "E90: Cannot unload last buffer" +msgstr "E90: Son arabellek bellekten kaldırılamıyor" + +msgid "E84: No modified buffer found" +msgstr "E84: Değiştirilmiş bir arabellek bulunamadı" + +msgid "E85: There is no listed buffer" +msgstr "E85: Listelenmiş bir arabellek yok" + +msgid "E87: Cannot go beyond last buffer" +msgstr "E87: Son arabellekten öteye gidilemez" + +msgid "E88: Cannot go before first buffer" +msgstr "E88: İlk arabellekten öncesine gidilemez" + +#, c-format +msgid "E89: No write since last change for buffer %d (add ! to override)" +msgstr "" +"E89: %d numaralı arabellek son değişiklikten sonra yazılmadı (geçersiz " +"kılmak için ! ekleyin)" + msgid "E515: No buffers were unloaded" msgstr "E515: Hiçbir arabellek bellekten kaldırılmadı" @@ -158,27 +182,6 @@ msgid_plural "%d buffers wiped out" msgstr[0] "%d arabellek yok edildi" msgstr[1] "%d arabellek yok edildi" -msgid "E90: Cannot unload last buffer" -msgstr "E90: Son arabellek bellekten kaldırılamıyor" - -msgid "E84: No modified buffer found" -msgstr "E84: Değiştirilmiş bir arabellek bulunamadı" - -msgid "E85: There is no listed buffer" -msgstr "E85: Listelenmiş bir arabellek yok" - -msgid "E87: Cannot go beyond last buffer" -msgstr "E87: Son arabellekten öteye gidilemez" - -msgid "E88: Cannot go before first buffer" -msgstr "E88: İlk arabellekten öncesine gidilemez" - -#, c-format -msgid "E89: No write since last change for buffer %d (add ! to override)" -msgstr "" -"E89: %d numaralı arabellek son değişiklikten sonra yazılmadı (geçersiz " -"kılmak için ! ekleyin)" - msgid "E948: Job still running (add ! to end the job)" msgstr "E948: İş hâlâ sürüyor (bitirmek için ! ekleyin)" @@ -424,13 +427,13 @@ msgid "E901: gethostbyname() in channel_open()" msgstr "E901: channel_open() içinde gethostbyname()" msgid "E903: received command with non-string argument" -msgstr "E903: Dizi olmayan değişken içeren komut alındı" +msgstr "E903: Dizi olmayan argüman içeren komut alındı" msgid "E904: last argument for expr/call must be a number" -msgstr "E904: İfadenin/çağrının son değişkeni bir sayı olmalıdır" +msgstr "E904: İfadenin/çağrının son argüman bir sayı olmalıdır" msgid "E904: third argument for call must be a list" -msgstr "E904: Çağrının üçüncü değişkeni bir liste olmalıdır" +msgstr "E904: Çağrının üçüncü argümanı bir liste olmalıdır" #, c-format msgid "E905: received unknown command: %s" @@ -449,7 +452,7 @@ msgstr "E631: %s(): Yazma başarısız" #, c-format msgid "E917: Cannot use a callback with %s()" -msgstr "E917: %s() ile geri çağırma kullanılamaz" +msgstr "E917: %s() ile geri çağırma kullanılamıyor" msgid "E912: cannot use ch_evalexpr()/ch_sendexpr() with a raw or nl channel" msgstr "E912: ch_evalexpr()/ch_sendexpr() raw/nl kanalları ile kullanılamaz" @@ -511,6 +514,11 @@ msgid "Warning: Using a weak encryption method; see :help 'cm'" msgstr "" "Uyarı: Zayıf bir şifreleme yöntemi kullanılıyor; bilgi için: :help 'cm'" +msgid "" +"Note: Encryption of swapfile not supported, disabling swap- and undofile" +msgstr "Takas dosyası şifrelemesi desteklenmiyor, takas ve geri al dosyası " +"devre dışı bırakılıyor" + msgid "Enter encryption key: " msgstr "Şifreleme anahtarı girin: " @@ -570,7 +578,7 @@ msgid "%3d expr %s" msgstr "%3d ifade %s" msgid "extend() argument" -msgstr "extend() değişkeni" +msgstr "extend() argümanı" #, c-format msgid "E737: Key already exists: %s" @@ -728,9 +736,6 @@ msgstr "E708: [:] en son gelmelidir" msgid "E709: [:] requires a List or Blob value" msgstr "E709: [:] bir liste veya ikili geniş nesne değeri gerektirir" -msgid "E972: Blob value does not have the right number of bytes" -msgstr "E972: İkili geniş nesne değeri doğru bayt sayısına sahip değil" - msgid "E996: Cannot lock a range" msgstr "E996: Erim kilitlenemiyor" @@ -741,7 +746,7 @@ msgid "E260: Missing name after ->" msgstr "E260: -> sonrası ad eksik" msgid "E695: Cannot index a Funcref" -msgstr "E695: Bir Funcref dizinlenemez" +msgstr "E695: Bir Funcref dizinlenemiyor" msgid "Not enough memory to set references, garbage collection aborted!" msgstr "Referansları ayarlamak için yetersiz bellek, atık toplama durduruldu" @@ -759,9 +764,6 @@ msgstr "" "\n" "\tEn son şuradan ayarlandı: " -msgid "E808: Number or Float required" -msgstr "E808: Sayı veya kayan noktalı değer gerekiyor" - #, c-format msgid "E158: Invalid buffer name: %s" msgstr "E158: Geçersiz arabellek adı: %s" @@ -780,7 +782,7 @@ msgid "E922: expected a dict" msgstr "E922: Bir sözlük bekleniyordu" msgid "E923: Second argument of function() must be a list or a dict" -msgstr "E923: function() ikinci değişkeni bir liste veya sözlük olmalıdır" +msgstr "E923: function() ikinci argümanı bir liste veya sözlük olmalıdır" msgid "" "&OK\n" @@ -882,7 +884,7 @@ msgid "E742: Cannot change value of %s" msgstr "E742: %s değeri değiştirilemiyor" msgid "E921: Invalid callback argument" -msgstr "E921: Geçersiz geri çağırma değişkeni" +msgstr "E921: Geçersiz geri çağırma argümanı" #, c-format msgid "<%s>%s%s %d, Hex %02x, Oct %03o, Digr %s" @@ -927,6 +929,10 @@ msgstr "E135: *Süzgeç* otokomutları şu anki arabelleği değiştirmemelidir" msgid "[No write since last change]\n" msgstr "[Son değişiklikten sonra yazılmadı]\n" +#, c-format +msgid "E503: \"%s\" is not a file or writable device" +msgstr "E503: \"%s\", bir dosya veya yazılabilir aygıt değil" + msgid "Save As" msgstr "Farklı Kaydet" @@ -985,7 +991,7 @@ msgid "E143: Autocommands unexpectedly deleted new buffer %s" msgstr "E143: yeni %s arabelleğini otokomutlar beklenmedik bir biçimde sildi" msgid "E144: non-numeric argument to :z" -msgstr "E144: :z için sayısal olmayan değişken" +msgstr "E144: :z için sayısal olmayan argüman" msgid "E145: Shell commands and some functionality not allowed in rvim" msgstr "E145: rvim içinde kabuk komutları ve bazı işlevselliğe izin verilmez" @@ -1091,9 +1097,6 @@ msgstr "Kaynak alınan dosyanın sonu" msgid "End of function" msgstr "İşlevin sonu" -msgid "E464: Ambiguous use of user-defined command" -msgstr "E464: Kullanıcı tanımlı komutun belirsiz kullanımı" - msgid "E492: Not an editor command" msgstr "E492: Bir düzenleyici komutu değil" @@ -1178,7 +1181,7 @@ msgid "E187: Unknown" msgstr "E187: Bilinmeyen" msgid "E465: :winsize requires two number arguments" -msgstr "E465: :winsize iki adet sayı değişken gerektirir" +msgstr "E465: :winsize iki adet sayı argüman gerektirir" #, c-format msgid "Window position: X %d, Y %d" @@ -1188,7 +1191,7 @@ msgid "E188: Obtaining window position not implemented for this platform" msgstr "E188: Pencere konumunu alma özelliği bu platformda mevcut değil" msgid "E466: :winpos requires two number arguments" -msgstr "E466: :winpos iki adet sayı değişken gerektirir" +msgstr "E466: :winpos iki adet sayı argüman gerektirir" msgid "E930: Cannot use :redir inside execute()" msgstr "E930: :redir, execute() içinde kullanılamaz" @@ -1340,6 +1343,9 @@ msgstr "E788: Şu anda başka bir arabellek düzenlenemez" msgid "E811: Not allowed to change buffer information now" msgstr "E811: Şu anda arabellek bilgisi değiştirilemez" +msgid "[Command Line]" +msgstr "[Komut Satırı]" + msgid "E199: Active window or buffer deleted" msgstr "E199: Etkin pencere veya arabellek silinmiş" @@ -1530,7 +1536,7 @@ msgid "E655: Too many symbolic links (cycle?)" msgstr "E655: Çok fazla sembolik bağlantı (çevrim?)" msgid "writefile() first argument must be a List or a Blob" -msgstr "writefile() ilk değişkeni bir liste veya ikili geniş nesne olmalıdır" +msgstr "writefile() ilk argümanı bir liste veya ikili geniş nesne olmalıdır" msgid "Select Directory dialog" msgstr "Dizin Seç iletişim kutusu" @@ -1581,6 +1587,9 @@ msgstr "E446: İmleç altında bir dosya adı yok" msgid "E447: Can't find file \"%s\" in path" msgstr "E447: \"%s\" dosyası yol içinde bulunamadı" +msgid "E808: Number or Float required" +msgstr "E808: Sayı veya kayan noktalı değer gerekiyor" + msgid "E490: No fold found" msgstr "E490: Kıvırma bulunamadı" @@ -1805,7 +1814,7 @@ msgstr "E671: Pencere başlığı \"%s\" bulunamıyor" #, c-format msgid "E243: Argument not supported: \"-%s\"; Use the OLE version." -msgstr "E243: \"-%s\" değişkeni desteklenmiyor; OLE sürümünü kullanın." +msgstr "E243: \"-%s\" argümanı desteklenmiyor; OLE sürümünü kullanın." msgid "E988: GUI cannot be used. Cannot execute gvim.exe." msgstr "E988: Grafik arabirim kullanılamaz. gvim.exe çalıştırılamadı." @@ -2042,11 +2051,11 @@ msgstr "E411: Vurgulama grubu bulunamadı: %s" #, c-format msgid "E412: Not enough arguments: \":highlight link %s\"" -msgstr "E412: Yetersiz sayıda değişken: \":highlight link %s\"" +msgstr "E412: Yetersiz sayıda argüman: \":highlight link %s\"" #, c-format msgid "E413: Too many arguments: \":highlight link %s\"" -msgstr "E413: Çok fazla değişken: \":highlight link %s\"" +msgstr "E413: Çok fazla argüman: \":highlight link %s\"" msgid "E414: group has settings, highlight link ignored" msgstr "E414: Grup ayarları mevcut, vurgulama bağlantısı yok sayıldı" @@ -2061,7 +2070,7 @@ msgstr "E416: Eksik eşittir imi: %s" #, c-format msgid "E417: missing argument: %s" -msgstr "E417: Eksik değişkenler: %s" +msgstr "E417: Argüman eksik: %s" #, c-format msgid "E418: Illegal value: %s" @@ -2086,7 +2095,7 @@ msgstr "E422: Uçbirim kodu çok uzun: %s" #, c-format msgid "E423: Illegal argument: %s" -msgstr "E423: İzin verilmeyen değişken: %s" +msgstr "E423: İzin verilmeyen argüman: %s" msgid "E424: Too many different highlighting attributes in use" msgstr "E424: Çok fazla değişik vurgulama kuralları kullanılıyor" @@ -2295,7 +2304,7 @@ msgid "unknown option" msgstr "bilinmeyen seçenek" msgid "window index is out of range" -msgstr "pencere dizini erimin dışında" +msgstr "pencere sırası erimin dışında" msgid "couldn't open buffer" msgstr "arabellek açılamadı" @@ -2513,9 +2522,6 @@ msgstr " Dahili anahtar sözcük tamamlaması (^N^P)" msgid "Hit end of paragraph" msgstr "Paragrafın sonuna varıldı" -msgid "E839: Completion function changed window" -msgstr "E839: Tamamlama işlevi pencereyi değiştirdi" - msgid "E840: Completion function deleted text" msgstr "E840: Tamamlama işlevi metni sildi" @@ -2594,23 +2600,23 @@ msgstr "E938: JSON'da yinelenmiş anahtar: \"%s\"" #, c-format msgid "E899: Argument of %s must be a List or Blob" -msgstr "E899: %s değişkeni bir liste veya ikili geniş nesne olmalıdır" +msgstr "E899: %s argümanı bir liste veya ikili geniş nesne olmalıdır" msgid "E900: maxdepth must be non-negative number" msgstr "E900: maxdepth negatif olmayan bir sayı olmalı" msgid "flatten() argument" -msgstr "flatten() değişkeni" +msgstr "flatten() argümanı" #, c-format msgid "E696: Missing comma in List: %s" msgstr "E696: Listede virgül eksik: %s" msgid "sort() argument" -msgstr "sort() değişkeni" +msgstr "sort() argümanı" msgid "uniq() argument" -msgstr "uniq() değişkeni" +msgstr "uniq() argümanı" msgid "E702: Sort compare function failed" msgstr "E702: Sıralayıp karşılaştırma işlevi başarısız oldu" @@ -2619,25 +2625,28 @@ msgid "E882: Uniq compare function failed" msgstr "E882: Benzersizlik karşılaştırma işlevi başarısız oldu" msgid "map() argument" -msgstr "map() değişkeni" +msgstr "map() argümanı" msgid "mapnew() argument" -msgstr "mapnew() değişkeni" +msgstr "mapnew() argümanı" msgid "filter() argument" -msgstr "filter() değişkeni" +msgstr "filter() argümanı" msgid "add() argument" -msgstr "add() değişkeni" +msgstr "add() argümanı" + +msgid "extendnew() argument" +msgstr "extendnew() argümanı" msgid "insert() argument" -msgstr "insert() değişkeni" +msgstr "insert() argümanı" msgid "remove() argument" -msgstr "remove() değişkeni" +msgstr "remove() argümanı" msgid "reverse() argument" -msgstr "reverse() değişkeni" +msgstr "reverse() argümanı" #, c-format msgid "Current %slanguage: \"%s\"" @@ -2648,22 +2657,22 @@ msgid "E197: Cannot set language to \"%s\"" msgstr "E197: \"%s\" diline ayarlanamıyor" msgid "Unknown option argument" -msgstr "Bilinmeyen seçenek değişkeni" +msgstr "Bilinmeyen seçenek argümanı" msgid "Too many edit arguments" -msgstr "Çok fazla düzenleme değişkeni" +msgstr "Çok fazla düzenleme argümanı" msgid "Argument missing after" -msgstr "Şundan sonra değişken eksik:" +msgstr "Şundan sonra argüman eksik:" msgid "Garbage after option argument" -msgstr "Seçenek değişkeninden sonra anlamsız veri" +msgstr "Seçenek argümanından sonra anlamsız veri" msgid "Too many \"+command\", \"-c command\" or \"--cmd command\" arguments" -msgstr "Çok fazla \"+komut\", \"-c komut\" veya \"--cmd komut\" değişkeni" +msgstr "Çok fazla \"+komut\", \"-c komut\" veya \"--cmd komut\" argümanı" msgid "Invalid argument for" -msgstr "Şunun için geçersiz değişken:" +msgstr "Şunun için geçersiz argüman:" #, c-format msgid "%d files to edit\n" @@ -2735,7 +2744,7 @@ msgstr "" "Kullanım:" msgid " vim [arguments] " -msgstr " vim [değişkenler] " +msgstr " vim [argümanlar] " msgid "" "\n" @@ -2967,21 +2976,21 @@ msgid "" "Arguments recognised by gvim (Motif version):\n" msgstr "" "\n" -"gvim tarafından tanınan değişkenler (Motif sürümü):\n" +"gvim tarafından tanınan argümanlar (Motif sürümü):\n" msgid "" "\n" "Arguments recognised by gvim (neXtaw version):\n" msgstr "" "\n" -"gvim tarafından tanınan değişkenler (neXtaw sürümü):\n" +"gvim tarafından tanınan argümanlar (neXtaw sürümü):\n" msgid "" "\n" "Arguments recognised by gvim (Athena version):\n" msgstr "" "\n" -"gvim tarafından tanınan değişkenler (Athena sürümü):\n" +"gvim tarafından tanınan argümanlar (Athena sürümü):\n" msgid "-display <display>\tRun Vim on <display>" msgstr "-display <ekran>\tVim'i <ekran>'da çalıştır" @@ -3032,7 +3041,7 @@ msgid "" "Arguments recognised by gvim (GTK+ version):\n" msgstr "" "\n" -"gvim tarafından tanınan değişkenler (GTK+ sürümü):\n" +"gvim tarafından tanınan argümanlar (GTK+ sürümü):\n" msgid "-display <display>\tRun Vim on <display> (also: --display)" msgstr "-display <ekran>\tVim'i <ekran>'da çalıştır (veya: --display)" @@ -3078,7 +3087,7 @@ msgid "E228: makemap: Illegal mode" msgstr "E228: makemap: İzin verilmeyen kip" msgid "E460: entries missing in mapset() dict argument" -msgstr "E460: mapset() sözlük değişkeninde eksik girdiler" +msgstr "E460: mapset() sözlük argümanında eksik girdiler" #, c-format msgid "E357: 'langmap': Matching character missing for %s" @@ -3716,13 +3725,13 @@ msgstr "" "İ&ptal" msgid "E766: Insufficient arguments for printf()" -msgstr "E766: printf() için yetersiz değişkenler" +msgstr "E766: printf() için yetersiz argüman" msgid "E807: Expected Float argument for printf()" -msgstr "E807: printf() için kayan noktalı değer türünde değişken bekleniyordu" +msgstr "E807: printf() için kayan noktalı değer türünde argüman bekleniyordu" msgid "E767: Too many arguments to printf()" -msgstr "E767: printf() için çok fazla değişken" +msgstr "E767: printf() için çok fazla argüman" msgid "Type number and <Enter> or click with the mouse (q or empty cancels): " msgstr "" @@ -4014,12 +4023,12 @@ msgstr "E531: Grafik arabirimi başlatmak için \":gui\" yazın" msgid "E589: 'backupext' and 'patchmode' are equal" msgstr "E589: 'backupext' ve 'patchmode' birbirine eşit" -msgid "E834: Conflicts with value of 'listchars'" -msgstr "E834: 'listchars' değeriyle çakışmalar var" - msgid "E835: Conflicts with value of 'fillchars'" msgstr "E835: 'fillchars' değeriyle çakışmalar var" +msgid "E834: Conflicts with value of 'listchars'" +msgstr "E834: 'listchars' değeriyle çakışmalar var" + msgid "E617: Cannot be changed in the GTK+ 2 GUI" msgstr "E617: GTK+ 2 grafik arabiriminde değiştirilemez" @@ -4392,7 +4401,7 @@ msgid "Cannot open file \"%s\"" msgstr "\"%s\" dosyası açılamıyor" msgid "cannot have both a list and a \"what\" argument" -msgstr "ya birinci ya da son değişken belirtilmelidir" +msgstr "ya birinci ya da son argüman belirtilmelidir" msgid "E681: Buffer is not loaded" msgstr "E681: Arabellek yüklenemedi" @@ -4725,10 +4734,10 @@ msgid "modeline" msgstr "kip satırı" msgid "--cmd argument" -msgstr "--cmd değişkeni" +msgstr "--cmd argümanı" msgid "-c argument" -msgstr "-c değişkeni" +msgstr "-c argümanı" msgid "environment variable" msgstr "ortam değişkeni" @@ -4736,6 +4745,9 @@ msgstr "ortam değişkeni" msgid "error handler" msgstr "hata işleyicisi" +msgid "changed window size" +msgstr "değiştirilen pencere boyutu" + msgid "W15: Warning: Wrong line separator, ^M may be missing" msgstr "W15: Uyarı: Yanlış satır ayırıcısı, ^M eksik olabilir" @@ -5215,6 +5227,9 @@ msgstr "E765: 'spellfile' içinde %d adet girdi yok" msgid "Word '%.*s' removed from %s" msgstr "'%.*s' sözcüğü %s içinden çıkartıldı" +msgid "Seek error in spellfile" +msgstr "Yazım dosyasında arama hatası" + #, c-format msgid "Word '%.*s' added to %s" msgstr "'%.*s' sözcüğü %s dosyasına eklendi" @@ -5242,7 +5257,7 @@ msgstr " < \"%.*s\"" #, c-format msgid "E390: Illegal argument: %s" -msgstr "E390: İzin verilmeyen değişken: %s" +msgstr "E390: İzin verilmeyen argüman: %s" msgid "No Syntax items defined for this buffer" msgstr "Bu arabellek için sözdizim ögeleri tanımlanmamış" @@ -5343,7 +5358,7 @@ msgid " line breaks" msgstr " satır sonu" msgid "E395: contains argument not accepted here" -msgstr "E395: Burada kabul edilmeyen bir değişken içeriyor" +msgstr "E395: Burada kabul edilmeyen bir argüman içeriyor" msgid "E844: invalid cchar value" msgstr "E844: Geçersiz cchar değeri" @@ -5375,7 +5390,7 @@ msgstr "E398: '=' eksik: %s" #, c-format msgid "E399: Not enough arguments: syntax region %s" -msgstr "E399: Yetersiz değişken: %s sözdizim bölgesi" +msgstr "E399: Yetersiz sayıda argüman: %s sözdizim bölgesi" msgid "E848: Too many syntax clusters" msgstr "E848: Çok fazla sözdizim kümesi" @@ -5396,7 +5411,7 @@ msgstr "E403: Sözdizim eşitlemesi: Satır devamları dizgisi iki kez tanımlan #, c-format msgid "E404: Illegal arguments: %s" -msgstr "E404: İzin verilmeyen değişkenler: %s" +msgstr "E404: İzin verilmeyen argümanlar: %s" #, c-format msgid "E405: Missing equal sign: %s" @@ -5404,7 +5419,7 @@ msgstr "E405: Eşittir imi eksik: %s" #, c-format msgid "E406: Empty argument: %s" -msgstr "E406: Boş değişken: %s" +msgstr "E406: Boş argüman: %s" #, c-format msgid "E407: %s not allowed here" @@ -5539,7 +5554,7 @@ msgid "E436: No \"%s\" entry in termcap" msgstr "E436: termcap içinde \"%s\" girdisi yok" msgid "E437: terminal capability \"cm\" required" -msgstr "E437: \"cm\" uçbirim kabiliyeti gerekiyor" +msgstr "E437: \"cm\" uçbirim yeteneği gerekiyor" msgid "" "\n" @@ -5688,16 +5703,16 @@ msgstr "E914: Bir Kanal, Kayan Noktalı Değer yerine kullanılıyor" msgid "E975: Using a Blob as a Float" msgstr "E975: Bir İkili Geniş Nesne, Kayan Noktalı Değer yerine kullanılıyor" -msgid "E729: using Funcref as a String" +msgid "E729: Using a Funcref as a String" msgstr "E729: Funcref bir Dizi yerine kullanılıyor" -msgid "E730: using List as a String" +msgid "E730: Using a List as a String" msgstr "E730: Liste bir Dizi yerine kullanılıyor" -msgid "E731: using Dictionary as a String" +msgid "E731: Using a Dictionary as a String" msgstr "E731: Sözlük bir Dizi yerine kullanılıyor" -msgid "E976: using Blob as a String" +msgid "E976: Using a Blob as a String" msgstr "E976: İkili Geniş Nesne bir Dizi yerine kullanılıyor" msgid "E977: Can only compare Blob with Blob" @@ -5892,16 +5907,16 @@ msgid "E180: Invalid complete value: %s" msgstr "E180: Geçersiz tam değer: %s" msgid "E468: Completion argument only allowed for custom completion" -msgstr "E468: Tamamlama değişkenine yalnızca özel tamamlamalarda izin verilir" +msgstr "E468: Tamamlama argümanına yalnızca özel tamamlamalarda izin verilir" msgid "E467: Custom completion requires a function argument" -msgstr "E467: Özel tamamlama bir işlev değişkeni gerektirir" +msgstr "E467: Özel tamamlama bir işlev argümanı gerektirir" msgid "E175: No attribute specified" msgstr "E175: Bir öznitelik belirtilmemiş" msgid "E176: Invalid number of arguments" -msgstr "E176: Geçersiz değişken sayısı" +msgstr "E176: Geçersiz argüman sayısı" msgid "E177: Count cannot be specified twice" msgstr "E177: Sayım iki defa belirtilemez" @@ -5910,10 +5925,10 @@ msgid "E178: Invalid default value for count" msgstr "E178: Sayım için geçersiz öntanımlı değer" msgid "E179: argument required for -complete" -msgstr "E179: -complete için değişken gerekiyor" +msgstr "E179: -complete için argüman gerekiyor" msgid "E179: argument required for -addr" -msgstr "E179: -addr için değişken gerekiyor" +msgstr "E179: -addr için argüman gerekiyor" #, c-format msgid "E174: Command already exists: add ! to replace it: %s" @@ -5948,14 +5963,21 @@ msgstr "E130: Bilinmeyen işlev: %s" #, c-format msgid "E125: Illegal argument: %s" -msgstr "E125: İzin verilmeyen değişken: %s" +msgstr "E125: İzin verilmeyen argüman: %s" #, c-format msgid "E853: Duplicate argument name: %s" -msgstr "E853: Yinelenen değişken adı: %s" +msgstr "E853: Yinelenen argüman adı: %s" msgid "E989: Non-default argument follows default argument" -msgstr "E989: Öntanımlı olmayan değişken öntanımlı değişkenden sonra" +msgstr "E989: Öntanımlı olmayan argüman öntanımlı argümandan sonra" + +msgid "E126: Missing :endfunction" +msgstr "E126: :endfunction eksik" + +#, c-format +msgid "W22: Text found after :endfunction: %s" +msgstr "W22: :endfunction sonrası metin bulundu: %s" #, c-format msgid "E451: Expected }: %s" @@ -5963,11 +5985,11 @@ msgstr "E451: } bekleniyordu: %s" #, c-format msgid "E740: Too many arguments for function %s" -msgstr "E740: %s işlevi için çok fazla değişken" +msgstr "E740: %s işlevi için çok fazla argüman" #, c-format msgid "E116: Invalid arguments for function %s" -msgstr "E116: %s işlevi için geçersiz değişkenler" +msgstr "E116: %s işlevi için geçersiz argümanlar" msgid "E132: Function call depth is higher than 'maxfuncdepth'" msgstr "E132: İşlevin çağırdığı derinlik 'maxfuncdepth'ten daha yüksek" @@ -5989,7 +6011,7 @@ msgid "%s returning %s" msgstr "%s, %s döndürüyor" msgid "E699: Too many arguments" -msgstr "E699: Çok fazla değişken" +msgstr "E699: Çok fazla argüman" #, c-format msgid "E276: Cannot use function as a method: %s" @@ -6032,17 +6054,6 @@ msgstr "E862: g: burada kullanılamaz" msgid "E932: Closure function should not be at top level: %s" msgstr "E932: Kapatma işlevi en üst düzeyde olmamalıdır: %s" -msgid "E126: Missing :endfunction" -msgstr "E126: :endfunction eksik" - -#, c-format -msgid "W1001: Text found after :enddef: %s" -msgstr "W1001: :enddef sonrası metin bulundu: %s" - -#, c-format -msgid "W22: Text found after :endfunction: %s" -msgstr "W22: :endfunction sonrası metin bulundu: %s" - #, c-format msgid "E707: Function name conflicts with variable: %s" msgstr "E707: İşlev adı şu değişken ile çakışıyor: %s" @@ -6605,6 +6616,55 @@ msgstr "gvimext.dll hatası" msgid "Path length too long!" msgstr "Yol çok uzun!" +msgid "E10: \\ should be followed by /, ? or &" +msgstr "E10: \\ sonrasında /, ? veya & gelmeli" + +msgid "E11: Invalid in command-line window; <CR> executes, CTRL-C quits" +msgstr "E11: Komut satırı penceresinde geçersiz; <CR> çalıştırır, CTRL-C çıkar" + +msgid "E12: Command not allowed from exrc/vimrc in current dir or tag search" +msgstr "" +"E12: Geçerli dizin veya etiket aramasında exrc veya vimrc'den komutlara izin " +"verilmiyor" + +msgid "E13: File exists (add ! to override)" +msgstr "E13: Dosya mevcut (geçersiz kılmak için ! ekleyin)" + +#, c-format +msgid "E15: Invalid expression: \"%s\"" +msgstr "E15: Geçersiz ifade: \"%s\"" + +msgid "E16: Invalid range" +msgstr "E16: Geçersiz erim" + +#, c-format +msgid "E17: \"%s\" is a directory" +msgstr "E17: \"%s\" bir dizin" + +msgid "E18: Unexpected characters in :let" +msgstr "E18: :let içinde beklenmeyen karakter" + +msgid "E18: Unexpected characters in assignment" +msgstr "E18: Atama içerisinde beklenmedik karakterler" + +msgid "E19: Mark has invalid line number" +msgstr "E19: İm satır numarası geçersiz" + +msgid "E20: Mark not set" +msgstr "E20: İm ayarlanmamış" + +msgid "E21: Cannot make changes, 'modifiable' is off" +msgstr "E21: Değişiklik yapılamıyor, 'modifiable' kapalı" + +msgid "E22: Scripts nested too deep" +msgstr "E22: Betikler çok iç içe geçmiş" + +msgid "E23: No alternate file" +msgstr "E23: Başka bir dosya yok" + +msgid "E24: No such abbreviation" +msgstr "E24: Böyle bir kısaltma yok" + #, c-format msgid "E121: Undefined variable: %s" msgstr "E121: Tanımlanmamış değişken: %s" @@ -6613,6 +6673,9 @@ msgstr "E121: Tanımlanmamış değişken: %s" msgid "E121: Undefined variable: %c:%s" msgstr "E121: Tanımlanmamış değişken: %c:%s" +msgid "E464: Ambiguous use of user-defined command" +msgstr "E464: Kullanıcı tanımlı komutun belirsiz kullanımı" + msgid "E476: Invalid command" msgstr "E476: Geçersiz komut" @@ -6633,15 +6696,19 @@ msgid "" "E856: \"assert_fails()\" second argument must be a string or a list with one " "or two strings" msgstr "" -"E856: \"assert_fails()\" ikinci değişkeni bir dizi veya bir veya iki dizili " +"E856: \"assert_fails()\" ikinci argüman bir dizi veya bir veya iki dizili " "bir liste olmalıdır" +#, c-format +msgid "E908: using an invalid value as a String: %s" +msgstr "E908: Geçersiz bir değer bir Dizi yerine kullanılıyor: %s" + msgid "E909: Cannot index a special variable" msgstr "E909: Özel bir değişken dizinlenemiyor" #, c-format -msgid "E1100: Missing :var: %s" -msgstr "E1100: :var eksik: %s" +msgid "E1100: Command not supported in Vim9 script (missing :var?): %s" +msgstr "E1100: Komut Vim9 betiğinde desteklenmiyor (:var? eksik): %s" #, c-format msgid "E1001: Variable not found: %s" @@ -6655,18 +6722,18 @@ msgid "E1003: Missing return value" msgstr "E1003: Dönüş değeri eksik" #, c-format -msgid "E1004: White space required before and after '%s'" -msgstr "E1004: '%s' öncesinde ve sonrasında boşluk gerekiyor" +msgid "E1004: White space required before and after '%s' at \"%s\"" +msgstr "E1004: Şu konumda '%s' öncesinde ve sonrasında boşluk gerekiyor: \"%s\"" msgid "E1005: Too many argument types" -msgstr "E1005: Çok fazla değişken türü" +msgstr "E1005: Çok fazla argüman türü" #, c-format msgid "E1006: %s is used as an argument" -msgstr "E1006: %s bir değişken olarak kullanılıyor" +msgstr "E1006: %s bir argüman olarak kullanılıyor" msgid "E1007: Mandatory argument after optional argument" -msgstr "E1007: İsteğe bağlı değişken sonrasında zorunlu değişken" +msgstr "E1007: İsteğe bağlı argüman sonrasında zorunlu argüman" msgid "E1008: Missing <type>" msgstr "E1008: <tür> eksik" @@ -6688,7 +6755,7 @@ msgstr "E1012: Tür uyumsuzluğu, %s bekleniyordu, ancak %s alındı" #, c-format msgid "E1013: Argument %d: type mismatch, expected %s but got %s" -msgstr "E1013: %d değişkeni: Tür uyumsuzluğu, %s bekleniyordu, ancak %s alındı" +msgstr "E1013: %d argümanı: Tür uyumsuzluğu, %s bekleniyordu, ancak %s alındı" #, c-format msgid "E1014: Invalid key: %s" @@ -6728,8 +6795,8 @@ msgid "E1022: Type or initialization required" msgstr "E1022: Tür veya ilklendirme gerekiyor" #, c-format -msgid "E1023: Using a Number as a Bool: %d" -msgstr "E1023: Bir Sayı, bir Bool yerine kullanılıyor: %d" +msgid "E1023: Using a Number as a Bool: %lld" +msgstr "E1023: Bir Sayı, bir Boole yerine kullanılıyor: %lld" msgid "E1024: Using a Number as a String" msgstr "E1024: Bir Sayı, bir Dizi yerine kullanılıyor" @@ -6768,11 +6835,11 @@ msgid "E1034: Cannot use reserved name %s" msgstr "E1034: Ayrılmış ad %s kullanılamaz" msgid "E1035: % requires number arguments" -msgstr "E1035: %, sayı değişkenler gerektirir" +msgstr "E1035: %, sayı argümanları gerektirir" #, c-format msgid "E1036: %c requires number or float arguments" -msgstr "E1036: %c, sayı veya kayan noktalı değer değişkenler gerektirir" +msgstr "E1036: %c, sayı veya kayan noktalı değer argümanları gerektirir" #, c-format msgid "E1037: Cannot use \"%s\" with %s" @@ -6798,7 +6865,7 @@ msgid "E1043: Invalid command after :export" msgstr "E1043: :export sonrası geçersiz komut" msgid "E1044: Export with invalid argument" -msgstr "E1044: Geçersiz değişkenle dışa aktarım" +msgstr "E1044: Geçersiz argümanla dışa aktarım" msgid "E1045: Missing \"as\" after *" msgstr "E1045: * sonrası \"as\" eksik" @@ -6817,11 +6884,12 @@ msgstr "E1048: Betikte öge bulunamadı: %s" msgid "E1049: Item not exported in script: %s" msgstr "E1049: Betikte öge dışa aktarılmadı: %s" -msgid "E1050: Colon required before a range" -msgstr "E1050: Bir erim öncesi iki nokta gerekiyor" +#, c-format +msgid "E1050: Colon required before a range: %s" +msgstr "E1050: Bir erim öncesi iki nokta gerekiyor: %s" msgid "E1051: Wrong argument type for +" -msgstr "E1051: + için hatalı değişken türü" +msgstr "E1051: + için hatalı argüman türü" #, c-format msgid "E1052: Cannot declare an option: %s" @@ -6875,12 +6943,12 @@ msgid "E1067: Separator mismatch: %s" msgstr "E1067: Ayırıcı uyumsuzluğu: %s" #, c-format -msgid "E1068: No white space allowed before '%s'" -msgstr "E1068: '%s' önce boşluğa izin verilmiyor" +msgid "E1068: No white space allowed before '%s': %s" +msgstr "E1068: '%s' önce boşluğa izin verilmiyor: %s" #, c-format -msgid "E1069: White space required after '%s'" -msgstr "E1069: '%s' sonrası boşluk gerekiyor" +msgid "E1069: White space required after '%s': %s" +msgstr "E1069: '%s' sonrası boşluk gerekiyor: %s" msgid "E1070: Missing \"from\"" msgstr "E1070: \"from\" eksik" @@ -6908,7 +6976,7 @@ msgstr "E1076: Bu Vim kayan noktalı değer desteği ile derlenmemiş" #, c-format msgid "E1077: Missing argument type for %s" -msgstr "E1077: %s için değişken türü eksik" +msgstr "E1077: %s için argüman türü eksik" #, c-format msgid "E1081: Cannot unlet %s" @@ -6933,7 +7001,7 @@ msgid "E1086: Cannot use :function inside :def" msgstr "E1086: :def içinde :function kullanılamaz" msgid "E1087: Cannot use an index when declaring a variable" -msgstr "E1087: Bir değişken tanımlarken indeks kullanılamaz" +msgstr "E1087: Bir değişken tanımlarken dizinleme kullanılamaz" #, c-format msgid "E1089: Unknown variable: %s" @@ -6941,7 +7009,7 @@ msgstr "E1089: Bilinmeyen değişken: %s" #, c-format msgid "E1090: Cannot assign to argument %s" -msgstr "E1090: %s değişkenine atanamıyor" +msgstr "E1090: %s argümanına atanamıyor" #, c-format msgid "E1091: Function is not compiled: %s" @@ -6989,11 +7057,11 @@ msgid "E1105: Cannot convert %s to string" msgstr "E1105: %s bir diziye dönüştürülemiyor" msgid "E1106: One argument too many" -msgstr "E1106: Bir değişken fazladan" +msgstr "E1106: Bir argüman fazladan" #, c-format msgid "E1106: %d arguments too many" -msgstr "E1106: %d değişken fazladan" +msgstr "E1106: %d argüman fazladan" msgid "E1107: String, List, Dict or Blob required" msgstr "E1107: Dizi, Liste, Sözlük veya İkili Nesne gerekiyor" @@ -7026,10 +7094,10 @@ msgid "E1114: Only values of 0x100 and higher supported" msgstr "E1114: Yalnızca 0x100 ve daha yüksek değerler destekleniyor" msgid "E1115: \"assert_fails()\" fourth argument must be a number" -msgstr "E1115: \"assert_fails()\" dördüncü değişkeni bir sayı olmalıdır" +msgstr "E1115: \"assert_fails()\" dördüncü argüman bir sayı olmalıdır" msgid "E1116: \"assert_fails()\" fifth argument must be a string" -msgstr "E1116: \"assert_fails()\" beşinci değişkeni bir dizi olmalıdır" +msgstr "E1116: \"assert_fails()\" beşinci argüman bir dizi olmalıdır" msgid "E1117: Cannot use ! with nested :def" msgstr "E1117: !, iç içe geçmiş :def ile kullanılamaz" @@ -7080,7 +7148,7 @@ msgid "E1131: Cannot add to null blob" msgstr "E1131: Null ikili geniş nesnesine ekleme yapılamaz" msgid "E1132: Missing function argument" -msgstr "E1132: İşlev değişkeni eksik" +msgstr "E1132: İşlev argümanı eksik" msgid "E1133: Cannot extend a null dict" msgstr "E1133: Bir null sözlük genişletilemez" @@ -7108,12 +7176,259 @@ msgstr "E1138: Bir Boole, Sayı yerine kullanılıyor" msgid "E1139: Missing matching bracket after dict key" msgstr "E1139: Sözlük anahtarı sonrası eşleşen ayraç eksik" -msgid "E1140: For argument must be a sequence of lists" -msgstr "E1140: For değişkeni listelerin bir sıralaması olmalıdır" +msgid "E1140: :for argument must be a sequence of lists" +msgstr "E1140: :for argümanı listelerin bir sıralaması olmalıdır" msgid "E1141: Indexable type required" msgstr "E1141: İndekslenebilir tür gerekiyor" +msgid "E1142: Non-empty string required" +msgstr "E1142: Boş olmayan dizi gerekiyor" + +#, c-format +msgid "E1143: Empty expression: \"%s\"" +msgstr "E1143: Boş ifade: \"%s\"" + +#, c-format +msgid "E1144: Command \"%s\" is not followed by white space: %s" +msgstr "E1144: \"%s\" komutu sonrasında boşluk gelmiyor: %s" + +#, c-format +msgid "E1145: Missing heredoc end marker: %s" +msgstr "E1145: Son imleyicisi eksik: %s" + +#, c-format +msgid "E1146: Command not recognized: %s" +msgstr "E1146: Komut tanınamadı: %s" + +msgid "E1147: List not set" +msgstr "E1147: Liste ayarlanmamış" + +#, c-format +msgid "E1148: Cannot index a %s" +msgstr "E1148: Bir %s dizinlenemiyor" + +#, c-format +msgid "E1149: Script variable is invalid after reload in function %s" +msgstr "E1149: %s işlevindeki yeniden yüklemeden sonra betik değişkeni geçersiz" + +msgid "E1150: Script variable type changed" +msgstr "E1150: Betik değişkeni türü değiştirildi" + +msgid "E1151: Mismatched endfunction" +msgstr "E1151: Eşleşmeyen endfunction" + +msgid "E1152: Mismatched enddef" +msgstr "E1152: Eşleşmeyen enddef" + +msgid "E1153: Invalid operation for bool" +msgstr "E1153: Boole için geçersiz işlem" + +msgid "E1154: Divide by zero" +msgstr "E1154: Sıfır ile bölüm" + +msgid "E1155: Cannot define autocommands for ALL events" +msgstr "E1155: Otokomutlar TÜM olaylar için tanımlanamıyor" + +msgid "E1156: Cannot change the argument list recursively" +msgstr "E1156: Değişken listesi özyineli olarak değiştirilemiyor" + +msgid "E1157: Missing return type" +msgstr "E1157: Dönüş türü eksik" + +msgid "E1158: Cannot use flatten() in Vim9 script" +msgstr "E1158: flatten(), Vim9 betiğinde kullanılamaz" + +msgid "E1159: Cannot split a window when closing the buffer" +msgstr "E1159: Arabellek kapatılırken bir pencere bölünemez" + +msgid "E1160: Cannot use a default for variable arguments" +msgstr "E1160: Değişken argümanları için bir öntanımlı kullanılamaz" + +#, c-format +msgid "E1161: Cannot json encode a %s" +msgstr "E1161: Bir %s JSON olarak kodlanamıyor" + +#, c-format +msgid "E1162: Register name must be one character: %s" +msgstr "E1162: Yazmaç adı tek bir karakter olmalıdır: %s" + +#, c-format +msgid "E1163: Variable %d: type mismatch, expected %s but got %s" +msgstr "E1163: %d değişkeni: Tür uyumsuzluğu, %s bekleniyordu, ancak %s alındı" + +msgid "E1164: vim9cmd must be followed by a command" +msgstr "E1164: vim9cmd sonrasında bir komut gelmelidir" + +#, c-format +msgid "E1165: Cannot use a range with an assignment: %s" +msgstr "E1165: Bir atama ile bir erim kullanılamıyor: %s" + +msgid "E1166: Cannot use a range with a dictionary" +msgstr "E1166: Bir sözlük ile bir erim kullanılamıyor" + +#, c-format +msgid "E1167: Argument name shadows existing variable: %s" +msgstr "E1167: Argüman adı var olan değişkeni gölgeliyor: %s" + +#, c-format +msgid "E1168: Argument already declared in the script: %s" +msgstr "E1168: Betikte argüman halihazırda tanımlanmış: %s" + +msgid "E1169: 'import * as {name}' not supported here" +msgstr "E1169: 'import * as {name} burada desteklenmiyor" + +msgid "E1170: Cannot use #{ to start a comment" +msgstr "E1170: Bir yorum başlatmak için #{ kullanılamaz" + +msgid "E1171: Missing } after inline function" +msgstr "E1171: Satıriçi işlevden sonra } eksik" + +msgid "E1172: Cannot use default values in a lambda" +msgstr "E1172: Bir lambda içerisinde öntanımlı değerler kullanılamıyor" + +#, c-format +msgid "E1173: Text found after enddef: %s" +msgstr "E1173: :enddef sonrası metin bulundu: %s" + +#, c-format +msgid "E1174: String required for argument %d" +msgstr "E1174: %d argümanı için dizi gerekiyor" + +#, c-format +msgid "E1175: Non-empty string required for argument %d" +msgstr "E1175: %d argümanı için boş olmayan dizi gerekiyor" + +msgid "E1176: Misplaced command modifier" +msgstr "E1176: Yanlış yere konulmuş komut değiştiricisi" + +#, c-format +msgid "E1177: For loop on %s not supported" +msgstr "E1177: %s üzerinde for döngüsü desteklenmiyor" + +msgid "E1178: Cannot lock or unlock a local variable" +msgstr "E1178: Bir yerel değişken kilitlenemiyor/kilidi açılamıyor" + +#, c-format +msgid "" +"E1179: Failed to extract PWD from %s, check your shell's config related to " +"OSC 7" +msgstr "" +"E1179: %s içinden PWD çıkarılamadı, kabuğunuzun OSC 7 ile ilgili " +"yapılandırmasını denetleyin" + +#, c-format +msgid "E1180: Variable arguments type must be a list: %s" +msgstr "E1180: Değişken argümanları türü bir liste olmalıdır: %s" + +msgid "E1181: Cannot use an underscore here" +msgstr "E1181: Alt çizgi burada kullanılamaz" + +msgid "E1182: Blob required" +msgstr "E1182: İkili geniş nesne gerekiyor" + +#, c-format +msgid "E1183: Cannot use a range with an assignment operator: %s" +msgstr "E1183: Bir atama işleci ile bir erim kullanılamıyor: %s" + +msgid "E1184: Blob not set" +msgstr "E1184: İkili geniş nesne ayarlanmamış" + +msgid "E1185: Cannot nest :redir" +msgstr "E1185: :redir içe geçirilemiyor" + +msgid "E1185: Missing :redir END" +msgstr "E1185: :redir END eksik" + +#, c-format +msgid "E1186: Expression does not result in a value: %s" +msgstr "E1186: İfade bir değer sonucu vermiyor: %s" + +msgid "E1187: Failed to source defaults.vim" +msgstr "E1187: defaults.vim kaynaklanamadı" + +msgid "E1188: Cannot open a terminal from the command line window" +msgstr "E1188: Komut satırı penceresinden bir uçbirim açılamıyor" + +#, c-format +msgid "E1189: Cannot use :legacy with this command: %s" +msgstr "E1189: :legacy, bu komut ile kullanılamıyor: %s" + +msgid "E1190: One argument too few" +msgstr "E1190: Bir argüman daha gerekiyor" + +#, c-format +msgid "E1190: %d arguments too few" +msgstr "E1190: %d argüman daha gerekiyor" + +#, c-format +msgid "E1191: Call to function that failed to compile: %s" +msgstr "E1191: Derlenemeyen işlev çağrısı: %s" + +msgid "E1192: Empty function name" +msgstr "E1192: Boş işlev adı" + +msgid "E1193: cryptmethod xchacha20 not built into this Vim" +msgstr "E1193: cryptmethod xchacha20 bu Vim ile kullanılamıyor" + +msgid "E1194: Cannot encrypt header, not enough space" +msgstr "E1194: Üstbilgi şifrelenemiyor, yetersiz alan" + +msgid "E1195: Cannot encrypt buffer, not enough space" +msgstr "E1195: Arabellek şifrelenemiyor, yetersiz alan" + +msgid "E1196: Cannot decrypt header, not enough space" +msgstr "E1196: Üstbilgi şifresi çözülemiyor, yetersiz alan" + +msgid "E1197: Cannot allocate_buffer for encryption" +msgstr "E1197: Şifreleme için allocate_buffer yapılamıyor" + +msgid "E1198: Decryption failed: Header incomplete!" +msgstr "E1198: Şifre çözümü başarısız: Üstbilgi tam değil!" + +msgid "E1199: Cannot decrypt buffer, not enough space" +msgstr "E1199: Arabellek şifresi çözülemiyor, yetersiz alan" + +msgid "E1200: Decryption failed!" +msgstr "E1200: Şifre çözümü başarısız!" + +msgid "E1201: Decryption failed: pre-mature end of file!" +msgstr "E1201: Şifre çözümü başarısız: Beklenmedik dosya sonu!" + +#, c-format +msgid "E1202: No white space allowed after '%s': %s" +msgstr "E1202: '%s' sonrası boşluğa izin verilmiyor: %s" + +#, c-format +msgid "E1203: Dot can only be used on a dictionary: %s" +msgstr "E1203: Nokta yalnızca bir sözlükte kullanılabilir: %s" + +#, c-format +msgid "E1204: No Number allowed after .: '\\%%%c'" +msgstr "E1204: . sonrası Sayıya izin verilmiyor: '\\%%%c'" + +msgid "E1205: No white space allowed between option and" +msgstr "E1205: and seçeneği arasında boşluğa izin verilmiyor" + +#, c-format +msgid "E1206: Dictionary required for argument %d" +msgstr "E1206: %d argümanı için sözlük gerekiyor" + +#, c-format +msgid "E1207: Expression without an effect: %s" +msgstr "E1207: Bir efekt olmadan ifade: %s" + +msgid "E1208: -complete used without -nargs" +msgstr "E1208: -complete, -nargs olmadan kullanıldı" + +#, c-format +msgid "E1209: Invalid value for a line number: \"%s\"" +msgstr "E1209: Satır numarası için geçersiz değer: \"%s\"" + +#, c-format +msgid "E1210: Number required for argument %d" +msgstr "E1210: %d argümanı için sayı gerekiyor" + msgid "--No lines in buffer--" msgstr "--Arabellek içinde satır yok--" @@ -7123,17 +7438,6 @@ msgstr "E470: Komut durduruldu" msgid "E471: Argument required" msgstr "E471: Değişken gerekiyor" -msgid "E10: \\ should be followed by /, ? or &" -msgstr "E10: \\ sonrasında /, ? veya & gelmeli" - -msgid "E11: Invalid in command-line window; <CR> executes, CTRL-C quits" -msgstr "E11: Komut satırı penceresinde geçersiz; <CR> çalıştırır, CTRL-C çıkar" - -msgid "E12: Command not allowed from exrc/vimrc in current dir or tag search" -msgstr "" -"E12: Geçerli dizin veya etiket aramasında exrc veya vimrc'den komutlara izin " -"verilmiyor" - msgid "E171: Missing :endif" msgstr "E171: :endif eksik" @@ -7164,9 +7468,6 @@ msgstr "E588: :while olmadan :endwhile" msgid "E588: :endfor without :for" msgstr "E588: :for olmadan :endfor" -msgid "E13: File exists (add ! to override)" -msgstr "E13: Dosya mevcut (geçersiz kılmak için ! ekleyin)" - msgid "E472: Command failed" msgstr "E472: Komut başarısız oldu" @@ -7193,34 +7494,23 @@ msgid "Interrupted" msgstr "Yarıda kesildi" msgid "E474: Invalid argument" -msgstr "E474: Geçersiz değişken" +msgstr "E474: Geçersiz argüman" #, c-format msgid "E475: Invalid argument: %s" -msgstr "E475: Geçersiz değişken: %s" +msgstr "E475: Geçersiz argüman: %s" #, c-format msgid "E983: Duplicate argument: %s" -msgstr "E983: Yinelenen değişken: %s" +msgstr "E983: Yinelenen argüman: %s" #, c-format msgid "E475: Invalid value for argument %s" -msgstr "E475: %s değişkeni için geçersiz değer" +msgstr "E475: %s argümanı için geçersiz değer" #, c-format msgid "E475: Invalid value for argument %s: %s" -msgstr "E475: %s değişkeni için geçersiz değer: %s" - -#, c-format -msgid "E15: Invalid expression: %s" -msgstr "E15: Geçersiz ifade: %s" - -msgid "E16: Invalid range" -msgstr "E16: Geçersiz erim" - -#, c-format -msgid "E17: \"%s\" is a directory" -msgstr "E17: \"%s\" bir dizin" +msgstr "E475: %s argümanı için geçersiz değer: %s" msgid "E756: Spell checking is not possible" msgstr "E756: Yazım denetimi olanaklı değil" @@ -7236,24 +7526,6 @@ msgstr "E667: Fsync başarısız oldu" msgid "E448: Could not load library function %s" msgstr "E448: %s kitaplık işlevi yüklenemedi" -msgid "E19: Mark has invalid line number" -msgstr "E19: İm satır numarası geçersiz" - -msgid "E20: Mark not set" -msgstr "E20: İm ayarlanmamış" - -msgid "E21: Cannot make changes, 'modifiable' is off" -msgstr "E21: Değişiklik yapılamıyor, 'modifiable' kapalı" - -msgid "E22: Scripts nested too deep" -msgstr "E22: Betikler çok iç içe geçmiş" - -msgid "E23: No alternate file" -msgstr "E23: Başka bir dosya yok" - -msgid "E24: No such abbreviation" -msgstr "E24: Böyle bir kısaltma yok" - msgid "E477: No ! allowed" msgstr "E477: ! imine izin verilmiyor" @@ -7327,7 +7599,7 @@ msgid "E485: Can't read file %s" msgstr "E485: %s dosyası okunamıyor" msgid "E38: Null argument" -msgstr "E38: Anlamsız değişken" +msgstr "E38: Anlamsız argüman" msgid "E39: Number expected" msgstr "E39: Sayı bekleniyordu" @@ -7392,6 +7664,9 @@ msgstr "E794: Değişken kum havuzunda ayarlanamıyor: \"%s\"" msgid "E928: String required" msgstr "E928: Dizi gerekiyor" +msgid "E889: Number required" +msgstr "E889: Sayı gerekiyor" + msgid "E713: Cannot use empty key for Dictionary" msgstr "E713: Sözlük için boş anahtar kullanılamaz" @@ -7411,11 +7686,11 @@ msgstr "E978: İkili geniş nesne için geçersiz işlem" #, c-format msgid "E118: Too many arguments for function: %s" -msgstr "E118: İşlev için çok fazla değişken: %s" +msgstr "E118: İşlev için çok fazla argüman: %s" #, c-format msgid "E119: Not enough arguments for function: %s" -msgstr "E119: Şu işlev için yetersiz sayıda değişken: %s" +msgstr "E119: Şu işlev için yetersiz sayıda argüman: %s" #, c-format msgid "E933: Function was deleted: %s" @@ -7437,18 +7712,15 @@ msgstr "E697: Liste sonunda ']' eksik: %s" #, c-format msgid "E712: Argument of %s must be a List or Dictionary" -msgstr "E712: %s ögesinin değişkeni bir liste veya sözlük olmalıdır" +msgstr "E712: %s ögesinin argümanı bir liste veya sözlük olmalıdır" #, c-format msgid "E896: Argument of %s must be a List, Dictionary or Blob" -msgstr "E896: %s değişkeni bir liste, sözlük veya ikili geniş nesne olmalıdır" +msgstr "E896: %s argümanı bir liste, sözlük veya ikili geniş nesne olmalıdır" msgid "E804: Cannot use '%' with Float" msgstr "E804: Bir kayan noktalı değer ile '%' kullanılamaz" -msgid "E908: using an invalid value as a String" -msgstr "E908: Geçersiz bir değer bir Dizi yerine kullanılıyor" - msgid "E996: Cannot lock an option" msgstr "E996: Seçenek kilitlenemiyor" @@ -7456,9 +7728,6 @@ msgstr "E996: Seçenek kilitlenemiyor" msgid "E113: Unknown option: %s" msgstr "E113: Bilinmeyen seçenek: %s" -msgid "E18: Unexpected characters in :let" -msgstr "E18: :let içinde beklenmeyen karakter" - #, c-format msgid "E998: Reduce of an empty %s with no initial value" msgstr "E998: Başlangıç değeri olmayan boş bir %s için reduce() yapılamıyor" @@ -7616,7 +7885,7 @@ msgstr "E957: Geçersiz pencere numarası" #, c-format msgid "E686: Argument of %s must be a List" -msgstr "E686: %s değişkeni bir liste olmalı" +msgstr "E686: %s argümanı bir liste olmalı" msgid "E109: Missing ':' after '?'" msgstr "E109: '?' sonrası ':' eksik" @@ -7685,7 +7954,7 @@ msgstr "'%s' anahtarı sözlüğe eklenemedi" #, c-format msgid "index must be int or slice, not %s" -msgstr "dizin bir tamsayı veya dilim olmalıdır, %s olamaz" +msgstr "sıra bir tamsayı veya dilim olmalıdır, %s olamaz" #, c-format msgid "expected str() or unicode() instance, but got %s" @@ -7762,10 +8031,10 @@ msgid "expected sequence element of size 2, but got sequence of size %d" msgstr "2 boyut bir sıralama bekleniyordu, ancak %d boyut bir sıralama geldi" msgid "list constructor does not accept keyword arguments" -msgstr "liste yapıcısı anahtar sözcük değişkenleri kabul etmez" +msgstr "liste yapıcısı anahtar sözcük argümanları kabul etmez" msgid "list index out of range" -msgstr "liste dizini erimin dışında" +msgstr "liste sırası erimin dışında" #, c-format msgid "internal error: failed to get Vim list item %d" @@ -8013,8 +8282,7 @@ msgstr "" "düzenleyebilirsiniz." msgid "\" Hit <Enter> on a help line to open a help window on this option." -msgstr "" -"\" Yardım penceresini açmak için seçenek adı üzerinde <Enter>'a basın." +msgstr "\" Yardım penceresini açmak için seçenek adı üzerinde <Enter>'a basın." msgid "\" Hit <Enter> on an index line to jump there." msgstr "" @@ -8056,7 +8324,8 @@ msgid "moving around, searching and patterns" msgstr "dolaşma, arama ve dizgeler" msgid "list of flags specifying which commands wrap to another line" -msgstr "hangi komutların diğer satıra kaydırıldığını belirleyen bayraklar\n" +msgstr "" +"hangi komutların diğer satıra kaydırıldığını belirleyen bayraklar\n" "listesi" msgid "" @@ -8081,6 +8350,9 @@ msgstr ":cd için kullanılan dizin adları listesi" msgid "change to directory of file in buffer" msgstr "arabellekteki dosyanın olduğu dizine değiştir" +msgid "change to pwd of shell in terminal buffer" +msgstr "uçbirim arabelleğindeki kabuğun pwd'sine geç" + msgid "search commands wrap around the end of the buffer" msgstr "arama komutları, arabelleğin sonunda kaydırılır" @@ -8320,7 +8592,8 @@ msgid "multiple windows" msgstr "çoklu pencereler" msgid "0, 1 or 2; when to use a status line for the last window" -msgstr "0, 1 veya 2; son pencere için ne zaman bir durum satırı\n" +msgstr "" +"0, 1 veya 2; son pencere için ne zaman bir durum satırı\n" "kullanılacağı" msgid "alternate format to be used for a status line" @@ -8382,7 +8655,8 @@ msgid "this window scrolls together with other bound windows" msgstr "bu pencere, bağlı diğer pencerelerle birlikte kayar" msgid "\"ver\", \"hor\" and/or \"jump\"; list of options for 'scrollbind'" -msgstr "\"ver\", \"hor\" ve/veya \"jump\"; 'scrollbind' için seçenekler listesi" +msgstr "" +"\"ver\", \"hor\" ve/veya \"jump\"; 'scrollbind' için seçenekler listesi" msgid "this window's cursor moves together with other bound windows" msgstr "bu pencerenin imleci bağlı diğer pencerelerle birlikte kayar" @@ -8394,7 +8668,8 @@ msgid "key that precedes Vim commands in a terminal window" msgstr "bir uçbirim penceresinde Vim komutlarından önce gelen düğme" msgid "max number of lines to keep for scrollback in a terminal window" -msgstr "bir uçbirim penceresinde geri kaydırma için kullanılacak\n" +msgstr "" +"bir uçbirim penceresinde geri kaydırma için kullanılacak\n" "en çok satır sayısı" msgid "type of pty to use for a terminal window" @@ -8522,8 +8797,7 @@ msgid "list of flags that specify how the GUI works" msgstr "grafik arabirimin nice çalıştığını belirleyen bayraklar listesi" msgid "\"icons\", \"text\" and/or \"tooltips\"; how to show the toolbar" -msgstr "" -"\"icons\", \"text\" ve/veya \"tooltips\"; araç çubuğu kipleri " +msgstr "\"icons\", \"text\" ve/veya \"tooltips\"; araç çubuğu kipleri " msgid "size of toolbar icons" msgstr "araç çubuğu simgelerinin boyutu" @@ -8679,7 +8953,8 @@ msgid "list of directories for undo files" msgstr "geri al dosyaları için dizinler listesi" msgid "maximum number lines to save for undo on a buffer reload" -msgstr "arabellek yeniden yüklemesinde geri al için kaydedilecek\n" +msgstr "" +"arabellek yeniden yüklemesinde geri al için kaydedilecek\n" "en çok satır sayısı" msgid "changes have been made and not written to a file" @@ -8704,7 +8979,8 @@ msgid "definition of what comment lines look like" msgstr "yorum satırlarının nice görüneceğinin tanımı" msgid "list of flags that tell how automatic formatting works" -msgstr "kendiliğinden biçimlendirmenin nice çalıştığını anlatan\n" +msgstr "" +"kendiliğinden biçimlendirmenin nice çalıştığını anlatan\n" "bayraklar listesi" msgid "pattern to recognize a numbered list" @@ -8714,7 +8990,8 @@ msgid "expression used for \"gq\" to format lines" msgstr "satırları biçimlendirmek için \"gq\" için kullanılan ifade" msgid "specifies how Insert mode completion works for CTRL-N and CTRL-P" -msgstr "Ekleme kipi tamamlamasının CTRL-N ve CTRL-P için nice çalıştığını\n" +msgstr "" +"Ekleme kipi tamamlamasının CTRL-N ve CTRL-P için nice çalıştığını\n" "belirler" msgid "whether to use a popup menu for Insert mode completion" @@ -8739,7 +9016,8 @@ msgid "list of dictionary files for keyword completion" msgstr "anahtar sözcük tamamlaması için sözlük dosyaları listesi" msgid "list of thesaurus files for keyword completion" -msgstr "anahtar sözcük tamamlaması için eşanlamlılar sözlüğü dosyaları\n" +msgstr "" +"anahtar sözcük tamamlaması için eşanlamlılar sözlüğü dosyaları\n" "listesi" msgid "adjust case of a keyword completion match" @@ -8883,7 +9161,8 @@ msgid "markers used when 'foldmethod' is \"marker\"" msgstr "'foldmethod' \"marker\" olduğunda kullanılan imleyiciler" msgid "maximum fold depth for when 'foldmethod' is \"indent\" or \"syntax\"" -msgstr "'foldmethod' \"indent\" veya \"syntax\" olduğunda kullanılan en çok\n" +msgstr "" +"'foldmethod' \"indent\" veya \"syntax\" olduğunda kullanılan en çok\n" "kıvırma derinliği" msgid "diff mode" @@ -9013,7 +9292,8 @@ msgid "use a swap file for this buffer" msgstr "bu arabellek için bir takas dosyası kullan" msgid "\"sync\", \"fsync\" or empty; how to flush a swap file to disk" -msgstr "\"sync\", \"fsync\", veya boş; bir takas dosyasının diske\n" +msgstr "" +"\"sync\", \"fsync\", veya boş; bir takas dosyasının diske\n" "nice floşlanacağı" msgid "number of characters typed to cause a swap file update" @@ -9089,13 +9369,14 @@ msgid "characters to escape when 'shellxquote' is (" msgstr "'shellxquote' ( iken kaçırılacak karakterler" msgid "argument for 'shell' to execute a command" -msgstr "bir komut çalıştırmak için 'shell' için değişken" +msgstr "bir komut çalıştırmak için 'shell' için argüman" msgid "used to redirect command output to a file" msgstr "komut çıktısını bir dosyaya yeniden yönlendirmek için kullanılır" msgid "use a temp file for shell commands instead of using a pipe" -msgstr "bir veri yolu kullanımı yerine kabuk komutları için geçici\n" +msgstr "" +"bir veri yolu kullanımı yerine kabuk komutları için geçici\n" "bir dosya kullan" msgid "program used for \"=\" command" @@ -9108,7 +9389,8 @@ msgid "program used for the \"K\" command" msgstr "\"K\" komutu için kullanılan program" msgid "warn when using a shell command and a buffer has changes" -msgstr "bir kabuk komutu kullanılıyorsa ve arabellekte değişiklikler\n" +msgstr "" +"bir kabuk komutu kullanılıyorsa ve arabellekte değişiklikler\n" "varsa uyar" msgid "running make and jumping to errors (quickfix)" @@ -9124,7 +9406,8 @@ msgid "program used for the \":make\" command" msgstr "\":make\" komutu için kullanılan program" msgid "string used to put the output of \":make\" in the error file" -msgstr "\":make\" komutunun çıktısını hata dosyasına koymak için\n" +msgstr "" +"\":make\" komutunun çıktısını hata dosyasına koymak için\n" "kullanılan dizi" msgid "name of the errorfile for the 'makeprg' command" @@ -9179,7 +9462,8 @@ msgid "insert characters backwards" msgstr "karakterleri geriye doğru ekle" msgid "allow CTRL-_ in Insert and Command-line mode to toggle 'revins'" -msgstr "'revins' açıp kapatmak için Ekleme ve Komut Satırı kipinde\n" +msgstr "" +"'revins' açıp kapatmak için Ekleme ve Komut Satırı kipinde\n" "CTRL-_ izin ver" msgid "the ASCII code for the first letter of the Hebrew alphabet" @@ -9210,8 +9494,9 @@ msgid "apply 'langmap' to mapped characters" msgstr "eşlemlenen karakterlere 'langmap' uygula" msgid "when set never use IM; overrules following IM options" -msgstr "ayarlandığında hiçbir zaman IM kullanma; aşağıdaki IM seçeneklerini " -"geçersiz kılar" +msgstr "" +"ayarlandığında hiçbir zaman IM kullanma; aşağıdaki IM seçeneklerini geçersiz " +"kılar" msgid "in Insert mode: 1: use :lmap; 2: use IM; 0: neither" msgstr "Ekleme kipinde: 1: :lmap kullan; 2; IM kullan; 0: hiçbiri" diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 3675591bbc..6fdcf8a838 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -135,7 +135,7 @@ static size_t linebuf_size = 0; static schar_T *linebuf_char = NULL; static sattr_T *linebuf_attr = NULL; -static match_T search_hl; /* used for 'hlsearch' highlight matching */ +static match_T search_hl; // used for 'hlsearch' highlight matching StlClickDefinition *tab_page_click_defs = NULL; @@ -210,7 +210,7 @@ void redraw_later(win_T *wp, int type) if (type >= NOT_VALID) { wp->w_lines_valid = 0; } - if (must_redraw < type) { /* must_redraw is the maximum of all windows */ + if (must_redraw < type) { // must_redraw is the maximum of all windows must_redraw = type; } } @@ -336,7 +336,7 @@ int update_screen(int type) } if (must_redraw) { - if (type < must_redraw) { /* use maximal type */ + if (type < must_redraw) { // use maximal type type = must_redraw; } @@ -347,7 +347,7 @@ int update_screen(int type) must_redraw = 0; } - /* Need to update w_lines[]. */ + // Need to update w_lines[]. if (curwin->w_lines_valid == 0 && type < NOT_VALID) { type = NOT_VALID; } @@ -447,10 +447,10 @@ int update_screen(int type) win_ui_flush(); msg_ext_check_clear(); - /* reset cmdline_row now (may have been changed temporarily) */ + // reset cmdline_row now (may have been changed temporarily) compute_cmdrow(); - /* Check for changed highlighting */ + // Check for changed highlighting if (need_highlight_changed) { highlight_changed(); } @@ -503,7 +503,7 @@ int update_screen(int type) redraw_tabline = true; } - if (clear_cmdline) { /* going to clear cmdline (done below) */ + if (clear_cmdline) { // going to clear cmdline (done below) check_for_delay(FALSE); } @@ -606,7 +606,7 @@ int update_screen(int type) win_update(wp, &providers); } - /* redraw status line after the window to minimize cursor movement */ + // redraw status line after the window to minimize cursor movement if (wp->w_redr_status) { win_redr_status(wp); } @@ -635,7 +635,7 @@ int update_screen(int type) showmode(); } - /* May put up an introductory message when not editing a file */ + // May put up an introductory message when not editing a file if (!did_intro) { maybe_intro_message(); } @@ -741,7 +741,7 @@ bool win_cursorline_standout(const win_T *wp) */ static void win_update(win_T *wp, Providers *providers) { - buf_T *buf = wp->w_buffer; + buf_T *buf = wp->w_buffer; int type; int top_end = 0; /* Below last row of the top area that needs updating. 0 when no top area updating. */ @@ -754,10 +754,10 @@ static void win_update(win_T *wp, Providers *providers) bool scrolled_down = false; // true when scrolled down when w_topline got smaller a bit bool top_to_mod = false; // redraw above mod_top - int row; /* current window row to display */ - linenr_T lnum; /* current buffer lnum to display */ - int idx; /* current index in w_lines[] */ - int srow; /* starting row of the current line */ + int row; // current window row to display + linenr_T lnum; // current buffer lnum to display + int idx; // current index in w_lines[] + int srow; // starting row of the current line bool eof = false; // if true, we hit the end of the file bool didline = false; // if true, we finished the last line @@ -765,14 +765,12 @@ static void win_update(win_T *wp, Providers *providers) long j; static bool recursive = false; // being called recursively const linenr_T old_botline = wp->w_botline; - const int old_wrow = wp->w_wrow; - const int old_wcol = wp->w_wcol; // Remember what happened to the previous line. #define DID_NONE 1 // didn't update a line #define DID_LINE 2 // updated a normal line #define DID_FOLD 3 // updated a folded line int did_update = DID_NONE; - linenr_T syntax_last_parsed = 0; /* last parsed text line */ + linenr_T syntax_last_parsed = 0; // last parsed text line linenr_T mod_top = 0; linenr_T mod_bot = 0; int save_got_int; @@ -952,10 +950,10 @@ static void win_update(win_T *wp, Providers *providers) } } if (top_end == 0) { - /* not found (cannot happen?): redraw everything */ + // not found (cannot happen?): redraw everything type = NOT_VALID; } else { - /* top area defined, the rest is VALID */ + // top area defined, the rest is VALID type = VALID; } } @@ -1003,7 +1001,7 @@ static void win_update(win_T *wp, Providers *providers) } if (j < wp->w_grid.Rows - 2) { // not too far off i = plines_m_win(wp, wp->w_topline, wp->w_lines[0].wl_lnum - 1); - /* insert extra lines for previously invisible filler lines */ + // insert extra lines for previously invisible filler lines if (wp->w_lines[0].wl_lnum != wp->w_topline) { i += diff_check_fill(wp, wp->w_lines[0].wl_lnum) - wp->w_old_topfill; @@ -1044,7 +1042,7 @@ static void win_update(win_T *wp, Providers *providers) * needs updating. */ - /* try to find wp->w_topline in wp->w_lines[].wl_lnum */ + // try to find wp->w_topline in wp->w_lines[].wl_lnum j = -1; row = 0; for (i = 0; i < wp->w_lines_valid; i++) { @@ -1071,7 +1069,7 @@ static void win_update(win_T *wp, Providers *providers) } else { row += diff_check_fill(wp, wp->w_topline); } - /* ... but don't delete new filler lines. */ + // ... but don't delete new filler lines. row -= wp->w_topfill; if (row > 0) { win_scroll_lines(wp, 0, -row); @@ -1097,7 +1095,7 @@ static void win_update(win_T *wp, Providers *providers) } bot_start += wp->w_lines[idx++].wl_size; - /* stop at the last valid entry in w_lines[].wl_size */ + // stop at the last valid entry in w_lines[].wl_size if (++j >= wp->w_lines_valid) { wp->w_lines_valid = idx; break; @@ -1119,19 +1117,19 @@ static void win_update(win_T *wp, Providers *providers) mid_end = wp->w_grid.Rows; } } else { - /* Not VALID or INVERTED: redraw all lines. */ + // Not VALID or INVERTED: redraw all lines. mid_start = 0; mid_end = wp->w_grid.Rows; } if (type == SOME_VALID) { - /* SOME_VALID: redraw all lines. */ + // SOME_VALID: redraw all lines. mid_start = 0; mid_end = wp->w_grid.Rows; type = NOT_VALID; } - /* check if we are updating or removing the inverted part */ + // check if we are updating or removing the inverted part if ((VIsual_active && buf == curwin->w_buffer) || (wp->w_old_cursor_lnum != 0 && type != NOT_VALID)) { linenr_T from, to; @@ -1148,7 +1146,7 @@ static void win_update(win_T *wp, Providers *providers) from = VIsual.lnum; to = curwin->w_cursor.lnum; } - /* redraw more when the cursor moved as well */ + // redraw more when the cursor moved as well if (wp->w_old_cursor_lnum < from) { from = wp->w_old_cursor_lnum; } @@ -1173,7 +1171,7 @@ static void win_update(win_T *wp, Providers *providers) } else { from = wp->w_old_cursor_lnum; to = curwin->w_cursor.lnum; - if (from == 0) { /* Visual mode just started */ + if (from == 0) { // Visual mode just started from = to; } } @@ -1231,7 +1229,7 @@ static void win_update(win_T *wp, Providers *providers) wp->w_old_cursor_lcol = toc; } } else { - /* Use the line numbers of the old Visual area. */ + // Use the line numbers of the old Visual area. if (wp->w_old_cursor_lnum < wp->w_old_visual_lnum) { from = wp->w_old_cursor_lnum; to = wp->w_old_visual_lnum; @@ -1279,7 +1277,7 @@ static void win_update(win_T *wp, Providers *providers) } else { mid_start = 0; } - while (lnum < from && idx < wp->w_lines_valid) { /* find start */ + while (lnum < from && idx < wp->w_lines_valid) { // find start if (wp->w_lines[idx].wl_valid) { mid_start += wp->w_lines[idx].wl_size; } else if (!scrolled_down) { @@ -1297,7 +1295,7 @@ static void win_update(win_T *wp, Providers *providers) for (; idx < wp->w_lines_valid; idx++) { // find end if (wp->w_lines[idx].wl_valid && wp->w_lines[idx].wl_lnum >= to + 1) { - /* Only update until first row of this line */ + // Only update until first row of this line mid_end = srow; break; } @@ -1319,7 +1317,7 @@ static void win_update(win_T *wp, Providers *providers) wp->w_old_visual_col = 0; } - /* reset got_int, otherwise regexp won't work */ + // reset got_int, otherwise regexp won't work save_got_int = got_int; got_int = 0; // Set the time limit to 'redrawtime'. @@ -1329,7 +1327,7 @@ static void win_update(win_T *wp, Providers *providers) /* * Update all the window rows. */ - idx = 0; /* first entry in w_lines[].wl_size */ + idx = 0; // first entry in w_lines[].wl_size row = 0; srow = 0; lnum = wp->w_topline; // first line shown in window @@ -1369,7 +1367,7 @@ static void win_update(win_T *wp, Providers *providers) break; } - /* stop updating when hit the end of the file */ + // stop updating when hit the end of the file if (lnum > buf->b_ml.ml_line_count) { eof = true; break; @@ -1509,15 +1507,15 @@ static void win_update(win_T *wp, Providers *providers) if (j < i) { int x = row + new_rows; - /* move entries in w_lines[] upwards */ + // move entries in w_lines[] upwards for (;; ) { - /* stop at last valid entry in w_lines[] */ + // stop at last valid entry in w_lines[] if (i >= wp->w_lines_valid) { wp->w_lines_valid = j; break; } wp->w_lines[j] = wp->w_lines[i]; - /* stop at a line that won't fit */ + // stop at a line that won't fit if (x + (int)wp->w_lines[j].wl_size > wp->w_grid.Rows) { wp->w_lines_valid = j + 1; @@ -1529,8 +1527,8 @@ static void win_update(win_T *wp, Providers *providers) if (bot_start > x) { bot_start = x; } - } else { /* j > i */ - /* move entries in w_lines[] downwards */ + } else { // j > i + // move entries in w_lines[] downwards j -= i; wp->w_lines_valid += j; if (wp->w_lines_valid > wp->w_grid.Rows) { @@ -1572,7 +1570,7 @@ static void win_update(win_T *wp, Providers *providers) row = wp->w_grid.Rows + 1; } else { prepare_search_hl(wp, lnum); - /* Let the syntax stuff know we skipped a few lines. */ + // Let the syntax stuff know we skipped a few lines. if (syntax_last_parsed != 0 && syntax_last_parsed + 1 < lnum && syntax_present(wp)) { syntax_end_parsing(syntax_last_parsed + 1); @@ -1695,17 +1693,11 @@ static void win_update(win_T *wp, Providers *providers) wp->w_botline = buf->b_ml.ml_line_count + 1; j = diff_check_fill(wp, wp->w_botline); if (j > 0 && !wp->w_botfill) { - // display filler lines at the end of the file - if (char2cells(wp->w_p_fcs_chars.diff) > 1) { - i = '-'; - } else { - i = wp->w_p_fcs_chars.diff; - } - if (row + j > wp->w_grid.Rows) { - j = wp->w_grid.Rows - row; - } - win_draw_end(wp, i, i, true, row, row + (int)j, HLF_DED); - row += j; + // Display filler text below last line. win_line() will check + // for ml_line_count+1 and only draw filler lines + foldinfo_T info = FOLDINFO_INIT; + row = win_line(wp, wp->w_botline, row, wp->w_grid.Rows, + false, false, info, &line_providers); } } else if (dollar_vcol == -1) { wp->w_botline = lnum; @@ -1724,7 +1716,7 @@ static void win_update(win_T *wp, Providers *providers) } syn_set_timeout(NULL); - /* Reset the type of redrawing required, the window has been updated. */ + // Reset the type of redrawing required, the window has been updated. wp->w_redr_type = 0; wp->w_old_topfill = wp->w_topfill; wp->w_old_botfill = wp->w_botfill; @@ -1745,56 +1737,23 @@ static void win_update(win_T *wp, Providers *providers) wp->w_valid |= VALID_BOTLINE; wp->w_viewport_invalid = true; if (wp == curwin && wp->w_botline != old_botline && !recursive) { - const linenr_T old_topline = wp->w_topline; - const int new_wcol = wp->w_wcol; recursive = true; curwin->w_valid &= ~VALID_TOPLINE; update_topline(curwin); // may invalidate w_botline again - - if (old_wcol != new_wcol - && (wp->w_valid & (VALID_WCOL|VALID_WROW)) - != (VALID_WCOL|VALID_WROW)) { - // A win_line() call applied a fix to screen cursor column to - // accommodate concealment of cursor line, but in this call to - // update_topline() the cursor's row or column got invalidated. - // If they are left invalid, setcursor() will recompute them - // but there won't be any further win_line() call to re-fix the - // column and the cursor will end up misplaced. So we call - // cursor validation now and reapply the fix again (or call - // win_line() to do it for us). - validate_cursor(); - if (wp->w_wcol == old_wcol - && wp->w_wrow == old_wrow - && old_topline == wp->w_topline) { - wp->w_wcol = new_wcol; - } else { - redrawWinline(wp, wp->w_cursor.lnum); - } - } - // New redraw either due to updated topline or due to wcol fix. - if (wp->w_redr_type != 0) { + if (must_redraw != 0) { // Don't update for changes in buffer again. i = curbuf->b_mod_set; curbuf->b_mod_set = false; - j = curbuf->b_mod_xlines; - curbuf->b_mod_xlines = 0; win_update(curwin, providers); + must_redraw = 0; curbuf->b_mod_set = i; - curbuf->b_mod_xlines = j; - } - // Other windows might have w_redr_type raised in update_topline(). - must_redraw = 0; - FOR_ALL_WINDOWS_IN_TAB(wwp, curtab) { - if (wwp->w_redr_type > must_redraw) { - must_redraw = wwp->w_redr_type; - } } recursive = false; } } - /* restore got_int, unless CTRL-C was hit while redrawing */ + // restore got_int, unless CTRL-C was hit while redrawing if (!got_int) { got_int = save_got_int; } @@ -2040,16 +1999,16 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc long vcol = 0; // virtual column (for tabs) long vcol_sbr = -1; // virtual column after showbreak long vcol_prev = -1; // "vcol" of previous character - char_u *line; // current line - char_u *ptr; // current position in "line" + char_u *line; // current line + char_u *ptr; // current position in "line" int row; // row in the window, excl w_winrow ScreenGrid *grid = &wp->w_grid; // grid specific to the window char_u extra[57]; // sign, line number and 'fdc' must // fit in here int n_extra = 0; // number of extra chars - char_u *p_extra = NULL; // string of extra chars, plus NUL - char_u *p_extra_free = NULL; // p_extra needs to be freed + char_u *p_extra = NULL; // string of extra chars, plus NUL + char_u *p_extra_free = NULL; // p_extra needs to be freed int c_extra = NUL; // extra chars, all the same int c_final = NUL; // final char, mandatory if set int extra_attr = 0; // attributes when n_extra != 0 @@ -2062,17 +2021,17 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc // saved "extra" items for when draw_state becomes WL_LINE (again) int saved_n_extra = 0; - char_u *saved_p_extra = NULL; + char_u *saved_p_extra = NULL; int saved_c_extra = 0; int saved_c_final = 0; int saved_char_attr = 0; - int n_attr = 0; /* chars with special attr */ - int saved_attr2 = 0; /* char_attr saved for n_attr */ - int n_attr3 = 0; /* chars with overruling special attr */ - int saved_attr3 = 0; /* char_attr saved for n_attr3 */ + int n_attr = 0; // chars with special attr + int saved_attr2 = 0; // char_attr saved for n_attr + int n_attr3 = 0; // chars with overruling special attr + int saved_attr3 = 0; // char_attr saved for n_attr3 - int n_skip = 0; /* nr of chars to skip for 'nowrap' */ + int n_skip = 0; // nr of chars to skip for 'nowrap' int fromcol = -10; // start of inverting int tocol = MAXCOL; // end of inverting @@ -2082,29 +2041,29 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc pos_T pos; long v; - int char_attr = 0; /* attributes for next character */ - int attr_pri = FALSE; /* char_attr has priority */ + int char_attr = 0; // attributes for next character + int attr_pri = FALSE; // char_attr has priority int area_highlighting = FALSE; /* Visual or incsearch highlighting in this line */ - int attr = 0; /* attributes for area highlighting */ - int area_attr = 0; /* attributes desired by highlighting */ - int search_attr = 0; /* attributes desired by 'hlsearch' */ - int vcol_save_attr = 0; /* saved attr for 'cursorcolumn' */ - int syntax_attr = 0; /* attributes desired by syntax */ - int has_syntax = FALSE; /* this buffer has syntax highl. */ + int attr = 0; // attributes for area highlighting + int area_attr = 0; // attributes desired by highlighting + int search_attr = 0; // attributes desired by 'hlsearch' + int vcol_save_attr = 0; // saved attr for 'cursorcolumn' + int syntax_attr = 0; // attributes desired by syntax + int has_syntax = FALSE; // this buffer has syntax highl. int save_did_emsg; int eol_hl_off = 0; // 1 if highlighted char after EOL bool draw_color_col = false; // highlight colorcolumn int *color_cols = NULL; // pointer to according columns array bool has_spell = false; // this buffer has spell checking # define SPWORDLEN 150 - char_u nextline[SPWORDLEN * 2]; /* text with start of the next line */ - int nextlinecol = 0; /* column where nextline[] starts */ + char_u nextline[SPWORDLEN * 2]; // text with start of the next line + int nextlinecol = 0; // column where nextline[] starts int nextline_idx = 0; /* index in nextline[] where next line starts */ - int spell_attr = 0; /* attributes desired by spelling */ - int word_end = 0; /* last byte with same spell_attr */ - static linenr_T checked_lnum = 0; /* line number for "checked_col" */ + int spell_attr = 0; // attributes desired by spelling + int word_end = 0; // last byte with same spell_attr + static linenr_T checked_lnum = 0; // line number for "checked_col" static int checked_col = 0; /* column in "checked_lnum" up to which * there are no spell errors */ static int cap_col = -1; // column to check for Cap word @@ -2131,7 +2090,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc int line_attr_lowprio = 0; // low-priority attribute for the line int line_attr_lowprio_save; matchitem_T *cur; // points to the match list - match_T *shl; // points to search_hl or a match + match_T *shl; // points to search_hl or a match bool shl_flag; // flag to indicate whether search_hl // has been processed or not bool prevcol_hl_flag; // flag to indicate whether prevcol @@ -2156,16 +2115,16 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc int left_curline_col = 0; int right_curline_col = 0; - /* draw_state: items that are drawn in sequence: */ -#define WL_START 0 /* nothing done yet */ -# define WL_CMDLINE WL_START + 1 /* cmdline window column */ -# define WL_FOLD WL_CMDLINE + 1 /* 'foldcolumn' */ -# define WL_SIGN WL_FOLD + 1 /* column for signs */ -#define WL_NR WL_SIGN + 1 /* line number */ -# define WL_BRI WL_NR + 1 /* 'breakindent' */ -# define WL_SBR WL_BRI + 1 /* 'showbreak' or 'diff' */ -#define WL_LINE WL_SBR + 1 /* text in the line */ - int draw_state = WL_START; /* what to draw next */ + // draw_state: items that are drawn in sequence: +#define WL_START 0 // nothing done yet +# define WL_CMDLINE WL_START + 1 // cmdline window column +# define WL_FOLD WL_CMDLINE + 1 // 'foldcolumn' +# define WL_SIGN WL_FOLD + 1 // column for signs +#define WL_NR WL_SIGN + 1 // line number +# define WL_BRI WL_NR + 1 // 'breakindent' +# define WL_SBR WL_BRI + 1 // 'showbreak' or 'diff' +#define WL_LINE WL_SBR + 1 // text in the line + int draw_state = WL_START; // what to draw next int syntax_flags = 0; int syntax_seqnr = 0; @@ -2189,13 +2148,14 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc boguscols = 0; \ } - if (startrow > endrow) { /* past the end already! */ + if (startrow > endrow) { // past the end already! return startrow; } row = startrow; buf_T *buf = wp->w_buffer; + bool end_fill = (lnum == buf->b_ml.ml_line_count+1); if (!number_only) { // To speed up the loop below, set extra_check when there is linebreak, @@ -2263,6 +2223,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc if (wp->w_p_spell && !has_fold + && !end_fill && *wp->w_s->b_p_spl != NUL && !GA_EMPTY(&wp->w_s->b_langp) && *(char **)(wp->w_s->b_langp.ga_data) != NULL) { @@ -2392,14 +2353,14 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc if (filler_lines < 0) { if (filler_lines == -1) { if (diff_find_change(wp, lnum, &change_start, &change_end)) { - diff_hlf = HLF_ADD; /* added line */ + diff_hlf = HLF_ADD; // added line } else if (change_start == 0) { - diff_hlf = HLF_TXD; /* changed text */ + diff_hlf = HLF_TXD; // changed text } else { - diff_hlf = HLF_CHD; /* changed line */ + diff_hlf = HLF_CHD; // changed line } } else { - diff_hlf = HLF_ADD; /* added line */ + diff_hlf = HLF_ADD; // added line } filler_lines = 0; area_highlighting = TRUE; @@ -2466,7 +2427,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc line_attr_lowprio_save = line_attr_lowprio; } - line = ml_get_buf(wp->w_buffer, lnum, false); + line = end_fill ? (char_u *)"" : ml_get_buf(wp->w_buffer, lnum, false); ptr = line; if (has_spell && !number_only) { @@ -2479,7 +2440,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc * current line into nextline[]. Above the start of the next line was * copied to nextline[SPWORDLEN]. */ if (nextline[SPWORDLEN] == NUL) { - /* No next line or it is empty. */ + // No next line or it is empty. nextlinecol = MAXCOL; nextline_idx = 0; } else { @@ -2492,7 +2453,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc STRMOVE(nextline + v, nextline + SPWORDLEN); nextline_idx = v + 1; } else { - /* Long line, use only the last SPWORDLEN bytes. */ + // Long line, use only the last SPWORDLEN bytes. nextlinecol = v - SPWORDLEN; memmove(nextline, line + nextlinecol, SPWORDLEN); // -V512 nextline_idx = SPWORDLEN + 1; @@ -2500,7 +2461,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc } } - if (wp->w_p_list && !has_fold) { + if (wp->w_p_list && !has_fold && !end_fill) { if (wp->w_p_lcs_chars.space || wp->w_p_lcs_chars.trail || wp->w_p_lcs_chars.lead @@ -2541,7 +2502,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc v = wp->w_leftcol; } if (v > 0 && !number_only) { - char_u *prev_ptr = ptr; + char_u *prev_ptr = ptr; while (vcol < v && *ptr != NUL) { c = win_lbr_chartabsize(wp, line, ptr, (colnr_T)vcol, NULL); vcol += c; @@ -2610,11 +2571,11 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc spell_hlf = HLF_COUNT; word_end = (int)(spell_to_word_end(ptr, wp) - line + 1); } else { - /* bad word found, use attributes until end of word */ + // bad word found, use attributes until end of word assert(len <= INT_MAX); word_end = wp->w_cursor.col + (int)len + 1; - /* Turn index into actual attributes. */ + // Turn index into actual attributes. if (spell_hlf != HLF_COUNT) { spell_attr = highlight_attr[spell_hlf]; } @@ -2640,7 +2601,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc fromcol_prev = fromcol; fromcol = -1; } else if ((colnr_T)fromcol < wp->w_virtcol) { - /* restart highlighting after the cursor */ + // restart highlighting after the cursor fromcol_prev = wp->w_virtcol; } } @@ -2656,7 +2617,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc cur = wp->w_match_head; shl_flag = false; while ((cur != NULL || !shl_flag) && !number_only - && !has_fold) { + && !has_fold && !end_fill) { if (!shl_flag) { shl = &search_hl; shl_flag = true; @@ -2748,7 +2709,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc if (draw_state == WL_CMDLINE - 1 && n_extra == 0) { draw_state = WL_CMDLINE; if (cmdwin_type != 0 && wp == curwin) { - /* Draw the cmdline character. */ + // Draw the cmdline character. n_extra = 1; c_extra = cmdwin_type; c_final = NUL; @@ -2889,7 +2850,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc } if (wp->w_briopt_sbr && draw_state == WL_BRI - 1 - && n_extra == 0 && *p_sbr != NUL) { + && n_extra == 0 && *get_showbreak_value(wp) != NUL) { // draw indent after showbreak value draw_state = WL_BRI; } else if (wp->w_briopt_sbr && draw_state == WL_SBR && n_extra == 0) { @@ -2948,19 +2909,20 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc } char_attr = win_hl_attr(wp, HLF_DED); } - if (*p_sbr != NUL && need_showbreak) { - /* Draw 'showbreak' at the start of each broken line. */ - p_extra = p_sbr; + char_u *const sbr = get_showbreak_value(wp); + if (*sbr != NUL && need_showbreak) { + // Draw 'showbreak' at the start of each broken line. + p_extra = sbr; c_extra = NUL; c_final = NUL; - n_extra = (int)STRLEN(p_sbr); + n_extra = (int)STRLEN(sbr); char_attr = win_hl_attr(wp, HLF_AT); if (wp->w_skipcol == 0 || !wp->w_p_wrap) { need_showbreak = false; } - vcol_sbr = vcol + MB_CHARLEN(p_sbr); - /* Correct end of highlighted area for 'showbreak', - * required when 'linebreak' is also set. */ + vcol_sbr = vcol + MB_CHARLEN(sbr); + // Correct end of highlighted area for 'showbreak', + // required when 'linebreak' is also set. if (tocol == vcol) { tocol += n_extra; } @@ -2981,7 +2943,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc } if (saved_n_extra) { - /* Continue item from end of wrapped line. */ + // Continue item from end of wrapped line. n_extra = saved_n_extra; c_extra = saved_c_extra; c_final = saved_c_final; @@ -3539,7 +3501,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc checked_col = (int)((p - nextline) + len - nextline_idx); } - /* Turn index into actual attributes. */ + // Turn index into actual attributes. if (spell_hlf != HLF_COUNT) { spell_attr = highlight_attr[spell_hlf]; } @@ -3553,7 +3515,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc cap_col = (int)((p - nextline) + cap_col - nextline_idx); } else { - /* Compute the actual column. */ + // Compute the actual column. cap_col += (int)(prev_ptr - line); } } @@ -3592,6 +3554,16 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc char_u *p = ptr - (mb_off + 1); // TODO: is passing p for start of the line OK? n_extra = win_lbr_chartabsize(wp, line, p, (colnr_T)vcol, NULL) - 1; + + // We have just drawn the showbreak value, no need to add + // space for it again. + if (vcol == vcol_sbr) { + n_extra -= MB_CHARLEN(get_showbreak_value(wp)); + if (n_extra < 0) { + n_extra = 0; + } + } + if (c == TAB && n_extra + col > grid->Columns) { n_extra = tabstop_padding(vcol, wp->w_buffer->b_p_ts, wp->w_buffer->b_p_vts_array) - 1; @@ -3600,7 +3572,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc c_final = NUL; if (ascii_iswhite(c)) { if (c == TAB) { - /* See "Tab alignment" below. */ + // See "Tab alignment" below. FIX_FOR_BOGUSCOLS; } if (!wp->w_p_list) { @@ -3658,10 +3630,12 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc if (c == TAB && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) { int tab_len = 0; long vcol_adjusted = vcol; // removed showbreak length + char_u *const sbr = get_showbreak_value(wp); + // Only adjust the tab_len, when at the first column after the // showbreak value was drawn. - if (*p_sbr != NUL && vcol == vcol_sbr && wp->w_p_wrap) { - vcol_adjusted = vcol - MB_CHARLEN(p_sbr); + if (*sbr != NUL && vcol == vcol_sbr && wp->w_p_wrap) { + vcol_adjusted = vcol - MB_CHARLEN(sbr); } // tab amount depends on current column tab_len = tabstop_padding(vcol_adjusted, @@ -3749,7 +3723,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc ? wp->w_p_lcs_chars.tab3 : wp->w_p_lcs_chars.tab1; if (wp->w_p_lbr) { - c_extra = NUL; /* using p_extra from above */ + c_extra = NUL; // using p_extra from above } else { c_extra = wp->w_p_lcs_chars.tab2; } @@ -3818,7 +3792,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc n_extra = byte2cells(c) - 1; } if ((dy_flags & DY_UHEX) && wp->w_p_rl) { - rl_mirror(p_extra); /* reverse "<12>" */ + rl_mirror(p_extra); // reverse "<12>" } c_extra = NUL; c_final = NUL; @@ -4068,7 +4042,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc v = wp->w_leftcol; } - /* check if line ends before left margin */ + // check if line ends before left margin if (vcol < v + col - win_col_off(wp)) { vcol = v + col - win_col_off(wp); } @@ -4290,7 +4264,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc tocol++; } if (wp->w_p_rl) { - /* now it's time to backup one cell */ + // now it's time to backup one cell --off; --col; } @@ -4376,12 +4350,12 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc char_attr = vcol_save_attr; } - /* restore attributes after "predeces" in 'listchars' */ + // restore attributes after "predeces" in 'listchars' if (draw_state > WL_NR && n_attr3 > 0 && --n_attr3 == 0) { char_attr = saved_attr3; } - /* restore attributes after last 'listchars' or 'number' char */ + // restore attributes after last 'listchars' or 'number' char if (n_attr > 0 && draw_state == WL_LINE && --n_attr == 0) { char_attr = saved_attr2; } @@ -4439,7 +4413,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc row = endrow; } - /* When line got too long for screen break here. */ + // When line got too long for screen break here. if (row == endrow) { ++row; break; @@ -4452,7 +4426,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc off += col; } - /* reset the drawing state for the start of a wrapped line */ + // reset the drawing state for the start of a wrapped line draw_state = WL_START; saved_n_extra = n_extra; saved_p_extra = p_extra; @@ -4467,13 +4441,13 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc filler_todo--; // When the filler lines are actually below the last line of the // file, don't draw the line itself, break here. - if (filler_todo == 0 && wp->w_botfill) { + if (filler_todo == 0 && (wp->w_botfill || end_fill)) { break; } } - } /* for every character in the line */ + } // for every character in the line - /* After an empty line check first word for capital. */ + // After an empty line check first word for capital. if (*skipwhite(line) == NUL) { capcol_lnum = lnum + 1; cap_col = 0; @@ -4711,7 +4685,7 @@ static void grid_put_linebuf(ScreenGrid *grid, int row, int coloff, int endcol, max_off_to = grid->line_offset[row] + grid->Columns; if (rlflag) { - /* Clear rest first, because it's left of the text. */ + // Clear rest first, because it's left of the text. if (clear_width > 0) { while (col <= endcol && grid->chars[off_to][0] == ' ' && grid->chars[off_to][1] == NUL @@ -4841,7 +4815,7 @@ static void grid_put_linebuf(ScreenGrid *grid, int row, int coloff, int endcol, */ void rl_mirror(char_u *str) { - char_u *p1, *p2; + char_u *p1, *p2; int t; for (p1 = str, p2 = str + STRLEN(str) - 1; p1 < p2; ++p1, --p2) { @@ -4945,7 +4919,7 @@ static int status_match_len(expand_T *xp, char_u *s) int emenu = (xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES); - /* Check for menu separators - replace with '|'. */ + // Check for menu separators - replace with '|'. if (emenu && menu_is_separator(s)) { return 1; } @@ -4980,54 +4954,54 @@ static int skip_status_match_char(expand_T *xp, char_u *s) return 0; } -/* - * Show wildchar matches in the status line. - * Show at least the "match" item. - * We start at item 'first_match' in the list and show all matches that fit. - * - * If inversion is possible we use it. Else '=' characters are used. - */ -void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, /* list of matches */ - int match, int showtail) +/// Show wildchar matches in the status line. +/// Show at least the "match" item. +/// We start at item 'first_match' in the list and show all matches that fit. +/// +/// If inversion is possible we use it. Else '=' characters are used. +/// +/// @param matches list of matches +void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, int match, + int showtail) { #define L_MATCH(m) (showtail ? sm_gettail(matches[m], false) : matches[m]) int row; - char_u *buf; + char_u *buf; int len; - int clen; /* length in screen cells */ + int clen; // length in screen cells int fillchar; int attr; int i; bool highlight = true; - char_u *selstart = NULL; + char_u *selstart = NULL; int selstart_col = 0; - char_u *selend = NULL; + char_u *selend = NULL; static int first_match = 0; bool add_left = false; - char_u *s; + char_u *s; int emenu; int l; - if (matches == NULL) { /* interrupted completion? */ + if (matches == NULL) { // interrupted completion? return; } buf = xmalloc(Columns * MB_MAXBYTES + 1); - if (match == -1) { /* don't show match but original text */ + if (match == -1) { // don't show match but original text match = 0; highlight = false; } - /* count 1 for the ending ">" */ + // count 1 for the ending ">" clen = status_match_len(xp, L_MATCH(match)) + 3; if (match == 0) { first_match = 0; } else if (match < first_match) { - /* jumping left, as far as we can go */ + // jumping left, as far as we can go first_match = match; add_left = true; } else { - /* check if match fits on the screen */ + // check if match fits on the screen for (i = first_match; i < match; ++i) { clen += status_match_len(xp, L_MATCH(i)) + 2; } @@ -5037,7 +5011,7 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, // jumping right, put match at the left if ((long)clen > Columns) { first_match = match; - /* if showing the last match, we can add some on the left */ + // if showing the last match, we can add some on the left clen = 2; for (i = match; i < num_matches; ++i) { clen += status_match_len(xp, L_MATCH(i)) + 2; @@ -5079,7 +5053,7 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, } s = L_MATCH(i); - /* Check for menu separators - replace with '|' */ + // Check for menu separators - replace with '|' emenu = (xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES); if (emenu && menu_is_separator(s)) { @@ -5174,7 +5148,7 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, static void win_redr_status(win_T *wp) { int row; - char_u *p; + char_u *p; int len; int fillchar; int attr; @@ -5199,7 +5173,7 @@ static void win_redr_status(win_T *wp) // popup menu is visible and may be drawn over it wp->w_redr_status = true; } else if (*p_stl != NUL || *wp->w_p_stl != NUL) { - /* redraw custom status line */ + // redraw custom status line redraw_custom_statusline(wp); } else { fillchar = fillchar_status(&attr, wp); @@ -5322,7 +5296,7 @@ static void redraw_custom_statusline(win_T *wp) /// line of the window right of it. If not, then it's a vertical separator. bool stl_connected(win_T *wp) { - frame_T *fr; + frame_T *fr; fr = wp->w_frame; while (fr->fr_parent != NULL) { @@ -5348,20 +5322,20 @@ bool stl_connected(win_T *wp) /// @param len length of buffer bool get_keymap_str(win_T *wp, char_u *fmt, char_u *buf, int len) { - char_u *p; + char_u *p; if (wp->w_buffer->b_p_iminsert != B_IMODE_LMAP) { return false; } { - buf_T *old_curbuf = curbuf; - win_T *old_curwin = curwin; - char_u *s; + buf_T *old_curbuf = curbuf; + win_T *old_curwin = curwin; + char_u *s; curbuf = wp->w_buffer; curwin = wp; - STRCPY(buf, "b:keymap_name"); /* must be writable */ + STRCPY(buf, "b:keymap_name"); // must be writable ++emsg_skip; s = p = eval_to_string(buf, NULL, FALSE); --emsg_skip; @@ -5399,12 +5373,12 @@ static void win_redr_custom(win_T *wp, bool draw_ruler) int len; int fillchar; char_u buf[MAXPATHL]; - char_u *stl; - char_u *p; + char_u *stl; + char_u *p; stl_hlrec_t *hltab; StlClickRecord *tabtab; int use_sandbox = false; - win_T *ewp; + win_T *ewp; int p_crb_save; ScreenGrid *grid = &default_grid; @@ -5417,9 +5391,9 @@ static void win_redr_custom(win_T *wp, bool draw_ruler) } entered = true; - /* setup environment for the task at hand */ + // setup environment for the task at hand if (wp == NULL) { - /* Use 'tabline'. Always at the first line of the screen. */ + // Use 'tabline'. Always at the first line of the screen. stl = p_tal; row = 0; fillchar = ' '; @@ -5433,7 +5407,7 @@ static void win_redr_custom(win_T *wp, bool draw_ruler) if (draw_ruler) { stl = p_ruf; - /* advance past any leading group spec - implicit in ru_col */ + // advance past any leading group spec - implicit in ru_col if (*stl == '%') { if (*++stl == '-') { stl++; @@ -5499,7 +5473,7 @@ static void win_redr_custom(win_T *wp, bool draw_ruler) len = (size_t)len < sizeof(buf) ? len : (int)sizeof(buf) - 1; xfree(p); - /* fill up with "fillchar" */ + // fill up with "fillchar" while (width < maxwidth && len < (int)sizeof(buf) - 1) { len += utf_char2bytes(fillchar, buf + len); width++; @@ -5773,7 +5747,7 @@ void grid_put_schar(ScreenGrid *grid, int row, int col, char_u *schar, int attr) void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col, int attr) { unsigned off; - char_u *ptr = text; + char_u *ptr = text; int len = textlen; int c; unsigned max_off; @@ -5782,7 +5756,7 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col int u8c = 0; int u8cc[MAX_MCO]; int clear_next_cell = FALSE; - int prev_c = 0; /* previous Arabic character */ + int prev_c = 0; // previous Arabic character int pc, nc, nc1; int pcc[MAX_MCO]; int need_redraw; @@ -6001,7 +5975,7 @@ static void prepare_search_hl(win_T *wp, linenr_T lnum) FUNC_ATTR_NONNULL_ALL { matchitem_T *cur; // points to the match list - match_T *shl; // points to search_hl or a match + match_T *shl; // points to search_hl or a match bool shl_flag; // flag to indicate whether search_hl // has been processed or not @@ -6057,18 +6031,18 @@ static void prepare_search_hl(win_T *wp, linenr_T lnum) } } -/* - * Search for a next 'hlsearch' or match. - * Uses shl->buf. - * Sets shl->lnum and shl->rm contents. - * Note: Assumes a previous match is always before "lnum", unless - * shl->lnum is zero. - * Careful: Any pointers for buffer lines will become invalid. - */ -static void next_search_hl(win_T *win, match_T *shl, /* points to search_hl or a match */ - linenr_T lnum, colnr_T mincol, /* minimal column for a match */ - matchitem_T *cur /* to retrieve match positions if any */ - ) +/// Search for a next 'hlsearch' or match. +/// Uses shl->buf. +/// Sets shl->lnum and shl->rm contents. +/// Note: Assumes a previous match is always before "lnum", unless +/// shl->lnum is zero. +/// Careful: Any pointers for buffer lines will become invalid. +/// +/// @param shl points to search_hl or a match +/// @param mincol minimal column for a match +/// @param cur to retrieve match positions if any +static void next_search_hl(win_T *win, match_T *shl, linenr_T lnum, colnr_T mincol, + matchitem_T *cur) FUNC_ATTR_NONNULL_ARG(2) { linenr_T l; @@ -6103,7 +6077,7 @@ static void next_search_hl(win_T *win, match_T *shl, /* points to for (;; ) { // Stop searching after passing the time limit. if (profile_passed_limit(shl->tm)) { - shl->lnum = 0; /* no match found in time */ + shl->lnum = 0; // no match found in time break; } // Three situations: @@ -6116,7 +6090,7 @@ static void next_search_hl(win_T *win, match_T *shl, /* points to } else if (vim_strchr(p_cpo, CPO_SEARCH) == NULL || (shl->rm.endpos[0].lnum == 0 && shl->rm.endpos[0].col <= shl->rm.startpos[0].col)) { - char_u *ml; + char_u *ml; matchcol = shl->rm.startpos[0].col; ml = ml_get_buf(shl->buf, lnum, false) + matchcol; @@ -6178,12 +6152,12 @@ static void next_search_hl(win_T *win, match_T *shl, /* points to } } -/// If there is a match fill "shl" and return one. -/// Return zero otherwise. -static int next_search_hl_pos(match_T *shl, // points to a match - linenr_T lnum, posmatch_T *posmatch, // match positions - colnr_T mincol // minimal column for a match - ) +/// @param shl points to a match. Fill on match. +/// @param posmatch match positions +/// @param mincol minimal column for a match +/// +/// @return one on match, otherwise return zero. +static int next_search_hl_pos(match_T *shl, linenr_T lnum, posmatch_T *posmatch, colnr_T mincol) FUNC_ATTR_NONNULL_ALL { int i; @@ -6476,9 +6450,9 @@ retry: msg_grid_invalid = true; } - win_new_shellsize(); /* fit the windows in the new sized shell */ + win_new_shellsize(); // fit the windows in the new sized shell - comp_col(); /* recompute columns for shown command and ruler */ + comp_col(); // recompute columns for shown command and ruler // We're changing the size of the screen. // - Allocate new arrays for default_grid @@ -6902,16 +6876,16 @@ int showmode(void) bool nwr_save = need_wait_return; - /* wait a bit before overwriting an important message */ + // wait a bit before overwriting an important message check_for_delay(FALSE); - /* if the cmdline is more than one line high, erase top lines */ + // if the cmdline is more than one line high, erase top lines need_clear = clear_cmdline; if (clear_cmdline && cmdline_row < Rows - 1) { msg_clr_cmdline(); // will reset clear_cmdline } - /* Position on the last line in the window, column 0 */ + // Position on the last line in the window, column 0 msg_pos_mode(); attr = HL_ATTR(HLF_CM); // Highlight mode @@ -6999,12 +6973,18 @@ int showmode(void) switch ((VIsual_select ? 4 : 0) + (VIsual_mode == Ctrl_V) * 2 + (VIsual_mode == 'V')) { - case 0: p = N_(" VISUAL"); break; - case 1: p = N_(" VISUAL LINE"); break; - case 2: p = N_(" VISUAL BLOCK"); break; - case 4: p = N_(" SELECT"); break; - case 5: p = N_(" SELECT LINE"); break; - default: p = N_(" SELECT BLOCK"); break; + case 0: + p = N_(" VISUAL"); break; + case 1: + p = N_(" VISUAL LINE"); break; + case 2: + p = N_(" VISUAL BLOCK"); break; + case 4: + p = N_(" SELECT"); break; + case 5: + p = N_(" SELECT LINE"); break; + default: + p = N_(" SELECT BLOCK"); break; } MSG_PUTS_ATTR(_(p), attr); } @@ -7038,7 +7018,7 @@ int showmode(void) // NB: also handles clearing the showmode if it was empty or disabled msg_ext_flush_showmode(); - /* In Visual mode the size of the selected area must be redrawn. */ + // In Visual mode the size of the selected area must be redrawn. if (VIsual_active) { clear_showcmd(); } @@ -7115,15 +7095,15 @@ void draw_tabline(void) int col = 0; int scol = 0; int attr; - win_T *wp; - win_T *cwp; + win_T *wp; + win_T *cwp; int wincount; int modified; int c; int len; int attr_nosel = HL_ATTR(HLF_TP); int attr_fill = HL_ATTR(HLF_TPF); - char_u *p; + char_u *p; int room; int use_sep_chars = (t_colors < 8 ); @@ -7147,7 +7127,7 @@ void draw_tabline(void) assert(Columns == tab_page_click_defs_size); clear_tab_page_click_defs(tab_page_click_defs, tab_page_click_defs_size); - /* Use the 'tabline' option if it's set. */ + // Use the 'tabline' option if it's set. if (*p_tal != NUL) { int saved_did_emsg = did_emsg; @@ -7233,7 +7213,7 @@ void draw_tabline(void) room = scol - col + tabwidth - 1; if (room > 0) { - /* Get buffer name in NameBuff[] */ + // Get buffer name in NameBuff[] get_trans_bufname(cwp->w_buffer); (void)shorten_dir(NameBuff); len = vim_strsize(NameBuff); @@ -7270,7 +7250,7 @@ void draw_tabline(void) } grid_fill(&default_grid, 0, 1, col, Columns, c, c, attr_fill); - /* Put an "X" for closing the current tab if there are several. */ + // Put an "X" for closing the current tab if there are several. if (first_tabpage->tp_next != NULL) { grid_putchar(&default_grid, 'X', 0, Columns - 1, attr_nosel); tab_page_click_defs[Columns - 1] = (StlClickDefinition) { @@ -7407,7 +7387,7 @@ void showruler(bool always) || (p_title && (stl_syntax & STL_IN_TITLE))) { maketitle(); } - /* Redraw the tab pages line if needed. */ + // Redraw the tab pages line if needed. if (redraw_tabline) { draw_tabline(); } @@ -7685,12 +7665,12 @@ void screen_resize(int width, int height) return; } - if (width < 0 || height < 0) { /* just checking... */ + if (width < 0 || height < 0) { // just checking... return; } if (State == HITRETURN || State == SETWSIZE) { - /* postpone the resizing */ + // postpone the resizing State = SETWSIZE; return; } diff --git a/src/nvim/search.c b/src/nvim/search.c index b0ee41b245..4be2402f1d 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -7,13 +7,11 @@ #include <assert.h> #include <inttypes.h> +#include <limits.h> // for INT_MAX on MSVC #include <stdbool.h> #include <string.h> -#include <limits.h> /* for INT_MAX on MSVC */ #include "nvim/ascii.h" -#include "nvim/vim.h" -#include "nvim/search.h" #include "nvim/buffer.h" #include "nvim/charset.h" #include "nvim/cursor.h" @@ -34,17 +32,19 @@ #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/move.h" #include "nvim/mouse.h" +#include "nvim/move.h" #include "nvim/normal.h" #include "nvim/option.h" +#include "nvim/os/time.h" #include "nvim/path.h" #include "nvim/regexp.h" #include "nvim/screen.h" +#include "nvim/search.h" #include "nvim/strings.h" #include "nvim/ui.h" +#include "nvim/vim.h" #include "nvim/window.h" -#include "nvim/os/time.h" #ifdef INCLUDE_GENERATED_DECLARATIONS # include "search.c.generated.h" @@ -79,12 +79,12 @@ static struct spat spats[2] = { // Last used search pattern - [0] = {NULL, true, false, 0, {'/', false, false, 0L}, NULL}, + [0] = { NULL, true, false, 0, { '/', false, false, 0L }, NULL }, // Last used substitute pattern - [1] = {NULL, true, false, 0, {'/', false, false, 0L}, NULL} + [1] = { NULL, true, false, 0, { '/', false, false, 0L }, NULL } }; -static int last_idx = 0; /* index in spats[] for RE_LAST */ +static int last_idx = 0; // index in spats[] for RE_LAST static char_u lastc[2] = { NUL, NUL }; // last character searched for static Direction lastcdir = FORWARD; // last direction of character search @@ -97,7 +97,7 @@ static struct spat saved_spats[2]; static int saved_spats_last_idx = 0; static bool saved_spats_no_hlsearch = false; -static char_u *mr_pattern = NULL; // pattern used by search_regcomp() +static char_u *mr_pattern = NULL; // pattern used by search_regcomp() static bool mr_pattern_alloced = false; // mr_pattern was allocated /* @@ -105,34 +105,27 @@ static bool mr_pattern_alloced = false; // mr_pattern was allocated * been searched already. */ typedef struct SearchedFile { - FILE *fp; /* File pointer */ - char_u *name; /* Full name of file */ - linenr_T lnum; /* Line we were up to in file */ - int matched; /* Found a match in this file */ + FILE *fp; // File pointer + char_u *name; // Full name of file + linenr_T lnum; // Line we were up to in file + int matched; // Found a match in this file } SearchedFile; -/* - * translate search pattern for vim_regcomp() - * - * pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd) - * pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command) - * pat_save == RE_BOTH: save pat in both patterns (:global command) - * pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL - * pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL - * pat_use == RE_LAST: use last used pattern if "pat" is NULL - * options & SEARCH_HIS: put search string in history - * options & SEARCH_KEEP: keep previous search pattern - * - * returns FAIL if failed, OK otherwise. - */ -int -search_regcomp( - char_u *pat, - int pat_save, - int pat_use, - int options, - regmmatch_T *regmatch /* return: pattern and ignore-case flag */ -) +/// translate search pattern for vim_regcomp() +/// +/// pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd) +/// pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command) +/// pat_save == RE_BOTH: save pat in both patterns (:global command) +/// pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL +/// pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL +/// pat_use == RE_LAST: use last used pattern if "pat" is NULL +/// options & SEARCH_HIS: put search string in history +/// options & SEARCH_KEEP: keep previous search pattern +/// +/// @param regmatch return: pattern and ignore-case flag +/// +/// @return FAIL if failed, OK otherwise. +int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatch_T *regmatch) { int magic; int i; @@ -144,15 +137,17 @@ search_regcomp( * If no pattern given, use a previously defined pattern. */ if (pat == NULL || *pat == NUL) { - if (pat_use == RE_LAST) + if (pat_use == RE_LAST) { i = last_idx; - else + } else { i = pat_use; - if (spats[i].pat == NULL) { /* pattern was never defined */ - if (pat_use == RE_SUBST) + } + if (spats[i].pat == NULL) { // pattern was never defined + if (pat_use == RE_SUBST) { EMSG(_(e_nopresub)); - else + } else { EMSG(_(e_noprevre)); + } rc_did_emsg = true; return FAIL; } @@ -180,19 +175,22 @@ search_regcomp( * unless the pattern should not be remembered. */ if (!(options & SEARCH_KEEP) && !cmdmod.keeppatterns) { - /* search or global command */ - if (pat_save == RE_SEARCH || pat_save == RE_BOTH) + // search or global command + if (pat_save == RE_SEARCH || pat_save == RE_BOTH) { save_re_pat(RE_SEARCH, pat, magic); - /* substitute or global command */ - if (pat_save == RE_SUBST || pat_save == RE_BOTH) + } + // substitute or global command + if (pat_save == RE_SUBST || pat_save == RE_BOTH) { save_re_pat(RE_SUBST, pat, magic); + } } regmatch->rmm_ic = ignorecase(pat); regmatch->rmm_maxcol = 0; regmatch->regprog = vim_regcomp(pat, magic ? RE_MAGIC : 0); - if (regmatch->regprog == NULL) + if (regmatch->regprog == NULL) { return FAIL; + } return OK; } @@ -239,9 +237,10 @@ void save_re_pat(int idx, char_u *pat, int magic) spats[idx].timestamp = os_time(); spats[idx].additional_data = NULL; last_idx = idx; - /* If 'hlsearch' set and search pat changed: need redraw. */ - if (p_hls) + // If 'hlsearch' set and search pat changed: need redraw. + if (p_hls) { redraw_all_later(SOME_VALID); + } set_no_hlsearch(false); } } @@ -256,11 +255,13 @@ void save_search_patterns(void) { if (save_level++ == 0) { saved_spats[0] = spats[0]; - if (spats[0].pat != NULL) + if (spats[0].pat != NULL) { saved_spats[0].pat = vim_strsave(spats[0].pat); + } saved_spats[1] = spats[1]; - if (spats[1].pat != NULL) + if (spats[1].pat != NULL) { saved_spats[1].pat = vim_strsave(spats[1].pat); + } saved_spats_last_idx = last_idx; saved_spats_no_hlsearch = no_hlsearch; } @@ -369,8 +370,8 @@ int ignorecase_opt(char_u *pat, int ic_in, int scs) { int ic = ic_in; if (ic && !no_smartcase && scs - && !(ctrl_x_mode_not_default() && curbuf->b_p_inf) - ) { + && !(ctrl_x_mode_not_default() && + curbuf->b_p_inf)) { ic = !pat_has_uppercase(pat); } no_smartcase = false; @@ -431,10 +432,11 @@ void set_last_csearch(int c, char_u *s, int len) { *lastc = c; lastc_bytelen = len; - if (len) + if (len) { memcpy(lastc_bytes, s, len); - else + } else { memset(lastc_bytes, 0, sizeof(lastc_bytes)); + } } void set_csearch_direction(Direction cdir) @@ -468,11 +470,12 @@ void reset_search_dir(void) void set_last_search_pat(const char_u *s, int idx, int magic, int setlast) { free_spat(&spats[idx]); - /* An empty string means that nothing should be matched. */ - if (*s == NUL) + // An empty string means that nothing should be matched. + if (*s == NUL) { spats[idx].pat = NULL; - else - spats[idx].pat = (char_u *) xstrdup((char *) s); + } else { + spats[idx].pat = (char_u *)xstrdup((char *)s); + } spats[idx].timestamp = os_time(); spats[idx].additional_data = NULL; spats[idx].magic = magic; @@ -482,20 +485,23 @@ void set_last_search_pat(const char_u *s, int idx, int magic, int setlast) spats[idx].off.line = FALSE; spats[idx].off.end = FALSE; spats[idx].off.off = 0; - if (setlast) + if (setlast) { last_idx = idx; + } if (save_level) { free_spat(&saved_spats[idx]); saved_spats[idx] = spats[0]; - if (spats[idx].pat == NULL) + if (spats[idx].pat == NULL) { saved_spats[idx].pat = NULL; - else + } else { saved_spats[idx].pat = vim_strsave(spats[idx].pat); + } saved_spats_last_idx = last_idx; } - /* If 'hlsearch' set and search pat changed: need redraw. */ - if (p_hls && idx == last_idx && !no_hlsearch) + // If 'hlsearch' set and search pat changed: need redraw. + if (p_hls && idx == last_idx && !no_hlsearch) { redraw_all_later(SOME_VALID); + } } /* @@ -509,7 +515,7 @@ void last_pat_prog(regmmatch_T *regmatch) regmatch->regprog = NULL; return; } - ++emsg_off; /* So it doesn't beep if bad expr */ + ++emsg_off; // So it doesn't beep if bad expr (void)search_regcomp((char_u *)"", 0, last_idx, SEARCH_KEEP, regmatch); --emsg_off; } @@ -529,27 +535,21 @@ void last_pat_prog(regmmatch_T *regmatch) /// if (options & SEARCH_PEEK) check for typed char, cancel search /// if (options & SEARCH_COL) start at pos->col instead of zero /// -/// @returns FAIL (zero) for failure, non-zero for success. -/// the index of the first matching -/// subpattern plus one; one if there was none. -int searchit( - win_T *win, // window to search in; can be NULL for a - // buffer without a window! - buf_T *buf, - pos_T *pos, - pos_T *end_pos, // set to end of the match, unless NULL - Direction dir, - char_u *pat, - long count, - int options, - int pat_use, // which pattern to use when "pat" is empty - searchit_arg_T *extra_arg // optional extra arguments, can be NULL -) +/// @param win window to search in; can be NULL for a buffer without a window! +/// @param end_pos set to end of the match, unless NULL +/// @param pat_use which pattern to use when "pat" is empty +/// @param extra_arg optional extra arguments, can be NULL +/// +/// @returns FAIL (zero) for failure, non-zero for success. +/// the index of the first matching +/// subpattern plus one; one if there was none. +int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, char_u *pat, + long count, int options, int pat_use, searchit_arg_T *extra_arg) { int found; - linenr_T lnum; /* no init to shut up Apollo cc */ + linenr_T lnum; // no init to shut up Apollo cc regmmatch_T regmatch; - char_u *ptr; + char_u *ptr; colnr_T matchcol; lpos_T endpos; lpos_T matchpos; @@ -569,15 +569,16 @@ int searchit( int *timed_out = NULL; // set when timed out or NULL if (extra_arg != NULL) { - stop_lnum = extra_arg->sa_stop_lnum; - tm = extra_arg->sa_tm; - timed_out = &extra_arg->sa_timed_out; + stop_lnum = extra_arg->sa_stop_lnum; + tm = extra_arg->sa_tm; + timed_out = &extra_arg->sa_timed_out; } if (search_regcomp(pat, RE_SEARCH, pat_use, - (options & (SEARCH_HIS + SEARCH_KEEP)), ®match) == FAIL) { - if ((options & SEARCH_MSG) && !rc_did_emsg) + (options & (SEARCH_HIS + SEARCH_KEEP)), ®match) == FAIL) { + if ((options & SEARCH_MSG) && !rc_did_emsg) { EMSG2(_("E383: Invalid search string: %s"), mr_pattern); + } return FAIL; } @@ -585,7 +586,7 @@ int searchit( * find the string */ called_emsg = FALSE; - do { /* loop for count */ + 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 // is zero. @@ -610,13 +611,13 @@ int searchit( extra_col = (options & SEARCH_START) ? start_char_len : 0; } - start_pos = *pos; /* remember start pos for detecting no match */ - found = 0; /* default: not found */ - at_first_line = TRUE; /* default: start in first line */ - if (pos->lnum == 0) { /* correct lnum for when starting in line 0 */ + start_pos = *pos; // remember start pos for detecting no match + found = 0; // default: not found + at_first_line = TRUE; // default: start in first line + if (pos->lnum == 0) { // correct lnum for when starting in line 0 pos->lnum = 1; pos->col = 0; - at_first_line = FALSE; /* not in first line now */ + at_first_line = FALSE; // not in first line now } /* @@ -630,19 +631,22 @@ int searchit( && (options & SEARCH_START) == 0) { lnum = pos->lnum - 1; at_first_line = FALSE; - } else + } else { lnum = pos->lnum; + } - for (loop = 0; loop <= 1; ++loop) { /* loop twice if 'wrapscan' set */ + for (loop = 0; loop <= 1; ++loop) { // loop twice if 'wrapscan' set for (; lnum > 0 && lnum <= buf->b_ml.ml_line_count; lnum += dir, at_first_line = FALSE) { - /* Stop after checking "stop_lnum", if it's set. */ + // Stop after checking "stop_lnum", if it's set. if (stop_lnum != 0 && (dir == FORWARD - ? lnum > stop_lnum : lnum < stop_lnum)) + ? lnum > stop_lnum : lnum < stop_lnum)) { break; - /* Stop after passing the "tm" time limit. */ - if (tm != NULL && profile_passed_limit(*tm)) + } + // Stop after passing the "tm" time limit. + if (tm != NULL && profile_passed_limit(*tm)) { break; + } // Look for a match somewhere in line "lnum". colnr_T col = at_first_line && (options & SEARCH_COL) ? pos->col : 0; @@ -657,7 +661,7 @@ int searchit( break; } if (nmatched > 0) { - /* match may actually be in another line when using \zs */ + // match may actually be in another line when using \zs matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; submatch = first_submatch(®match); @@ -740,8 +744,9 @@ int searchit( // have made it invalid. ptr = ml_get_buf(buf, lnum, false); } - if (!match_ok) + if (!match_ok) { continue; + } } if (dir == BACKWARD) { /* @@ -775,8 +780,9 @@ int searchit( matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; submatch = first_submatch(®match); - } else + } else { break; + } // We found a valid match, now check if there is // another one after it. @@ -804,16 +810,16 @@ int searchit( } } if (ptr[matchcol] == NUL - || (nmatched = vim_regexec_multi( - ®match, win, buf, lnum + matchpos.lnum, matchcol, - tm, timed_out)) == 0) { - // If the search timed out, we did find a match - // but it might be the wrong one, so that's not - // OK. - if (tm != NULL && profile_passed_limit(*tm)) { - match_ok = false; - } - break; + || (nmatched = + vim_regexec_multi(®match, win, buf, lnum + matchpos.lnum, matchcol, + tm, timed_out)) == 0) { + // If the search timed out, we did find a match + // but it might be the wrong one, so that's not + // OK. + if (tm != NULL && profile_passed_limit(*tm)) { + match_ok = false; + } + break; } // vim_regexec_multi() may clear "regprog" if (regmatch.regprog == NULL) { @@ -828,8 +834,9 @@ int searchit( * If there is only a match after the cursor, skip * this match. */ - if (!match_ok) + if (!match_ok) { continue; + } } /* With the SEARCH_END option move to the last character @@ -873,14 +880,15 @@ int searchit( found = 1; first_match = false; - /* Set variables used for 'incsearch' highlighting. */ + // Set variables used for 'incsearch' highlighting. search_match_lines = endpos.lnum - matchpos.lnum; search_match_endcol = endpos.col; break; } - line_breakcheck(); /* stop if ctrl-C typed */ - if (got_int) + line_breakcheck(); // stop if ctrl-C typed + if (got_int) { break; + } /* Cancel searching if a character was typed. Used for * 'incsearch'. Don't check too often, that would slowdown @@ -892,8 +900,9 @@ int searchit( break; } - if (loop && lnum == start_pos.lnum) - break; /* if second loop, stop where started */ + if (loop && lnum == start_pos.lnum) { + break; // if second loop, stop where started + } } at_first_line = FALSE; @@ -933,8 +942,7 @@ int searchit( } if (got_int || called_emsg || (timed_out != NULL && *timed_out) - || break_loop - ) { + || break_loop) { break; } } while (--count > 0 && found); // stop after count matches or no match @@ -943,23 +951,24 @@ int searchit( called_emsg |= save_called_emsg; - if (!found) { /* did not find it */ - if (got_int) + if (!found) { // did not find it + if (got_int) { EMSG(_(e_interr)); - else if ((options & SEARCH_MSG) == SEARCH_MSG) { - if (p_ws) + } else if ((options & SEARCH_MSG) == SEARCH_MSG) { + if (p_ws) { EMSG2(_(e_patnotf2), mr_pattern); - else if (lnum == 0) + } else if (lnum == 0) { EMSG2(_("E384: search hit TOP without match for: %s"), - mr_pattern); - else + mr_pattern); + } else { EMSG2(_("E385: search hit BOTTOM without match for: %s"), - mr_pattern); + mr_pattern); + } } return FAIL; } - /* A pattern like "\n\zs" may go past the last line. */ + // A pattern like "\n\zs" may go past the last line. if (pos->lnum > buf->b_ml.ml_line_count) { pos->lnum = buf->b_ml.ml_line_count; pos->col = (int)STRLEN(ml_get_buf(buf, pos->lnum, false)); @@ -988,8 +997,9 @@ static int first_submatch(regmmatch_T *rp) int submatch; for (submatch = 1;; ++submatch) { - if (rp->startpos[submatch].lnum >= 0) + if (rp->startpos[submatch].lnum >= 0) { break; + } if (submatch == 9) { submatch = 0; break; @@ -998,47 +1008,44 @@ static int first_submatch(regmmatch_T *rp) return submatch; } -/* - * Highest level string search function. - * Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc' - * If 'dirc' is 0: use previous dir. - * If 'pat' is NULL or empty : use previous string. - * If 'options & SEARCH_REV' : go in reverse of previous dir. - * If 'options & SEARCH_ECHO': echo the search command and handle options - * If 'options & SEARCH_MSG' : may give error message - * If 'options & SEARCH_OPT' : interpret optional flags - * If 'options & SEARCH_HIS' : put search pattern in history - * If 'options & SEARCH_NOOF': don't add offset to position - * If 'options & SEARCH_MARK': set previous context mark - * If 'options & SEARCH_KEEP': keep previous search pattern - * If 'options & SEARCH_START': accept match at curpos itself - * If 'options & SEARCH_PEEK': check for typed char, cancel search - * - * Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this - * makes the movement linewise without moving the match position. - * - * Return 0 for failure, 1 for found, 2 for found and line offset added. - */ -int do_search( - oparg_T *oap, // can be NULL - int dirc, // '/' or '?' - int search_delim, // delimiter for search, e.g. '%' in s%regex%replacement - char_u *pat, - long count, - int options, - searchit_arg_T *sia // optional arguments or NULL -) +/// Highest level string search function. +/// Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc' +/// +/// Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this +/// makes the movement linewise without moving the match position. +/// +/// @param dirc if 0: use previous dir. +/// @param pat NULL or empty : use previous string. +/// @param options if TRUE and +/// SEARCH_REV == TRUE : go in reverse of previous dir. +/// SEARCH_ECHO == TRUE : echo the search command and handle options +/// SEARCH_MSG == TRUE : may give error message +/// SEARCH_OPT == TRUE : interpret optional flags +/// SEARCH_HIS == TRUE : put search pattern in history +/// SEARCH_NOOF == TRUE : don't add offset to position +/// SEARCH_MARK == TRUE : set previous context mark +/// SEARCH_KEEP == TRUE : keep previous search pattern +/// SEARCH_START == TRUE : accept match at curpos itself +/// SEARCH_PEEK == TRUE : check for typed char, cancel search +/// @param oap can be NULL +/// @param dirc '/' or '?' +/// @param search_delim delimiter for search, e.g. '%' in s%regex%replacement +/// @param sia optional arguments or NULL +/// +/// @return 0 for failure, 1 for found, 2 for found and line offset added. +int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count, int options, + searchit_arg_T *sia) { - pos_T pos; /* position of the last match */ - char_u *searchstr; + pos_T pos; // position of the last match + char_u *searchstr; struct soffset old_off; - int retval; /* Return value */ - char_u *p; + int retval; // Return value + char_u *p; long c; - char_u *dircp; - char_u *strcopy = NULL; - char_u *ps; - char_u *msgbuf = NULL; + char_u *dircp; + char_u *strcopy = NULL; + char_u *ps; + char_u *msgbuf = NULL; size_t len; bool has_offset = false; @@ -1056,32 +1063,35 @@ int do_search( */ old_off = spats[0].off; - pos = curwin->w_cursor; /* start searching at the cursor position */ + pos = curwin->w_cursor; // start searching at the cursor position /* * Find out the direction of the search. */ - if (dirc == 0) + if (dirc == 0) { dirc = spats[0].off.dir; - else { + } else { spats[0].off.dir = dirc; set_vv_searchforward(); } if (options & SEARCH_REV) { - if (dirc == '/') + if (dirc == '/') { dirc = '?'; - else + } else { dirc = '/'; + } } /* If the cursor is in a closed fold, don't find another match in the same * fold. */ if (dirc == '/') { - if (hasFolding(pos.lnum, NULL, &pos.lnum)) - pos.col = MAXCOL - 2; /* avoid overflow when adding 1 */ + if (hasFolding(pos.lnum, NULL, &pos.lnum)) { + pos.col = MAXCOL - 2; // avoid overflow when adding 1 + } } else { - if (hasFolding(pos.lnum, &pos.lnum, NULL)) + if (hasFolding(pos.lnum, &pos.lnum, NULL)) { pos.col = 0; + } } /* @@ -1110,12 +1120,12 @@ int do_search( goto end_do_search; } } else { - /* make search_regcomp() use spats[RE_SEARCH].pat */ + // make search_regcomp() use spats[RE_SEARCH].pat searchstr = (char_u *)""; } } - if (pat != NULL && *pat != NUL) { /* look for (new) offset */ + if (pat != NULL && *pat != NUL) { // look for (new) offset /* * Find end of regular expression. * If there is a matching '/' or '?', toss it. @@ -1123,7 +1133,7 @@ int do_search( ps = strcopy; p = skip_regexp(pat, search_delim, p_magic, &strcopy); if (strcopy != ps) { - /* made a copy of "pat" to change "\?" to "?" */ + // made a copy of "pat" to change "\?" to "?" searchcmdlen += (int)(STRLEN(pat) - STRLEN(strcopy)); pat = strcopy; searchstr = strcopy; @@ -1148,28 +1158,30 @@ int do_search( } p++; } - if (ascii_isdigit(*p) || *p == '+' || *p == '-') { /* got an offset */ - /* 'nr' or '+nr' or '-nr' */ - if (ascii_isdigit(*p) || ascii_isdigit(*(p + 1))) + if (ascii_isdigit(*p) || *p == '+' || *p == '-') { // got an offset + // 'nr' or '+nr' or '-nr' + if (ascii_isdigit(*p) || ascii_isdigit(*(p + 1))) { spats[0].off.off = atol((char *)p); - else if (*p == '-') /* single '-' */ + } else if (*p == '-') { // single '-' spats[0].off.off = -1; - else /* single '+' */ + } else { // single '+' spats[0].off.off = 1; + } ++p; - while (ascii_isdigit(*p)) /* skip number */ + while (ascii_isdigit(*p)) { // skip number ++p; + } } - /* compute length of search command for get_address() */ + // compute length of search command for get_address() searchcmdlen += (int)(p - pat); - pat = p; /* put pat after search command */ + pat = p; // put pat after search command } if ((options & SEARCH_ECHO) && messaging() && !msg_silent && (!cmd_silent || !shortmess(SHM_SEARCHCOUNT))) { - char_u *trunc; + char_u *trunc; char_u off_buf[40]; size_t off_len = 0; @@ -1291,18 +1303,22 @@ int do_search( */ 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) - if (decl(&pos) == -1) + for (c = spats[0].off.off; c; --c) { + if (decl(&pos) == -1) { break; - if (c) { /* at start of buffer */ - pos.lnum = 0; /* allow lnum == 0 here */ + } + } + if (c) { // at start of buffer + pos.lnum = 0; // allow lnum == 0 here pos.col = MAXCOL; } } else { - for (c = spats[0].off.off; c; ++c) - if (incl(&pos) == -1) + for (c = spats[0].off.off; c; ++c) { + if (incl(&pos) == -1) { break; - if (c) { /* at end of buffer */ + } + } + if (c) { // at end of buffer pos.lnum = curbuf->b_ml.ml_line_count + 1; pos.col = 0; } @@ -1332,10 +1348,10 @@ int do_search( retval = 0; goto end_do_search; } - if (spats[0].off.end && oap != NULL) - oap->inclusive = true; /* 'e' includes last character */ - - retval = 1; /* pattern found */ + if (spats[0].off.end && oap != NULL) { + oap->inclusive = true; // 'e' includes last character + } + retval = 1; // pattern found /* * Add character and/or line offset @@ -1345,28 +1361,33 @@ int do_search( if (spats[0].off.line) { // Add the offset to the line number. c = pos.lnum + spats[0].off.off; - if (c < 1) + if (c < 1) { pos.lnum = 1; - else if (c > curbuf->b_ml.ml_line_count) + } else if (c > curbuf->b_ml.ml_line_count) { pos.lnum = curbuf->b_ml.ml_line_count; - else + } else { pos.lnum = c; + } pos.col = 0; - retval = 2; /* pattern found, line offset added */ - } else if (pos.col < MAXCOL - 2) { /* just in case */ - /* to the right, check for end of file */ + retval = 2; // pattern found, line offset added + } else if (pos.col < MAXCOL - 2) { // just in case + // to the right, check for end of file c = spats[0].off.off; if (c > 0) { - while (c-- > 0) - if (incl(&pos) == -1) + while (c-- > 0) { + if (incl(&pos) == -1) { break; + } + } } - /* to the left, check for start of file */ + // to the left, check for start of file else { - while (c++ < 0) - if (decl(&pos) == -1) + while (c++ < 0) { + if (decl(&pos) == -1) { break; + } + } } } if (!equalpos(pos, org_pos)) { @@ -1411,14 +1432,16 @@ int do_search( ++pat; } - if (options & SEARCH_MARK) + if (options & SEARCH_MARK) { setpcmark(); + } curwin->w_cursor = pos; curwin->w_set_curswant = TRUE; end_do_search: - if ((options & SEARCH_KEEP) || cmdmod.keeppatterns) + if ((options & SEARCH_KEEP) || cmdmod.keeppatterns) { spats[0].off = old_off; + } xfree(msgbuf); return retval; @@ -1436,18 +1459,20 @@ end_do_search: int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) { linenr_T start = 0; - char_u *ptr; - char_u *p; + char_u *ptr; + char_u *p; - if (buf->b_ml.ml_line_count == 0) + if (buf->b_ml.ml_line_count == 0) { return FAIL; + } for (;; ) { pos->lnum += dir; if (pos->lnum < 1) { if (p_ws) { pos->lnum = buf->b_ml.ml_line_count; - if (!shortmess(SHM_SEARCH)) + if (!shortmess(SHM_SEARCH)) { give_warning((char_u *)_(top_bot_msg), true); + } } else { pos->lnum = 1; break; @@ -1455,20 +1480,23 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) } else if (pos->lnum > buf->b_ml.ml_line_count) { if (p_ws) { pos->lnum = 1; - if (!shortmess(SHM_SEARCH)) + if (!shortmess(SHM_SEARCH)) { give_warning((char_u *)_(bot_top_msg), true); + } } else { pos->lnum = 1; break; } } - if (pos->lnum == start) + if (pos->lnum == start) { break; - if (start == 0) + } + if (start == 0) { start = pos->lnum; + } ptr = ml_get_buf(buf, pos->lnum, false); p = skipwhite(ptr); - pos->col = (colnr_T) (p - ptr); + pos->col = (colnr_T)(p - ptr); /* when adding lines the matching line may be empty but it is not * ignored because we are interested in the next line -- Acevedo */ @@ -1481,8 +1509,9 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat) // Expanding lines or words. assert(compl_length >= 0); if ((p_ic ? mb_strnicmp(p, pat, (size_t)compl_length) - : STRNCMP(p, pat, compl_length)) == 0) + : STRNCMP(p, pat, compl_length)) == 0) { return OK; + } } } return FAIL; @@ -1505,12 +1534,12 @@ int searchc(cmdarg_T *cap, int t_cmd) int dir = cap->arg; // true for searching forward long count = cap->count1; // repeat count int col; - char_u *p; + char_u *p; int len; bool stop = true; - if (c != NUL) { /* normal search: remember args for repeat */ - if (!KeyStuffed) { /* don't remember when redoing */ + if (c != NUL) { // normal search: remember args for repeat + if (!KeyStuffed) { // don't remember when redoing *lastc = c; set_csearch_direction(dir); set_csearch_until(t_cmd); @@ -1535,7 +1564,7 @@ int searchc(cmdarg_T *cap, int t_cmd) } t_cmd = last_t_cmd; c = *lastc; - /* For multi-byte re-use last lastc_bytes[] and lastc_bytelen. */ + // For multi-byte re-use last lastc_bytes[] and lastc_bytelen. /* Force a move of at least one char, so ";" and "," will move the * cursor, even if the cursor is right in front of char we are looking @@ -1545,10 +1574,11 @@ int searchc(cmdarg_T *cap, int t_cmd) } } - if (dir == BACKWARD) + if (dir == BACKWARD) { cap->oap->inclusive = false; - else + } else { cap->oap->inclusive = true; + } p = get_cursor_line_ptr(); col = curwin->w_cursor.col; @@ -1667,8 +1697,7 @@ static bool find_rawstring_end(char_u *linep, pos_T *startpos, pos_T *endpos) /// If there is a match set "*initc" to the matching character and "*findc" to /// the opposite character. Set "*backwards" to the direction. /// When "switchit" is true swap the direction. -static void find_mps_values(int *initc, int *findc, bool *backwards, - bool switchit) +static void find_mps_values(int *initc, int *findc, bool *backwards, bool switchit) FUNC_ATTR_NONNULL_ALL { char_u *ptr = curbuf->b_p_mps; @@ -1734,7 +1763,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) bool backwards = false; // init for gcc bool raw_string = false; // search for raw string bool inquote = false; // true when inside quotes - char_u *ptr; + char_u *ptr; int hash_dir = 0; // Direction searched for # things int comment_dir = 0; // Direction searched for comments int traveled = 0; // how far we've searched so far @@ -1754,13 +1783,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) // don't recognize backslashes bool cpo_bsl = (vim_strchr(p_cpo, CPO_MATCHBSL) != NULL); - /* Direction to search when initc is '/', '*' or '#' */ - if (flags & FM_BACKWARD) + // Direction to search when initc is '/', '*' or '#' + if (flags & FM_BACKWARD) { dir = BACKWARD; - else if (flags & FM_FORWARD) + } else if (flags & FM_FORWARD) { dir = FORWARD; - else + } else { dir = 0; + } /* * if initc given, look in the table for the matching character @@ -1770,8 +1800,9 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) */ if (initc == '/' || initc == '*' || initc == 'R') { comment_dir = dir; - if (initc == '/') + if (initc == '/') { ignore_cend = true; + } backwards = (dir == FORWARD) ? false : true; raw_string = (initc == 'R'); initc = NUL; @@ -1794,16 +1825,17 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * Only check for special things when 'cpo' doesn't have '%'. */ if (!cpo_match) { - /* Are we before or at #if, #else etc.? */ + // Are we before or at #if, #else etc.? ptr = skipwhite(linep); if (*ptr == '#' && pos.col <= (colnr_T)(ptr - linep)) { ptr = skipwhite(ptr + 1); - if ( STRNCMP(ptr, "if", 2) == 0 - || STRNCMP(ptr, "endif", 5) == 0 - || STRNCMP(ptr, "el", 2) == 0) + if (STRNCMP(ptr, "if", 2) == 0 + || STRNCMP(ptr, "endif", 5) == 0 + || STRNCMP(ptr, "el", 2) == 0) { hash_dir = 1; + } } - /* Are we on a comment? */ + // Are we on a comment? else if (linep[pos.col] == '/') { if (linep[pos.col + 1] == '*') { comment_dir = FORWARD; @@ -1835,12 +1867,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * If beyond the end of the line, use the last character in * the line. */ - if (linep[pos.col] == NUL && pos.col) + if (linep[pos.col] == NUL && pos.col) { --pos.col; + } for (;; ) { initc = PTR2CHAR(linep + pos.col); - if (initc == NUL) + if (initc == NUL) { break; + } find_mps_values(&initc, &findc, &backwards, false); if (findc) { @@ -1849,18 +1883,20 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos.col += utfc_ptr2len(linep + pos.col); } if (!findc) { - /* no brace in the line, maybe use " #if" then */ - if (!cpo_match && *skipwhite(linep) == '#') + // no brace in the line, maybe use " #if" then + if (!cpo_match && *skipwhite(linep) == '#') { hash_dir = 1; - else + } else { return NULL; + } } else if (!cpo_bsl) { int col, bslcnt = 0; /* Set "match_escaped" if there are an odd number of * backslashes. */ - for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) + for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) { bslcnt++; + } match_escaped = (bslcnt & 1); } } @@ -1874,49 +1910,58 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } if (initc != '#') { ptr = skipwhite(skipwhite(linep) + 1); - if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0) + if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0) { hash_dir = 1; - else if (STRNCMP(ptr, "endif", 5) == 0) + } else if (STRNCMP(ptr, "endif", 5) == 0) { hash_dir = -1; - else + } else { return NULL; + } } pos.col = 0; while (!got_int) { if (hash_dir > 0) { - if (pos.lnum == curbuf->b_ml.ml_line_count) + if (pos.lnum == curbuf->b_ml.ml_line_count) { break; - } else if (pos.lnum == 1) + } + } else if (pos.lnum == 1) { break; + } pos.lnum += hash_dir; linep = ml_get(pos.lnum); - line_breakcheck(); /* check for CTRL-C typed */ + line_breakcheck(); // check for CTRL-C typed ptr = skipwhite(linep); - if (*ptr != '#') + if (*ptr != '#') { continue; - pos.col = (colnr_T) (ptr - linep); + } + pos.col = (colnr_T)(ptr - linep); ptr = skipwhite(ptr + 1); if (hash_dir > 0) { - if (STRNCMP(ptr, "if", 2) == 0) + if (STRNCMP(ptr, "if", 2) == 0) { count++; - else if (STRNCMP(ptr, "el", 2) == 0) { - if (count == 0) + } else if (STRNCMP(ptr, "el", 2) == 0) { + if (count == 0) { return &pos; + } } else if (STRNCMP(ptr, "endif", 5) == 0) { - if (count == 0) + if (count == 0) { return &pos; + } count--; } } else { if (STRNCMP(ptr, "if", 2) == 0) { - if (count == 0) + if (count == 0) { return &pos; + } count--; } else if (initc == '#' && STRNCMP(ptr, "el", 2) == 0) { - if (count == 0) + if (count == 0) { return &pos; - } else if (STRNCMP(ptr, "endif", 5) == 0) + } + } else if (STRNCMP(ptr, "endif", 5) == 0) { count++; + } } } return NULL; @@ -1935,11 +1980,11 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos_T match_pos; // Where last slash-star was found clearpos(&match_pos); - /* backward search: Check if this line contains a single-line comment */ + // backward search: Check if this line contains a single-line comment if ((backwards && comment_dir) - || lisp - ) + || lisp) { comment_col = check_linecomment(linep); + } if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col) { lispcomm = true; // find match inside this comment } @@ -1949,58 +1994,63 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * 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) + // char to match is inside of comment, don't search outside + if (lispcomm && pos.col < (colnr_T)comment_col) { break; - if (pos.col == 0) { /* at start of line, go to prev. one */ - if (pos.lnum == 1) /* start of file */ + } + if (pos.col == 0) { // at start of line, go to prev. one + if (pos.lnum == 1) { // start of file break; + } --pos.lnum; - if (maxtravel > 0 && ++traveled > maxtravel) + if (maxtravel > 0 && ++traveled > maxtravel) { break; + } linep = ml_get(pos.lnum); - pos.col = (colnr_T)STRLEN(linep); /* pos.col on trailing NUL */ + pos.col = (colnr_T)STRLEN(linep); // pos.col on trailing NUL do_quotes = -1; line_breakcheck(); - /* Check if this line contains a single-line comment */ + // Check if this line contains a single-line comment if (comment_dir - || lisp - ) + || lisp) { comment_col = check_linecomment(linep); - /* skip comment */ - if (lisp && comment_col != MAXCOL) + } + // skip comment + if (lisp && comment_col != MAXCOL) { pos.col = comment_col; + } } else { pos.col--; pos.col -= utf_head_off(linep, linep + pos.col); } - } else { /* forward search */ + } else { // forward search if (linep[pos.col] == NUL - /* at end of line, go to next one */ - /* don't search for match in comment */ + // at end of line, go to next one + // don't search for match in comment || (lisp && comment_col != MAXCOL - && pos.col == (colnr_T)comment_col) - ) { - if (pos.lnum == curbuf->b_ml.ml_line_count /* end of file */ + && pos.col == (colnr_T)comment_col)) { + if (pos.lnum == curbuf->b_ml.ml_line_count // end of file /* line is exhausted and comment with it, * don't search for match in code */ - || lispcomm - ) + || lispcomm) { break; + } ++pos.lnum; - if (maxtravel && traveled++ > maxtravel) + if (maxtravel && traveled++ > maxtravel) { break; + } linep = ml_get(pos.lnum); pos.col = 0; do_quotes = -1; line_breakcheck(); - if (lisp) /* find comment pos in new line */ + if (lisp) { // find comment pos in new line comment_col = check_linecomment(linep); + } } else { pos.col += utfc_ptr2len(linep + pos.col); } @@ -2016,40 +2066,37 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) } if (comment_dir) { - /* Note: comments do not nest, and we ignore quotes in them */ - /* TODO: ignore comment brackets inside strings */ + // Note: comments do not nest, and we ignore quotes in them + // TODO: ignore comment brackets inside strings if (comment_dir == FORWARD) { if (linep[pos.col] == '*' && linep[pos.col + 1] == '/') { pos.col++; return &pos; } - } else { /* Searching backwards */ + } else { // Searching backwards /* * A comment may contain / * or / /, it may also start or end * with / * /. Ignore a / * after / / and after *. */ - if (pos.col == 0) + if (pos.col == 0) { continue; - else if (raw_string) - { + } else if (raw_string) { if (linep[pos.col - 1] == 'R' && linep[pos.col] == '"' - && vim_strchr(linep + pos.col + 1, '(') != NULL) - { + && vim_strchr(linep + pos.col + 1, '(') != NULL) { /* Possible start of raw string. Now that we have the * 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, - count > 0 ? &match_pos : &curwin->w_cursor)) - { + count > 0 ? &match_pos : &curwin->w_cursor)) { count++; match_pos = pos; match_pos.col--; } - linep = ml_get(pos.lnum); /* may have been released */ + linep = ml_get(pos.lnum); // may have been released } - } else if ( linep[pos.col - 1] == '/' + } else if (linep[pos.col - 1] == '/' && linep[pos.col] == '*' && (pos.col == 1 || linep[pos.col - 2] != '*') && (int)pos.col < comment_col) { @@ -2057,15 +2104,16 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) match_pos = pos; match_pos.col--; } else if (linep[pos.col - 1] == '*' && linep[pos.col] == '/') { - if (count > 0) + if (count > 0) { pos = match_pos; - else if (pos.col > 1 && linep[pos.col - 2] == '/' - && (int)pos.col <= comment_col) + } else if (pos.col > 1 && linep[pos.col - 2] == '/' + && (int)pos.col <= comment_col) { pos.col -= 2; - else if (ignore_cend) + } else if (ignore_cend) { continue; - else + } else { return NULL; + } return &pos; } } @@ -2077,24 +2125,27 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) * of quotes are ignored, but only if there is an even number of * quotes in the line. */ - if (cpo_match) + if (cpo_match) { do_quotes = 0; - else if (do_quotes == -1) { + } else if (do_quotes == -1) { /* * 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) + if (ptr == linep + pos.col + backwards) { at_start = (do_quotes & 1); + } if (*ptr == '"' - && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) + && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) { ++do_quotes; - if (*ptr == '\\' && ptr[1] != NUL) + } + if (*ptr == '\\' && ptr[1] != NUL) { ++ptr; + } } - do_quotes &= 1; /* result is 1 with even number of quotes */ + do_quotes &= 1; // result is 1 with even number of quotes /* * If we find an uneven count, check current line and previous @@ -2126,7 +2177,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 */ + // ml_get() only keeps one line, need to get linep again linep = ml_get(pos.lnum); } } @@ -2149,7 +2200,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) const int c = PTR2CHAR(linep + pos.col); switch (c) { case NUL: - /* at end of line without trailing backslash, reset inquote */ + // at end of line without trailing backslash, reset inquote if (pos.col == 0 || linep[pos.col - 1] != '\\') { inquote = false; start_in_quotes = kFalse; @@ -2162,9 +2213,11 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) if (do_quotes) { int col; - for (col = pos.col - 1; col >= 0; --col) - if (linep[col] != '\\') + for (col = pos.col - 1; col >= 0; --col) { + if (linep[col] != '\\') { break; + } + } if ((((int)pos.col - 1 - col) & 1) == 0) { inquote = !inquote; start_in_quotes = kFalse; @@ -2214,8 +2267,9 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) && vim_strchr((char_u *)"(){}[]", c) != NULL && pos.col > 1 && check_prevcol(linep, pos.col, '\\', NULL) - && check_prevcol(linep, pos.col - 1, '#', NULL)) + && check_prevcol(linep, pos.col - 1, '#', NULL)) { break; + } /* Check for match outside of quotes, and inside of * quotes when the start is also inside of quotes. */ @@ -2224,17 +2278,19 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) int col, bslcnt = 0; if (!cpo_bsl) { - for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) + for (col = pos.col; check_prevcol(linep, col, '\\', &col); ) { bslcnt++; + } } /* Only accept a match when 'M' is in 'cpo' or when escaping * is what we expect. */ if (cpo_bsl || (bslcnt & 1) == match_escaped) { - if (c == initc) + if (c == initc) { count++; - else { - if (count == 0) + } else { + if (count == 0) { return &pos; + } count--; } } @@ -2246,7 +2302,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel) pos = match_pos; return &pos; } - return (pos_T *)NULL; /* never found it */ + return (pos_T *)NULL; // never found it } /* @@ -2279,34 +2335,35 @@ static int check_linecomment(const char_u *line) } p++; } - } else + } else { p = NULL; - } else + } + } else { while ((p = vim_strchr(p, '/')) != NULL) { /* accept a double /, unless it's preceded with * and followed by *, * because * / / * is an end and start of a C comment */ - if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*')) + if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*')) { break; + } ++p; } + } - if (p == NULL) + if (p == NULL) { return MAXCOL; + } return (int)(p - line); } -/* - * Move cursor briefly to character matching the one under the cursor. - * Used for Insert mode and "r" command. - * Show the match only if it is visible on the screen. - * If there isn't a match, then beep. - */ -void -showmatch( - int c // char to show match for -) +/// Move cursor briefly to character matching the one under the cursor. +/// Used for Insert mode and "r" command. +/// Show the match only if it is visible on the screen. +/// If there isn't a match, then beep. +/// +/// @param c char to show match for +void showmatch(int c) { - pos_T *lpos, save_cursor; + pos_T *lpos, save_cursor; pos_T mpos; colnr_T vcol; long *so = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so; @@ -2315,15 +2372,16 @@ showmatch( long save_siso; int save_state; colnr_T save_dollar_vcol; - char_u *p; + char_u *p; /* * Only show match for chars in the 'matchpairs' option. */ - /* 'matchpairs' is "x:y,x:y" */ + // 'matchpairs' is "x:y,x:y" for (p = curbuf->b_p_mps; *p != NUL; ++p) { - if (PTR2CHAR(p) == c && (curwin->w_p_rl ^ p_ri)) + if (PTR2CHAR(p) == c && (curwin->w_p_rl ^ p_ri)) { break; + } p += utfc_ptr2len(p) + 1; if (PTR2CHAR(p) == c && !(curwin->w_p_rl ^ p_ri)) { break; @@ -2340,7 +2398,7 @@ showmatch( if ((lpos = findmatch(NULL, NUL)) == NULL) { // no match, so beep vim_beep(BO_MATCH); } else if (lpos->lnum >= curwin->w_topline - && lpos->lnum < curwin->w_botline) { + && lpos->lnum < curwin->w_botline) { if (!curwin->w_p_wrap) { getvcol(curwin, lpos, NULL, &vcol, NULL); } @@ -2405,10 +2463,11 @@ int findsent(Direction dir, long count) bool noskip = false; // do not skip blanks pos = curwin->w_cursor; - if (dir == FORWARD) + if (dir == FORWARD) { func = incl; - else + } else { func = decl; + } while (count--) { const pos_T prev_pos = pos; @@ -2423,8 +2482,8 @@ int findsent(Direction dir, long count) if (dir == FORWARD) { goto found; } - // if on the start of a paragraph or a section and searching forward, - // go to the next line + // if on the start of a paragraph or a section and searching forward, + // go to the next line } else if (dir == FORWARD && pos.col == 0 && startPS(pos.lnum, NUL, false)) { if (pos.lnum == curbuf->b_ml.ml_line_count) { @@ -2447,11 +2506,11 @@ int findsent(Direction dir, long count) if (found_dot) { break; } - if (vim_strchr((char_u *) ".!?", c) != NULL) { + if (vim_strchr((char_u *)".!?", c) != NULL) { found_dot = true; } - if (vim_strchr((char_u *) ")]\"'", c) != NULL - && vim_strchr((char_u *) ".!?)]\"'", gchar_pos(&tpos)) == NULL) { + if (vim_strchr((char_u *)")]\"'", c) != NULL + && vim_strchr((char_u *)".!?)]\"'", gchar_pos(&tpos)) == NULL) { break; } decl(&pos); @@ -2461,41 +2520,47 @@ int findsent(Direction dir, long count) const int startlnum = pos.lnum; const bool cpo_J = vim_strchr(p_cpo, CPO_ENDOFSENT) != NULL; - for (;; ) { /* find end of sentence */ + for (;; ) { // find end of sentence c = gchar_pos(&pos); if (c == NUL || (pos.col == 0 && startPS(pos.lnum, NUL, FALSE))) { - if (dir == BACKWARD && pos.lnum != startlnum) + if (dir == BACKWARD && pos.lnum != startlnum) { ++pos.lnum; + } break; } if (c == '.' || c == '!' || c == '?') { tpos = pos; do - if ((c = inc(&tpos)) == -1) + if ((c = inc(&tpos)) == -1) { break; + } while (vim_strchr((char_u *)")]\"'", c = gchar_pos(&tpos)) != NULL); if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL || (cpo_J && (c == ' ' && inc(&tpos) >= 0 && gchar_pos(&tpos) == ' '))) { pos = tpos; - if (gchar_pos(&pos) == NUL) /* skip NUL at EOL */ + if (gchar_pos(&pos) == NUL) { // skip NUL at EOL inc(&pos); + } break; } } if ((*func)(&pos) == -1) { - if (count) + if (count) { return FAIL; + } noskip = true; break; } } found: - /* skip white space */ - while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t')) - if (incl(&pos) == -1) + // skip white space + while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t')) { + if (incl(&pos) == -1) { break; + } + } if (equalpos(prev_pos, pos)) { // didn't actually move, advance one character and try again @@ -2514,28 +2579,22 @@ found: return OK; } -/* - * Find the next paragraph or section in direction 'dir'. - * Paragraphs are currently supposed to be separated by empty lines. - * If 'what' is NUL we go to the next paragraph. - * If 'what' is '{' or '}' we go to the next section. - * If 'both' is TRUE also stop at '}'. - * Return TRUE if the next paragraph or section was found. - */ -bool -findpar ( - bool *pincl, /* Return: true if last char is to be included */ - int dir, - long count, - int what, - int both -) +/// Find the next paragraph or section in direction 'dir'. +/// Paragraphs are currently supposed to be separated by empty lines. +/// If 'what' is NUL we go to the next paragraph. +/// If 'what' is '{' or '}' we go to the next section. +/// If 'both' is TRUE also stop at '}'. +/// +/// @param pincl Return: true if last char is to be included +/// +/// @return TRUE if the next paragraph or section was found. +bool findpar(bool *pincl, int dir, long count, int what, int both) { linenr_T curr; - bool did_skip; /* true after separating lines have been skipped */ - bool first; /* true on first line */ - linenr_T fold_first; /* first line of a closed fold */ - linenr_T fold_last; /* last line of a closed fold */ + bool did_skip; // true after separating lines have been skipped + bool first; // true on first line + linenr_T fold_first; // first line of a closed fold + linenr_T fold_last; // last line of a closed fold bool fold_skipped; /* true if a closed fold was skipped this iteration */ @@ -2544,32 +2603,37 @@ findpar ( while (count--) { did_skip = false; for (first = true;; first = false) { - if (*ml_get(curr) != NUL) + if (*ml_get(curr) != NUL) { did_skip = true; + } - /* skip folded lines */ + // skip folded lines fold_skipped = false; if (first && hasFolding(curr, &fold_first, &fold_last)) { curr = ((dir > 0) ? fold_last : fold_first) + dir; fold_skipped = true; } - if (!first && did_skip && startPS(curr, what, both)) + if (!first && did_skip && startPS(curr, what, both)) { break; + } - if (fold_skipped) + if (fold_skipped) { curr -= dir; + } if ((curr += dir) < 1 || curr > curbuf->b_ml.ml_line_count) { - if (count) + if (count) { return false; + } curr -= dir; break; } } } setpcmark(); - if (both && *ml_get(curr) == '}') /* include line with '}' */ + if (both && *ml_get(curr) == '}') { // include line with '}' ++curr; + } curwin->w_cursor.lnum = curr; if (curr == curbuf->b_ml.ml_line_count && what != '}') { char_u *line = ml_get(curr); @@ -2581,8 +2645,9 @@ findpar ( curwin->w_cursor.col -= utf_head_off(line, line + curwin->w_cursor.col); *pincl = true; } - } else + } else { curwin->w_cursor.col = 0; + } return true; } @@ -2591,7 +2656,7 @@ findpar ( */ static int inmacro(char_u *opt, char_u *s) { - char_u *macro; + char_u *macro; for (macro = opt; macro[0]; ++macro) { /* Accept two characters in the option being equal to two characters @@ -2602,11 +2667,13 @@ static int inmacro(char_u *opt, char_u *s) && (s[0] == NUL || s[0] == ' '))) && (macro[1] == s[1] || ((macro[1] == NUL || macro[1] == ' ') - && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) + && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) { break; + } ++macro; - if (macro[0] == NUL) + if (macro[0] == NUL) { break; + } } return macro[0] != NUL; } @@ -2618,7 +2685,7 @@ static int inmacro(char_u *opt, char_u *s) */ int startPS(linenr_T lnum, int para, int both) { - char_u *s; + char_u *s; s = ml_get(lnum); if (*s == para || *s == '\f' || (both && *s == '}')) { @@ -2647,7 +2714,7 @@ int startPS(linenr_T lnum, int para, int both) * 2 or higher - keyword characters (letters, digits and underscore) */ -static int cls_bigword; /* TRUE for "W", "B" or "E" */ +static int cls_bigword; // TRUE for "W", "B" or "E" /* * cls() - returns the class of character at curwin->w_cursor @@ -2674,20 +2741,15 @@ static int cls(void) return c; } -/* - * fwd_word(count, type, eol) - move forward one word - * - * Returns FAIL if the cursor was already at the end of the file. - * If eol is TRUE, last word stops at end of line (for operators). - */ -int -fwd_word( - long count, - int bigword, /* "W", "E" or "B" */ - int eol -) +/// fwd_word(count, type, eol) - move forward one word +/// +/// @return FAIL if the cursor was already at the end of the file. +/// If eol is TRUE, last word stops at end of line (for operators). +/// +/// @param bigword "W", "E" or "B" +int fwd_word(long count, int bigword, int eol) { - int sclass; /* starting class */ + int sclass; // starting class int i; int last_line; @@ -2707,20 +2769,24 @@ fwd_word( */ last_line = (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count); i = inc_cursor(); - if (i == -1 || (i >= 1 && last_line)) /* started at last char in file */ + if (i == -1 || (i >= 1 && last_line)) { // started at last char in file return FAIL; - if (i >= 1 && eol && count == 0) /* started at last char in line */ + } + if (i >= 1 && eol && count == 0) { // started at last char in line return OK; + } /* * Go one char past end of current word (if any) */ - if (sclass != 0) + if (sclass != 0) { while (cls() == sclass) { i = inc_cursor(); - if (i == -1 || (i >= 1 && eol && count == 0)) + if (i == -1 || (i >= 1 && eol && count == 0)) { return OK; + } } + } /* * go to next non-white @@ -2729,12 +2795,14 @@ fwd_word( /* * We'll stop if we land on a blank line */ - if (curwin->w_cursor.col == 0 && *get_cursor_line_ptr() == NUL) + if (curwin->w_cursor.col == 0 && *get_cursor_line_ptr() == NUL) { break; + } i = inc_cursor(); - if (i == -1 || (i >= 1 && eol && count == 0)) + if (i == -1 || (i >= 1 && eol && count == 0)) { return OK; + } } } return OK; @@ -2749,18 +2817,20 @@ fwd_word( */ int bck_word(long count, int bigword, int stop) { - int sclass; /* starting class */ + int sclass; // starting class curwin->w_cursor.coladd = 0; cls_bigword = bigword; while (--count >= 0) { /* When inside a range of folded lines, move to the first char of the * first line. */ - if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) + if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) { curwin->w_cursor.col = 0; + } sclass = cls(); - if (dec_cursor() == -1) /* started at start of file */ + if (dec_cursor() == -1) { // started at start of file return FAIL; + } if (!stop || sclass == cls() || sclass == 0) { /* @@ -2780,11 +2850,12 @@ int bck_word(long count, int bigword, int stop) /* * Move backward to start of this word. */ - if (skip_chars(cls(), BACKWARD)) + if (skip_chars(cls(), BACKWARD)) { return OK; + } } - inc_cursor(); /* overshot - forward one */ + inc_cursor(); // overshot - forward one finished: stop = FALSE; } @@ -2808,7 +2879,7 @@ finished: */ int end_word(long count, int bigword, int stop, int empty) { - int sclass; /* starting class */ + int sclass; // starting class curwin->w_cursor.coladd = 0; cls_bigword = bigword; @@ -2819,8 +2890,9 @@ int end_word(long count, int bigword, int stop, int empty) coladvance(MAXCOL); } sclass = cls(); - if (inc_cursor() == -1) + if (inc_cursor() == -1) { return FAIL; + } /* * If we're in the middle of a word, we just have to move to the end @@ -2830,8 +2902,9 @@ int end_word(long count, int bigword, int stop, int empty) /* * Move forward to end of the current word */ - if (skip_chars(sclass, FORWARD)) + if (skip_chars(sclass, FORWARD)) { return FAIL; + } } else if (!stop || sclass == 0) { /* * We were at the end of a word. Go to the end of the next word. @@ -2850,12 +2923,13 @@ int end_word(long count, int bigword, int stop, int empty) /* * Move forward to the end of this word. */ - if (skip_chars(cls(), FORWARD)) + if (skip_chars(cls(), FORWARD)) { return FAIL; + } } - dec_cursor(); /* overshot - one char backward */ + dec_cursor(); // overshot - one char backward finished: - stop = FALSE; /* we move only one word less */ + stop = FALSE; // we move only one word less } return OK; } @@ -2868,25 +2942,29 @@ finished: /// @return FAIL if start of the file was reached. int bckend_word(long count, int bigword, bool eol) { - int sclass; /* starting class */ + int sclass; // starting class int i; curwin->w_cursor.coladd = 0; cls_bigword = bigword; while (--count >= 0) { sclass = cls(); - if ((i = dec_cursor()) == -1) + if ((i = dec_cursor()) == -1) { return FAIL; - if (eol && i == 1) + } + if (eol && i == 1) { return OK; + } /* * Move backward to before the start of this word. */ if (sclass != 0) { - while (cls() == sclass) - if ((i = dec_cursor()) == -1 || (eol && i == 1)) + while (cls() == sclass) { + if ((i = dec_cursor()) == -1 || (eol && i == 1)) { return OK; + } + } } /* @@ -2922,14 +3000,15 @@ static bool skip_chars(int cclass, int dir) */ static void back_in_line(void) { - int sclass; /* starting class */ + int sclass; // starting class sclass = cls(); for (;; ) { - if (curwin->w_cursor.col == 0) /* stop at start of line */ + if (curwin->w_cursor.col == 0) { // stop at start of line break; + } dec_cursor(); - if (cls() != sclass) { /* stop at start of word */ + if (cls() != sclass) { // stop at start of word inc_cursor(); break; } @@ -2956,25 +3035,22 @@ static void findsent_forward(long count, bool at_start_sent) { while (count--) { findsent(FORWARD, 1L); - if (at_start_sent) + if (at_start_sent) { find_first_blank(&curwin->w_cursor); - if (count == 0 || at_start_sent) + } + if (count == 0 || at_start_sent) { decl(&curwin->w_cursor); + } at_start_sent = !at_start_sent; } } -/* - * Find word under cursor, cursor at end. - * Used while an operator is pending, and in Visual mode. - */ -int -current_word( - oparg_T *oap, - long count, - int include, /* TRUE: include word and white space */ - int bigword /* FALSE == word, TRUE == WORD */ -) +/// Find word under cursor, cursor at end. +/// Used while an operator is pending, and in Visual mode. +/// +/// @param include TRUE: include word and white space +/// @param bigword FALSE == word, TRUE == WORD +int current_word(oparg_T *oap, long count, int include, int bigword) { pos_T start_pos; pos_T pos; @@ -2984,9 +3060,10 @@ current_word( cls_bigword = bigword; clearpos(&start_pos); - /* Correct cursor when 'selection' is exclusive */ - if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) + // Correct cursor when 'selection' is exclusive + if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) { dec_cursor(); + } /* * When Visual mode is not active, or when the VIsual area is only one @@ -3005,8 +3082,9 @@ current_word( * not be included ("word"), find end of word. */ if ((cls() == 0) == include) { - if (end_word(1L, bigword, TRUE, TRUE) == FAIL) + if (end_word(1L, bigword, TRUE, TRUE) == FAIL) { return FAIL; + } } else { /* * If the start is not on white space, and white space should be @@ -3016,19 +3094,21 @@ current_word( * word) back up to end of the line. */ fwd_word(1L, bigword, TRUE); - if (curwin->w_cursor.col == 0) + if (curwin->w_cursor.col == 0) { decl(&curwin->w_cursor); - else + } else { oneleft(); + } - if (include) + if (include) { include_white = TRUE; + } } if (VIsual_active) { - /* should do something when inclusive == false ! */ + // should do something when inclusive == false ! VIsual = start_pos; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion } else { oap->start = start_pos; oap->motion_type = kMTCharWise; @@ -3045,11 +3125,13 @@ current_word( /* * In Visual mode, with cursor at start: move cursor back. */ - if (decl(&curwin->w_cursor) == -1) + if (decl(&curwin->w_cursor) == -1) { return FAIL; + } if (include != (cls() != 0)) { - if (bck_word(1L, bigword, TRUE) == FAIL) + if (bck_word(1L, bigword, TRUE) == FAIL) { return FAIL; + } } else { if (bckend_word(1L, bigword, true) == FAIL) { return FAIL; @@ -3060,21 +3142,25 @@ current_word( /* * Move cursor forward one word and/or white area. */ - if (incl(&curwin->w_cursor) == -1) + if (incl(&curwin->w_cursor) == -1) { return FAIL; + } if (include != (cls() == 0)) { - if (fwd_word(1L, bigword, TRUE) == FAIL && count > 1) + if (fwd_word(1L, bigword, TRUE) == FAIL && count > 1) { return FAIL; + } /* * If end is just past a new-line, we don't want to include * the first character on the line. * Put cursor on last char of white. */ - if (oneleft() == FAIL) + if (oneleft() == FAIL) { inclusive = false; + } } else { - if (end_word(1L, bigword, TRUE, TRUE) == FAIL) + if (end_word(1L, bigword, TRUE, TRUE) == FAIL) { return FAIL; + } } } --count; @@ -3090,29 +3176,32 @@ current_word( * (cursor is at start of next line). * But don't delete white space at start of line (indent). */ - pos = curwin->w_cursor; /* save cursor position */ + pos = curwin->w_cursor; // save cursor position curwin->w_cursor = start_pos; if (oneleft() == OK) { back_in_line(); if (cls() == 0 && curwin->w_cursor.col > 0) { - if (VIsual_active) + if (VIsual_active) { VIsual = curwin->w_cursor; - else + } else { oap->start = curwin->w_cursor; + } } } - curwin->w_cursor = pos; /* put cursor back at end */ + curwin->w_cursor = pos; // put cursor back at end } if (VIsual_active) { - if (*p_sel == 'e' && inclusive && ltoreq(VIsual, curwin->w_cursor)) + if (*p_sel == 'e' && inclusive && ltoreq(VIsual, curwin->w_cursor)) { inc_cursor(); + } if (VIsual_mode == 'V') { VIsual_mode = 'v'; redraw_cmdline = true; // show mode later } - } else + } else { oap->inclusive = inclusive; + } return OK; } @@ -3132,7 +3221,7 @@ int current_sent(oparg_T *oap, long count, int include) start_pos = curwin->w_cursor; pos = start_pos; - findsent(FORWARD, 1L); /* Find start of next sentence. */ + findsent(FORWARD, 1L); // Find start of next sentence. /* * When the Visual area is bigger than one character: Extend it. @@ -3166,14 +3255,17 @@ extend: findsent(FORWARD, 1L); } } - if (include) /* "as" gets twice as much as "is" */ + if (include) { // "as" gets twice as much as "is" count *= 2; + } while (count--) { - if (at_start_sent) + if (at_start_sent) { find_first_blank(&curwin->w_cursor); + } c = gchar_cursor(); - if (!at_start_sent || (!include && !ascii_iswhite(c))) + if (!at_start_sent || (!include && !ascii_iswhite(c))) { findsent(BACKWARD, 1L); + } at_start_sent = !at_start_sent; } } else { @@ -3196,17 +3288,20 @@ extend: } incl(&pos); } - if (at_start_sent) /* in the sentence */ + if (at_start_sent) { // in the sentence findsent(BACKWARD, 1L); - else /* in/before white before a sentence */ + } else { // in/before white before a sentence curwin->w_cursor = start_pos; + } } - if (include) /* "as" gets twice as much as "is" */ + if (include) { // "as" gets twice as much as "is" count *= 2; + } findsent_forward(count, at_start_sent); - if (*p_sel == 'e') + if (*p_sel == 'e') { ++curwin->w_cursor.col; + } } return OK; } @@ -3215,8 +3310,9 @@ extend: * If the cursor started on a blank, check if it is just before the start * of the next sentence. */ - while (c = gchar_pos(&pos), ascii_iswhite(c)) + while (c = gchar_pos(&pos), ascii_iswhite(c)) { incl(&pos); + } if (equalpos(pos, curwin->w_cursor)) { start_blank = true; find_first_blank(&start_pos); // go back to first blank @@ -3225,12 +3321,13 @@ extend: findsent(BACKWARD, 1L); start_pos = curwin->w_cursor; } - if (include) + if (include) { ncount = count * 2; - else { + } else { ncount = count; - if (start_blank) + if (start_blank) { --ncount; + } } if (ncount > 0) { findsent_forward(ncount, true); @@ -3247,57 +3344,57 @@ extend: if (start_blank) { find_first_blank(&curwin->w_cursor); c = gchar_pos(&curwin->w_cursor); - if (ascii_iswhite(c)) + if (ascii_iswhite(c)) { decl(&curwin->w_cursor); - } else if (c = gchar_cursor(), !ascii_iswhite(c)) + } + } else if (c = gchar_cursor(), !ascii_iswhite(c)) { find_first_blank(&start_pos); + } } if (VIsual_active) { - /* Avoid getting stuck with "is" on a single space before a sentence. */ - if (equalpos(start_pos, curwin->w_cursor)) + // Avoid getting stuck with "is" on a single space before a sentence. + if (equalpos(start_pos, curwin->w_cursor)) { goto extend; - if (*p_sel == 'e') + } + if (*p_sel == 'e') { ++curwin->w_cursor.col; + } VIsual = start_pos; VIsual_mode = 'v'; redraw_cmdline = true; // show mode later redraw_curbuf_later(INVERTED); // update the inversion } else { - /* include a newline after the sentence, if there is one */ - if (incl(&curwin->w_cursor) == -1) + // include a newline after the sentence, if there is one + if (incl(&curwin->w_cursor) == -1) { oap->inclusive = true; - else + } else { oap->inclusive = false; + } oap->start = start_pos; oap->motion_type = kMTCharWise; } return OK; } -/* - * Find block under the cursor, cursor at end. - * "what" and "other" are two matching parenthesis/brace/etc. - */ -int -current_block( - oparg_T *oap, - long count, - int include, /* TRUE == include white space */ - int what, /* '(', '{', etc. */ - int other /* ')', '}', etc. */ -) +/// Find block under the cursor, cursor at end. +/// "what" and "other" are two matching parenthesis/brace/etc. +/// +/// @param include TRUE == include white space +/// @param what '(', '{', etc. +/// @param other ')', '}', etc. +int current_block(oparg_T *oap, long count, int include, int what, int other) { pos_T old_pos; - pos_T *pos = NULL; + pos_T *pos = NULL; pos_T start_pos; - pos_T *end_pos; + pos_T *end_pos; pos_T old_start, old_end; - char_u *save_cpo; + char_u *save_cpo; bool sol = false; // '{' at start of line old_pos = curwin->w_cursor; - old_end = curwin->w_cursor; /* remember where we started */ + old_end = curwin->w_cursor; // remember where we started old_start = old_end; /* @@ -3305,18 +3402,23 @@ current_block( */ if (!VIsual_active || equalpos(VIsual, curwin->w_cursor)) { setpcmark(); - if (what == '{') /* ignore indent */ - while (inindent(1)) - if (inc_cursor() != 0) + if (what == '{') { // ignore indent + while (inindent(1)) { + if (inc_cursor() != 0) { break; - if (gchar_cursor() == what) - /* cursor on '(' or '{', move cursor just after it */ + } + } + } + if (gchar_cursor() == what) { + // cursor on '(' or '{', move cursor just after it ++curwin->w_cursor.col; + } } else if (lt(VIsual, curwin->w_cursor)) { old_start = VIsual; - curwin->w_cursor = VIsual; /* cursor at low end of Visual */ - } else + curwin->w_cursor = VIsual; // cursor at low end of Visual + } else { old_end = VIsual; + } // Search backwards for unclosed '(', '{', etc.. // Put this position in start_pos. @@ -3377,8 +3479,9 @@ current_block( return FAIL; } curwin->w_cursor = *end_pos; - } else + } else { break; + } } if (VIsual_active) { @@ -3390,21 +3493,22 @@ current_block( } VIsual = start_pos; VIsual_mode = 'v'; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion showmode(); } else { oap->start = start_pos; oap->motion_type = kMTCharWise; oap->inclusive = false; - if (sol) + if (sol) { incl(&curwin->w_cursor); - else if (ltoreq(start_pos, curwin->w_cursor)) - /* Include the character under the cursor. */ + } else if (ltoreq(start_pos, curwin->w_cursor)) { + // Include the character under the cursor. oap->inclusive = true; - else + } else { /* End is before the start (no text in between <>, [], etc.): don't * operate on any text. */ curwin->w_cursor = start_pos; + } } return OK; @@ -3416,8 +3520,8 @@ current_block( /// @return true if the cursor is on a "<aaa>" tag. Ignore "<aaa/>". static bool in_html_tag(bool end_tag) { - char_u *line = get_cursor_line_ptr(); - char_u *p; + char_u *line = get_cursor_line_ptr(); + char_u *p; int c; int lc = NUL; pos_T pos; @@ -3449,36 +3553,32 @@ static bool in_html_tag(bool end_tag) return false; } - /* check that the matching '>' is not preceded by '/' */ + // check that the matching '>' is not preceded by '/' for (;; ) { if (inc(&pos) < 0) { return false; } c = *ml_get_pos(&pos); - if (c == '>') + if (c == '>') { break; + } lc = c; } return lc != '/'; } -/* - * Find tag block under the cursor, cursor at end. - */ -int -current_tagblock( - oparg_T *oap, - long count_arg, - bool include // true == include white space -) +/// Find tag block under the cursor, cursor at end. +/// +/// @param include true == include white space +int current_tagblock(oparg_T *oap, long count_arg, bool include) { long count = count_arg; pos_T old_pos; pos_T start_pos; pos_T end_pos; pos_T old_start, old_end; - char_u *p; - char_u *cp; + char_u *p; + char_u *cp; int len; bool do_include = include; bool save_p_ws = p_ws; @@ -3488,21 +3588,23 @@ current_tagblock( p_ws = false; old_pos = curwin->w_cursor; - old_end = curwin->w_cursor; /* remember where we started */ + old_end = curwin->w_cursor; // remember where we started old_start = old_end; - if (!VIsual_active || *p_sel == 'e') - decl(&old_end); /* old_end is inclusive */ - + if (!VIsual_active || *p_sel == 'e') { + decl(&old_end); // old_end is inclusive + } /* * If we start on "<aaa>" select that block. */ if (!VIsual_active || equalpos(VIsual, curwin->w_cursor)) { setpcmark(); - /* ignore indent */ - while (inindent(1)) - if (inc_cursor() != 0) + // ignore indent + while (inindent(1)) { + if (inc_cursor() != 0) { break; + } + } if (in_html_tag(false)) { // cursor on start tag, move to its '>' @@ -3523,9 +3625,10 @@ current_tagblock( } } else if (lt(VIsual, curwin->w_cursor)) { old_start = VIsual; - curwin->w_cursor = VIsual; /* cursor at low end of Visual */ - } else + curwin->w_cursor = VIsual; // cursor at low end of Visual + } else { old_end = VIsual; + } again: /* @@ -3533,11 +3636,10 @@ again: * Put this position in start_pos. */ for (long n = 0; n < count; n++) { - if (do_searchpair( - "<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", - "", - "</[^>]*>", BACKWARD, NULL, 0, - NULL, (linenr_T)0, 0L) <= 0) { + if (do_searchpair("<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", + "", + "</[^>]*>", BACKWARD, NULL, 0, + NULL, (linenr_T)0, 0L) <= 0) { curwin->w_cursor = old_pos; goto theend; } @@ -3603,14 +3705,15 @@ again: end_pos = curwin->w_cursor; if (!do_include) { - /* Exclude the start tag. */ + // Exclude the start tag. curwin->w_cursor = start_pos; - while (inc_cursor() >= 0) + while (inc_cursor() >= 0) { if (*get_cursor_pos_ptr() == '>') { inc_cursor(); start_pos = curwin->w_cursor; break; } + } curwin->w_cursor = end_pos; // If we are in Visual mode and now have the same text as before set @@ -3635,7 +3738,7 @@ again: } VIsual = start_pos; VIsual_mode = 'v'; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion showmode(); } else { oap->start = start_pos; @@ -3656,13 +3759,9 @@ theend: return retval; } -int -current_par( - oparg_T *oap, - long count, - int include, /* TRUE == include white space */ - int type /* 'p' for paragraph, 'S' for section */ -) +/// @param include TRUE == include white space +/// @param type 'p' for paragraph, 'S' for section +int current_par(oparg_T *oap, long count, int include, int type) { linenr_T start_lnum; linenr_T end_lnum; @@ -3675,8 +3774,9 @@ current_par( int t; int i; - if (type == 'S') /* not implemented yet */ + if (type == 'S') { // not implemented yet return FAIL; + } start_lnum = curwin->w_cursor.lnum; @@ -3685,10 +3785,11 @@ current_par( */ if (VIsual_active && start_lnum != VIsual.lnum) { extend: - if (start_lnum < VIsual.lnum) + if (start_lnum < VIsual.lnum) { dir = BACKWARD; - else + } else { dir = FORWARD; + } for (i = count; --i >= 0; ) { if (start_lnum == (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count)) { @@ -3706,20 +3807,24 @@ extend: } for (;; ) { if (start_lnum == (dir == BACKWARD - ? 1 : curbuf->b_ml.ml_line_count)) + ? 1 : curbuf->b_ml.ml_line_count)) { break; + } if (start_is_white != linewhite(start_lnum + dir) || (!start_is_white && startPS(start_lnum + (dir > 0 - ? 1 : 0), 0, 0))) + ? 1 : 0), 0, 0))) { break; + } start_lnum += dir; } - if (!include) + if (!include) { break; + } if (start_lnum == (dir == BACKWARD - ? 1 : curbuf->b_ml.ml_line_count)) + ? 1 : curbuf->b_ml.ml_line_count)) { break; + } prev_start_is_white = start_is_white; } } @@ -3733,12 +3838,14 @@ extend: */ white_in_front = linewhite(start_lnum); while (start_lnum > 1) { - if (white_in_front) { /* stop at first white line */ - if (!linewhite(start_lnum - 1)) + if (white_in_front) { // stop at first white line + if (!linewhite(start_lnum - 1)) { break; - } else { /* stop at first non-white line of start of paragraph */ - if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0)) + } + } else { // stop at first non-white line of start of paragraph + if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0)) { break; + } } --start_lnum; } @@ -3747,19 +3854,23 @@ extend: * Move past the end of any white lines. */ end_lnum = start_lnum; - while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum)) + while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum)) { ++end_lnum; + } --end_lnum; i = count; - if (!include && white_in_front) + if (!include && white_in_front) { --i; + } while (i--) { - if (end_lnum == curbuf->b_ml.ml_line_count) + if (end_lnum == curbuf->b_ml.ml_line_count) { return FAIL; + } - if (!include) + if (!include) { do_white = linewhite(end_lnum + 1); + } if (include || !do_white) { ++end_lnum; @@ -3768,29 +3879,35 @@ extend: */ while (end_lnum < curbuf->b_ml.ml_line_count && !linewhite(end_lnum + 1) - && !startPS(end_lnum + 1, 0, 0)) + && !startPS(end_lnum + 1, 0, 0)) { ++end_lnum; + } } - if (i == 0 && white_in_front && include) + if (i == 0 && white_in_front && include) { break; + } /* * skip to end of white lines after paragraph */ - if (include || do_white) + if (include || do_white) { while (end_lnum < curbuf->b_ml.ml_line_count - && linewhite(end_lnum + 1)) + && linewhite(end_lnum + 1)) { ++end_lnum; + } + } } /* * If there are no empty lines at the end, try to find some empty lines at * the start (unless that has been done already). */ - if (!white_in_front && !linewhite(end_lnum) && include) - while (start_lnum > 1 && linewhite(start_lnum - 1)) + if (!white_in_front && !linewhite(end_lnum) && include) { + while (start_lnum > 1 && linewhite(start_lnum - 1)) { --start_lnum; + } + } if (VIsual_active) { // Problem: when doing "Vipipip" nothing happens in a single white @@ -3799,11 +3916,11 @@ extend: goto extend; } if (VIsual.lnum != start_lnum) { - VIsual.lnum = start_lnum; - VIsual.col = 0; + VIsual.lnum = start_lnum; + VIsual.col = 0; } VIsual_mode = 'V'; - redraw_curbuf_later(INVERTED); /* update the inversion */ + redraw_curbuf_later(INVERTED); // update the inversion showmode(); } else { oap->start.lnum = start_lnum; @@ -3817,19 +3934,14 @@ extend: } -/* - * Search quote char from string line[col]. - * Quote character escaped by one of the characters in "escape" is not counted - * as a quote. - * Returns column number of "quotechar" or -1 when not found. - */ -static int -find_next_quote( - char_u *line, - int col, - int quotechar, - char_u *escape /* escape characters, can be NULL */ -) +/// Search quote char from string line[col]. +/// Quote character escaped by one of the characters in "escape" is not counted +/// as a quote. +/// +/// @param escape escape characters, can be NULL +/// +/// @return column number of "quotechar" or -1 when not found. +static int find_next_quote(char_u *line, int col, int quotechar, char_u *escape) { int c; @@ -3847,19 +3959,14 @@ find_next_quote( return col; } -/* - * Search backwards in "line" from column "col_start" to find "quotechar". - * Quote character escaped by one of the characters in "escape" is not counted - * as a quote. - * Return the found column or zero. - */ -static int -find_prev_quote( - char_u *line, - int col_start, - int quotechar, - char_u *escape /* escape characters, can be NULL */ -) +/// Search backwards in "line" from column "col_start" to find "quotechar". +/// Quote character escaped by one of the characters in "escape" is not counted +/// as a quote. +/// +/// @param escape escape characters, can be NULL +/// +/// @return the found column or zero. +static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *escape) { int n; @@ -3867,29 +3974,32 @@ find_prev_quote( col_start--; col_start -= utf_head_off(line, line + col_start); n = 0; - if (escape != NULL) + if (escape != NULL) { while (col_start - n > 0 && vim_strchr(escape, - line[col_start - n - 1]) != NULL) + line[col_start - n - 1]) != NULL) { ++n; - if (n & 1) - col_start -= n; /* uneven number of escape chars, skip it */ - else if (line[col_start] == quotechar) + } + } + if (n & 1) { + col_start -= n; // uneven number of escape chars, skip it + } else if (line[col_start] == + quotechar) { break; + } } return col_start; } -// Find quote under the cursor, cursor at end. -// Returns true if found, else false. -bool current_quote( - oparg_T *oap, - long count, - bool include, // true == include quote char - int quotechar // Quote character -) +/// Find quote under the cursor, cursor at end. +/// +/// @param include true == include quote char +/// @param quotechar Quote character +/// +/// @return true if found, else false. +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 = get_cursor_line_ptr(); int col_end; int col_start = curwin->w_cursor.col; bool inclusive = false; @@ -3907,7 +4017,7 @@ bool current_quote( if (VIsual_active) { // this only works within one line if (VIsual.lnum != curwin->w_cursor.lnum) { - return false; + return false; } vis_bef_curs = lt(VIsual, curwin->w_cursor); @@ -3952,12 +4062,13 @@ bool current_quote( col_end = VIsual.col; } - /* Find out if we have a quote in the selection. */ - while (i <= col_end) + // Find out if we have a quote in the selection. + while (i <= col_end) { if (line[i++] == quotechar) { selected_quote = true; break; } + } } if (!vis_empty && line[col_start] == quotechar) { @@ -3971,9 +4082,9 @@ bool current_quote( goto abort_search; } col_end = find_next_quote(line, col_start + 1, quotechar, - curbuf->b_p_qe); + curbuf->b_p_qe); if (col_end < 0) { - /* We were on a starting quote perhaps? */ + // We were on a starting quote perhaps? col_end = col_start; col_start = curwin->w_cursor.col; } @@ -3983,23 +4094,23 @@ bool current_quote( goto abort_search; } col_start = find_prev_quote(line, col_end, quotechar, - curbuf->b_p_qe); + curbuf->b_p_qe); if (line[col_start] != quotechar) { - /* We were on an ending quote perhaps? */ + // We were on an ending quote perhaps? col_start = col_end; col_end = curwin->w_cursor.col; } } } else if (line[col_start] == quotechar - || !vis_empty - ) { + || !vis_empty) { int first_col = col_start; if (!vis_empty) { - if (vis_bef_curs) + if (vis_bef_curs) { first_col = find_next_quote(line, col_start, quotechar, NULL); - else + } else { first_col = find_prev_quote(line, col_start, quotechar, NULL); + } } /* The cursor is on a quote, we don't know if it's the opening or * closing quote. Search from the start of the line to find out. @@ -4007,14 +4118,14 @@ bool current_quote( * in between two strings. */ col_start = 0; for (;; ) { - /* Find open quote character. */ + // Find open quote character. col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0 || col_start > first_col) { goto abort_search; } // Find close quote character. col_end = find_next_quote(line, col_start + 1, quotechar, - curbuf->b_p_qe); + curbuf->b_p_qe); if (col_end < 0) { goto abort_search; } @@ -4026,17 +4137,17 @@ bool current_quote( col_start = col_end + 1; } } else { - /* Search backward for a starting quote. */ + // Search backward for a starting quote. col_start = find_prev_quote(line, col_start, quotechar, curbuf->b_p_qe); if (line[col_start] != quotechar) { - /* No quote before the cursor, look after the cursor. */ + // No quote before the cursor, look after the cursor. col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0) { goto abort_search; } } - /* Find close quote character. */ + // Find close quote character. col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) { @@ -4047,20 +4158,23 @@ bool current_quote( // When "include" is true, include spaces after closing quote or before // the starting quote. if (include) { - if (ascii_iswhite(line[col_end + 1])) - while (ascii_iswhite(line[col_end + 1])) + if (ascii_iswhite(line[col_end + 1])) { + while (ascii_iswhite(line[col_end + 1])) { ++col_end; - else - while (col_start > 0 && ascii_iswhite(line[col_start - 1])) + } + } else { + while (col_start > 0 && ascii_iswhite(line[col_start - 1])) { --col_start; + } + } } /* Set start position. After vi" another i" must include the ". * For v2i" include the quotes. */ if (!include && count < 2 - && (vis_empty || !inside_quotes) - ) + && (vis_empty || !inside_quotes)) { ++col_start; + } curwin->w_cursor.col = col_start; if (VIsual_active) { /* Set the start of the Visual area when the Visual area was empty, we @@ -4082,13 +4196,14 @@ bool current_quote( oap->motion_type = kMTCharWise; } - /* Set end position. */ + // Set end position. curwin->w_cursor.col = col_end; if ((include || count > 1 - /* After vi" another i" must include the ". */ + // After vi" another i" must include the ". || (!vis_empty && inside_quotes) - ) && inc_cursor() == 2) + ) && inc_cursor() == 2) { inclusive = true; + } if (VIsual_active) { if (vis_empty || vis_bef_curs) { // decrement cursor when 'selection' is not exclusive @@ -4114,7 +4229,7 @@ bool current_quote( redraw_cmdline = true; // show mode later } } else { - /* Set inclusive and other oap's flags. */ + // Set inclusive and other oap's flags. oap->inclusive = inclusive; } @@ -4126,10 +4241,10 @@ abort_search: inc_cursor(); } if (restore_vis_bef) { - pos_T t = curwin->w_cursor; + pos_T t = curwin->w_cursor; - curwin->w_cursor = VIsual; - VIsual = t; + curwin->w_cursor = VIsual; + VIsual = t; } } return false; @@ -4137,22 +4252,19 @@ abort_search: -/* - * Find next search match under cursor, cursor at end. - * Used while an operator is pending, and in Visual mode. - */ -int -current_search( - long count, - bool forward // true for forward, false for backward -) +/// Find next search match under cursor, cursor at end. +/// Used while an operator is pending, and in Visual mode. +/// +/// @param forward true for forward, false for backward +int current_search(long count, bool forward) { bool old_p_ws = p_ws; pos_T save_VIsual = VIsual; - /* Correct cursor when 'selection' is exclusive */ - if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) + // Correct cursor when 'selection' is exclusive + if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) { dec_cursor(); + } pos_T end_pos; // end position of the pattern match pos_T orig_pos; // position of the cursor at beginning @@ -4162,7 +4274,7 @@ current_search( // When searching forward and the cursor is at the start of the Visual // area, skip the first search backward, otherwise it doesn't move. const bool skip_first_backward = forward && VIsual_active - && lt(curwin->w_cursor, VIsual); + && lt(curwin->w_cursor, VIsual); orig_pos = pos = curwin->w_cursor; if (VIsual_active) { @@ -4220,8 +4332,9 @@ current_search( // selection works. if (i == 1 && !result) { // not found, abort */ curwin->w_cursor = orig_pos; - if (VIsual_active) + if (VIsual_active) { VIsual = save_VIsual; + } return FAIL; } else if (i == 0 && !result) { if (forward) { // try again from start of buffer @@ -4229,8 +4342,7 @@ current_search( } else { // try again from end of buffer // searching backwards, so set pos to last line and col pos.lnum = curwin->w_buffer->b_ml.ml_line_count; - pos.col = (colnr_T)STRLEN( - ml_get(curwin->w_buffer->b_ml.ml_line_count)); + pos.col = (colnr_T)STRLEN(ml_get(curwin->w_buffer->b_ml.ml_line_count)); } } } @@ -4283,8 +4395,7 @@ current_search( /// else from position "cur". /// "direction" is FORWARD or BACKWARD. /// Returns TRUE, FALSE or -1 for failure. -static int -is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) +static int is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) { regmmatch_T regmatch; int nmatched = 0; @@ -4298,8 +4409,9 @@ is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) } if (search_regcomp(pattern, RE_SEARCH, RE_SEARCH, - SEARCH_KEEP, ®match) == FAIL) + SEARCH_KEEP, ®match) == FAIL) { return -1; + } // init startcol correctly regmatch.startpos[0].col = -1; @@ -4346,7 +4458,7 @@ is_zero_width(char_u *pattern, int move, pos_T *cur, Direction direction) */ int linewhite(linenr_T lnum) { - char_u *p; + char_u *p; p = skipwhite(ml_get(lnum)); return *p == NUL; @@ -4354,64 +4466,63 @@ int linewhite(linenr_T lnum) // Add the search count "[3/19]" to "msgbuf". // See update_search_stat() for other arguments. -static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, - bool show_top_bot_msg, char_u *msgbuf, - bool recompute, int maxcount, long timeout) +static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, bool show_top_bot_msg, + char_u *msgbuf, bool recompute, int maxcount, long timeout) { - searchstat_T stat; - - update_search_stat(dirc, pos, cursor_pos, &stat, recompute, maxcount, - timeout); - if (stat.cur > 0) { - char t[SEARCH_STAT_BUF_LEN]; - - if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { - if (stat.incomplete == 1) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); - } else if (stat.cnt > maxcount && stat.cur > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", - maxcount, maxcount); - } else if (stat.cnt > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/%d]", - maxcount, stat.cur); - } else { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", - stat.cnt, stat.cur); - } + searchstat_T stat; + + update_search_stat(dirc, pos, cursor_pos, &stat, recompute, maxcount, + timeout); + if (stat.cur > 0) { + char t[SEARCH_STAT_BUF_LEN]; + + if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { + if (stat.incomplete == 1) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); + } else if (stat.cnt > maxcount && stat.cur > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", + maxcount, maxcount); + } else if (stat.cnt > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/%d]", + maxcount, stat.cur); } else { - if (stat.incomplete == 1) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); - } else if (stat.cnt > maxcount && stat.cur > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", - maxcount, maxcount); - } else if (stat.cnt > maxcount) { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/>%d]", - stat.cur, maxcount); - } else { - vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", - stat.cur, stat.cnt); - } + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", + stat.cnt, stat.cur); } - - size_t len = strlen(t); - if (show_top_bot_msg && len + 2 < SEARCH_STAT_BUF_LEN) { - memmove(t + 2, t, len); - t[0] = 'W'; - t[1] = ' '; - len += 2; + } else { + if (stat.incomplete == 1) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]"); + } else if (stat.cnt > maxcount && stat.cur > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]", + maxcount, maxcount); + } else if (stat.cnt > maxcount) { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/>%d]", + stat.cur, maxcount); + } else { + vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]", + stat.cur, stat.cnt); } + } - memmove(msgbuf + STRLEN(msgbuf) - len, t, len); - if (dirc == '?' && stat.cur == maxcount + 1) { - stat.cur = -1; - } + size_t len = strlen(t); + if (show_top_bot_msg && len + 2 < SEARCH_STAT_BUF_LEN) { + memmove(t + 2, t, len); + t[0] = 'W'; + t[1] = ' '; + len += 2; + } - // keep the message even after redraw, but don't put in history - msg_hist_off = true; - msg_ext_set_kind("search_count"); - give_warning(msgbuf, false); - msg_hist_off = false; + memmove(msgbuf + STRLEN(msgbuf) - len, t, len); + if (dirc == '?' && stat.cur == maxcount + 1) { + stat.cur = -1; } + + // keep the message even after redraw, but don't put in history + msg_hist_off = true; + msg_ext_set_kind("search_count"); + give_warning(msgbuf, false); + msg_hist_off = false; + } } // Add the search count information to "stat". @@ -4420,258 +4531,253 @@ static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, // dirc == 0: don't find the next/previous match (only set the result to "stat") // dirc == '/': find the next match // dirc == '?': find the previous match -static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, - searchstat_T *stat, bool recompute, int maxcount, - long timeout) +static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, searchstat_T *stat, + bool recompute, int maxcount, long timeout) { - int save_ws = p_ws; - bool wraparound = false; - pos_T p = (*pos); - static pos_T lastpos = { 0, 0, 0 }; - static int cur = 0; - static int cnt = 0; - static bool exact_match = false; - static int incomplete = 0; - static int last_maxcount = SEARCH_STAT_DEF_MAX_COUNT; - static int chgtick = 0; - static char_u *lastpat = NULL; - static buf_T *lbuf = NULL; - proftime_T start; - - memset(stat, 0, sizeof(searchstat_T)); - - if (dirc == 0 && !recompute && !EMPTY_POS(lastpos)) { - stat->cur = cur; - stat->cnt = cnt; - stat->exact_match = exact_match; - stat->incomplete = incomplete; - stat->last_maxcount = last_maxcount; - return; - } - last_maxcount = maxcount; - wraparound = ((dirc == '?' && lt(lastpos, p)) - || (dirc == '/' && lt(p, lastpos))); - - // If anything relevant changed the count has to be recomputed. - // STRNICMP ignores case, but we should not ignore case. - // Unfortunately, there is no STRNICMP function. - // XXX: above comment should be "no MB_STRCMP function" ? - if (!(chgtick == buf_get_changedtick(curbuf) - && lastpat != NULL // suppress clang/NULL passed as nonnull parameter - && STRNICMP(lastpat, spats[last_idx].pat, STRLEN(lastpat)) == 0 - && STRLEN(lastpat) == STRLEN(spats[last_idx].pat) - && equalpos(lastpos, *cursor_pos) - && lbuf == curbuf) - || wraparound || cur < 0 || (maxcount > 0 && cur > maxcount) - || recompute) { - cur = 0; - cnt = 0; - exact_match = false; - incomplete = 0; - clearpos(&lastpos); - lbuf = curbuf; - } - - if (equalpos(lastpos, *cursor_pos) && !wraparound - && (dirc == 0 || dirc == '/' ? cur < cnt : cur > 0)) { - cur += dirc == 0 ? 0 : dirc == '/' ? 1 : -1; - } else { - bool done_search = false; - pos_T endpos = { 0, 0, 0 }; - p_ws = false; - if (timeout > 0) { - start = profile_setlimit(timeout); - } - while (!got_int && searchit(curwin, curbuf, &lastpos, &endpos, - FORWARD, NULL, 1, SEARCH_KEEP, RE_LAST, - NULL) != FAIL) { - done_search = true; - // Stop after passing the time limit. - if (timeout > 0 && profile_passed_limit(start)) { - incomplete = 1; - break; - } - cnt++; - if (ltoreq(lastpos, p)) { - cur = cnt; - if (lt(p, endpos)) { - exact_match = true; - } - } - fast_breakcheck(); - if (maxcount > 0 && cnt > maxcount) { - incomplete = 2; // max count exceeded - break; - } - } - if (got_int) { - cur = -1; // abort - } - if (done_search) { - xfree(lastpat); - lastpat = vim_strsave(spats[last_idx].pat); - chgtick = buf_get_changedtick(curbuf); - lbuf = curbuf; - lastpos = p; - } - } + int save_ws = p_ws; + bool wraparound = false; + pos_T p = (*pos); + static pos_T lastpos = { 0, 0, 0 }; + static int cur = 0; + static int cnt = 0; + static bool exact_match = false; + static int incomplete = 0; + static int last_maxcount = SEARCH_STAT_DEF_MAX_COUNT; + static int chgtick = 0; + static char_u *lastpat = NULL; + static buf_T *lbuf = NULL; + proftime_T start; + + memset(stat, 0, sizeof(searchstat_T)); + + if (dirc == 0 && !recompute && !EMPTY_POS(lastpos)) { stat->cur = cur; stat->cnt = cnt; stat->exact_match = exact_match; stat->incomplete = incomplete; stat->last_maxcount = last_maxcount; - p_ws = save_ws; + return; + } + last_maxcount = maxcount; + wraparound = ((dirc == '?' && lt(lastpos, p)) + || (dirc == '/' && lt(p, lastpos))); + + // If anything relevant changed the count has to be recomputed. + // STRNICMP ignores case, but we should not ignore case. + // Unfortunately, there is no STRNICMP function. + // XXX: above comment should be "no MB_STRCMP function" ? + if (!(chgtick == buf_get_changedtick(curbuf) + && lastpat != NULL // suppress clang/NULL passed as nonnull parameter + && STRNICMP(lastpat, spats[last_idx].pat, STRLEN(lastpat)) == 0 + && STRLEN(lastpat) == STRLEN(spats[last_idx].pat) + && equalpos(lastpos, *cursor_pos) + && lbuf == curbuf) + || wraparound || cur < 0 || (maxcount > 0 && cur > maxcount) + || recompute) { + cur = 0; + cnt = 0; + exact_match = false; + incomplete = 0; + clearpos(&lastpos); + lbuf = curbuf; + } + + if (equalpos(lastpos, *cursor_pos) && !wraparound + && (dirc == 0 || dirc == '/' ? cur < cnt : cur > 0)) { + cur += dirc == 0 ? 0 : dirc == '/' ? 1 : -1; + } else { + bool done_search = false; + pos_T endpos = { 0, 0, 0 }; + p_ws = false; + if (timeout > 0) { + start = profile_setlimit(timeout); + } + while (!got_int && searchit(curwin, curbuf, &lastpos, &endpos, + FORWARD, NULL, 1, SEARCH_KEEP, RE_LAST, + NULL) != FAIL) { + done_search = true; + // Stop after passing the time limit. + if (timeout > 0 && profile_passed_limit(start)) { + incomplete = 1; + break; + } + cnt++; + if (ltoreq(lastpos, p)) { + cur = cnt; + if (lt(p, endpos)) { + exact_match = true; + } + } + fast_breakcheck(); + if (maxcount > 0 && cnt > maxcount) { + incomplete = 2; // max count exceeded + break; + } + } + if (got_int) { + cur = -1; // abort + } + if (done_search) { + xfree(lastpat); + lastpat = vim_strsave(spats[last_idx].pat); + chgtick = buf_get_changedtick(curbuf); + lbuf = curbuf; + lastpos = p; + } + } + stat->cur = cur; + stat->cnt = cnt; + stat->exact_match = exact_match; + stat->incomplete = incomplete; + stat->last_maxcount = last_maxcount; + p_ws = save_ws; } // "searchcount()" function void f_searchcount(typval_T *argvars, typval_T *rettv, FunPtr fptr) { - pos_T pos = curwin->w_cursor; - char_u *pattern = NULL; - int maxcount = SEARCH_STAT_DEF_MAX_COUNT; - long timeout = SEARCH_STAT_DEF_TIMEOUT; - bool recompute = true; - searchstat_T stat; + pos_T pos = curwin->w_cursor; + char_u *pattern = NULL; + int maxcount = SEARCH_STAT_DEF_MAX_COUNT; + long timeout = SEARCH_STAT_DEF_TIMEOUT; + bool recompute = true; + searchstat_T stat; - tv_dict_alloc_ret(rettv); + tv_dict_alloc_ret(rettv); - if (shortmess(SHM_SEARCHCOUNT)) { // 'shortmess' contains 'S' flag - recompute = true; - } + if (shortmess(SHM_SEARCHCOUNT)) { // 'shortmess' contains 'S' flag + recompute = true; + } - if (argvars[0].v_type != VAR_UNKNOWN) { - dict_T *dict; - dictitem_T *di; - listitem_T *li; - bool error = false; + if (argvars[0].v_type != VAR_UNKNOWN) { + dict_T *dict; + dictitem_T *di; + listitem_T *li; + bool error = false; - if (argvars[0].v_type != VAR_DICT || argvars[0].vval.v_dict == NULL) { - EMSG(_(e_dictreq)); + if (argvars[0].v_type != VAR_DICT || argvars[0].vval.v_dict == NULL) { + EMSG(_(e_dictreq)); + return; + } + dict = argvars[0].vval.v_dict; + di = tv_dict_find(dict, (const char *)"timeout", -1); + if (di != NULL) { + timeout = (long)tv_get_number_chk(&di->di_tv, &error); + if (error) { return; } - dict = argvars[0].vval.v_dict; - di = tv_dict_find(dict, (const char *)"timeout", -1); - if (di != NULL) { - timeout = (long)tv_get_number_chk(&di->di_tv, &error); - if (error) { - return; - } + } + di = tv_dict_find(dict, (const char *)"maxcount", -1); + if (di != NULL) { + maxcount = (int)tv_get_number_chk(&di->di_tv, &error); + if (error) { + return; } - di = tv_dict_find(dict, (const char *)"maxcount", -1); - if (di != NULL) { - maxcount = (int)tv_get_number_chk(&di->di_tv, &error); - if (error) { - return; - } + } + di = tv_dict_find(dict, (const char *)"recompute", -1); + if (di != NULL) { + recompute = tv_get_number_chk(&di->di_tv, &error); + if (error) { + return; + } + } + di = tv_dict_find(dict, (const char *)"pattern", -1); + if (di != NULL) { + pattern = (char_u *)tv_get_string_chk(&di->di_tv); + if (pattern == NULL) { + return; + } + } + di = tv_dict_find(dict, (const char *)"pos", -1); + if (di != NULL) { + if (di->di_tv.v_type != VAR_LIST) { + EMSG2(_(e_invarg2), "pos"); + return; } - di = tv_dict_find(dict, (const char *)"recompute", -1); - if (di != NULL) { - recompute = tv_get_number_chk(&di->di_tv, &error); + if (tv_list_len(di->di_tv.vval.v_list) != 3) { + EMSG2(_(e_invarg2), "List format should be [lnum, col, off]"); + return; + } + li = tv_list_find(di->di_tv.vval.v_list, 0L); + if (li != NULL) { + pos.lnum = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); if (error) { return; } } - di = tv_dict_find(dict, (const char *)"pattern", -1); - if (di != NULL) { - pattern = (char_u *)tv_get_string_chk(&di->di_tv); - if (pattern == NULL) { + li = tv_list_find(di->di_tv.vval.v_list, 1L); + if (li != NULL) { + pos.col = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error) - 1; + if (error) { return; } } - di = tv_dict_find(dict, (const char *)"pos", -1); - if (di != NULL) { - if (di->di_tv.v_type != VAR_LIST) { - EMSG2(_(e_invarg2), "pos"); - return; - } - if (tv_list_len(di->di_tv.vval.v_list) != 3) { - EMSG2(_(e_invarg2), "List format should be [lnum, col, off]"); + li = tv_list_find(di->di_tv.vval.v_list, 2L); + if (li != NULL) { + pos.coladd = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); + if (error) { return; } - li = tv_list_find(di->di_tv.vval.v_list, 0L); - if (li != NULL) { - pos.lnum = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); - if (error) { - return; - } - } - li = tv_list_find(di->di_tv.vval.v_list, 1L); - if (li != NULL) { - pos.col = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error) - 1; - if (error) { - return; - } - } - li = tv_list_find(di->di_tv.vval.v_list, 2L); - if (li != NULL) { - pos.coladd = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); - if (error) { - return; - } - } } } + } - save_last_search_pattern(); - if (pattern != NULL) { - if (*pattern == NUL) { - goto the_end; - } - xfree(spats[last_idx].pat); - spats[last_idx].pat = vim_strsave(pattern); - } - if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) { - goto the_end; // the previous pattern was never defined + save_last_search_pattern(); + if (pattern != NULL) { + if (*pattern == NUL) { + goto the_end; } + xfree(spats[last_idx].pat); + spats[last_idx].pat = vim_strsave(pattern); + } + if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) { + goto the_end; // the previous pattern was never defined + } - update_search_stat(0, &pos, &pos, &stat, recompute, maxcount, timeout); + update_search_stat(0, &pos, &pos, &stat, recompute, maxcount, timeout); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("current"), stat.cur); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("total"), stat.cnt); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("exact_match"), stat.exact_match); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("incomplete"), stat.incomplete); - tv_dict_add_nr(rettv->vval.v_dict, S_LEN("maxcount"), stat.last_maxcount); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("current"), stat.cur); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("total"), stat.cnt); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("exact_match"), stat.exact_match); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("incomplete"), stat.incomplete); + tv_dict_add_nr(rettv->vval.v_dict, S_LEN("maxcount"), stat.last_maxcount); the_end: - restore_last_search_pattern(); + restore_last_search_pattern(); } -/* - * Find identifiers or defines in included files. - * If p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase. - */ -void -find_pattern_in_path( - char_u *ptr, // pointer to search pattern - Direction dir, // direction of expansion - size_t len, // length of search pattern - bool whole, // match whole words only - bool skip_comments, // don't match inside comments - int type, // Type of search; are we looking for a type? - // a macro? - long count, - int action, // What to do when we find it - linenr_T start_lnum, // first line to start searching - linenr_T end_lnum // last line for searching -) +/// Find identifiers or defines in included files. +/// If p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase. +/// +/// @param ptr pointer to search pattern +/// @param dir direction of expansion +/// @param len length of search pattern +/// @param whole match whole words only +/// @param skip_comments don't match inside comments +/// @param type Type of search; are we looking for a type? a macro? +/// @param action What to do when we find it +/// @param start_lnum first line to start searching +/// @param end_lnum last line for searching +void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bool skip_comments, + int type, long count, int action, linenr_T start_lnum, linenr_T end_lnum) { - SearchedFile *files; /* Stack of included files */ - SearchedFile *bigger; /* When we need more space */ + SearchedFile *files; // Stack of included files + SearchedFile *bigger; // When we need more space int max_path_depth = 50; long match_count = 1; - char_u *pat; - char_u *new_fname; - char_u *curr_fname = curbuf->b_fname; - char_u *prev_fname = NULL; + char_u *pat; + char_u *new_fname; + char_u *curr_fname = curbuf->b_fname; + char_u *prev_fname = NULL; linenr_T lnum; int depth; - int depth_displayed; /* For type==CHECK_PATH */ + int depth_displayed; // For type==CHECK_PATH int old_files; int already_searched; - char_u *file_line; - char_u *line; - char_u *p; + char_u *file_line; + char_u *line; + char_u *p; char_u save_char; bool define_matched; regmatch_T regmatch; @@ -4681,10 +4787,10 @@ find_pattern_in_path( bool did_show = false; bool found = false; int i; - char_u *already = NULL; - char_u *startp = NULL; - char_u *inc_opt = NULL; - win_T *curwin_save = NULL; + 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; regmatch.regprog = NULL; @@ -4696,41 +4802,45 @@ find_pattern_in_path( if (type != CHECK_PATH && type != FIND_DEFINE /* when CONT_SOL is set compare "ptr" with the beginning of the line * is faster than quote_meta/regcomp/regexec "ptr" -- Acevedo */ - && !(compl_cont_status & CONT_SOL) - ) { + && !(compl_cont_status & CONT_SOL)) { pat = xmalloc(len + 5); assert(len <= INT_MAX); sprintf((char *)pat, whole ? "\\<%.*s\\>" : "%.*s", (int)len, ptr); - /* ignore case according to p_ic, p_scs and pat */ + // ignore case according to p_ic, p_scs and pat regmatch.rm_ic = ignorecase(pat); regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); xfree(pat); - if (regmatch.regprog == NULL) + if (regmatch.regprog == NULL) { goto fpip_end; + } } inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc; if (*inc_opt != NUL) { incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0); - if (incl_regmatch.regprog == NULL) + if (incl_regmatch.regprog == NULL) { goto fpip_end; - incl_regmatch.rm_ic = FALSE; /* don't ignore case in incl. pat. */ + } + incl_regmatch.rm_ic = FALSE; // don't ignore case in incl. pat. } if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL)) { def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL ? p_def : curbuf->b_p_def, p_magic ? RE_MAGIC : 0); - if (def_regmatch.regprog == NULL) + if (def_regmatch.regprog == NULL) { goto fpip_end; - def_regmatch.rm_ic = FALSE; /* don't ignore case in define pat. */ + } + def_regmatch.rm_ic = FALSE; // don't ignore case in define pat. } files = xcalloc(max_path_depth, sizeof(SearchedFile)); old_files = max_path_depth; depth = depth_displayed = -1; lnum = start_lnum; - if (end_lnum > curbuf->b_ml.ml_line_count) + if (end_lnum > curbuf->b_ml.ml_line_count) { end_lnum = curbuf->b_ml.ml_line_count; - if (lnum > end_lnum) /* do at least one line */ + } + if (lnum > end_lnum) { // do at least one line lnum = end_lnum; + } line = ml_get(lnum); for (;; ) { @@ -4739,17 +4849,18 @@ find_pattern_in_path( char_u *p_fname = (curr_fname == curbuf->b_fname) ? curbuf->b_ffname : curr_fname; - if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) - /* Use text from '\zs' to '\ze' (or end) of 'include'. */ + if (inc_opt != NULL && strstr((char *)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); - else - /* Use text after match with 'include'. */ + } else { + // Use text after match with 'include'. new_fname = file_name_in_line(incl_regmatch.endp[0], 0, - FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); + FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); + } already_searched = FALSE; if (new_fname != NULL) { // Check whether we have already searched in this file @@ -4794,15 +4905,17 @@ find_pattern_in_path( did_show = true; while (depth_displayed < depth && !got_int) { ++depth_displayed; - for (i = 0; i < depth_displayed; i++) + for (i = 0; i < depth_displayed; i++) { MSG_PUTS(" "); + } msg_home_replace(files[depth_displayed].name); MSG_PUTS(" -->\n"); } if (!got_int) { /* don't display if 'q' typed for "--more--" message */ - for (i = 0; i <= depth_displayed; i++) + for (i = 0; i <= depth_displayed; i++) { MSG_PUTS(" "); + } if (new_fname != NULL) { /* using "new_fname" is more reliable, e.g., when * 'includeexpr' is set. */ @@ -4814,21 +4927,23 @@ find_pattern_in_path( */ if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) { - /* pattern contains \zs, use the match */ + // pattern contains \zs, use the match p = incl_regmatch.startp[0]; i = (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]); } else { - /* find the file name after the end of the match */ + // find the file name after the end of the match for (p = incl_regmatch.endp[0]; - *p && !vim_isfilec(*p); p++) + *p && !vim_isfilec(*p); p++) { ; - for (i = 0; vim_isfilec(p[i]); i++) + } + for (i = 0; vim_isfilec(p[i]); i++) { ; + } } if (i == 0) { - /* Nothing found, use the rest of the line. */ + // Nothing found, use the rest of the line. p = incl_regmatch.endp[0]; i = (int)STRLEN(p); } @@ -4839,8 +4954,9 @@ find_pattern_in_path( --p; ++i; } - if (p[i] == '"' || p[i] == '>') + if (p[i] == '"' || p[i] == '>') { ++i; + } } save_char = p[i]; p[i] = NUL; @@ -4849,29 +4965,32 @@ find_pattern_in_path( } if (new_fname == NULL && action == ACTION_SHOW_ALL) { - if (already_searched) + if (already_searched) { MSG_PUTS(_(" (Already listed)")); - else + } else { MSG_PUTS(_(" NOT FOUND")); + } } } - ui_flush(); /* output each line directly */ + ui_flush(); // output each line directly } if (new_fname != NULL) { - /* Push the new file onto the file stack */ + // Push the new file onto the file stack if (depth + 1 == old_files) { bigger = xmalloc(max_path_depth * 2 * sizeof(SearchedFile)); - for (i = 0; i <= depth; i++) + for (i = 0; i <= depth; i++) { bigger[i] = files[i]; + } for (i = depth + 1; i < old_files + max_path_depth; i++) { bigger[i].fp = NULL; bigger[i].name = NULL; bigger[i].lnum = 0; bigger[i].matched = FALSE; } - for (i = old_files; i < max_path_depth; i++) + for (i = old_files; i < max_path_depth; i++) { bigger[i + max_path_depth] = files[i]; + } old_files += max_path_depth; max_path_depth *= 2; xfree(files); @@ -4898,10 +5017,9 @@ find_pattern_in_path( } else if (p_verbose >= 5) { verbose_enter(); smsg(_("Searching included file %s"), - (char *)new_fname); + (char *)new_fname); verbose_leave(); } - } } } else { @@ -4919,8 +5037,9 @@ search_line: * don't let it match beyond the end of this identifier. */ p = def_regmatch.endp[0]; - while (*p && !vim_iswordc(*p)) + while (*p && !vim_iswordc(*p)) { p++; + } define_matched = true; } @@ -4930,18 +5049,18 @@ search_line: */ if (def_regmatch.regprog == NULL || define_matched) { if (define_matched - || (compl_cont_status & CONT_SOL) - ) { - /* compare the first "len" chars from "ptr" */ + || (compl_cont_status & CONT_SOL)) { + // compare the first "len" chars from "ptr" startp = skipwhite(p); if (p_ic) { matched = !mb_strnicmp(startp, ptr, len); - } - else + } else { matched = !STRNCMP(startp, ptr, len); + } if (matched && define_matched && whole - && vim_iswordc(startp[len])) + && vim_iswordc(startp[len])) { matched = false; + } } else if (regmatch.regprog != NULL && vim_regexec(®match, line, (colnr_T)(p - line))) { matched = true; @@ -4964,7 +5083,7 @@ search_line: */ p = skipwhite(line); if (matched - || (p[0] == '/' && p[1] == '*') || p[0] == '*') + || (p[0] == '/' && p[1] == '*') || p[0] == '*') { for (p = line; *p && p < startp; ++p) { if (matched && p[0] == '/' @@ -4981,6 +5100,7 @@ search_line: p++; } } + } } } } @@ -4988,35 +5108,39 @@ search_line: if (matched) { if (action == ACTION_EXPAND) { bool cont_s_ipos = false; - char_u *aux; + char_u *aux; - if (depth == -1 && lnum == curwin->w_cursor.lnum) + if (depth == -1 && lnum == curwin->w_cursor.lnum) { break; + } found = true; aux = p = startp; if (compl_cont_status & CONT_ADDING) { p += compl_length; - if (vim_iswordp(p)) + if (vim_iswordp(p)) { goto exit_matched; + } p = find_word_start(p); } p = find_word_end(p); i = (int)(p - aux); if ((compl_cont_status & CONT_ADDING) && i == compl_length) { - /* IOSIZE > compl_length, so the STRNCPY works */ + // IOSIZE > compl_length, so the STRNCPY works STRNCPY(IObuff, aux, i); /* Get the next line: when "depth" < 0 from the current * buffer, otherwise from the included file. Jump to * exit_matched when past the last line. */ if (depth < 0) { - if (lnum >= end_lnum) + if (lnum >= end_lnum) { goto exit_matched; + } line = ml_get(++lnum); } else if (vim_fgets(line = file_line, - LSIZE, files[depth].fp)) + LSIZE, files[depth].fp)) { goto exit_matched; + } /* we read a line, set "already" to check this "line" later * if depth >= 0 we'll increase files[depth].lnum far @@ -5026,9 +5150,10 @@ search_line: p = find_word_end(p); if (p > aux) { if (*aux != ')' && IObuff[i-1] != TAB) { - if (IObuff[i-1] != ' ') + if (IObuff[i-1] != ' ') { IObuff[i++] = ' '; - /* IObuf =~ "\(\k\|\i\).* ", thus i >= 2*/ + } + // IObuf =~ "\(\k\|\i\).* ", thus i >= 2 if (p_js && (IObuff[i-2] == '.' || IObuff[i-2] == '?' @@ -5036,9 +5161,10 @@ search_line: IObuff[i++] = ' '; } } - /* copy as much as possible of the new word */ - if (p - aux >= IOSIZE - i) + // copy as much as possible of the new word + if (p - aux >= IOSIZE - i) { p = aux + IOSIZE - i - 1; + } STRNCPY(IObuff + i, aux, p - aux); i += (int)(p - aux); cont_s_ipos = true; @@ -5046,13 +5172,14 @@ search_line: IObuff[i] = NUL; aux = IObuff; - if (i == compl_length) + if (i == compl_length) { goto exit_matched; + } } - const int add_r = ins_compl_add_infercase( - aux, i, p_ic, curr_fname == curbuf->b_fname ? NULL : curr_fname, - dir, cont_s_ipos); + const int add_r = ins_compl_add_infercase(aux, i, p_ic, + curr_fname == curbuf->b_fname ? NULL : curr_fname, + dir, cont_s_ipos); if (add_r == OK) { // if dir was BACKWARD then honor it just once dir = FORWARD; @@ -5065,11 +5192,13 @@ search_line: gotocmdline(true); // cursor at status line } if (curr_fname != prev_fname) { - if (did_show) - msg_putchar('\n'); /* cursor below last one */ - if (!got_int) /* don't display if 'q' typed + if (did_show) { + msg_putchar('\n'); // cursor below last one + } + if (!got_int) { /* don't display if 'q' typed at "--more--" message */ msg_home_replace_hl(curr_fname); + } prev_fname = curr_fname; } did_show = true; @@ -5082,8 +5211,9 @@ search_line: /* Set matched flag for this file and all the ones that * include it */ - for (i = 0; i <= depth; ++i) + for (i = 0; i <= depth; ++i) { files[i].matched = TRUE; + } } else if (--count <= 0) { found = true; if (depth == -1 && lnum == curwin->w_cursor.lnum @@ -5095,14 +5225,15 @@ search_line: (depth == -1) ? &lnum : &files[depth].lnum, 1L); did_show = true; } else { - /* ":psearch" uses the preview window */ + // ":psearch" uses the preview window if (l_g_do_tagpreview != 0) { curwin_save = curwin; prepare_tagpreview(true); } if (action == ACTION_SPLIT) { - if (win_split(0, 0) == FAIL) + if (win_split(0, 0) == FAIL) { break; + } RESET_BINDING(curwin); } if (depth == -1) { @@ -5134,7 +5265,7 @@ search_line: if (l_g_do_tagpreview != 0 && curwin != curwin_save && win_valid(curwin_save)) { - /* Return cursor to where we were */ + // Return cursor to where we were validate_cursor(); redraw_later(curwin, VALID); win_enter(curwin_save, true); @@ -5154,10 +5285,12 @@ exit_matched: } } line_breakcheck(); - if (action == ACTION_EXPAND) + if (action == ACTION_EXPAND) { ins_compl_check_keys(30, false); - if (got_int || compl_interrupted) + } + if (got_int || compl_interrupted) { break; + } /* * Read the next line. When reading an included file and encountering @@ -5172,55 +5305,62 @@ exit_matched: files[old_files].matched = files[depth].matched; --depth; curr_fname = (depth == -1) ? curbuf->b_fname - : files[depth].name; - if (depth < depth_displayed) + : files[depth].name; + if (depth < depth_displayed) { depth_displayed = depth; + } } - if (depth >= 0) { /* we could read the line */ + if (depth >= 0) { // we could read the line files[depth].lnum++; - /* Remove any CR and LF from the line. */ + // Remove any CR and LF from the line. i = (int)STRLEN(line); - if (i > 0 && line[i - 1] == '\n') + if (i > 0 && line[i - 1] == '\n') { line[--i] = NUL; - if (i > 0 && line[i - 1] == '\r') + } + if (i > 0 && line[i - 1] == '\r') { line[--i] = NUL; + } } else if (!already) { - if (++lnum > end_lnum) + if (++lnum > end_lnum) { break; + } line = ml_get(lnum); } already = NULL; } - /* End of big for (;;) loop. */ + // End of big for (;;) loop. - /* Close any files that are still open. */ + // Close any files that are still open. for (i = 0; i <= depth; i++) { fclose(files[i].fp); xfree(files[i].name); } - for (i = old_files; i < max_path_depth; i++) + for (i = old_files; i < max_path_depth; i++) { xfree(files[i].name); + } xfree(files); if (type == CHECK_PATH) { if (!did_show) { - if (action != ACTION_SHOW_ALL) + if (action != ACTION_SHOW_ALL) { MSG(_("All included files were found")); - else + } else { MSG(_("No included files")); + } } } else if (!found - && action != ACTION_EXPAND - ) { - if (got_int || compl_interrupted) + && action != ACTION_EXPAND) { + if (got_int || compl_interrupted) { EMSG(_(e_interr)); - else if (type == FIND_DEFINE) + } else if (type == FIND_DEFINE) { EMSG(_("E388: Couldn't find definition")); - else + } else { EMSG(_("E389: Couldn't find pattern")); + } } - if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) + if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) { msg_end(); + } fpip_end: xfree(file_line); @@ -5229,11 +5369,11 @@ fpip_end: vim_regfree(def_regmatch.regprog); } -static void show_pat_in_path(char_u *line, int type, bool did_show, int action, - FILE *fp, linenr_T *lnum, long count) +static void show_pat_in_path(char_u *line, int type, bool did_show, int action, FILE *fp, + linenr_T *lnum, long count) FUNC_ATTR_NONNULL_ARG(1, 6) { - char_u *p; + char_u *p; if (did_show) { msg_putchar('\n'); // cursor below last one @@ -5246,11 +5386,13 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, for (;; ) { p = line + STRLEN(line) - 1; if (fp != NULL) { - /* We used fgets(), so get rid of newline at end */ - if (p >= line && *p == '\n') + // We used fgets(), so get rid of newline at end + if (p >= line && *p == '\n') { --p; - if (p >= line && *p == '\r') + } + if (p >= line && *p == '\r') { --p; + } *(p + 1) = NUL; } if (action == ACTION_SHOW_ALL) { @@ -5262,19 +5404,22 @@ static void show_pat_in_path(char_u *line, int type, bool did_show, int action, msg_puts(" "); } msg_prt_line(line, FALSE); - ui_flush(); /* show one line at a time */ + 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 != '\\') + // Definition continues until line that doesn't end with '\' + if (got_int || type != FIND_DEFINE || p < line || *p != '\\') { break; + } if (fp != NULL) { - if (vim_fgets(line, LSIZE, fp)) /* end of file */ + if (vim_fgets(line, LSIZE, fp)) { // end of file break; + } ++*lnum; } else { - if (++*lnum > curbuf->b_ml.ml_line_count) + if (++*lnum > curbuf->b_ml.ml_line_count) { break; + } line = ml_get(*lnum); } msg_putchar('\n'); diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c index e5d4752760..77d2b21a7a 100644 --- a/src/nvim/syntax.c +++ b/src/nvim/syntax.c @@ -9,13 +9,12 @@ #include <ctype.h> #include <inttypes.h> #include <stdbool.h> -#include <string.h> #include <stdlib.h> +#include <string.h> -#include "nvim/vim.h" -#include "nvim/ascii.h" #include "nvim/api/private/helpers.h" -#include "nvim/syntax.h" +#include "nvim/ascii.h" +#include "nvim/buffer.h" #include "nvim/charset.h" #include "nvim/cursor_shape.h" #include "nvim/eval.h" @@ -23,30 +22,31 @@ #include "nvim/ex_docmd.h" #include "nvim/fileio.h" #include "nvim/fold.h" +#include "nvim/garray.h" #include "nvim/hashtab.h" #include "nvim/highlight.h" #include "nvim/indent_c.h" +#include "nvim/keymap.h" +#include "nvim/macros.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/keymap.h" -#include "nvim/garray.h" #include "nvim/option.h" +#include "nvim/os/os.h" +#include "nvim/os/time.h" #include "nvim/os_unix.h" #include "nvim/path.h" -#include "nvim/macros.h" #include "nvim/regexp.h" #include "nvim/screen.h" #include "nvim/sign.h" #include "nvim/strings.h" +#include "nvim/syntax.h" #include "nvim/syntax_defs.h" #include "nvim/terminal.h" #include "nvim/ui.h" -#include "nvim/os/os.h" -#include "nvim/os/time.h" -#include "nvim/buffer.h" +#include "nvim/vim.h" static bool did_syntax_onoff = false; @@ -54,8 +54,8 @@ static bool did_syntax_onoff = false; /// The ID of a highlight group is also called group ID. It is the index in /// the highlight_ga array PLUS ONE. typedef struct hl_group { - char_u *sg_name; ///< highlight group name - char *sg_name_u; ///< uppercase of sg_name + char_u *sg_name; ///< highlight group name + char *sg_name_u; ///< uppercase of sg_name bool sg_cleared; ///< "hi clear" was used int sg_attr; ///< Screen attr @see ATTR_ENTRY int sg_link; ///< link to this highlight group ID @@ -98,22 +98,22 @@ static inline struct hl_group * HL_TABLE(void) return ((struct hl_group *)((highlight_ga.ga_data))); } -#define MAX_HL_ID 20000 /* maximum value for a highlight ID. */ +#define MAX_HL_ID 20000 // maximum value for a highlight ID. -/* different types of offsets that are possible */ -#define SPO_MS_OFF 0 /* match start offset */ -#define SPO_ME_OFF 1 /* match end offset */ -#define SPO_HS_OFF 2 /* highl. start offset */ -#define SPO_HE_OFF 3 /* highl. end offset */ -#define SPO_RS_OFF 4 /* region start offset */ -#define SPO_RE_OFF 5 /* region end offset */ -#define SPO_LC_OFF 6 /* leading context offset */ +// different types of offsets that are possible +#define SPO_MS_OFF 0 // match start offset +#define SPO_ME_OFF 1 // match end offset +#define SPO_HS_OFF 2 // highl. start offset +#define SPO_HE_OFF 3 // highl. end offset +#define SPO_RS_OFF 4 // region start offset +#define SPO_RE_OFF 5 // region end offset +#define SPO_LC_OFF 6 // leading context offset #define SPO_COUNT 7 -/* Flags to indicate an additional string for highlight name completion. */ -static int include_none = 0; /* when 1 include "nvim/None" */ -static int include_default = 0; /* when 1 include "nvim/default" */ -static int include_link = 0; /* when 2 include "nvim/link" and "clear" */ +// Flags to indicate an additional string for highlight name completion. +static int include_none = 0; // when 1 include "nvim/None" +static int include_default = 0; // when 1 include "nvim/default" +static int include_link = 0; // when 2 include "nvim/link" and "clear" /// The "term", "cterm" and "gui" arguments can be any combination of the /// following names, separated by commas (but no spaces!). @@ -215,12 +215,12 @@ typedef struct { proftime_T slowest; proftime_T average; int id; - char_u *pattern; + char_u *pattern; } time_entry_T; struct name_list { int flag; - char *name; + char *name; }; #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -228,40 +228,40 @@ struct name_list { #endif static char *(spo_name_tab[SPO_COUNT]) = -{"ms=", "me=", "hs=", "he=", "rs=", "re=", "lc="}; +{ "ms=", "me=", "hs=", "he=", "rs=", "re=", "lc=" }; /* The sp_off_flags are computed like this: * offset from the start of the matched text: (1 << SPO_XX_OFF) - * offset from the end of the matched text: (1 << (SPO_XX_OFF + SPO_COUNT)) + * offset from the end of the matched text: (1 << (SPO_XX_OFF + SPO_COUNT)) * When both are present, only one is used. */ -#define SPTYPE_MATCH 1 /* match keyword with this group ID */ -#define SPTYPE_START 2 /* match a regexp, start of item */ -#define SPTYPE_END 3 /* match a regexp, end of item */ -#define SPTYPE_SKIP 4 /* match a regexp, skip within item */ +#define SPTYPE_MATCH 1 // match keyword with this group ID +#define SPTYPE_START 2 // match a regexp, start of item +#define SPTYPE_END 3 // match a regexp, end of item +#define SPTYPE_SKIP 4 // match a regexp, skip within item #define SYN_ITEMS(buf) ((synpat_T *)((buf)->b_syn_patterns.ga_data)) -#define NONE_IDX -2 /* value of sp_sync_idx for "NONE" */ +#define NONE_IDX -2 // value of sp_sync_idx for "NONE" /* * 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 */ +#define SF_CCOMMENT 0x01 // sync on a C-style comment +#define SF_MATCH 0x02 // sync by matching a pattern #define SYN_STATE_P(ssp) ((bufstate_T *)((ssp)->ga_data)) -#define MAXKEYWLEN 80 /* maximum length of a keyword */ +#define MAXKEYWLEN 80 // maximum length of a keyword /* * 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 */ +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 static int current_flags = 0; static int current_seqnr = 0; static int current_sub_char = 0; @@ -269,9 +269,9 @@ static int current_sub_char = 0; /* * 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 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)) @@ -283,12 +283,12 @@ static int current_sub_char = 0; * 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 */ -#define SYNID_CLUSTER 23000 /* first syntax group ID for clusters */ +#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 +#define SYNID_CLUSTER 23000 // first syntax group ID for clusters -#define MAX_SYN_INC_TAG 999 /* maximum before the above overflow */ +#define MAX_SYN_INC_TAG 999 // maximum before the above overflow #define MAX_CLUSTER_ID (32767 - SYNID_CLUSTER) /* @@ -334,7 +334,7 @@ static char msg_no_items[] = N_("No Syntax items defined for this buffer"); // valid of si_cont_list for containing all but contained groups #define ID_LIST_ALL (int16_t *)-1 -static int next_seqnr = 1; /* value to use for si_seqnr */ +static int next_seqnr = 1; // value to use for si_seqnr /* * The next possible match in the current line for any pattern is remembered, @@ -343,15 +343,15 @@ static int next_seqnr = 1; /* value to use for si_seqnr */ * 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 */ -static lpos_T next_match_h_endpos; /* pos. for highl. end of next match */ -static int next_match_idx; /* index of matched item */ -static long next_match_flags; /* flags for next match */ -static lpos_T next_match_eos_pos; /* end of start pattn (start region) */ -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 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 +static lpos_T next_match_h_endpos; // pos. for highl. end of next match +static int next_match_idx; // index of matched item +static long next_match_flags; // flags for next match +static lpos_T next_match_eos_pos; // end of start pattn (start region) +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; /* @@ -365,8 +365,8 @@ static reg_extmatch_T *next_match_extmatch = NULL; * 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 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 static proftime_T *syn_tm; // timeout limit static linenr_T current_lnum = 0; // lnum of current state @@ -396,19 +396,19 @@ void syn_set_timeout(proftime_T *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 + * 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; - synstate_T *last_valid = NULL; - synstate_T *last_min_valid = NULL; - synstate_T *sp, *prev = NULL; + synstate_T *p; + synstate_T *last_valid = NULL; + synstate_T *last_min_valid = NULL; + synstate_T *sp, *prev = NULL; linenr_T parsed_lnum; linenr_T first_stored; int dist; - static int changedtick = 0; /* remember the last change ID */ + static int changedtick = 0; // remember the last change ID current_sub_char = NUL; @@ -431,8 +431,9 @@ void syntax_start(win_T *wp, linenr_T lnum) * Allocate syntax stack when needed. */ syn_stack_alloc(); - if (syn_block->b_sst_array == NULL) - return; /* out of memory */ + if (syn_block->b_sst_array == NULL) { + return; // out of memory + } syn_block->b_sst_lasttick = display_tick; /* @@ -452,29 +453,33 @@ void syntax_start(win_T *wp, linenr_T lnum) * state (this happens very often!). Otherwise invalidate * current_state and figure it out below. */ - if (current_lnum != lnum) + if (current_lnum != lnum) { invalidate_current_state(); - } else + } + } else { 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. */ if (INVALID_STATE(¤t_state) && syn_block->b_sst_array != NULL) { - /* Find last valid saved state before start_lnum. */ + // Find last valid saved state before start_lnum. for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) { if (p->sst_lnum > lnum) { break; } if (p->sst_change_lnum == 0) { last_valid = p; - if (p->sst_lnum >= lnum - syn_block->b_syn_sync_minlines) + if (p->sst_lnum >= lnum - syn_block->b_syn_sync_minlines) { last_min_valid = p; + } } } - if (last_min_valid != NULL) + if (last_min_valid != NULL) { load_current_state(last_min_valid); + } } /* @@ -483,24 +488,27 @@ void syntax_start(win_T *wp, linenr_T lnum) */ if (INVALID_STATE(¤t_state)) { syn_sync(wp, lnum, last_valid); - if (current_lnum == 1) - /* First line is always valid, no matter "minlines". */ + if (current_lnum == 1) { + // First line is always valid, no matter "minlines". first_stored = 1; - else + } else { /* Need to parse "minlines" lines before state can be considered * valid to store. */ first_stored = current_lnum + syn_block->b_syn_sync_minlines; - } else + } + } else { first_stored = current_lnum; + } /* * 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) + if (syn_block->b_sst_len <= Rows) { dist = 999999; - else + } else { dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1; + } while (current_lnum < lnum) { syn_start_line(); (void)syn_finish_line(false); @@ -512,26 +520,30 @@ void syntax_start(win_T *wp, linenr_T lnum) /* Check if the saved state entry is for the current line and is * equal to the current state. If so, then validate all saved * states that depended on a change before the parsed line. */ - if (prev == NULL) + if (prev == NULL) { prev = syn_stack_find_entry(current_lnum - 1); - if (prev == NULL) + } + if (prev == NULL) { sp = syn_block->b_sst_first; - else + } else { sp = prev; - while (sp != NULL && sp->sst_lnum < current_lnum) + } + while (sp != NULL && sp->sst_lnum < current_lnum) { sp = sp->sst_next; + } if (sp != NULL && sp->sst_lnum == current_lnum && syn_stack_equal(sp)) { parsed_lnum = current_lnum; prev = sp; while (sp != NULL && sp->sst_change_lnum <= parsed_lnum) { - if (sp->sst_lnum <= lnum) - /* valid state before desired line, use this one */ + if (sp->sst_lnum <= lnum) { + // valid state before desired line, use this one prev = sp; - else if (sp->sst_change_lnum == 0) - /* past saved states depending on change, break here. */ + } else if (sp->sst_change_lnum == 0) { + // past saved states depending on change, break here. break; + } sp->sst_change_lnum = 0; sp = sp->sst_next; } @@ -542,8 +554,9 @@ void syntax_start(win_T *wp, linenr_T lnum) * saved state. But only when parsed at least 'minlines'. */ else if (prev == NULL || current_lnum == lnum - || current_lnum >= prev->sst_lnum + dist) + || current_lnum >= prev->sst_lnum + dist) { prev = store_current_state(); + } } /* This can take a long time: break when CTRL-C pressed. The current @@ -594,8 +607,8 @@ static void clear_current_state(void) */ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) { - buf_T *curbuf_save; - win_T *curwin_save; + buf_T *curbuf_save; + win_T *curwin_save; pos_T cursor_save; int idx; linenr_T lnum; @@ -603,8 +616,8 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) linenr_T break_lnum; bool had_sync_point; stateitem_T *cur_si; - synpat_T *spp; - char_u *line; + synpat_T *spp; + char_u *line; int found_flags = 0; int found_match_idx = 0; linenr_T found_current_lnum = 0; @@ -625,22 +638,25 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) * 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) + if (syn_block->b_syn_sync_minlines > start_lnum) { start_lnum = 1; - else { - if (syn_block->b_syn_sync_minlines == 1) + } else { + if (syn_block->b_syn_sync_minlines == 1) { lnum = 1; - else if (syn_block->b_syn_sync_minlines < 10) + } else if (syn_block->b_syn_sync_minlines < 10) { lnum = syn_block->b_syn_sync_minlines * 2; - else + } else { lnum = syn_block->b_syn_sync_minlines * 3 / 2; + } if (syn_block->b_syn_sync_maxlines != 0 - && lnum > syn_block->b_syn_sync_maxlines) + && lnum > syn_block->b_syn_sync_maxlines) { lnum = syn_block->b_syn_sync_maxlines; - if (lnum >= start_lnum) + } + if (lnum >= start_lnum) { start_lnum = 1; - else + } else { start_lnum -= lnum; + } } current_lnum = start_lnum; @@ -660,12 +676,13 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) */ for (; start_lnum > 1; --start_lnum) { line = ml_get(start_lnum - 1); - if (*line == NUL || *(line + STRLEN(line) - 1) != '\\') + if (*line == NUL || *(line + STRLEN(line) - 1) != '\\') { break; + } } current_lnum = start_lnum; - /* set cursor to start of search */ + // set cursor to start of search cursor_save = wp->w_cursor; wp->w_cursor.lnum = start_lnum; wp->w_cursor.col = 0; @@ -676,7 +693,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) * 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; ) + for (idx = syn_block->b_syn_patterns.ga_len; --idx >= 0; ) { if (SYN_ITEMS(syn_block)[idx].sp_syn.id == syn_block->b_syn_sync_id && SYN_ITEMS(syn_block)[idx].sp_type == SPTYPE_START) { @@ -685,9 +702,10 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) update_si_attr(current_state.ga_len - 1); break; } + } } - /* restore cursor and buffer */ + // restore cursor and buffer wp->w_cursor = cursor_save; curwin = curwin_save; curbuf = curbuf_save; @@ -697,17 +715,18 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) */ else if (syn_block->b_syn_sync_flags & SF_MATCH) { if (syn_block->b_syn_sync_maxlines != 0 - && start_lnum > syn_block->b_syn_sync_maxlines) + && start_lnum > syn_block->b_syn_sync_maxlines) { break_lnum = start_lnum - syn_block->b_syn_sync_maxlines; - else + } else { break_lnum = 0; + } found_m_endpos.lnum = 0; found_m_endpos.col = 0; end_lnum = start_lnum; lnum = start_lnum; while (--lnum > break_lnum) { - /* This can take a long time: break when CTRL-C pressed. */ + // This can take a long time: break when CTRL-C pressed. line_breakcheck(); if (got_int) { invalidate_current_state(); @@ -715,7 +734,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) break; } - /* Check if we have run into a valid saved state stack now. */ + // Check if we have run into a valid saved state stack now. if (last_valid != NULL && lnum == last_valid->sst_lnum) { load_current_state(last_valid); break; @@ -724,8 +743,9 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) /* * Check if the previous line has the line-continuation pattern. */ - if (lnum > 1 && syn_match_linecont(lnum - 1)) + if (lnum > 1 && syn_match_linecont(lnum - 1)) { continue; + } /* * Start with nothing on the state stack @@ -741,12 +761,12 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) if (had_sync_point && current_state.ga_len) { cur_si = &CUR_STATE(current_state.ga_len - 1); if (cur_si->si_m_endpos.lnum > start_lnum) { - /* ignore match that goes to after where started */ + // ignore match that goes to after where started current_lnum = end_lnum; break; } if (cur_si->si_idx < 0) { - /* Cannot happen? */ + // Cannot happen? found_flags = 0; found_match_idx = KEYWORD_IDX; } else { @@ -764,23 +784,27 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) if (found_m_endpos.lnum > current_lnum) { current_lnum = found_m_endpos.lnum; current_col = found_m_endpos.col; - if (current_lnum >= end_lnum) + if (current_lnum >= end_lnum) { break; - } else if (found_m_endpos.col > current_col) + } + } else if (found_m_endpos.col > current_col) { current_col = found_m_endpos.col; - else + } else { ++current_col; + } /* syn_current_attr() will have skipped the check for * an item that ends here, need to do that now. Be * careful not to go past the NUL. */ prev_current_col = current_col; - if (syn_getcurline()[current_col] != NUL) + if (syn_getcurline()[current_col] != NUL) { ++current_col; + } check_state_ends(); current_col = prev_current_col; - } else + } else { break; + } } } @@ -828,7 +852,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid) invalidate_current_state(); } - /* Ran into start of the file or exceeded maximum number of lines */ + // Ran into start of the file or exceeded maximum number of lines if (lnum <= break_lnum) { invalidate_current_state(); current_lnum = break_lnum + 1; @@ -934,10 +958,13 @@ static void syn_update_ends(bool startofline) * Then check for items ending in column 0. */ int i = current_state.ga_len - 1; - if (keepend_level >= 0) - for (; i > keepend_level; --i) - if (CUR_STATE(i).si_flags & HL_EXTEND) + if (keepend_level >= 0) { + for (; i > keepend_level; --i) { + if (CUR_STATE(i).si_flags & HL_EXTEND) { break; + } + } + } bool seen_keepend = false; for (; i < current_state.ga_len; i++) { @@ -945,11 +972,12 @@ static void syn_update_ends(bool startofline) if ((cur_si->si_flags & HL_KEEPEND) || (seen_keepend && !startofline) || (i == current_state.ga_len - 1 && startofline)) { - cur_si->si_h_startpos.col = 0; /* start highl. in col 0 */ + cur_si->si_h_startpos.col = 0; // start highl. in col 0 cur_si->si_h_startpos.lnum = current_lnum; - if (!(cur_si->si_flags & HL_MATCHCONT)) + if (!(cur_si->si_flags & HL_MATCHCONT)) { update_si_end(cur_si, (int)current_col, !startofline); + } if (!startofline && (cur_si->si_flags & HL_KEEPEND)) { seen_keepend = true; @@ -997,7 +1025,7 @@ static void syn_update_ends(bool startofline) static void syn_stack_free_block(synblock_T *block) { - synstate_T *p; + synstate_T *p; if (block->b_sst_array != NULL) { for (p = block->b_sst_first; p != NULL; p = p->sst_next) { @@ -1016,7 +1044,7 @@ void syn_stack_free_all(synblock_T *block) { syn_stack_free_block(block); - /* When using "syntax" fold method, must update all folds. */ + // When using "syntax" fold method, must update all folds. FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { if (wp->w_s == block && foldmethodIsSyntax(wp)) { foldUpdateAll(wp); @@ -1033,31 +1061,35 @@ void syn_stack_free_all(synblock_T *block) static void syn_stack_alloc(void) { long len; - synstate_T *to, *from; - synstate_T *sstp; + synstate_T *to, *from; + synstate_T *sstp; len = syn_buf->b_ml.ml_line_count / SST_DIST + Rows * 2; - if (len < SST_MIN_ENTRIES) + if (len < SST_MIN_ENTRIES) { len = SST_MIN_ENTRIES; - else if (len > SST_MAX_ENTRIES) + } else if (len > SST_MAX_ENTRIES) { len = SST_MAX_ENTRIES; + } if (syn_block->b_sst_len > len * 2 || syn_block->b_sst_len < len) { - /* Allocate 50% too much, to avoid reallocating too often. */ + // Allocate 50% too much, to avoid reallocating too often. len = syn_buf->b_ml.ml_line_count; len = (len + len / 2) / SST_DIST + Rows * 2; - if (len < SST_MIN_ENTRIES) + if (len < SST_MIN_ENTRIES) { len = SST_MIN_ENTRIES; - else if (len > SST_MAX_ENTRIES) + } else if (len > SST_MAX_ENTRIES) { len = SST_MAX_ENTRIES; + } if (syn_block->b_sst_array != NULL) { /* When shrinking the array, cleanup the existing stack. * Make sure that all valid entries fit in the new array. */ while (syn_block->b_sst_len - syn_block->b_sst_freecount + 2 > len - && syn_stack_cleanup()) + && syn_stack_cleanup()) { ; - if (len < syn_block->b_sst_len - syn_block->b_sst_freecount + 2) + } + if (len < syn_block->b_sst_len - syn_block->b_sst_freecount + 2) { len = syn_block->b_sst_len - syn_block->b_sst_freecount + 2; + } } assert(len >= 0); @@ -1065,7 +1097,7 @@ static void syn_stack_alloc(void) to = sstp - 1; if (syn_block->b_sst_array != NULL) { - /* Move the states from the old array to the new one. */ + // Move the states from the old array to the new one. for (from = syn_block->b_sst_first; from != NULL; from = from->sst_next) { ++to; @@ -1082,10 +1114,11 @@ static void syn_stack_alloc(void) syn_block->b_sst_freecount = len; } - /* Create the list of free entries. */ + // Create the list of free entries. syn_block->b_sst_firstfree = to + 1; - while (++to < sstp + len) + while (++to < sstp + len) { to->sst_next = to + 1; + } (sstp + len - 1)->sst_next = NULL; xfree(syn_block->b_sst_array); @@ -1113,7 +1146,7 @@ void syn_stack_apply_changes(buf_T *buf) static void syn_stack_apply_changes_block(synblock_T *block, buf_T *buf) { - synstate_T *p, *prev, *np; + synstate_T *p, *prev, *np; linenr_T n; prev = NULL; @@ -1121,12 +1154,13 @@ static void syn_stack_apply_changes_block(synblock_T *block, buf_T *buf) if (p->sst_lnum + block->b_syn_sync_linebreaks > buf->b_mod_top) { n = p->sst_lnum + buf->b_mod_xlines; if (n <= buf->b_mod_bot) { - /* this state is inside the changed area, remove it */ + // this state is inside the changed area, remove it np = p->sst_next; - if (prev == NULL) + if (prev == NULL) { block->b_sst_first = np; - else + } else { prev->sst_next = np; + } syn_stack_free_entry(block, p); p = np; continue; @@ -1135,14 +1169,16 @@ static void syn_stack_apply_changes_block(synblock_T *block, buf_T *buf) * that needs to be parsed before this entry can be made valid * again. */ if (p->sst_change_lnum != 0 && p->sst_change_lnum > buf->b_mod_top) { - if (p->sst_change_lnum + buf->b_mod_xlines > buf->b_mod_top) + if (p->sst_change_lnum + buf->b_mod_xlines > buf->b_mod_top) { p->sst_change_lnum += buf->b_mod_xlines; - else + } else { p->sst_change_lnum = buf->b_mod_top; + } } if (p->sst_change_lnum == 0 - || p->sst_change_lnum < buf->b_mod_bot) + || p->sst_change_lnum < buf->b_mod_bot) { p->sst_change_lnum = buf->b_mod_bot; + } p->sst_lnum = n; } @@ -1156,7 +1192,7 @@ static void syn_stack_apply_changes_block(synblock_T *block, buf_T *buf) /// @return true if at least one entry was freed. static bool syn_stack_cleanup(void) { - synstate_T *p, *prev; + synstate_T *p, *prev; disptick_T tick; int dist; bool retval = false; @@ -1165,11 +1201,12 @@ static bool syn_stack_cleanup(void) return retval; } - /* Compute normal distance between non-displayed entries. */ - if (syn_block->b_sst_len <= Rows) + // Compute normal distance between non-displayed entries. + if (syn_block->b_sst_len <= Rows) { dist = 999999; - else + } else { 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 @@ -1182,8 +1219,9 @@ static bool syn_stack_cleanup(void) for (p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) { if (prev->sst_lnum + dist > p->sst_lnum) { if (p->sst_tick > syn_block->b_sst_lasttick) { - if (!above || p->sst_tick < tick) + if (!above || p->sst_tick < tick) { tick = p->sst_tick; + } above = true; } else if (!above && p->sst_tick < tick) { tick = p->sst_tick; @@ -1198,7 +1236,7 @@ static bool syn_stack_cleanup(void) 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) { - /* Move this entry from used list to free list */ + // Move this entry from used list to free list prev->sst_next = p->sst_next; syn_stack_free_entry(syn_block, p); p = prev; @@ -1226,14 +1264,16 @@ static void syn_stack_free_entry(synblock_T *block, synstate_T *p) */ static synstate_T *syn_stack_find_entry(linenr_T lnum) { - synstate_T *p, *prev; + synstate_T *p, *prev; prev = NULL; for (p = syn_block->b_sst_first; p != NULL; prev = p, p = p->sst_next) { - if (p->sst_lnum == lnum) + if (p->sst_lnum == lnum) { return p; - if (p->sst_lnum > lnum) + } + if (p->sst_lnum > lnum) { break; + } } return prev; } @@ -1245,10 +1285,10 @@ static synstate_T *syn_stack_find_entry(linenr_T lnum) static synstate_T *store_current_state(void) { int i; - synstate_T *p; - bufstate_T *bp; + synstate_T *p; + bufstate_T *bp; stateitem_T *cur_si; - synstate_T *sp = syn_stack_find_entry(current_lnum); + synstate_T *sp = syn_stack_find_entry(current_lnum); /* * If the current state contains a start or end pattern that continues @@ -1260,51 +1300,55 @@ static synstate_T *store_current_state(void) || cur_si->si_m_endpos.lnum >= current_lnum || cur_si->si_h_endpos.lnum >= current_lnum || (cur_si->si_end_idx - && cur_si->si_eoe_pos.lnum >= current_lnum)) + && cur_si->si_eoe_pos.lnum >= current_lnum)) { break; + } } if (i >= 0) { if (sp != NULL) { - /* find "sp" in the list and remove it */ - if (syn_block->b_sst_first == sp) - /* it's the first entry */ + // find "sp" in the list and remove it + if (syn_block->b_sst_first == sp) { + // it's the first entry syn_block->b_sst_first = sp->sst_next; - else { - /* find the entry just before this one to adjust sst_next */ - for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) - if (p->sst_next == sp) + } else { + // find the entry just before this one to adjust sst_next + for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) { + if (p->sst_next == sp) { break; - if (p != NULL) /* just in case */ + } + } + if (p != NULL) { // just in case p->sst_next = sp->sst_next; + } } syn_stack_free_entry(syn_block, sp); sp = NULL; } - } else if (sp == NULL || sp->sst_lnum != current_lnum) { + } else if (sp == NULL || sp->sst_lnum != current_lnum) { /* * Add a new entry */ - /* If no free items, cleanup the array first. */ + // If no free items, cleanup the array first. if (syn_block->b_sst_freecount == 0) { (void)syn_stack_cleanup(); - /* "sp" may have been moved to the freelist now */ + // "sp" may have been moved to the freelist now sp = syn_stack_find_entry(current_lnum); } - /* Still no free items? Must be a strange problem... */ - if (syn_block->b_sst_freecount == 0) + // Still no free items? Must be a strange problem... + if (syn_block->b_sst_freecount == 0) { sp = NULL; - else { + } else { /* Take the first item from the free list and put it in the used * list, after *sp */ p = syn_block->b_sst_firstfree; syn_block->b_sst_firstfree = p->sst_next; --syn_block->b_sst_freecount; if (sp == NULL) { - /* Insert in front of the list */ + // Insert in front of the list p->sst_next = syn_block->b_sst_first; syn_block->b_sst_first = p; } else { - /* insert in list after *sp */ + // insert in list after *sp p->sst_next = sp->sst_next; sp->sst_next = p; } @@ -1314,7 +1358,7 @@ static synstate_T *store_current_state(void) } } if (sp != NULL) { - /* When overwriting an existing state stack, clear it first */ + // When overwriting an existing state stack, clear it first clear_syn_state(sp); sp->sst_stacksize = current_state.ga_len; if (current_state.ga_len > SST_FIX_STATES) { @@ -1324,8 +1368,9 @@ static synstate_T *store_current_state(void) ga_grow(&sp->sst_union.sst_ga, current_state.ga_len); sp->sst_union.sst_ga.ga_len = current_state.ga_len; bp = SYN_STATE_P(&(sp->sst_union.sst_ga)); - } else + } else { bp = sp->sst_union.sst_stack; + } for (i = 0; i < sp->sst_stacksize; ++i) { bp[i].bs_idx = CUR_STATE(i).si_idx; bp[i].bs_flags = CUR_STATE(i).si_flags; @@ -1348,32 +1393,35 @@ static synstate_T *store_current_state(void) static void load_current_state(synstate_T *from) { int i; - bufstate_T *bp; + bufstate_T *bp; clear_current_state(); validate_current_state(); keepend_level = -1; if (from->sst_stacksize) { ga_grow(¤t_state, from->sst_stacksize); - if (from->sst_stacksize > SST_FIX_STATES) + if (from->sst_stacksize > SST_FIX_STATES) { bp = SYN_STATE_P(&(from->sst_union.sst_ga)); - else + } else { bp = from->sst_union.sst_stack; + } for (i = 0; i < from->sst_stacksize; ++i) { CUR_STATE(i).si_idx = bp[i].bs_idx; CUR_STATE(i).si_flags = bp[i].bs_flags; CUR_STATE(i).si_seqnr = bp[i].bs_seqnr; CUR_STATE(i).si_cchar = bp[i].bs_cchar; CUR_STATE(i).si_extmatch = ref_extmatch(bp[i].bs_extmatch); - if (keepend_level < 0 && (CUR_STATE(i).si_flags & HL_KEEPEND)) + if (keepend_level < 0 && (CUR_STATE(i).si_flags & HL_KEEPEND)) { keepend_level = i; + } CUR_STATE(i).si_ends = FALSE; CUR_STATE(i).si_m_lnum = 0; - if (CUR_STATE(i).si_idx >= 0) + if (CUR_STATE(i).si_idx >= 0) { CUR_STATE(i).si_next_list = (SYN_ITEMS(syn_block)[CUR_STATE(i).si_idx]).sp_next_list; - else + } else { CUR_STATE(i).si_next_list = NULL; + } update_si_attr(i); } current_state.ga_len = from->sst_stacksize; @@ -1388,26 +1436,28 @@ static void load_current_state(synstate_T *from) /// @return true when they are equal. static bool syn_stack_equal(synstate_T *sp) { - bufstate_T *bp; - reg_extmatch_T *six, *bsx; + bufstate_T *bp; + reg_extmatch_T *six, *bsx; - /* First a quick check if the stacks have the same size end nextlist. */ + // First a quick check if the stacks have the same size end nextlist. if (sp->sst_stacksize != current_state.ga_len || sp->sst_next_list != current_next_list) { return false; } - /* Need to compare all states on both stacks. */ - if (sp->sst_stacksize > SST_FIX_STATES) + // Need to compare all states on both stacks. + if (sp->sst_stacksize > SST_FIX_STATES) { bp = SYN_STATE_P(&(sp->sst_union.sst_ga)); - else + } else { bp = sp->sst_union.sst_stack; + } int i; for (i = current_state.ga_len; --i >= 0; ) { - /* If the item has another index the state is different. */ - if (bp[i].bs_idx != CUR_STATE(i).si_idx) + // If the item has another index the state is different. + if (bp[i].bs_idx != CUR_STATE(i).si_idx) { break; + } if (bp[i].bs_extmatch == CUR_STATE(i).si_extmatch) { continue; } @@ -1418,8 +1468,9 @@ static bool syn_stack_equal(synstate_T *sp) six = CUR_STATE(i).si_extmatch; /* If one of the extmatch pointers is NULL the states are * different. */ - if (bsx == NULL || six == NULL) + if (bsx == NULL || six == NULL) { break; + } int j; for (j = 0; j < NSUBEXP; ++j) { /* Check each referenced match string. They must all be @@ -1438,8 +1489,9 @@ static bool syn_stack_equal(synstate_T *sp) } } } - if (j != NSUBEXP) + if (j != NSUBEXP) { break; + } } if (i < 0) { return true; @@ -1453,21 +1505,23 @@ static bool syn_stack_equal(synstate_T *sp) * 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 + * line which changed + * displayed line + * displayed line * lnum -> line below window */ void syntax_end_parsing(linenr_T lnum) { - synstate_T *sp; + synstate_T *sp; sp = syn_stack_find_entry(lnum); - if (sp != NULL && sp->sst_lnum < lnum) + if (sp != NULL && sp->sst_lnum < lnum) { sp = sp->sst_next; + } - if (sp != NULL && sp->sst_change_lnum != 0) + if (sp != NULL && sp->sst_change_lnum != 0) { sp->sst_change_lnum = lnum; + } } /* @@ -1477,7 +1531,7 @@ void syntax_end_parsing(linenr_T lnum) static void invalidate_current_state(void) { clear_current_state(); - current_state.ga_itemsize = 0; /* mark current_state invalid */ + current_state.ga_itemsize = 0; // mark current_state invalid current_next_list = NULL; keepend_level = -1; } @@ -1495,7 +1549,7 @@ static void validate_current_state(void) bool syntax_check_changed(linenr_T lnum) { bool retval = true; - synstate_T *sp; + synstate_T *sp; /* * Check the state stack when: @@ -1532,16 +1586,13 @@ bool syntax_check_changed(linenr_T lnum) return retval; } -/* - * Finish the current line. - * This doesn't return any attributes, it only gets the state at the end of - * the line. It can start anywhere in the line, as long as the current state - * is valid. - */ -static bool -syn_finish_line( - const bool syncing // called for syncing -) +/// Finish the current line. +/// This doesn't return any attributes, it only gets the state at the end of +/// the line. It can start anywhere in the line, as long as the current state +/// is valid. +/// +/// @param syncing called for syncing +static bool syn_finish_line(const bool syncing) { while (!current_finished) { (void)syn_current_attr(syncing, false, NULL, false); @@ -1571,36 +1622,35 @@ syn_finish_line( return false; } -/* - * Return highlight attributes for next character. - * Must first call syntax_start() once for the line. - * "col" is normally 0 for the first use in a line, and increments by one each - * time. It's allowed to skip characters and to stop before the end of the - * line. But only a "col" after a previously used column is allowed. - * When "can_spell" is not NULL set it to TRUE when spell-checking should be - * done. - */ -int -get_syntax_attr( - const colnr_T col, - bool *const can_spell, - const bool keep_state // keep state of char at "col" -) +/// Gets highlight attributes for next character. +/// Must first call syntax_start() once for the line. +/// "col" is normally 0 for the first use in a line, and increments by one each +/// time. It's allowed to skip characters and to stop before the end of the +/// line. But only a "col" after a previously used column is allowed. +/// When "can_spell" is not NULL set it to TRUE when spell-checking should be +/// done. +/// +/// @param keep_state keep state of char at "col" +/// +/// @return highlight attributes for next character. +int get_syntax_attr(const colnr_T col, bool *const can_spell, const bool keep_state) { int attr = 0; - if (can_spell != NULL) + if (can_spell != NULL) { /* Default: Only do spelling when there is no @Spell cluster or when * ":syn spell toplevel" was used. */ *can_spell = syn_block->b_syn_spell == SYNSPL_DEFAULT ? (syn_block->b_spell_cluster_id == 0) : (syn_block->b_syn_spell == SYNSPL_TOP); + } - /* check for out of memory situation */ - if (syn_block->b_sst_array == NULL) + // check for out of memory situation + if (syn_block->b_sst_array == NULL) { return 0; + } - /* After 'synmaxcol' the attribute is always zero. */ + // After 'synmaxcol' the attribute is always zero. if (syn_buf->b_p_smc > 0 && col >= (colnr_T)syn_buf->b_p_smc) { clear_current_state(); current_id = 0; @@ -1610,9 +1660,10 @@ get_syntax_attr( return 0; } - /* Make sure current_state is valid */ - if (INVALID_STATE(¤t_state)) + // Make sure current_state is valid + if (INVALID_STATE(¤t_state)) { validate_current_state(); + } /* * Skip from the current column to "col", get the attributes for "col". @@ -1626,15 +1677,14 @@ get_syntax_attr( return attr; } -/* - * Get syntax attributes for current_lnum, current_col. - */ -static int syn_current_attr( - const bool syncing, // When true: called for syncing - const bool displaying, // result will be displayed - bool *const can_spell, // return: do spell checking - const bool keep_state // keep syntax stack afterwards -) +/// Get syntax attributes for current_lnum, current_col. +/// +/// @param syncing When true: called for syncing +/// @param displaying result will be displayed +/// @param can_spell return: do spell checking +/// @param keep_state keep syntax stack afterwards +static int syn_current_attr(const bool syncing, const bool displaying, bool *const can_spell, + const bool keep_state) { lpos_T endpos; // was: char_u *endp; lpos_T hl_startpos; // was: int hl_startcol; @@ -1654,8 +1704,8 @@ static int syn_current_attr( lpos_T pos; reg_extmatch_T *cur_extmatch = NULL; char_u buf_chartab[32]; // chartab array for syn iskeyword - char_u *line; // current line. NOTE: becomes invalid after - // looking for a pattern match! + char_u *line; // current line. NOTE: becomes invalid after + // looking for a pattern match! // variables for zero-width matches that have a "nextgroup" argument bool keep_next_list; @@ -1681,7 +1731,7 @@ static int syn_current_attr( return 0; } - /* if the current or next character is NUL, we will finish the line now */ + // if the current or next character is NUL, we will finish the line now if (line[current_col] == NUL || line[current_col + 1] == NUL) { current_finished = true; current_state_stored = false; @@ -1699,8 +1749,8 @@ static int syn_current_attr( // Only check for keywords when not syncing and there are some. const bool do_keywords = !syncing - && (syn_block->b_keywtab.ht_used > 0 - || syn_block->b_keywtab_ic.ht_used > 0); + && (syn_block->b_keywtab.ht_used > 0 + || syn_block->b_keywtab_ic.ht_used > 0); /* Init the list of zero-width matches with a nextlist. This is used to * avoid matching the same item in the same position twice. */ @@ -1726,23 +1776,25 @@ static int syn_current_attr( * Always need to check for contained items if some item has the * "containedin" argument (takes extra time!). */ - if (current_state.ga_len) + if (current_state.ga_len) { cur_si = &CUR_STATE(current_state.ga_len - 1); - else + } else { cur_si = NULL; + } 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. + * char. Don't do this when syncing. */ if (do_keywords) { line = syn_getcurline(); 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), syn_buf))) { + && (current_col == 0 || + !vim_iswordp_buf(cur_pos - 1 - utf_head_off(line, cur_pos - 1), + syn_buf))) { syn_id = check_keyword_id(line, (int)current_col, &endcol, &flags, &next_list, cur_si, &cchar); if (syn_id != 0) { @@ -1751,7 +1803,7 @@ static int syn_current_attr( cur_si = &CUR_STATE(current_state.ga_len - 1); cur_si->si_m_startcol = current_col; cur_si->si_h_startpos.lnum = current_lnum; - cur_si->si_h_startpos.col = 0; /* starts right away */ + cur_si->si_h_startpos.col = 0; // starts right away cur_si->si_m_endpos.lnum = current_lnum; cur_si->si_m_endpos.col = endcol; cur_si->si_h_endpos.lnum = current_lnum; @@ -1761,10 +1813,11 @@ static int syn_current_attr( cur_si->si_flags = flags; cur_si->si_seqnr = next_seqnr++; cur_si->si_cchar = cchar; - if (current_state.ga_len > 1) + if (current_state.ga_len > 1) { cur_si->si_flags |= CUR_STATE(current_state.ga_len - 2).si_flags & HL_CONCEAL; + } cur_si->si_id = syn_id; cur_si->si_trans_id = syn_id; if (flags & HL_TRANSP) { @@ -1772,10 +1825,8 @@ static int syn_current_attr( cur_si->si_attr = 0; cur_si->si_trans_id = 0; } else { - cur_si->si_attr = CUR_STATE( - current_state.ga_len - 2).si_attr; - cur_si->si_trans_id = CUR_STATE( - current_state.ga_len - 2).si_trans_id; + cur_si->si_attr = CUR_STATE(current_state.ga_len - 2).si_attr; + cur_si->si_trans_id = CUR_STATE(current_state.ga_len - 2).si_trans_id; } } else { cur_si->si_attr = syn_id2attr(syn_id); @@ -1803,28 +1854,29 @@ static int syn_current_attr( * 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_idx = 0; // no match in this line yet next_match_col = MAXCOL; for (int idx = syn_block->b_syn_patterns.ga_len; --idx >= 0; ) { synpat_T *const spp = &(SYN_ITEMS(syn_block)[idx]); - if ( spp->sp_syncing == syncing - && (displaying || !(spp->sp_flags & HL_DISPLAY)) - && (spp->sp_type == SPTYPE_MATCH - || spp->sp_type == SPTYPE_START) - && (current_next_list != NULL + if (spp->sp_syncing == syncing + && (displaying || !(spp->sp_flags & HL_DISPLAY)) + && (spp->sp_type == SPTYPE_MATCH + || spp->sp_type == SPTYPE_START) + && (current_next_list != NULL ? in_id_list(NULL, current_next_list, - &spp->sp_syn, 0) + &spp->sp_syn, 0) : (cur_si == NULL ? !(spp->sp_flags & HL_CONTAINED) : in_id_list(cur_si, - cur_si->si_cont_list, &spp->sp_syn, - spp->sp_flags & HL_CONTAINED)))) { + cur_si->si_cont_list, &spp->sp_syn, + spp->sp_flags & HL_CONTAINED)))) { /* If we already tried matching in this line, and * there isn't a match before next_match_col, skip * this item. */ if (spp->sp_line_id == current_line_id - && spp->sp_startcol >= next_match_col) + && spp->sp_startcol >= next_match_col) { continue; + } spp->sp_line_id = current_line_id; colnr_T lc_col = current_col - spp->sp_offsets[SPO_LC_OFF]; @@ -1838,7 +1890,7 @@ static int syn_current_attr( IF_SYN_TIME(&spp->sp_time)); spp->sp_prog = regmatch.regprog; if (!r) { - /* no match in this line, try another one */ + // no match in this line, try another one spp->sp_startcol = MAXCOL; continue; } @@ -1847,7 +1899,7 @@ static int syn_current_attr( * Compute the first column of the match. */ syn_add_start_off(&pos, ®match, - spp, SPO_MS_OFF, -1); + spp, SPO_MS_OFF, -1); if (pos.lnum > current_lnum) { /* must have used end of match in a next line, * we can't handle that */ @@ -1864,8 +1916,9 @@ static int syn_current_attr( * If a previously found match starts at a lower * column number, don't use this one. */ - if (startcol >= next_match_col) + if (startcol >= next_match_col) { continue; + } /* * If we matched this pattern at this position @@ -1880,14 +1933,14 @@ static int syn_current_attr( endpos.lnum = regmatch.endpos[0].lnum; endpos.col = regmatch.endpos[0].col; - /* Compute the highlight start. */ + // Compute the highlight start. syn_add_start_off(&hl_startpos, ®match, - spp, SPO_HS_OFF, -1); + spp, SPO_HS_OFF, -1); - /* Compute the region start. */ - /* Default is to use the end of the match. */ + // Compute the region start. + // Default is to use the end of the match. syn_add_end_off(&eos_pos, ®match, - spp, SPO_RS_OFF, 0); + spp, SPO_RS_OFF, 0); /* * Grab the external submatches before they get @@ -1898,7 +1951,7 @@ static int syn_current_attr( re_extmatch_out = NULL; flags = 0; - eoe_pos.lnum = 0; /* avoid warning */ + eoe_pos.lnum = 0; // avoid warning eoe_pos.col = 0; end_idx = 0; hl_endpos.lnum = 0; @@ -1915,9 +1968,10 @@ static int syn_current_attr( startpos = endpos; find_endpos(idx, &startpos, &endpos, &hl_endpos, - &flags, &eoe_pos, &end_idx, cur_extmatch); - if (endpos.lnum == 0) - continue; /* not found */ + &flags, &eoe_pos, &end_idx, cur_extmatch); + if (endpos.lnum == 0) { + continue; // not found + } } /* * For a "match" the size must be > 0 after the @@ -1926,9 +1980,9 @@ static int syn_current_attr( */ else if (spp->sp_type == SPTYPE_MATCH) { syn_add_end_off(&hl_endpos, ®match, spp, - SPO_HE_OFF, 0); + SPO_HE_OFF, 0); syn_add_end_off(&endpos, ®match, spp, - SPO_ME_OFF, 0); + SPO_ME_OFF, 0); if (endpos.lnum == current_lnum && (int)endpos.col + syncing < startcol) { /* @@ -1948,8 +2002,9 @@ static int syn_current_attr( /* Highlighting must start after startpos and end * before endpos. */ if (hl_startpos.lnum == current_lnum - && (int)hl_startpos.col < startcol) + && (int)hl_startpos.col < startcol) { hl_startpos.col = startcol; + } limit_pos_zero(&hl_endpos, &endpos); next_match_idx = idx; @@ -1972,7 +2027,7 @@ static int syn_current_attr( * 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; + synpat_T *lspp; /* When a zero-width item matched which has a nextgroup, * don't push the item but set nextgroup. */ @@ -2012,8 +2067,9 @@ static int syn_current_attr( if (((current_next_flags & HL_SKIPWHITE) && ascii_iswhite(line[current_col])) || ((current_next_flags & HL_SKIPEMPTY) - && *line == NUL)) + && *line == NUL)) { break; + } } /* @@ -2030,7 +2086,6 @@ static int syn_current_attr( found_match = true; } } - } while (found_match); restore_chartab(buf_chartab); @@ -2075,9 +2130,9 @@ static int syn_current_attr( /* There is no @Spell cluster: Do spelling for items without * @NoSpell cluster. */ if (syn_block->b_nospell_cluster_id == 0 - || current_trans_id == 0) + || current_trans_id == 0) { *can_spell = (syn_block->b_syn_spell != SYNSPL_NOTOP); - else { + } else { sps.inc_tag = 0; sps.id = syn_block->b_nospell_cluster_id; sps.cont_in_list = NULL; @@ -2088,9 +2143,9 @@ static int syn_current_attr( * the @Spell cluster. But not when @NoSpell is also there. * At the toplevel only spell check when ":syn spell toplevel" * was used. */ - if (current_trans_id == 0) + if (current_trans_id == 0) { *can_spell = (syn_block->b_syn_spell == SYNSPL_TOP); - else { + } else { sps.inc_tag = 0; sps.id = syn_block->b_spell_cluster_id; sps.cont_in_list = NULL; @@ -2098,8 +2153,9 @@ static int syn_current_attr( if (syn_block->b_nospell_cluster_id != 0) { sps.id = syn_block->b_nospell_cluster_id; - if (in_id_list(sip, sip->si_cont_list, &sps, 0)) + if (in_id_list(sip, sip->si_cont_list, &sps, 0)) { *can_spell = false; + } } } } @@ -2123,14 +2179,15 @@ static int syn_current_attr( --current_col; } } - } else if (can_spell != NULL) + } else if (can_spell != NULL) { /* Default: Only do spelling when there is no @Spell cluster or when * ":syn spell toplevel" was used. */ *can_spell = syn_block->b_syn_spell == SYNSPL_DEFAULT ? (syn_block->b_spell_cluster_id == 0) : (syn_block->b_syn_spell == SYNSPL_TOP); + } - /* nextgroup ends at end of line, unless "skipnl" or "skipempty" present */ + // nextgroup ends at end of line, unless "skipnl" or "skipempty" present if (current_next_list != NULL && (line = syn_getcurline())[current_col] != NUL && line[current_col + 1] == NUL @@ -2138,10 +2195,11 @@ static int syn_current_attr( current_next_list = NULL; } - if (!GA_EMPTY(&zero_width_next_ga)) + if (!GA_EMPTY(&zero_width_next_ga)) { ga_clear(&zero_width_next_ga); + } - /* No longer need external matches. But keep next_match_extmatch. */ + // No longer need external matches. But keep next_match_extmatch. unref_extmatch(re_extmatch_out); re_extmatch_out = NULL; unref_extmatch(cur_extmatch); @@ -2199,9 +2257,10 @@ static stateitem_T *push_next_match(void) cur_si->si_flags = spp->sp_flags; cur_si->si_seqnr = next_seqnr++; cur_si->si_cchar = spp->sp_cchar; - if (current_state.ga_len > 1) + if (current_state.ga_len > 1) { cur_si->si_flags |= CUR_STATE(current_state.ga_len - 2).si_flags & HL_CONCEAL; + } cur_si->si_next_list = spp->sp_next_list; cur_si->si_extmatch = ref_extmatch(next_match_extmatch); if (spp->sp_type == SPTYPE_START && !(spp->sp_flags & HL_ONELINE)) { @@ -2216,8 +2275,9 @@ static stateitem_T *push_next_match(void) cur_si->si_eoe_pos = next_match_eoe_pos; cur_si->si_end_idx = next_match_end_idx; } - if (keepend_level < 0 && (cur_si->si_flags & HL_KEEPEND)) + if (keepend_level < 0 && (cur_si->si_flags & HL_KEEPEND)) { keepend_level = current_state.ga_len - 1; + } check_keepend(); update_si_attr(current_state.ga_len - 1); @@ -2239,15 +2299,16 @@ static stateitem_T *push_next_match(void) cur_si->si_flags = HL_MATCH; cur_si->si_seqnr = next_seqnr++; cur_si->si_flags |= save_flags; - if (cur_si->si_flags & HL_CONCEALENDS) + if (cur_si->si_flags & HL_CONCEALENDS) { cur_si->si_flags |= HL_CONCEAL; + } cur_si->si_next_list = NULL; check_keepend(); update_si_attr(current_state.ga_len - 1); } } - next_match_idx = -1; /* try other match next time */ + next_match_idx = -1; // try other match next time return cur_si; } @@ -2282,14 +2343,15 @@ static void check_state_ends(void) cur_si->si_h_endpos = cur_si->si_eoe_pos; cur_si->si_flags |= HL_MATCH; cur_si->si_seqnr = next_seqnr++; - if (cur_si->si_flags & HL_CONCEALENDS) + if (cur_si->si_flags & HL_CONCEALENDS) { cur_si->si_flags |= HL_CONCEAL; + } update_si_attr(current_state.ga_len - 1); - /* nextgroup= should not match in the end pattern */ + // nextgroup= should not match in the end pattern current_next_list = NULL; - /* what matches next may be different now, clear it */ + // what matches next may be different now, clear it next_match_idx = 0; next_match_col = MAXCOL; break; @@ -2299,8 +2361,9 @@ static void check_state_ends(void) current_next_list = cur_si->si_next_list; current_next_flags = cur_si->si_flags; if (!(current_next_flags & (HL_SKIPNL | HL_SKIPEMPTY)) - && syn_getcurline()[current_col] == NUL) + && syn_getcurline()[current_col] == NUL) { current_next_list = NULL; + } /* When the ended item has "extend", another item with * "keepend" now needs to check for its end. */ @@ -2308,8 +2371,9 @@ static void check_state_ends(void) pop_current_state(); - if (GA_EMPTY(¤t_state)) + if (GA_EMPTY(¤t_state)) { break; + } if (had_extend && keepend_level >= 0) { syn_update_ends(false); @@ -2337,12 +2401,14 @@ static void check_state_ends(void) check_keepend(); if ((current_next_flags & HL_HAS_EOL) && keepend_level < 0 - && syn_getcurline()[current_col] == NUL) + && syn_getcurline()[current_col] == NUL) { break; + } } } - } else + } else { break; + } } } @@ -2353,23 +2419,26 @@ static void check_state_ends(void) static void update_si_attr(int idx) { stateitem_T *sip = &CUR_STATE(idx); - synpat_T *spp; + synpat_T *spp; - /* This should not happen... */ - if (sip->si_idx < 0) + // This should not happen... + if (sip->si_idx < 0) { return; + } spp = &(SYN_ITEMS(syn_block)[sip->si_idx]); - if (sip->si_flags & HL_MATCH) + if (sip->si_flags & HL_MATCH) { sip->si_id = spp->sp_syn_match_id; - else + } else { sip->si_id = spp->sp_syn.id; + } sip->si_attr = syn_id2attr(sip->si_id); sip->si_trans_id = sip->si_id; - if (sip->si_flags & HL_MATCH) + if (sip->si_flags & HL_MATCH) { sip->si_cont_list = NULL; - else + } else { sip->si_cont_list = spp->sp_cont_list; + } /* * For transparent items, take attr from outer item. @@ -2380,8 +2449,9 @@ static void update_si_attr(int idx) if (idx == 0) { sip->si_attr = 0; sip->si_trans_id = 0; - if (sip->si_cont_list == NULL) + if (sip->si_cont_list == NULL) { sip->si_cont_list = ID_LIST_ALL; + } } else { sip->si_attr = CUR_STATE(idx - 1).si_attr; sip->si_trans_id = CUR_STATE(idx - 1).si_trans_id; @@ -2410,17 +2480,20 @@ static void check_keepend(void) * This check can consume a lot of time; only do it from the level where * there really is a keepend. */ - if (keepend_level < 0) + 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. */ - for (i = current_state.ga_len - 1; i > keepend_level; --i) - if (CUR_STATE(i).si_flags & HL_EXTEND) + for (i = current_state.ga_len - 1; i > keepend_level; --i) { + if (CUR_STATE(i).si_flags & HL_EXTEND) { break; + } + } maxpos.lnum = 0; maxpos.col = 0; @@ -2438,13 +2511,15 @@ static void check_keepend(void) if (maxpos.lnum == 0 || maxpos.lnum > sip->si_m_endpos.lnum || (maxpos.lnum == sip->si_m_endpos.lnum - && maxpos.col > sip->si_m_endpos.col)) + && maxpos.col > sip->si_m_endpos.col)) { maxpos = sip->si_m_endpos; + } if (maxpos_h.lnum == 0 || maxpos_h.lnum > sip->si_h_endpos.lnum || (maxpos_h.lnum == sip->si_h_endpos.lnum - && maxpos_h.col > sip->si_h_endpos.col)) + && maxpos_h.col > sip->si_h_endpos.col)) { maxpos_h = sip->si_h_endpos; + } } } } @@ -2461,15 +2536,17 @@ static void update_si_end(stateitem_T *sip, int startcol, bool force) lpos_T hl_endpos; lpos_T end_endpos; - /* return quickly for a keyword */ - if (sip->si_idx < 0) + // return quickly for a keyword + if (sip->si_idx < 0) { return; + } /* Don't update when it's already done. Can be a match of an end pattern * that started in a previous line. Watch out: can also be a "keepend" * from a containing item. */ - if (!force && sip->si_m_endpos.lnum >= current_lnum) + if (!force && sip->si_m_endpos.lnum >= current_lnum) { return; + } /* * We need to find the end of the region. It may continue in the next @@ -2482,23 +2559,23 @@ static void update_si_end(stateitem_T *sip, int startcol, bool force) }; lpos_T endpos = { 0 }; find_endpos(sip->si_idx, &startpos, &endpos, &hl_endpos, - &(sip->si_flags), &end_endpos, &end_idx, sip->si_extmatch); + &(sip->si_flags), &end_endpos, &end_idx, sip->si_extmatch); if (endpos.lnum == 0) { - /* No end pattern matched. */ + // No end pattern matched. if (SYN_ITEMS(syn_block)[sip->si_idx].sp_flags & HL_ONELINE) { - /* a "oneline" never continues in the next line */ + // a "oneline" never continues in the next line sip->si_ends = TRUE; sip->si_m_endpos.lnum = current_lnum; sip->si_m_endpos.col = (colnr_T)STRLEN(syn_getcurline()); } else { - /* continues in the next line */ + // continues in the next line sip->si_ends = FALSE; sip->si_m_endpos.lnum = 0; } sip->si_h_endpos = sip->si_m_endpos; } else { - /* match within this line */ + // match within this line sip->si_m_endpos = endpos; sip->si_h_endpos = hl_endpos; sip->si_eoe_pos = end_endpos; @@ -2527,49 +2604,49 @@ static void pop_current_state(void) unref_extmatch(CUR_STATE(current_state.ga_len - 1).si_extmatch); --current_state.ga_len; } - /* after the end of a pattern, try matching a keyword or pattern */ + // after the end of a pattern, try matching a keyword or pattern next_match_idx = -1; - /* if first state with "keepend" is popped, reset keepend_level */ - if (keepend_level >= current_state.ga_len) + // if first state with "keepend" is popped, reset keepend_level + if (keepend_level >= current_state.ga_len) { keepend_level = -1; + } } -/* - * Find the end of a start/skip/end syntax region after "startpos". - * Only checks one line. - * Also handles a match item that continued from a previous line. - * If not found, the syntax item continues in the next line. m_endpos->lnum - * will be 0. - * If found, the end of the region and the end of the highlighting is - * computed. - */ -static void -find_endpos( - int idx, // index of the pattern - lpos_T *startpos, // where to start looking for an END match - lpos_T *m_endpos, // return: end of match - lpos_T *hl_endpos, // return: end of highlighting - long *flagsp, // return: flags of matching END - lpos_T *end_endpos, // return: end of end pattern match - int *end_idx, // return: group ID for end pat. match, or 0 - reg_extmatch_T *start_ext // submatches from the start pattern -) +/// Find the end of a start/skip/end syntax region after "startpos". +/// Only checks one line. +/// Also handles a match item that continued from a previous line. +/// If not found, the syntax item continues in the next line. m_endpos->lnum +/// will be 0. +/// If found, the end of the region and the end of the highlighting is +/// computed. +/// +/// @param idx index of the pattern +/// @param startpos where to start looking for an END match +/// @param m_endpos return: end of match +/// @param hl_endpos return: end of highlighting +/// @param flagsp return: flags of matching END +/// @param end_endpos return: end of end pattern match +/// @param end_idx return: group ID for end pat. match, or 0 +/// @param start_ext submatches from the start pattern +static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_endpos, + long *flagsp, lpos_T *end_endpos, int *end_idx, reg_extmatch_T *start_ext) { colnr_T matchcol; - synpat_T *spp, *spp_skip; + synpat_T *spp, *spp_skip; int start_idx; int best_idx; regmmatch_T regmatch; - regmmatch_T best_regmatch; /* startpos/endpos of best match */ + regmmatch_T best_regmatch; // startpos/endpos of best match lpos_T pos; - char_u *line; + char_u *line; bool had_match = false; char_u buf_chartab[32]; // chartab array for syn option iskeyword - /* just in case we are invoked for a keyword */ - if (idx < 0) + // just in case we are invoked for a keyword + if (idx < 0) { return; + } /* * Check for being called with a START pattern. @@ -2587,21 +2664,23 @@ find_endpos( */ for (;; ) { spp = &(SYN_ITEMS(syn_block)[idx]); - if (spp->sp_type != SPTYPE_START) + if (spp->sp_type != SPTYPE_START) { break; + } ++idx; } /* - * Lookup the SKIP pattern (if present) + * Lookup the SKIP pattern (if present) */ if (spp->sp_type == SPTYPE_SKIP) { spp_skip = spp; ++idx; - } else + } else { spp_skip = NULL; + } - /* Setup external matches for syn_regexec(). */ + // Setup external matches for syn_regexec(). unref_extmatch(re_extmatch_in); re_extmatch_in = ref_extmatch(start_ext); @@ -2621,11 +2700,13 @@ find_endpos( int lc_col = matchcol; spp = &(SYN_ITEMS(syn_block)[idx]); - if (spp->sp_type != SPTYPE_END) /* past last END pattern */ + if (spp->sp_type != SPTYPE_END) { // past last END pattern break; + } lc_col -= spp->sp_offsets[SPO_LC_OFF]; - if (lc_col < 0) + if (lc_col < 0) { lc_col = 0; + } regmatch.rmm_ic = spp->sp_ic; regmatch.regprog = spp->sp_prog; @@ -2646,8 +2727,9 @@ find_endpos( * If all end patterns have been tried, and there is no match, the * item continues until end-of-line. */ - if (best_idx == -1) + if (best_idx == -1) { break; + } /* * If the skip pattern matches before the end pattern, @@ -2656,8 +2738,9 @@ find_endpos( if (spp_skip != NULL) { int lc_col = matchcol - spp_skip->sp_offsets[SPO_LC_OFF]; - if (lc_col < 0) + if (lc_col < 0) { lc_col = 0; + } regmatch.rmm_ic = spp_skip->sp_ic; regmatch.regprog = spp_skip->sp_prog; int r = syn_regexec(®match, startpos->lnum, lc_col, @@ -2704,16 +2787,18 @@ find_endpos( */ 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 */ - if (m_endpos->lnum == startpos->lnum && m_endpos->col < startpos->col) + // can't end before the start + if (m_endpos->lnum == startpos->lnum && m_endpos->col < startpos->col) { m_endpos->col = startpos->col; + } syn_add_end_off(end_endpos, &best_regmatch, spp, SPO_HE_OFF, 1); - /* can't end before the start */ + // can't end before the start if (end_endpos->lnum == startpos->lnum - && end_endpos->col < startpos->col) + && end_endpos->col < startpos->col) { end_endpos->col = startpos->col; - /* can't end after the match */ + } + // can't end after the match limit_pos(end_endpos, m_endpos); /* @@ -2730,10 +2815,11 @@ find_endpos( } hl_endpos->col += spp->sp_offsets[SPO_RE_OFF]; - /* can't end before the start */ + // can't end before the start if (hl_endpos->lnum == startpos->lnum - && hl_endpos->col < startpos->col) + && hl_endpos->col < startpos->col) { hl_endpos->col = startpos->col; + } limit_pos(hl_endpos, m_endpos); /* now the match ends where the highlighting ends, it is turned @@ -2750,13 +2836,14 @@ find_endpos( break; } - /* no match for an END pattern in this line */ - if (!had_match) + // no match for an END pattern in this line + if (!had_match) { m_endpos->lnum = 0; + } restore_chartab(buf_chartab); - /* Remove external matches. */ + // Remove external matches. unref_extmatch(re_extmatch_in); re_extmatch_in = NULL; } @@ -2766,10 +2853,11 @@ find_endpos( */ static void limit_pos(lpos_T *pos, lpos_T *limit) { - if (pos->lnum > limit->lnum) + if (pos->lnum > limit->lnum) { *pos = *limit; - else if (pos->lnum == limit->lnum && pos->col > limit->col) + } else if (pos->lnum == limit->lnum && pos->col > limit->col) { pos->col = limit->col; + } } /* @@ -2777,28 +2865,27 @@ static void limit_pos(lpos_T *pos, lpos_T *limit) */ static void limit_pos_zero(lpos_T *pos, lpos_T *limit) { - if (pos->lnum == 0) + if (pos->lnum == 0) { *pos = *limit; - else + } else { limit_pos(pos, limit); + } } -/* - * Add offset to matched text for end of match or highlight. - */ -static void -syn_add_end_off( - lpos_T *result, // returned position - regmmatch_T *regmatch, // start/end of match - synpat_T *spp, // matched pattern - int idx, // index of offset - int extra // extra chars for offset to start -) +/// Add offset to matched text for end of match or highlight. +/// +/// @param result returned position +/// @param regmatch start/end of match +/// @param spp matched pattern +/// @param idx index of offset +/// @param extra extra chars for offset to start +static void syn_add_end_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *spp, int idx, + int extra) { int col; int off; - char_u *base; - char_u *p; + char_u *base; + char_u *p; if (spp->sp_off_flags & (1 << idx)) { result->lnum = regmatch->startpos[0].lnum; @@ -2830,23 +2917,19 @@ syn_add_end_off( result->col = col; } -/* - * Add offset to matched text for start of match or highlight. - * Avoid resulting column to become negative. - */ -static void -syn_add_start_off( - lpos_T *result, // returned position - regmmatch_T *regmatch, // start/end of match - synpat_T *spp, - int idx, - int extra // extra chars for offset to end -) +/// Add offset to matched text for start of match or highlight. +/// Avoid resulting column to become negative. +/// +/// @param result returned position +/// @param regmatch start/end of match +/// @param extra extra chars for offset to end +static void syn_add_start_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *spp, int idx, + int extra) { int col; int off; - char_u *base; - char_u *p; + char_u *base; + char_u *p; if (spp->sp_off_flags & (1 << (idx + SPO_COUNT))) { result->lnum = regmatch->endpos[0].lnum; @@ -2858,7 +2941,7 @@ syn_add_start_off( off = spp->sp_offsets[idx]; } if (result->lnum > syn_buf->b_ml.ml_line_count) { - /* a "\n" at the end of the pattern may take us below the last line */ + // a "\n" at the end of the pattern may take us below the last line result->lnum = syn_buf->b_ml.ml_line_count; col = (int)STRLEN(ml_get_buf(syn_buf, result->lnum, false)); } @@ -2920,8 +3003,9 @@ static int syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T st->slowest = pt; } ++st->count; - if (r > 0) + if (r > 0) { ++st->match; + } } if (timed_out && !syn_win->w_s->b_syn_slow) { syn_win->w_s->b_syn_slow = true; @@ -2936,20 +3020,19 @@ static int syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T return FALSE; } -/* - * Check one position in a line for a matching keyword. - * The caller must check if a keyword can start at startcol. - * Return its ID if found, 0 otherwise. - */ -static int check_keyword_id( - char_u *const line, - const int startcol, // position in line to check for keyword - int *const endcolp, // return: character after found keyword - long *const flagsp, // return: flags of matching keyword - int16_t **const next_listp, // return: next_list of matching keyword - stateitem_T *const cur_si, // item at the top of the stack - int *const ccharp // conceal substitution char -) +/// Check one position in a line for a matching keyword. +/// The caller must check if a keyword can start at startcol. +/// Return its ID if found, 0 otherwise. +/// +/// @param startcol position in line to check for keyword +/// @param endcolp return: character after found keyword +/// @param flagsp return: flags of matching keyword +/// @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, + 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. @@ -2997,11 +3080,10 @@ static int check_keyword_id( /// 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_u *keyword, hashtab_T *ht, stateitem_T *cur_si) { hashitem_T *hi = hash_find(ht, keyword); - if (!HASHITEM_EMPTY(hi)) + if (!HASHITEM_EMPTY(hi)) { for (keyentry_T *kp = HI2KE(hi); kp != NULL; kp = kp->ke_next) { if (current_next_list != 0 ? in_id_list(NULL, current_next_list, &kp->k_syn, 0) @@ -3012,6 +3094,7 @@ static keyentry_T *match_keyword(char_u *keyword, hashtab_T *ht, return kp; } } + } return NULL; } @@ -3020,12 +3103,13 @@ static keyentry_T *match_keyword(char_u *keyword, hashtab_T *ht, */ static void syn_cmd_conceal(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *next; + char_u *arg = eap->arg; + char_u *next; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } next = skiptowhite(arg); if (*arg == NUL) { @@ -3048,12 +3132,13 @@ static void syn_cmd_conceal(exarg_T *eap, int syncing) */ static void syn_cmd_case(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *next; + char_u *arg = eap->arg; + char_u *next; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } next = skiptowhite(arg); if (*arg == NUL) { @@ -3078,14 +3163,18 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) char_u *arg_end; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } if (*arg == NUL) { switch (curwin->w_s->b_syn_foldlevel) { - case SYNFLD_START: MSG(_("syntax foldlevel start")); break; - case SYNFLD_MINIMUM: MSG(_("syntax foldlevel minimum")); break; - default: break; + case SYNFLD_START: + MSG(_("syntax foldlevel start")); break; + case SYNFLD_MINIMUM: + MSG(_("syntax foldlevel minimum")); break; + default: + break; } return; } @@ -3111,12 +3200,13 @@ static void syn_cmd_foldlevel(exarg_T *eap, int syncing) */ static void syn_cmd_spell(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *next; + char_u *arg = eap->arg; + char_u *next; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } next = skiptowhite(arg); if (*arg == NUL) { @@ -3195,17 +3285,17 @@ void syntax_clear(synblock_T *block) block->b_syn_containedin = false; block->b_syn_conceal = false; - /* free the keywords */ + // free the keywords clear_keywtab(&block->b_keywtab); clear_keywtab(&block->b_keywtab_ic); - /* free the syntax patterns */ + // free the syntax patterns for (int i = block->b_syn_patterns.ga_len; --i >= 0; ) { syn_clear_pattern(block, i); } ga_clear(&block->b_syn_patterns); - /* free the syntax clusters */ + // free the syntax clusters for (int i = block->b_syn_clusters.ga_len; --i >= 0; ) { syn_clear_cluster(block, i); } @@ -3224,11 +3314,11 @@ void syntax_clear(synblock_T *block) block->b_syn_folditems = 0; clear_string_option(&block->b_syn_isk); - /* free the stored states */ + // free the stored states syn_stack_free_all(block); invalidate_current_state(); - /* Reset the counter for ":syn include" */ + // Reset the counter for ":syn include" running_syn_inc_tag = 0; } @@ -3249,7 +3339,7 @@ void reset_synblock(win_T *wp) */ static void syntax_sync_clear(void) { - /* free the syntax patterns */ + // free the syntax patterns for (int i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0; ) { if (SYN_ITEMS(curwin->w_s)[i].sp_syncing) { syn_remove_pattern(curwin->w_s, i); @@ -3266,7 +3356,7 @@ static void syntax_sync_clear(void) XFREE_CLEAR(curwin->w_s->b_syn_linecont_pat); clear_string_option(&curwin->w_s->b_syn_isk); - syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ + syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } /* @@ -3274,14 +3364,15 @@ static void syntax_sync_clear(void) */ static void syn_remove_pattern(synblock_T *block, int idx) { - synpat_T *spp; + synpat_T *spp; spp = &(SYN_ITEMS(block)[idx]); - if (spp->sp_flags & HL_FOLD) + if (spp->sp_flags & HL_FOLD) { --block->b_syn_folditems; + } syn_clear_pattern(block, idx); memmove(spp, spp + 1, - sizeof(synpat_T) * (block->b_syn_patterns.ga_len - idx - 1)); + sizeof(synpat_T) * (block->b_syn_patterns.ga_len - idx - 1)); --block->b_syn_patterns.ga_len; } @@ -3293,7 +3384,7 @@ static void syn_clear_pattern(synblock_T *block, int i) { xfree(SYN_ITEMS(block)[i].sp_pattern); vim_regfree(SYN_ITEMS(block)[i].sp_prog); - /* Only free sp_cont_list and sp_next_list of first start pattern */ + // Only free sp_cont_list and sp_next_list of first start pattern if (i == 0 || SYN_ITEMS(block)[i - 1].sp_type != SPTYPE_START) { xfree(SYN_ITEMS(block)[i].sp_cont_list); xfree(SYN_ITEMS(block)[i].sp_next_list); @@ -3316,13 +3407,14 @@ static void syn_clear_cluster(synblock_T *block, int i) */ static void syn_cmd_clear(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *arg_end; + char_u *arg = eap->arg; + char_u *arg_end; int id; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } /* * We have to disable this within ":syn include @group filename", @@ -3330,16 +3422,17 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) * Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn * clear". */ - if (curwin->w_s->b_syn_topgrp != 0) + if (curwin->w_s->b_syn_topgrp != 0) { return; + } if (ends_excmd(*arg)) { /* * No argument: Clear all syntax items. */ - if (syncing) + if (syncing) { syntax_sync_clear(); - else { + } else { syntax_clear(curwin->w_s); if (curwin->w_s == &curwin->w_buffer->b_s) { do_unlet(S_LEN("b:current_syntax"), true); @@ -3370,14 +3463,15 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) if (id == 0) { EMSG2(_(e_nogroup), arg); break; - } else + } else { syn_clear_one(id, syncing); + } } arg = skipwhite(arg_end); } } redraw_curbuf_later(SOME_VALID); - syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ + syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } /* @@ -3385,19 +3479,20 @@ static void syn_cmd_clear(exarg_T *eap, int syncing) */ static void syn_clear_one(const int id, const bool syncing) { - synpat_T *spp; + synpat_T *spp; - /* Clear keywords only when not ":syn sync clear group-name" */ + // Clear keywords only when not ":syn sync clear group-name" if (!syncing) { syn_clear_keyword(id, &curwin->w_s->b_keywtab); syn_clear_keyword(id, &curwin->w_s->b_keywtab_ic); } - /* clear the patterns for "id" */ + // clear the patterns for "id" for (int idx = curwin->w_s->b_syn_patterns.ga_len; --idx >= 0; ) { spp = &(SYN_ITEMS(curwin->w_s)[idx]); - if (spp->sp_syn.id != id || spp->sp_syncing != syncing) + if (spp->sp_syn.id != id || spp->sp_syncing != syncing) { continue; + } syn_remove_pattern(curwin->w_s, idx); } } @@ -3461,21 +3556,18 @@ void syn_maybe_enable(void) } } -/* - * Handle ":syntax [list]" command: list current syntax words. - */ -static void -syn_cmd_list( - exarg_T *eap, - int syncing /* when TRUE: list syncing items */ -) +/// Handle ":syntax [list]" command: list current syntax words. +/// +/// @param syncing when TRUE: list syncing items +static void syn_cmd_list(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *arg_end; + char_u *arg = eap->arg; + char_u *arg_end; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } if (!syntax_present(curwin)) { MSG(_(msg_no_items)); @@ -3488,7 +3580,7 @@ syn_cmd_list( syn_lines_msg(); syn_match_msg(); return; - } else if (!(curwin->w_s->b_syn_sync_flags & SF_MATCH)) { + } else if (!(curwin->w_s->b_syn_sync_flags & SF_MATCH)) { if (curwin->w_s->b_syn_sync_minlines == 0) { MSG_PUTS(_("no syncing")); } else { @@ -3511,8 +3603,9 @@ syn_cmd_list( syn_lines_msg(); syn_match_msg(); } - } else + } else { MSG_PUTS_TITLE(_("\n--- Syntax items ---")); + } if (ends_excmd(*arg)) { /* * No argument: List all group IDs and all syntax clusters. @@ -3531,10 +3624,11 @@ syn_cmd_list( arg_end = skiptowhite(arg); if (*arg == '@') { int id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1)); - if (id == 0) + if (id == 0) { EMSG2(_("E392: No such syntax cluster: %s"), arg); - else + } else { syn_list_cluster(id - SYNID_CLUSTER); + } } else { int id = syn_name2id_len(arg, (int)(arg_end - arg)); if (id == 0) { @@ -3585,37 +3679,33 @@ static void syn_match_msg(void) static int last_matchgroup; -/* - * List one syntax item, for ":syntax" or "syntax list syntax_name". - */ -static void -syn_list_one( - const int id, - const bool syncing, // when true: list syncing items - const bool link_only // when true; list link-only too -) +/// List one syntax item, for ":syntax" or "syntax list syntax_name". +/// +/// @param syncing when true: list syncing items +/// @param link_only when true; list link-only too +static void syn_list_one(const int id, const bool syncing, const bool link_only) { bool did_header = false; static struct name_list namelist1[] = { - {HL_DISPLAY, "display"}, - {HL_CONTAINED, "contained"}, - {HL_ONELINE, "oneline"}, - {HL_KEEPEND, "keepend"}, - {HL_EXTEND, "extend"}, - {HL_EXCLUDENL, "excludenl"}, - {HL_TRANSP, "transparent"}, - {HL_FOLD, "fold"}, - {HL_CONCEAL, "conceal"}, - {HL_CONCEALENDS, "concealends"}, - {0, NULL} + { HL_DISPLAY, "display" }, + { HL_CONTAINED, "contained" }, + { HL_ONELINE, "oneline" }, + { HL_KEEPEND, "keepend" }, + { HL_EXTEND, "extend" }, + { HL_EXCLUDENL, "excludenl" }, + { HL_TRANSP, "transparent" }, + { HL_FOLD, "fold" }, + { HL_CONCEAL, "conceal" }, + { HL_CONCEALENDS, "concealends" }, + { 0, NULL } }; static struct name_list namelist2[] = { - {HL_SKIPWHITE, "skipwhite"}, - {HL_SKIPNL, "skipnl"}, - {HL_SKIPEMPTY, "skipempty"}, - {0, NULL} + { HL_SKIPWHITE, "skipwhite" }, + { HL_SKIPNL, "skipnl" }, + { HL_SKIPEMPTY, "skipempty" }, + { 0, NULL } }; const int attr = HL_ATTR(HLF_D); // highlight like directories @@ -3642,14 +3732,17 @@ syn_list_one( if (spp->sp_type == SPTYPE_MATCH) { put_pattern("match", ' ', spp, attr); msg_putchar(' '); - } else if (spp->sp_type == SPTYPE_START) { - while (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_START) + } else if (spp->sp_type == SPTYPE_START) { + while (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_START) { put_pattern("start", '=', &SYN_ITEMS(curwin->w_s)[idx++], attr); - if (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_SKIP) + } + if (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_SKIP) { put_pattern("skip", '=', &SYN_ITEMS(curwin->w_s)[idx++], attr); + } while (idx < curwin->w_s->b_syn_patterns.ga_len - && SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_END) + && SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_END) { put_pattern("end", '=', &SYN_ITEMS(curwin->w_s)[idx++], attr); + } --idx; msg_putchar(' '); } @@ -3674,16 +3767,17 @@ syn_list_one( msg_puts_attr("groupthere", attr); } msg_putchar(' '); - if (spp->sp_sync_idx >= 0) + if (spp->sp_sync_idx >= 0) { msg_outtrans(HL_TABLE()[SYN_ITEMS(curwin->w_s) [spp->sp_sync_idx].sp_syn.id - 1].sg_name); - else + } else { MSG_PUTS("NONE"); + } msg_putchar(' '); } } - /* list the link, if there is one */ + // list the link, if there is one if (HL_TABLE()[id - 1].sg_link && (did_header || link_only) && !got_int) { (void)syn_list_header(did_header, 0, id, true); msg_puts_attr("links to", attr); @@ -3696,11 +3790,12 @@ static void syn_list_flags(struct name_list *nlist, int flags, int attr) { int i; - for (i = 0; nlist[i].flag != 0; ++i) + for (i = 0; nlist[i].flag != 0; ++i) { if (flags & nlist[i].flag) { msg_puts_attr(nlist[i].name, attr); msg_putchar(' '); } + } } /* @@ -3710,14 +3805,16 @@ static void syn_list_cluster(int id) { int endcol = 15; - /* slight hack: roughly duplicate the guts of syn_list_header() */ + // slight hack: roughly duplicate the guts of syn_list_header() msg_putchar('\n'); msg_outtrans(SYN_CLSTR(curwin->w_s)[id].scl_name); - if (msg_col >= endcol) /* output at least one space */ + if (msg_col >= endcol) { // output at least one space endcol = msg_col + 1; - if (Columns <= endcol) /* avoid hang for tiny window */ + } + if (Columns <= endcol) { // avoid hang for tiny window endcol = Columns - 1; + } msg_advance(endcol); if (SYN_CLSTR(curwin->w_s)[id].scl_list != NULL) { @@ -3728,9 +3825,7 @@ static void syn_list_cluster(int id) } } -static void put_id_list(const char *const name, - const int16_t *const list, - const int attr) +static void put_id_list(const char *const name, const int16_t *const list, const int attr) { msg_puts_attr(name, attr); msg_putchar('='); @@ -3741,38 +3836,40 @@ static void put_id_list(const char *const name, } else { msg_puts("ALL"); } - } else if (*p >= SYNID_TOP && *p < SYNID_CONTAINED) { + } else if (*p >= SYNID_TOP && *p < SYNID_CONTAINED) { msg_puts("TOP"); - } else if (*p >= SYNID_CONTAINED && *p < SYNID_CLUSTER) { + } else if (*p >= SYNID_CONTAINED && *p < SYNID_CLUSTER) { msg_puts("CONTAINED"); - } else if (*p >= SYNID_CLUSTER) { + } else if (*p >= SYNID_CLUSTER) { int scl_id = *p - SYNID_CLUSTER; msg_putchar('@'); msg_outtrans(SYN_CLSTR(curwin->w_s)[scl_id].scl_name); - } else + } else { msg_outtrans(HL_TABLE()[*p - 1].sg_name); - if (p[1]) + } + if (p[1]) { msg_putchar(','); + } } msg_putchar(' '); } -static void put_pattern(const char *const s, const int c, - const synpat_T *const spp, const int attr) +static void put_pattern(const char *const s, const int c, const synpat_T *const spp, const int attr) { static const char *const sepchars = "/+=-#@\"|'^&"; int i; - /* May have to write "matchgroup=group" */ + // May have to write "matchgroup=group" if (last_matchgroup != spp->sp_syn_match_id) { last_matchgroup = spp->sp_syn_match_id; msg_puts_attr("matchgroup", attr); msg_putchar('='); - if (last_matchgroup == 0) + if (last_matchgroup == 0) { msg_outtrans((char_u *)"NONE"); - else + } else { msg_outtrans(HL_TABLE()[last_matchgroup - 1].sg_name); + } msg_putchar(' '); } @@ -3780,12 +3877,13 @@ static void put_pattern(const char *const s, const int c, msg_puts_attr(s, attr); msg_putchar(c); - /* output the pattern, in between a char that is not in the pattern */ - for (i = 0; vim_strchr(spp->sp_pattern, sepchars[i]) != NULL; ) + // output the pattern, in between a char that is not in the pattern + 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 */ + i = 0; // no good char found, just use the first one break; } + } msg_putchar(sepchars[i]); msg_outtrans(spp->sp_pattern); msg_putchar(sepchars[i]); @@ -3803,12 +3901,14 @@ static void put_pattern(const char *const s, const int c, msg_puts(spo_name_tab[i]); const long n = spp->sp_offsets[i]; if (i != SPO_LC_OFF) { - if (spp->sp_off_flags & mask) + if (spp->sp_off_flags & mask) { msg_putchar('s'); - else + } else { msg_putchar('e'); - if (n > 0) + } + if (n > 0) { msg_putchar('+'); + } } if (n || i == SPO_LC_OFF) { msg_outnum(n); @@ -3818,14 +3918,13 @@ static void put_pattern(const char *const s, const int c, msg_putchar(' '); } -// List or clear the keywords for one syntax group. -// Return true if the header has been printed. -static bool syn_list_keywords( - const int id, - const hashtab_T *const ht, - bool did_header, // header has already been printed - const int attr -) +/// List or clear the keywords for one syntax group. +/// +/// @param did_header header has already been printed +/// +/// @return true if the header has been printed. +static bool syn_list_keywords(const int id, const hashtab_T *const ht, bool did_header, + const int attr) { int prev_contained = 0; const int16_t *prev_next_list = NULL; @@ -3852,7 +3951,7 @@ static bool syn_list_keywords( || prev_skipempty != (kp->flags & HL_SKIPEMPTY) || prev_cont_in_list != kp->k_syn.cont_in_list || prev_next_list != kp->next_list) { - force_newline = true; + force_newline = true; } else { outlen = (int)STRLEN(kp->keyword); } @@ -3906,10 +4005,10 @@ static bool syn_list_keywords( static void syn_clear_keyword(int id, hashtab_T *ht) { - hashitem_T *hi; - keyentry_T *kp; - keyentry_T *kp_prev; - keyentry_T *kp_next; + hashitem_T *hi; + keyentry_T *kp; + keyentry_T *kp_prev; + keyentry_T *kp_next; int todo; hash_lock(ht); @@ -3924,12 +4023,14 @@ static void syn_clear_keyword(int id, hashtab_T *ht) if (kp->k_syn.id == id) { kp_next = kp->ke_next; if (kp_prev == NULL) { - if (kp_next == NULL) + if (kp_next == NULL) { hash_remove(ht, hi); - else + } else { hi->hi_key = KE2HIKEY(kp_next); - } else + } + } else { kp_prev->ke_next = kp_next; + } xfree(kp->next_list); xfree(kp->k_syn.cont_in_list); xfree(kp); @@ -3948,10 +4049,10 @@ static void syn_clear_keyword(int id, hashtab_T *ht) */ static void clear_keywtab(hashtab_T *ht) { - hashitem_T *hi; + hashitem_T *hi; int todo; - keyentry_T *kp; - keyentry_T *kp_next; + keyentry_T *kp; + keyentry_T *kp_next; todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { @@ -3976,11 +4077,8 @@ 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, - int16_t *const cont_in_list, - int16_t *const next_list, +static void add_keyword(char_u *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]; @@ -4022,18 +4120,16 @@ static void add_keyword(char_u *const name, } } -/* - * Get the start and end of the group name argument. - * Return a pointer to the first argument. - * Return NULL if the end of the command was found instead of further args. - */ -static char_u * -get_group_name ( - char_u *arg, /* start of the argument */ - char_u **name_end /* pointer to end of the name */ -) +/// Get the start and end of the group name argument. +/// +/// @param arg start of the argument +/// @param name_end pointer to end of the name +/// +/// @return a pointer to the first argument. +/// Return NULL if the end of the command was found instead of further args. +static char_u *get_group_name(char_u *arg, char_u **name_end) { - char_u *rest; + char_u *rest; *name_end = skiptowhite(arg); rest = skipwhite(*name_end); @@ -4042,62 +4138,62 @@ get_group_name ( * Check if there are enough arguments. The first argument may be a * pattern, where '|' is allowed, so only check for NUL. */ - if (ends_excmd(*arg) || *rest == NUL) + if (ends_excmd(*arg) || *rest == NUL) { return NULL; + } return rest; } -/* - * Check for syntax command option arguments. - * This can be called at any place in the list of arguments, and just picks - * out the arguments that are known. Can be called several times in a row to - * collect all options in between other arguments. - * Return a pointer to the next argument (which isn't an option). - * Return NULL for any error; - */ -static char_u * -get_syn_options( - char_u *arg, // next argument to be checked - syn_opt_arg_T *opt, // various things - int *conceal_char, - int skip // TRUE if skipping over command -) -{ - char_u *gname_start, *gname; +/// Check for syntax command option arguments. +/// This can be called at any place in the list of arguments, and just picks +/// out the arguments that are known. Can be called several times in a row to +/// collect all options in between other arguments. +/// +/// @param arg next argument to be checked +/// @param opt various things +/// @param skip TRUE if skipping over command +/// +/// @return a pointer to the next argument (which isn't an option). +/// Return NULL for any error; +static char_u *get_syn_options(char_u *arg, syn_opt_arg_T *opt, int *conceal_char, int skip) +{ + char_u *gname_start, *gname; int syn_id; int len = 0; - char *p; + char *p; int fidx; static const struct flag { - char *name; + char *name; int argtype; int flags; - } flagtab[] = { {"cCoOnNtTaAiInNeEdD", 0, HL_CONTAINED}, - {"oOnNeElLiInNeE", 0, HL_ONELINE}, - {"kKeEeEpPeEnNdD", 0, HL_KEEPEND}, - {"eExXtTeEnNdD", 0, HL_EXTEND}, - {"eExXcClLuUdDeEnNlL", 0, HL_EXCLUDENL}, - {"tTrRaAnNsSpPaArReEnNtT", 0, HL_TRANSP}, - {"sSkKiIpPnNlL", 0, HL_SKIPNL}, - {"sSkKiIpPwWhHiItTeE", 0, HL_SKIPWHITE}, - {"sSkKiIpPeEmMpPtTyY", 0, HL_SKIPEMPTY}, - {"gGrRoOuUpPhHeErReE", 0, HL_SYNC_HERE}, - {"gGrRoOuUpPtThHeErReE", 0, HL_SYNC_THERE}, - {"dDiIsSpPlLaAyY", 0, HL_DISPLAY}, - {"fFoOlLdD", 0, HL_FOLD}, - {"cCoOnNcCeEaAlL", 0, HL_CONCEAL}, - {"cCoOnNcCeEaAlLeEnNdDsS", 0, HL_CONCEALENDS}, - {"cCcChHaArR", 11, 0}, - {"cCoOnNtTaAiInNsS", 1, 0}, - {"cCoOnNtTaAiInNeEdDiInN", 2, 0}, - {"nNeExXtTgGrRoOuUpP", 3, 0},}; + } flagtab[] = { { "cCoOnNtTaAiInNeEdD", 0, HL_CONTAINED }, + { "oOnNeElLiInNeE", 0, HL_ONELINE }, + { "kKeEeEpPeEnNdD", 0, HL_KEEPEND }, + { "eExXtTeEnNdD", 0, HL_EXTEND }, + { "eExXcClLuUdDeEnNlL", 0, HL_EXCLUDENL }, + { "tTrRaAnNsSpPaArReEnNtT", 0, HL_TRANSP }, + { "sSkKiIpPnNlL", 0, HL_SKIPNL }, + { "sSkKiIpPwWhHiItTeE", 0, HL_SKIPWHITE }, + { "sSkKiIpPeEmMpPtTyY", 0, HL_SKIPEMPTY }, + { "gGrRoOuUpPhHeErReE", 0, HL_SYNC_HERE }, + { "gGrRoOuUpPtThHeErReE", 0, HL_SYNC_THERE }, + { "dDiIsSpPlLaAyY", 0, HL_DISPLAY }, + { "fFoOlLdD", 0, HL_FOLD }, + { "cCoOnNcCeEaAlL", 0, HL_CONCEAL }, + { "cCoOnNcCeEaAlLeEnNdDsS", 0, HL_CONCEALENDS }, + { "cCcChHaArR", 11, 0 }, + { "cCoOnNtTaAiInNsS", 1, 0 }, + { "cCoOnNtTaAiInNeEdDiInN", 2, 0 }, + { "nNeExXtTgGrRoOuUpP", 3, 0 }, }; static const char *const first_letters = "cCoOkKeEtTsSgGdDfFnN"; - if (arg == NULL) /* already detected error */ + if (arg == NULL) { // already detected error return NULL; + } - if (curwin->w_s->b_syn_conceal) + if (curwin->w_s->b_syn_conceal) { opt->flags |= HL_CONCEAL; + } for (;; ) { /* @@ -4105,15 +4201,17 @@ get_syn_options( * Need to skip quickly when no option name is found. * Also avoid tolower(), it's slow. */ - if (strchr(first_letters, *arg) == NULL) + if (strchr(first_letters, *arg) == NULL) { break; + } for (fidx = ARRAY_SIZE(flagtab); --fidx >= 0; ) { p = flagtab[fidx].name; int i; for (i = 0, len = 0; p[i] != NUL; i += 2, ++len) { - if (arg[len] != p[i] && arg[len] != p[i + 1]) + if (arg[len] != p[i] && arg[len] != p[i + 1]) { break; + } } if (p[i] == NUL && (ascii_iswhite(arg[len]) || (flagtab[fidx].argtype > 0 @@ -4122,14 +4220,16 @@ get_syn_options( if (opt->keyword && (flagtab[fidx].flags == HL_DISPLAY || flagtab[fidx].flags == HL_FOLD - || flagtab[fidx].flags == HL_EXTEND)) - /* treat "display", "fold" and "extend" as a keyword */ + || flagtab[fidx].flags == HL_EXTEND)) { + // treat "display", "fold" and "extend" as a keyword fidx = -1; + } break; } } - if (fidx < 0) /* no match found */ + if (fidx < 0) { // no match found break; + } if (flagtab[fidx].argtype == 1) { if (!opt->has_cont_list) { @@ -4139,15 +4239,15 @@ get_syn_options( if (get_id_list(&arg, 8, &opt->cont_list, skip) == FAIL) { return NULL; } - } else if (flagtab[fidx].argtype == 2) { + } else if (flagtab[fidx].argtype == 2) { if (get_id_list(&arg, 11, &opt->cont_in_list, skip) == FAIL) { return NULL; } - } else if (flagtab[fidx].argtype == 3) { + } else if (flagtab[fidx].argtype == 3) { if (get_id_list(&arg, 9, &opt->next_list, skip) == FAIL) { return NULL; } - } else if (flagtab[fidx].argtype == 11 && arg[5] == '=') { + } else if (flagtab[fidx].argtype == 11 && arg[5] == '=') { // cchar=? *conceal_char = utf_ptr2char(arg + 6); arg += mb_ptr2len(arg + 6) - 1; @@ -4168,20 +4268,22 @@ get_syn_options( } gname_start = arg; arg = skiptowhite(arg); - if (gname_start == arg) + if (gname_start == arg) { return NULL; + } gname = vim_strnsave(gname_start, arg - gname_start); if (STRCMP(gname, "NONE") == 0) { *opt->sync_idx = NONE_IDX; } else { syn_id = syn_name2id(gname); int i; - for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0; ) + for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0; ) { if (SYN_ITEMS(curwin->w_s)[i].sp_syn.id == syn_id && SYN_ITEMS(curwin->w_s)[i].sp_type == SPTYPE_START) { *opt->sync_idx = i; break; } + } if (i < 0) { EMSG2(_("E394: Didn't find region item for %s"), gname); xfree(gname); @@ -4192,9 +4294,10 @@ get_syn_options( xfree(gname); arg = skipwhite(arg); } else if (flagtab[fidx].flags == HL_FOLD - && foldmethodIsSyntax(curwin)) - /* Need to update folds later. */ + && foldmethodIsSyntax(curwin)) { + // Need to update folds later. foldUpdateAll(curwin); + } } } @@ -4208,8 +4311,9 @@ get_syn_options( */ static void syn_incl_toplevel(int id, int *flagsp) { - if ((*flagsp & HL_CONTAINED) || curwin->w_s->b_syn_topgrp == 0) + if ((*flagsp & HL_CONTAINED) || curwin->w_s->b_syn_topgrp == 0) { return; + } *flagsp |= HL_CONTAINED; if (curwin->w_s->b_syn_topgrp >= SYNID_CLUSTER) { // We have to alloc this, because syn_combine_list() will free it. @@ -4219,7 +4323,7 @@ static void syn_incl_toplevel(int id, int *flagsp) grp_list[0] = id; grp_list[1] = 0; syn_combine_list(&SYN_CLSTR(curwin->w_s)[tlg_id].scl_list, &grp_list, - CLUSTER_ADD); + CLUSTER_ADD); } } @@ -4228,18 +4332,19 @@ static void syn_incl_toplevel(int id, int *flagsp) */ static void syn_cmd_include(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; + char_u *arg = eap->arg; int sgl_id = 1; - char_u *group_name_end; - char_u *rest; - char_u *errormsg = NULL; + char_u *group_name_end; + char_u *rest; + char_u *errormsg = NULL; int prev_toplvl_grp; int prev_syn_inc_tag; bool source = false; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } if (arg[0] == '@') { ++arg; @@ -4249,9 +4354,10 @@ static void syn_cmd_include(exarg_T *eap, int syncing) return; } sgl_id = syn_check_cluster(arg, (int)(group_name_end - arg)); - if (sgl_id == 0) + if (sgl_id == 0) { return; - /* separate_nextcmd() and expand_filename() depend on this */ + } + // separate_nextcmd() and expand_filename() depend on this eap->arg = rest; } @@ -4267,8 +4373,9 @@ static void syn_cmd_include(exarg_T *eap, int syncing) // ":runtime!" is used. source = true; if (expand_filename(eap, syn_cmdlinep, &errormsg) == FAIL) { - if (errormsg != NULL) + if (errormsg != NULL) { EMSG(errormsg); + } return; } } @@ -4299,13 +4406,13 @@ static void syn_cmd_include(exarg_T *eap, int syncing) */ static void syn_cmd_keyword(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *group_name_end; + char_u *arg = eap->arg; + char_u *group_name_end; int syn_id; - char_u *rest; - char_u *keyword_copy = NULL; - char_u *p; - char_u *kw; + char_u *rest; + char_u *keyword_copy = NULL; + char_u *p; + char_u *kw; syn_opt_arg_T syn_opt_arg; int cnt; int conceal_char = NUL; @@ -4395,39 +4502,36 @@ error: } } - if (rest != NULL) + if (rest != NULL) { eap->nextcmd = check_nextcmd(rest); - else + } else { EMSG2(_(e_invarg2), arg); + } redraw_curbuf_later(SOME_VALID); - syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ + syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } -/* - * Handle ":syntax match {name} [{options}] {pattern} [{options}]". - * - * Also ":syntax sync match {name} [[grouphere | groupthere] {group-name}] .." - */ -static void -syn_cmd_match( - exarg_T *eap, - int syncing /* TRUE for ":syntax sync match .. " */ -) -{ - char_u *arg = eap->arg; - char_u *group_name_end; - char_u *rest; - synpat_T item; /* the item found in the line */ +/// Handle ":syntax match {name} [{options}] {pattern} [{options}]". +/// +/// Also ":syntax sync match {name} [[grouphere | groupthere] {group-name}] .." +/// +/// @param syncing TRUE for ":syntax sync match .. " +static void syn_cmd_match(exarg_T *eap, int syncing) +{ + char_u *arg = eap->arg; + char_u *group_name_end; + char_u *rest; + synpat_T item; // the item found in the line int syn_id; syn_opt_arg_T syn_opt_arg; int sync_idx = 0; int conceal_char = NUL; - /* Isolate the group name, check for validity */ + // Isolate the group name, check for validity rest = get_group_name(arg, &group_name_end); - /* Get options before the pattern */ + // Get options before the pattern syn_opt_arg.flags = 0; syn_opt_arg.keyword = false; syn_opt_arg.sync_idx = syncing ? &sync_idx : NULL; @@ -4437,7 +4541,7 @@ syn_cmd_match( syn_opt_arg.next_list = NULL; rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); - /* get the pattern. */ + // get the pattern. init_syn_patterns(); memset(&item, 0, sizeof(item)); rest = get_syn_pattern(rest, &item); @@ -4448,14 +4552,14 @@ syn_cmd_match( // Get options after the pattern rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip); - if (rest != NULL) { /* all arguments are valid */ + if (rest != NULL) { // all arguments are valid /* * Check for trailing command and illegal trailing arguments. */ eap->nextcmd = check_nextcmd(rest); - if (!ends_excmd(*rest) || eap->skip) + if (!ends_excmd(*rest) || eap->skip) { rest = NULL; - else { + } else { if ((syn_id = syn_check_group(arg, (int)(group_name_end - arg))) != 0) { syn_incl_toplevel(syn_id, &syn_opt_arg.flags); /* @@ -4473,19 +4577,22 @@ syn_cmd_match( spp->sp_cont_list = syn_opt_arg.cont_list; spp->sp_syn.cont_in_list = syn_opt_arg.cont_in_list; spp->sp_cchar = conceal_char; - if (syn_opt_arg.cont_in_list != NULL) + if (syn_opt_arg.cont_in_list != NULL) { curwin->w_s->b_syn_containedin = TRUE; + } spp->sp_next_list = syn_opt_arg.next_list; - /* remember that we found a match for syncing on */ - if (syn_opt_arg.flags & (HL_SYNC_HERE|HL_SYNC_THERE)) + // remember that we found a match for syncing on + if (syn_opt_arg.flags & (HL_SYNC_HERE|HL_SYNC_THERE)) { curwin->w_s->b_syn_sync_flags |= SF_MATCH; - if (syn_opt_arg.flags & HL_FOLD) + } + if (syn_opt_arg.flags & HL_FOLD) { ++curwin->w_s->b_syn_folditems; + } redraw_curbuf_later(SOME_VALID); - syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ - return; /* don't free the progs and patterns now */ + syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. + return; // don't free the progs and patterns now } } } @@ -4499,40 +4606,37 @@ syn_cmd_match( xfree(syn_opt_arg.cont_in_list); xfree(syn_opt_arg.next_list); - if (rest == NULL) + if (rest == NULL) { EMSG2(_(e_invarg2), arg); + } } -/* - * Handle ":syntax region {group-name} [matchgroup={group-name}] - * start {start} .. [skip {skip}] end {end} .. [{options}]". - */ -static void -syn_cmd_region( - exarg_T *eap, - int syncing /* TRUE for ":syntax sync region .." */ -) -{ - char_u *arg = eap->arg; - char_u *group_name_end; - char_u *rest; /* next arg, NULL on error */ - char_u *key_end; - char_u *key = NULL; - char_u *p; +/// Handle ":syntax region {group-name} [matchgroup={group-name}] +/// start {start} .. [skip {skip}] end {end} .. [{options}]". +/// +/// @param syncing TRUE for ":syntax sync region .." +static void syn_cmd_region(exarg_T *eap, int syncing) +{ + char_u *arg = eap->arg; + char_u *group_name_end; + char_u *rest; // next arg, NULL on error + char_u *key_end; + char_u *key = NULL; + char_u *p; int item; #define ITEM_START 0 #define ITEM_SKIP 1 #define ITEM_END 2 #define ITEM_MATCHGROUP 3 struct pat_ptr { - synpat_T *pp_synp; /* pointer to syn_pattern */ - int pp_matchgroup_id; /* matchgroup ID */ - struct pat_ptr *pp_next; /* pointer to next pat_ptr */ + synpat_T *pp_synp; // pointer to syn_pattern + int pp_matchgroup_id; // matchgroup ID + struct pat_ptr *pp_next; // pointer to next pat_ptr } *(pat_ptrs[3]); - /* patterns found in the line */ - struct pat_ptr *ppp; - struct pat_ptr *ppp_next; - int pat_count = 0; /* nr of syn_patterns found */ + // patterns found in the line + struct pat_ptr *ppp; + struct pat_ptr *ppp_next; + int pat_count = 0; // nr of syn_patterns found int syn_id; int matchgroup_id = 0; bool not_enough = false; // not enough arguments @@ -4541,7 +4645,7 @@ syn_cmd_region( syn_opt_arg_T syn_opt_arg; int conceal_char = NUL; - /* Isolate the group name, check for validity */ + // Isolate the group name, check for validity rest = get_group_name(arg, &group_name_end); pat_ptrs[0] = NULL; @@ -4566,10 +4670,11 @@ syn_cmd_region( break; } - /* must be a pattern or matchgroup then */ + // must be a pattern or matchgroup then key_end = rest; - while (*key_end && !ascii_iswhite(*key_end) && *key_end != '=') + while (*key_end && !ascii_iswhite(*key_end) && *key_end != '=') { ++key_end; + } xfree(key); key = vim_strnsave_up(rest, key_end - rest); if (STRCMP(key, "MATCHGROUP") == 0) { @@ -4601,9 +4706,9 @@ syn_cmd_region( if (item == ITEM_MATCHGROUP) { p = skiptowhite(rest); - if ((p - rest == 4 && STRNCMP(rest, "NONE", 4) == 0) || eap->skip) + if ((p - rest == 4 && STRNCMP(rest, "NONE", 4) == 0) || eap->skip) { matchgroup_id = 0; - else { + } else { matchgroup_id = syn_check_group(rest, (int)(p - rest)); if (matchgroup_id == 0) { illegal = true; @@ -4642,8 +4747,9 @@ syn_cmd_region( } } xfree(key); - if (illegal || not_enough) + if (illegal || not_enough) { rest = NULL; + } // Must have a "start" and "end" pattern. if (rest != NULL && (pat_ptrs[ITEM_START] == NULL @@ -4658,9 +4764,9 @@ syn_cmd_region( * If OK, add the item. */ eap->nextcmd = check_nextcmd(rest); - if (!ends_excmd(*rest) || eap->skip) + if (!ends_excmd(*rest) || eap->skip) { rest = NULL; - else { + } else { ga_grow(&(curwin->w_s->b_syn_patterns), pat_count); if ((syn_id = syn_check_group(arg, (int)(group_name_end - arg))) != 0) { syn_incl_toplevel(syn_id, &syn_opt_arg.flags); @@ -4687,15 +4793,17 @@ syn_cmd_region( syn_opt_arg.cont_list; SYN_ITEMS(curwin->w_s)[idx].sp_syn.cont_in_list = syn_opt_arg.cont_in_list; - if (syn_opt_arg.cont_in_list != NULL) + if (syn_opt_arg.cont_in_list != NULL) { curwin->w_s->b_syn_containedin = TRUE; + } SYN_ITEMS(curwin->w_s)[idx].sp_next_list = syn_opt_arg.next_list; } ++curwin->w_s->b_syn_patterns.ga_len; ++idx; - if (syn_opt_arg.flags & HL_FOLD) + if (syn_opt_arg.flags & HL_FOLD) { ++curwin->w_s->b_syn_folditems; + } } } @@ -4709,7 +4817,7 @@ syn_cmd_region( /* * Free the allocated memory. */ - for (item = ITEM_START; item <= ITEM_END; ++item) + for (item = ITEM_START; item <= ITEM_END; ++item) { for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp_next) { if (!success && ppp->pp_synp != NULL) { vim_regfree(ppp->pp_synp->sp_prog); @@ -4719,15 +4827,17 @@ syn_cmd_region( ppp_next = ppp->pp_next; xfree(ppp); } + } if (!success) { xfree(syn_opt_arg.cont_list); xfree(syn_opt_arg.cont_in_list); xfree(syn_opt_arg.next_list); - if (not_enough) + if (not_enough) { EMSG2(_("E399: Not enough arguments: syntax region %s"), arg); - else if (illegal || rest == NULL) + } else if (illegal || rest == NULL) { EMSG2(_(e_invarg2), arg); + } } } @@ -4742,8 +4852,7 @@ static int syn_compare_stub(const void *const v1, const void *const v2) // Combines lists of syntax clusters. // *clstr1 and *clstr2 must both be allocated memory; they will be consumed. -static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, - const int list_op) +static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, const int list_op) { size_t count1 = 0; size_t count2 = 0; @@ -4754,15 +4863,18 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, /* * Handle degenerate cases. */ - if (*clstr2 == NULL) + if (*clstr2 == NULL) { return; + } if (*clstr1 == NULL || list_op == CLUSTER_REPLACE) { - if (list_op == CLUSTER_REPLACE) + if (list_op == CLUSTER_REPLACE) { xfree(*clstr1); - if (list_op == CLUSTER_REPLACE || list_op == CLUSTER_ADD) + } + if (list_op == CLUSTER_REPLACE || list_op == CLUSTER_ADD) { *clstr1 = *clstr2; - else + } else { xfree(*clstr2); + } return; } @@ -4794,8 +4906,9 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, * We always want to add from the first list. */ if (*g1 < *g2) { - if (round == 2) + if (round == 2) { clstr[count] = *g1; + } count++; g1++; continue; @@ -4805,12 +4918,14 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, * lists. */ if (list_op == CLUSTER_ADD) { - if (round == 2) + if (round == 2) { clstr[count] = *g2; + } count++; } - if (*g1 == *g2) + if (*g1 == *g2) { g1++; + } g2++; } @@ -4819,13 +4934,18 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, * 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) + for (; *g1; g1++, count++) { + if (round == 2) { clstr[count] = *g1; - if (list_op == CLUSTER_ADD) - for (; *g2; g2++, count++) - if (round == 2) + } + } + if (list_op == CLUSTER_ADD) { + for (; *g2; g2++, count++) { + if (round == 2) { clstr[count] = *g2; + } + } + } if (round == 1) { /* @@ -4885,15 +5005,16 @@ static int syn_scl_namen2id(char_u *linep, int len) static int syn_check_cluster(char_u *pp, int len) { int id; - char_u *name; + char_u *name; name = vim_strnsave(pp, len); id = syn_scl_name2id(name); - if (id == 0) /* doesn't exist yet */ + if (id == 0) { // doesn't exist yet id = syn_add_cluster(name); - else + } else { xfree(name); + } return id; } @@ -4924,30 +5045,33 @@ static int syn_add_cluster(char_u *name) scp->scl_name_u = vim_strsave_up(name); scp->scl_list = NULL; - if (STRICMP(name, "Spell") == 0) + if (STRICMP(name, "Spell") == 0) { curwin->w_s->b_spell_cluster_id = len + SYNID_CLUSTER; - if (STRICMP(name, "NoSpell") == 0) + } + if (STRICMP(name, "NoSpell") == 0) { curwin->w_s->b_nospell_cluster_id = len + SYNID_CLUSTER; + } return len + SYNID_CLUSTER; } /* * Handle ":syntax cluster {cluster-name} [contains={groupname},..] - * [add={groupname},..] [remove={groupname},..]". + * [add={groupname},..] [remove={groupname},..]". */ static void syn_cmd_cluster(exarg_T *eap, int syncing) { - char_u *arg = eap->arg; - char_u *group_name_end; - char_u *rest; + char_u *arg = eap->arg; + char_u *group_name_end; + char_u *rest; bool got_clstr = false; int opt_len; int list_op; eap->nextcmd = find_nextcmd(arg); - if (eap->skip) + if (eap->skip) { return; + } rest = get_group_name(arg, &group_name_end); @@ -4971,8 +5095,9 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) && (ascii_iswhite(rest[8]) || rest[8] == '=')) { opt_len = 8; list_op = CLUSTER_REPLACE; - } else + } else { break; + } int16_t *clstr_list = NULL; if (get_id_list(&rest, opt_len, &clstr_list, eap->skip) == FAIL) { @@ -4990,14 +5115,16 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing) if (got_clstr) { redraw_curbuf_later(SOME_VALID); - syn_stack_free_all(curwin->w_s); /* Need to recompute all. */ + syn_stack_free_all(curwin->w_s); // Need to recompute all. } } - if (!got_clstr) + if (!got_clstr) { EMSG(_("E400: No cluster specified")); - if (rest == NULL || !ends_excmd(*rest)) + } + if (rest == NULL || !ends_excmd(*rest)) { EMSG2(_(e_invarg2), arg); + } } /* @@ -5016,10 +5143,10 @@ static void init_syn_patterns(void) */ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) { - char_u *end; - int *p; + char_u *end; + int *p; int idx; - char_u *cpo_save; + char_u *cpo_save; // need at least three chars if (arg == NULL || arg[0] == NUL || arg[1] == NUL || arg[2] == NUL) { @@ -5027,21 +5154,22 @@ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) } end = skip_regexp(arg + 1, *arg, TRUE, NULL); - if (*end != *arg) { /* end delimiter not found */ + if (*end != *arg) { // end delimiter not found EMSG2(_("E401: Pattern delimiter not found: %s"), arg); return NULL; } // store the pattern and compiled regexp program ci->sp_pattern = vim_strnsave(arg + 1, end - arg - 1); - /* Make 'cpoptions' empty, to avoid the 'l' flag */ + // Make 'cpoptions' empty, to avoid the 'l' flag cpo_save = p_cpo; p_cpo = (char_u *)""; ci->sp_prog = vim_regcomp(ci->sp_pattern, RE_MAGIC); p_cpo = cpo_save; - if (ci->sp_prog == NULL) + if (ci->sp_prog == NULL) { return NULL; + } ci->sp_ic = curwin->w_s->b_syn_ic; syn_clear_time(&ci->sp_time); @@ -5050,41 +5178,49 @@ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) */ ++end; do { - for (idx = SPO_COUNT; --idx >= 0; ) - if (STRNCMP(end, spo_name_tab[idx], 3) == 0) + for (idx = SPO_COUNT; --idx >= 0; ) { + if (STRNCMP(end, spo_name_tab[idx], 3) == 0) { break; + } + } if (idx >= 0) { p = &(ci->sp_offsets[idx]); - if (idx != SPO_LC_OFF) + if (idx != SPO_LC_OFF) { switch (end[3]) { - case 's': break; - case 'b': break; - case 'e': idx += SPO_COUNT; break; - default: idx = -1; break; + case 's': + break; + case 'b': + break; + case 'e': + idx += SPO_COUNT; break; + default: + idx = -1; break; } + } if (idx >= 0) { ci->sp_off_flags |= (1 << idx); - if (idx == SPO_LC_OFF) { /* lc=99 */ + if (idx == SPO_LC_OFF) { // lc=99 end += 3; *p = getdigits_int(&end, true, 0); - /* "lc=" offset automatically sets "ms=" offset */ + // "lc=" offset automatically sets "ms=" offset if (!(ci->sp_off_flags & (1 << SPO_MS_OFF))) { ci->sp_off_flags |= (1 << SPO_MS_OFF); ci->sp_offsets[SPO_MS_OFF] = *p; } - } else { /* yy=x+99 */ + } else { // yy=x+99 end += 4; if (*end == '+') { end++; *p = getdigits_int(&end, true, 0); // positive offset - } else if (*end == '-') { + } else if (*end == '-') { end++; *p = -getdigits_int(&end, true, 0); // negative offset } } - if (*end != ',') + if (*end != ',') { break; + } ++end; } } @@ -5102,14 +5238,14 @@ static char_u *get_syn_pattern(char_u *arg, synpat_T *ci) */ static void syn_cmd_sync(exarg_T *eap, int syncing) { - char_u *arg_start = eap->arg; - char_u *arg_end; - char_u *key = NULL; - char_u *next_arg; + char_u *arg_start = eap->arg; + char_u *arg_end; + char_u *key = NULL; + char_u *next_arg; int illegal = FALSE; int finished = FALSE; long n; - char_u *cpo_save; + char_u *cpo_save; if (ends_excmd(*arg_start)) { syn_cmd_list(eap, TRUE); @@ -5122,45 +5258,50 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) xfree(key); key = vim_strnsave_up(arg_start, arg_end - arg_start); if (STRCMP(key, "CCOMMENT") == 0) { - if (!eap->skip) + if (!eap->skip) { curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT; + } if (!ends_excmd(*next_arg)) { arg_end = skiptowhite(next_arg); - if (!eap->skip) + if (!eap->skip) { curwin->w_s->b_syn_sync_id = syn_check_group(next_arg, - (int)(arg_end - next_arg)); + (int)(arg_end - next_arg)); + } next_arg = skipwhite(arg_end); - } else if (!eap->skip) + } else if (!eap->skip) { curwin->w_s->b_syn_sync_id = syn_name2id((char_u *)"Comment"); - } else if ( STRNCMP(key, "LINES", 5) == 0 - || STRNCMP(key, "MINLINES", 8) == 0 - || STRNCMP(key, "MAXLINES", 8) == 0 - || STRNCMP(key, "LINEBREAKS", 10) == 0) { - if (key[4] == 'S') + } + } else if (STRNCMP(key, "LINES", 5) == 0 + || STRNCMP(key, "MINLINES", 8) == 0 + || STRNCMP(key, "MAXLINES", 8) == 0 + || STRNCMP(key, "LINEBREAKS", 10) == 0) { + if (key[4] == 'S') { arg_end = key + 6; - else if (key[0] == 'L') + } else if (key[0] == 'L') { arg_end = key + 11; - else + } else { arg_end = key + 9; + } if (arg_end[-1] != '=' || !ascii_isdigit(*arg_end)) { illegal = TRUE; break; } n = getdigits_long(&arg_end, false, 0); if (!eap->skip) { - if (key[4] == 'B') + if (key[4] == 'B') { curwin->w_s->b_syn_sync_linebreaks = n; - else if (key[1] == 'A') + } else if (key[1] == 'A') { curwin->w_s->b_syn_sync_maxlines = n; - else + } else { curwin->w_s->b_syn_sync_minlines = n; + } } - } else if (STRCMP(key, "FROMSTART") == 0) { + } else if (STRCMP(key, "FROMSTART") == 0) { if (!eap->skip) { curwin->w_s->b_syn_sync_minlines = MAXLNUM; curwin->w_s->b_syn_sync_maxlines = 0; } - } else if (STRCMP(key, "LINECONT") == 0) { + } else if (STRCMP(key, "LINECONT") == 0) { if (*next_arg == NUL) { // missing pattern illegal = true; break; @@ -5171,18 +5312,18 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) break; } arg_end = skip_regexp(next_arg + 1, *next_arg, TRUE, NULL); - if (*arg_end != *next_arg) { /* end delimiter not found */ + if (*arg_end != *next_arg) { // end delimiter not found illegal = TRUE; break; } if (!eap->skip) { - /* store the pattern and compiled regexp program */ + // store the pattern and compiled regexp program curwin->w_s->b_syn_linecont_pat = vim_strnsave(next_arg + 1, 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 */ + // Make 'cpoptions' empty, to avoid the 'l' flag cpo_save = p_cpo; p_cpo = (char_u *)""; curwin->w_s->b_syn_linecont_prog = @@ -5199,47 +5340,43 @@ static void syn_cmd_sync(exarg_T *eap, int syncing) next_arg = skipwhite(arg_end + 1); } else { eap->arg = next_arg; - if (STRCMP(key, "MATCH") == 0) + if (STRCMP(key, "MATCH") == 0) { syn_cmd_match(eap, TRUE); - else if (STRCMP(key, "REGION") == 0) + } else if (STRCMP(key, "REGION") == 0) { syn_cmd_region(eap, TRUE); - else if (STRCMP(key, "CLEAR") == 0) + } else if (STRCMP(key, "CLEAR") == 0) { syn_cmd_clear(eap, TRUE); - else + } else { illegal = TRUE; + } finished = TRUE; break; } arg_start = next_arg; } xfree(key); - if (illegal) + if (illegal) { EMSG2(_("E404: Illegal arguments: %s"), arg_start); - else if (!finished) { + } else if (!finished) { eap->nextcmd = check_nextcmd(arg_start); redraw_curbuf_later(SOME_VALID); - syn_stack_free_all(curwin->w_s); /* Need to recompute all syntax. */ + syn_stack_free_all(curwin->w_s); // Need to recompute all syntax. } } -/* - * Convert a line of highlight group names into a list of group ID numbers. - * "arg" should point to the "contains" or "nextgroup" keyword. - * "arg" is advanced to after the last group name. - * Careful: the argument is modified (NULs added). - * returns FAIL for some error, OK for success. - */ -static int -get_id_list( - char_u **const arg, - const int keylen, // length of keyword - int16_t **const list, // where to store the resulting list, if not - // NULL, the list is silently skipped! - const bool skip -) -{ - char_u *p = NULL; - char_u *end; +/// Convert a line of highlight group names into a list of group ID numbers. +/// "arg" should point to the "contains" or "nextgroup" keyword. +/// "arg" is advanced to after the last group name. +/// Careful: the argument is modified (NULs added). +/// +/// @param keylen length of keyword +/// @param list where to store the resulting list, if not NULL, the list is silently skipped! +/// +/// @return FAIL for some error, OK for success. +static int get_id_list(char_u **const arg, const int keylen, int16_t **const list, const bool skip) +{ + char_u *p = NULL; + char_u *end; int total_count = 0; int16_t *retval = NULL; regmatch_T regmatch; @@ -5271,10 +5408,10 @@ get_id_list( } char_u *const name = xmalloc((int)(end - p + 3)); // leave room for "^$" STRLCPY(name + 1, p, end - p + 1); - if ( STRCMP(name + 1, "ALLBUT") == 0 - || STRCMP(name + 1, "ALL") == 0 - || STRCMP(name + 1, "TOP") == 0 - || STRCMP(name + 1, "CONTAINED") == 0) { + if (STRCMP(name + 1, "ALLBUT") == 0 + || STRCMP(name + 1, "ALL") == 0 + || STRCMP(name + 1, "TOP") == 0 + || STRCMP(name + 1, "CONTAINED") == 0) { if (TOUPPER_ASC(**arg) != 'C') { EMSG2(_("E407: %s not allowed here"), name + 1); failed = true; @@ -5299,7 +5436,7 @@ get_id_list( } else { id = SYNID_CONTAINED + current_syn_inc_tag; } - } else if (name[1] == '@') { + } else if (name[1] == '@') { if (skip) { id = -1; } else { @@ -5364,12 +5501,14 @@ get_id_list( ++count; } p = skipwhite(end); - if (*p != ',') + if (*p != ',') { break; - p = skipwhite(p + 1); /* skip comma in between arguments */ + } + p = skipwhite(p + 1); // skip comma in between arguments } while (!ends_excmd(*p)); - if (failed) + if (failed) { break; + } if (round == 1) { retval = xmalloc((count + 1) * sizeof(*retval)); retval[count] = 0; // zero means end of the list @@ -5383,11 +5522,11 @@ get_id_list( return FAIL; } - if (*list == NULL) + if (*list == NULL) { *list = retval; - else - xfree(retval); /* list already found, don't overwrite it */ - + } else { + xfree(retval); // list already found, don't overwrite it + } return OK; } @@ -5410,20 +5549,17 @@ static int16_t *copy_id_list(const int16_t *const list) return retval; } -/* - * Check if syntax group "ssp" is in the ID list "list" of "cur_si". - * "cur_si" can be NULL if not checking the "containedin" list. - * Used to check if a syntax item is in the "contains" or "nextgroup" list of - * the current item. - * This function is called very often, keep it fast!! - */ -static int -in_id_list( - stateitem_T *cur_si, // current item or NULL - int16_t *list, // id list - struct sp_syn *ssp, // group id and ":syn include" tag of group - int contained // group id is contained -) +/// Check if syntax group "ssp" is in the ID list "list" of "cur_si". +/// "cur_si" can be NULL if not checking the "containedin" list. +/// Used to check if a syntax item is in the "contains" or "nextgroup" list of +/// the current item. +/// This function is called very often, keep it fast!! +/// +/// @param cur_si current item or NULL +/// @param list id list +/// @param ssp group id and ":syn include" tag of group +/// @param contained group id is contained +static int in_id_list(stateitem_T *cur_si, int16_t *list, struct sp_syn *ssp, int contained) { int retval; int16_t *scl_list; @@ -5432,30 +5568,35 @@ in_id_list( static int depth = 0; int r; - /* If ssp has a "containedin" list and "cur_si" is in it, return TRUE. */ + // If ssp has a "containedin" list and "cur_si" is in it, return TRUE. if (cur_si != NULL && ssp->cont_in_list != NULL && !(cur_si->si_flags & HL_MATCH)) { /* Ignore transparent items without a contains argument. Double check * that we don't go back past the first one. */ while ((cur_si->si_flags & HL_TRANS_CONT) - && cur_si > (stateitem_T *)(current_state.ga_data)) + && cur_si > (stateitem_T *)(current_state.ga_data)) { --cur_si; - /* cur_si->si_idx is -1 for keywords, these never contain anything. */ + } + // cur_si->si_idx is -1 for keywords, these never contain anything. if (cur_si->si_idx >= 0 && in_id_list(NULL, ssp->cont_in_list, - &(SYN_ITEMS(syn_block)[cur_si->si_idx].sp_syn), - SYN_ITEMS(syn_block)[cur_si->si_idx].sp_flags & HL_CONTAINED)) + &(SYN_ITEMS(syn_block)[cur_si->si_idx].sp_syn), + SYN_ITEMS(syn_block)[cur_si->si_idx].sp_flags & + HL_CONTAINED)) { return TRUE; + } } - if (list == NULL) + if (list == NULL) { 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 == ID_LIST_ALL) + if (list == ID_LIST_ALL) { return !contained; + } /* * If the first item is "ALLBUT", return TRUE if "id" is NOT in the @@ -5465,29 +5606,34 @@ in_id_list( item = *list; if (item >= SYNID_ALLBUT && item < SYNID_CLUSTER) { if (item < SYNID_TOP) { - /* ALL or ALLBUT: accept all groups in the same file */ - if (item - SYNID_ALLBUT != ssp->inc_tag) + // ALL or ALLBUT: accept all groups in the same file + if (item - SYNID_ALLBUT != ssp->inc_tag) { return FALSE; - } else if (item < SYNID_CONTAINED) { - /* TOP: accept all not-contained groups in the same file */ - if (item - SYNID_TOP != ssp->inc_tag || contained) + } + } else if (item < SYNID_CONTAINED) { + // TOP: accept all not-contained groups in the same file + if (item - SYNID_TOP != ssp->inc_tag || contained) { return FALSE; + } } else { - /* CONTAINED: accept all contained groups in the same file */ - if (item - SYNID_CONTAINED != ssp->inc_tag || !contained) + // CONTAINED: accept all contained groups in the same file + if (item - SYNID_CONTAINED != ssp->inc_tag || !contained) { return FALSE; + } } item = *++list; retval = FALSE; - } else + } else { retval = TRUE; + } /* * Return "retval" if id is in the contains list. */ while (item != 0) { - if (item == id) + if (item == id) { return retval; + } if (item >= SYNID_CLUSTER) { scl_list = SYN_CLSTR(syn_block)[item - SYNID_CLUSTER].scl_list; /* restrict recursiveness to 30 to avoid an endless loop for a @@ -5496,8 +5642,9 @@ in_id_list( ++depth; r = in_id_list(NULL, scl_list, ssp, contained); --depth; - if (r) + if (r) { return retval; + } } } item = *++list; @@ -5506,8 +5653,8 @@ in_id_list( } struct subcommand { - char *name; /* subcommand name */ - void (*func)(exarg_T *, int); /* function to call */ + char *name; // subcommand name + void (*func)(exarg_T *, int); // function to call }; static struct subcommand subcommands[] = @@ -5541,8 +5688,8 @@ static struct subcommand subcommands[] = */ void ex_syntax(exarg_T *eap) { - char_u *arg = eap->arg; - char_u *subcmd_end; + char_u *arg = eap->arg; + char_u *subcmd_end; syn_cmdlinep = eap->cmdlinep; @@ -5565,14 +5712,15 @@ void ex_syntax(exarg_T *eap) } } xfree(subcmd_name); - if (eap->skip) + if (eap->skip) { --emsg_skip; + } } void ex_ownsyntax(exarg_T *eap) { - char_u *old_value; - char_u *new_value; + char_u *old_value; + char_u *new_value; if (curwin->w_s == &curwin->w_buffer->b_s) { curwin->w_s = xmalloc(sizeof(synblock_T)); @@ -5662,7 +5810,7 @@ void set_context_in_syntax_cmd(expand_T *xp, const char *arg) include_link = 0; include_default = 0; - /* (part of) subcommand already typed */ + // (part of) subcommand already typed if (*arg != NUL) { const char *p = (const char *)skiptowhite((const char_u *)arg); if (*p != NUL) { // Past first word. @@ -5694,47 +5842,44 @@ void set_context_in_syntax_cmd(expand_T *xp, const char *arg) char_u *get_syntax_name(expand_T *xp, int idx) { switch (expand_what) { - case EXP_SUBCMD: - return (char_u *)subcommands[idx].name; - case EXP_CASE: { - static char *case_args[] = { "match", "ignore", NULL }; - return (char_u *)case_args[idx]; + case EXP_SUBCMD: + return (char_u *)subcommands[idx].name; + case EXP_CASE: { + static char *case_args[] = { "match", "ignore", NULL }; + return (char_u *)case_args[idx]; } - case EXP_SPELL: { - static char *spell_args[] = - { "toplevel", "notoplevel", "default", NULL }; - return (char_u *)spell_args[idx]; + case EXP_SPELL: { + static char *spell_args[] = + { "toplevel", "notoplevel", "default", NULL }; + return (char_u *)spell_args[idx]; } - case EXP_SYNC: { - static char *sync_args[] = - { "ccomment", "clear", "fromstart", - "linebreaks=", "linecont", "lines=", "match", - "maxlines=", "minlines=", "region", NULL }; - return (char_u *)sync_args[idx]; + case EXP_SYNC: { + static char *sync_args[] = + { "ccomment", "clear", "fromstart", + "linebreaks=", "linecont", "lines=", "match", + "maxlines=", "minlines=", "region", NULL }; + return (char_u *)sync_args[idx]; } } return NULL; } -// Function called for expression evaluation: get syntax ID at file position. -int syn_get_id( - win_T *wp, - long lnum, - colnr_T col, - int trans, // remove transparency - bool *spellp, // return: can do spell checking - int keep_state // keep state of char at "col" -) +/// Function called for expression evaluation: get syntax ID at file position. +/// +/// @param trans remove transparency +/// @param spellp return: can do spell checking +/// @param keep_state keep state of char at "col" +int syn_get_id(win_T *wp, long lnum, colnr_T col, int trans, bool *spellp, int keep_state) { // When the position is not after the current position and in the same // line of the same buffer, need to restart parsing. if (wp->w_buffer != syn_buf || lnum != current_lnum || col < current_col) { syntax_start(wp, lnum); } else if (col > current_col) { - // next_match may not be correct when moving around, e.g. with the - // "skip" expression in searchpair() - next_match_idx = -1; + // next_match may not be correct when moving around, e.g. with the + // "skip" expression in searchpair() + next_match_idx = -1; } (void)get_syntax_attr(col, spellp, keep_state); @@ -5842,8 +5987,9 @@ int syn_get_foldlevel(win_T *wp, long lnum) } if (level > wp->w_p_fdn) { level = wp->w_p_fdn; - if (level < 0) + if (level < 0) { level = 0; + } } return level; } @@ -5879,7 +6025,7 @@ static void syn_clear_time(syn_time_T *st) */ static void syntime_clear(void) { - synpat_T *spp; + synpat_T *spp; if (!syntax_present(curwin)) { MSG(_(msg_no_items)); @@ -5898,18 +6044,22 @@ static void syntime_clear(void) char_u *get_syntime_arg(expand_T *xp, int idx) { switch (idx) { - case 0: return (char_u *)"on"; - case 1: return (char_u *)"off"; - case 2: return (char_u *)"clear"; - case 3: return (char_u *)"report"; + case 0: + return (char_u *)"on"; + case 1: + return (char_u *)"off"; + case 2: + return (char_u *)"clear"; + case 3: + return (char_u *)"report"; } return NULL; } static int syn_compare_syntime(const void *v1, const void *v2) { - const time_entry_T *s1 = v1; - const time_entry_T *s2 = v2; + const time_entry_T *s1 = v1; + const time_entry_T *s2 = v2; return profile_cmp(s1->total, s2->total); } @@ -5954,14 +6104,13 @@ static void syntime_report(void) syn_compare_syntime); } - MSG_PUTS_TITLE(_( - " TOTAL COUNT MATCH SLOWEST AVERAGE NAME PATTERN")); + MSG_PUTS_TITLE(_(" TOTAL COUNT MATCH SLOWEST AVERAGE NAME PATTERN")); MSG_PUTS("\n"); for (int idx = 0; idx < ga.ga_len && !got_int; ++idx) { p = ((time_entry_T *)ga.ga_data) + idx; MSG_PUTS(profile_msg(p->total)); - MSG_PUTS(" "); /* make sure there is always a separating space */ + MSG_PUTS(" "); // make sure there is always a separating space msg_advance(13); msg_outnum(p->count); MSG_PUTS(" "); @@ -5980,12 +6129,14 @@ static void syntime_report(void) msg_advance(69); int len; - if (Columns < 80) - len = 20; /* will wrap anyway */ - else + if (Columns < 80) { + len = 20; // will wrap anyway + } else { len = Columns - 70; - if (len > (int)STRLEN(p->pattern)) + } + if (len > (int)STRLEN(p->pattern)) { len = (int)STRLEN(p->pattern); + } msg_outtrans_len(p->pattern, len); MSG_PUTS("\n"); } @@ -6000,7 +6151,7 @@ static void syntime_report(void) } /************************************** -* Highlighting stuff * +* Highlighting stuff * **************************************/ // The default highlight groups. These are compiled-in for fast startup and @@ -6009,8 +6160,7 @@ static void syntime_report(void) // When making changes here, also change runtime/colors/default.vim! static const char *highlight_init_both[] = { - "Conceal " - "ctermbg=DarkGrey ctermfg=LightGrey guibg=DarkGrey guifg=LightGrey", + "Conceal ctermbg=DarkGrey ctermfg=LightGrey guibg=DarkGrey guifg=LightGrey", "Cursor guibg=fg guifg=bg", "lCursor guibg=fg guifg=bg", "DiffText cterm=bold ctermbg=Red gui=bold guibg=Red", @@ -6042,10 +6192,8 @@ static const char *highlight_init_both[] = { "RedrawDebugClear ctermbg=Yellow guibg=Yellow", "RedrawDebugComposed ctermbg=Green guibg=Green", "RedrawDebugRecompose ctermbg=Red guibg=Red", - "Error term=reverse cterm=NONE ctermfg=White ctermbg=Red gui=NONE " - "guifg=White guibg=Red", - "Todo term=standout cterm=NONE ctermfg=Black ctermbg=Yellow gui=NONE " - "guifg=Blue guibg=Yellow", + "Error term=reverse cterm=NONE ctermfg=White ctermbg=Red gui=NONE guifg=White guibg=Red", + "Todo term=standout cterm=NONE ctermfg=Black ctermbg=Yellow gui=NONE guifg=Blue guibg=Yellow", "default link String Constant", "default link Character Constant", "default link Number Constant", @@ -6103,24 +6251,15 @@ static const char *highlight_init_light[] = { "Title ctermfg=DarkMagenta gui=bold guifg=Magenta", "Visual guibg=LightGrey", "WarningMsg ctermfg=DarkRed guifg=Red", - "Comment term=bold cterm=NONE ctermfg=DarkBlue ctermbg=NONE " - "gui=NONE guifg=Blue guibg=NONE", - "Constant term=underline cterm=NONE ctermfg=DarkRed ctermbg=NONE " - "gui=NONE guifg=Magenta guibg=NONE", - "Special term=bold cterm=NONE ctermfg=DarkMagenta ctermbg=NONE " - "gui=NONE guifg=#6a5acd guibg=NONE", - "Identifier term=underline cterm=NONE ctermfg=DarkCyan ctermbg=NONE " - "gui=NONE guifg=DarkCyan guibg=NONE", - "Statement term=bold cterm=NONE ctermfg=Brown ctermbg=NONE " - "gui=bold guifg=Brown guibg=NONE", - "PreProc term=underline cterm=NONE ctermfg=DarkMagenta ctermbg=NONE " - "gui=NONE guifg=#6a0dad guibg=NONE", - "Type term=underline cterm=NONE ctermfg=DarkGreen ctermbg=NONE " - "gui=bold guifg=SeaGreen guibg=NONE", - "Underlined term=underline cterm=underline ctermfg=DarkMagenta " - "gui=underline guifg=SlateBlue", - "Ignore term=NONE cterm=NONE ctermfg=white ctermbg=NONE " - "gui=NONE guifg=bg guibg=NONE", + "Comment term=bold cterm=NONE ctermfg=DarkBlue ctermbg=NONE gui=NONE guifg=Blue guibg=NONE", + "Constant term=underline cterm=NONE ctermfg=DarkRed ctermbg=NONE gui=NONE guifg=Magenta guibg=NONE", + "Special term=bold cterm=NONE ctermfg=DarkMagenta ctermbg=NONE gui=NONE guifg=#6a5acd guibg=NONE", + "Identifier term=underline cterm=NONE ctermfg=DarkCyan ctermbg=NONE gui=NONE guifg=DarkCyan guibg=NONE", + "Statement term=bold cterm=NONE ctermfg=Brown ctermbg=NONE gui=bold guifg=Brown guibg=NONE", + "PreProc term=underline cterm=NONE ctermfg=DarkMagenta ctermbg=NONE gui=NONE guifg=#6a0dad guibg=NONE", + "Type term=underline cterm=NONE ctermfg=DarkGreen ctermbg=NONE gui=bold guifg=SeaGreen guibg=NONE", + "Underlined term=underline cterm=underline ctermfg=DarkMagenta gui=underline guifg=SlateBlue", + "Ignore term=NONE cterm=NONE ctermfg=white ctermbg=NONE gui=NONE guifg=bg guibg=NONE", NULL }; @@ -6154,24 +6293,15 @@ static const char *highlight_init_dark[] = { "Title ctermfg=LightMagenta gui=bold guifg=Magenta", "Visual guibg=DarkGrey", "WarningMsg ctermfg=LightRed guifg=Red", - "Comment term=bold cterm=NONE ctermfg=Cyan ctermbg=NONE " - "gui=NONE guifg=#80a0ff guibg=NONE", - "Constant term=underline cterm=NONE ctermfg=Magenta ctermbg=NONE " - "gui=NONE guifg=#ffa0a0 guibg=NONE", - "Special term=bold cterm=NONE ctermfg=LightRed ctermbg=NONE " - "gui=NONE guifg=Orange guibg=NONE", - "Identifier term=underline cterm=bold ctermfg=Cyan ctermbg=NONE " - "gui=NONE guifg=#40ffff guibg=NONE", - "Statement term=bold cterm=NONE ctermfg=Yellow ctermbg=NONE " - "gui=bold guifg=#ffff60 guibg=NONE", - "PreProc term=underline cterm=NONE ctermfg=LightBlue ctermbg=NONE " - "gui=NONE guifg=#ff80ff guibg=NONE", - "Type term=underline cterm=NONE ctermfg=LightGreen ctermbg=NONE " - "gui=bold guifg=#60ff60 guibg=NONE", - "Underlined term=underline cterm=underline ctermfg=LightBlue " - "gui=underline guifg=#80a0ff", - "Ignore term=NONE cterm=NONE ctermfg=black ctermbg=NONE " - "gui=NONE guifg=bg guibg=NONE", + "Comment term=bold cterm=NONE ctermfg=Cyan ctermbg=NONE gui=NONE guifg=#80a0ff guibg=NONE", + "Constant term=underline cterm=NONE ctermfg=Magenta ctermbg=NONE gui=NONE guifg=#ffa0a0 guibg=NONE", + "Special term=bold cterm=NONE ctermfg=LightRed ctermbg=NONE gui=NONE guifg=Orange guibg=NONE", + "Identifier term=underline cterm=bold ctermfg=Cyan ctermbg=NONE gui=NONE guifg=#40ffff guibg=NONE", + "Statement term=bold cterm=NONE ctermfg=Yellow ctermbg=NONE gui=bold guifg=#ffff60 guibg=NONE", + "PreProc term=underline cterm=NONE ctermfg=LightBlue ctermbg=NONE gui=NONE guifg=#ff80ff guibg=NONE", + "Type term=underline cterm=NONE ctermfg=LightGreen ctermbg=NONE gui=bold guifg=#60ff60 guibg=NONE", + "Underlined term=underline cterm=underline ctermfg=LightBlue gui=underline guifg=#80a0ff", + "Ignore term=NONE cterm=NONE ctermfg=black ctermbg=NONE gui=NONE guifg=bg guibg=NONE", NULL }; @@ -6278,12 +6408,9 @@ const char *const highlight_init_cmdline[] = { "default link NvimInvalidAssignment NvimInvalid", "default link NvimInvalidPlainAssignment NvimInvalidAssignment", "default link NvimInvalidAugmentedAssignment NvimInvalidAssignment", - "default link NvimInvalidAssignmentWithAddition " - "NvimInvalidAugmentedAssignment", - "default link NvimInvalidAssignmentWithSubtraction " - "NvimInvalidAugmentedAssignment", - "default link NvimInvalidAssignmentWithConcatenation " - "NvimInvalidAugmentedAssignment", + "default link NvimInvalidAssignmentWithAddition NvimInvalidAugmentedAssignment", + "default link NvimInvalidAssignmentWithSubtraction NvimInvalidAugmentedAssignment", + "default link NvimInvalidAssignmentWithConcatenation NvimInvalidAugmentedAssignment", "default link NvimInvalidOperator NvimInvalid", @@ -6345,7 +6472,7 @@ const char *const highlight_init_cmdline[] = { "default link NvimInvalidOptionName NvimInvalidIdentifier", "default link NvimInvalidOptionScope NvimInvalidIdentifierScope", "default link NvimInvalidOptionScopeDelimiter " - "NvimInvalidIdentifierScopeDelimiter", + "NvimInvalidIdentifierScopeDelimiter", "default link NvimInvalidEnvironmentSigil NvimInvalidOptionSigil", "default link NvimInvalidEnvironmentName NvimInvalidIdentifier", @@ -6403,7 +6530,7 @@ void init_highlight(bool both, bool reset) bool okay = load_colors(copy_p); xfree(copy_p); if (okay) { - return; + return; } } @@ -6436,8 +6563,7 @@ void init_highlight(bool both, bool reset) * to avoid Statement highlighted text disappears. * Clear the attributes, needed when changing the t_Co value. */ if (t_colors > 8) { - do_highlight( - (*p_bg == 'l' + do_highlight((*p_bg == 'l' ? "Visual cterm=NONE ctermbg=LightGrey" : "Visual cterm=NONE ctermbg=DarkGrey"), false, true); } else { @@ -6456,7 +6582,7 @@ void init_highlight(bool both, bool reset) */ int load_colors(char_u *name) { - char_u *buf; + char_u *buf; int retval = FAIL; static bool recursive = false; @@ -6492,46 +6618,47 @@ static char *(color_names[28]) = { "DarkGray", "DarkGrey", "Blue", "LightBlue", "Green", "LightGreen", "Cyan", "LightCyan", "Red", "LightRed", "Magenta", - "LightMagenta", "Yellow", "LightYellow", "White", "NONE" }; - // indices: - // 0, 1, 2, 3, - // 4, 5, 6, 7, - // 8, 9, 10, 11, - // 12, 13, - // 14, 15, 16, 17, - // 18, 19, 20, 21, 22, - // 23, 24, 25, 26, 27 + "LightMagenta", "Yellow", "LightYellow", "White", "NONE" +}; +// indices: +// 0, 1, 2, 3, +// 4, 5, 6, 7, +// 8, 9, 10, 11, +// 12, 13, +// 14, 15, 16, 17, +// 18, 19, 20, 21, 22, +// 23, 24, 25, 26, 27 static int color_numbers_16[28] = { 0, 1, 2, 3, - 4, 5, 6, 6, - 7, 7, 7, 7, - 8, 8, - 9, 9, 10, 10, - 11, 11, 12, 12, 13, - 13, 14, 14, 15, -1 }; + 4, 5, 6, 6, + 7, 7, 7, 7, + 8, 8, + 9, 9, 10, 10, + 11, 11, 12, 12, 13, + 13, 14, 14, 15, -1 }; // for xterm with 88 colors... static int color_numbers_88[28] = { 0, 4, 2, 6, - 1, 5, 32, 72, - 84, 84, 7, 7, - 82, 82, - 12, 43, 10, 61, - 14, 63, 9, 74, 13, - 75, 11, 78, 15, -1 }; + 1, 5, 32, 72, + 84, 84, 7, 7, + 82, 82, + 12, 43, 10, 61, + 14, 63, 9, 74, 13, + 75, 11, 78, 15, -1 }; // for xterm with 256 colors... static int color_numbers_256[28] = { 0, 4, 2, 6, - 1, 5, 130, 3, - 248, 248, 7, 7, - 242, 242, - 12, 81, 10, 121, - 14, 159, 9, 224, 13, - 225, 11, 229, 15, -1 }; + 1, 5, 130, 3, + 248, 248, 7, 7, + 242, 242, + 12, 81, 10, 121, + 14, 159, 9, 224, 13, + 225, 11, 229, 15, -1 }; // for terminals with less than 16 colors... static int color_numbers_8[28] = { 0, 4, 2, 6, - 1, 5, 3, 3, - 7, 7, 7, 7, - 0+8, 0+8, - 4+8, 4+8, 2+8, 2+8, - 6+8, 6+8, 1+8, 1+8, 5+8, - 5+8, 3+8, 3+8, 7+8, -1 }; + 1, 5, 3, 3, + 7, 7, 7, 7, + 0+8, 0+8, + 4+8, 4+8, 2+8, 2+8, + 6+8, 6+8, 1+8, 1+8, 5+8, + 5+8, 3+8, 3+8, 7+8, -1 }; // Lookup the "cterm" value to be used for color with index "idx" in // color_names[]. @@ -6849,7 +6976,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (error) { break; } - if (*key == 'C') { + if (*key == 'C') { if (!init || !(HL_TABLE()[idx].sg_set & SG_CTERM)) { if (!init) { HL_TABLE()[idx].sg_set |= SG_CTERM; @@ -6865,7 +6992,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) HL_TABLE()[idx].sg_gui = attr; } } - } else if (STRCMP(key, "FONT") == 0) { + } else if (STRCMP(key, "FONT") == 0) { // in non-GUI fonts are simply ignored } else if (STRCMP(key, "CTERMFG") == 0 || STRCMP(key, "CTERMBG") == 0) { if (!init || !(HL_TABLE()[idx].sg_set & SG_CTERM)) { @@ -6890,10 +7017,10 @@ void do_highlight(const char *line, const bool forceit, const bool init) error = true; break; } - } else if (STRICMP(arg, "bg") == 0) { - if (cterm_normal_bg_color > 0) + } else if (STRICMP(arg, "bg") == 0) { + if (cterm_normal_bg_color > 0) { color = cterm_normal_bg_color - 1; - else { + } else { EMSG(_("E420: BG color unknown")); error = true; break; @@ -6960,7 +7087,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) } } } - } else if (strcmp(key, "GUIFG") == 0) { + } else if (strcmp(key, "GUIFG") == 0) { char **namep = &HL_TABLE()[idx].sg_rgb_fg_name; if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { @@ -6984,7 +7111,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (is_normal_group) { normal_fg = HL_TABLE()[idx].sg_rgb_fg; } - } else if (STRCMP(key, "GUIBG") == 0) { + } else if (STRCMP(key, "GUIBG") == 0) { char **const namep = &HL_TABLE()[idx].sg_rgb_bg_name; if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { @@ -7008,7 +7135,7 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (is_normal_group) { normal_bg = HL_TABLE()[idx].sg_rgb_bg; } - } else if (strcmp(key, "GUISP") == 0) { + } else if (strcmp(key, "GUISP") == 0) { char **const namep = &HL_TABLE()[idx].sg_rgb_sp_name; if (!init || !(HL_TABLE()[idx].sg_set & SG_GUI)) { @@ -7032,9 +7159,9 @@ void do_highlight(const char *line, const bool forceit, const bool init) if (is_normal_group) { normal_sp = HL_TABLE()[idx].sg_rgb_sp; } - } else if (strcmp(key, "START") == 0 || strcmp(key, "STOP") == 0) { + } else if (strcmp(key, "START") == 0 || strcmp(key, "STOP") == 0) { // Ignored for now - } else if (strcmp(key, "BLEND") == 0) { + } else if (strcmp(key, "BLEND") == 0) { if (strcmp(arg, "NONE") != 0) { HL_TABLE()[idx].sg_blend = strtol(arg, NULL, 10); } else { @@ -7134,13 +7261,13 @@ void restore_cterm_colors(void) static int hl_has_settings(int idx, bool check_link) { return HL_TABLE()[idx].sg_cleared == 0 - && (HL_TABLE()[idx].sg_attr != 0 - || HL_TABLE()[idx].sg_cterm_fg != 0 - || HL_TABLE()[idx].sg_cterm_bg != 0 - || HL_TABLE()[idx].sg_rgb_fg_name != NULL - || HL_TABLE()[idx].sg_rgb_bg_name != NULL - || HL_TABLE()[idx].sg_rgb_sp_name != NULL - || (check_link && (HL_TABLE()[idx].sg_set & SG_LINK))); + && (HL_TABLE()[idx].sg_attr != 0 + || HL_TABLE()[idx].sg_cterm_fg != 0 + || HL_TABLE()[idx].sg_cterm_bg != 0 + || HL_TABLE()[idx].sg_rgb_fg_name != NULL + || HL_TABLE()[idx].sg_rgb_bg_name != NULL + || HL_TABLE()[idx].sg_rgb_sp_name != NULL + || (check_link && (HL_TABLE()[idx].sg_set & SG_LINK))); } /* @@ -7188,18 +7315,18 @@ static void highlight_list_one(const int id) } didh = highlight_list_arg(id, didh, LIST_ATTR, - sgp->sg_cterm, NULL, "cterm"); + sgp->sg_cterm, NULL, "cterm"); didh = highlight_list_arg(id, didh, LIST_INT, - sgp->sg_cterm_fg, NULL, "ctermfg"); + sgp->sg_cterm_fg, NULL, "ctermfg"); didh = highlight_list_arg(id, didh, LIST_INT, - sgp->sg_cterm_bg, NULL, "ctermbg"); + sgp->sg_cterm_bg, NULL, "ctermbg"); didh = highlight_list_arg(id, didh, LIST_ATTR, - sgp->sg_gui, NULL, "gui"); + sgp->sg_gui, NULL, "gui"); didh = highlight_list_arg(id, didh, LIST_STRING, - 0, sgp->sg_rgb_fg_name, "guifg"); + 0, sgp->sg_rgb_fg_name, "guifg"); didh = highlight_list_arg(id, didh, LIST_STRING, - 0, sgp->sg_rgb_bg_name, "guibg"); + 0, sgp->sg_rgb_bg_name, "guibg"); didh = highlight_list_arg(id, didh, LIST_STRING, 0, sgp->sg_rgb_sp_name, "guisp"); @@ -7245,9 +7372,8 @@ Dictionary get_global_hl_defs(void) /// @param type one of \ref LIST_XXX /// @param iarg integer argument used if \p type == LIST_INT /// @param sarg string used if \p type == LIST_STRING -static bool highlight_list_arg( - const int id, bool didh, const int type, int iarg, - char *const sarg, const char *const name) +static bool highlight_list_arg(const int id, bool didh, const int type, int iarg, char *const sarg, + const char *const name) { char buf[100]; @@ -7264,10 +7390,11 @@ static bool highlight_list_arg( buf[0] = NUL; for (int i = 0; hl_attr_table[i] != 0; i++) { if (iarg & hl_attr_table[i]) { - if (buf[0] != NUL) + if (buf[0] != NUL) { xstrlcat((char *)buf, ",", 100); + } xstrlcat((char *)buf, hl_name_table[i], 100); - iarg &= ~hl_attr_table[i]; /* don't want "inverse" */ + iarg &= ~hl_attr_table[i]; // don't want "inverse" } } } @@ -7320,8 +7447,7 @@ const char *highlight_has_attr(const int id, const int flag, const int modec) /// /// @return color name, possibly in a static buffer. Buffer will be overwritten /// on next highlight_color() call. May return NULL. -const char *highlight_color(const int id, const char *const what, - const int modec) +const char *highlight_color(const int id, const char *const what, const int modec) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL { static char name[20]; @@ -7347,11 +7473,11 @@ const char *highlight_color(const int id, const char *const what, if (modec == 'g') { if (what[2] == '#' && ui_rgb_attached()) { if (fg) { - n = HL_TABLE()[id - 1].sg_rgb_fg; + n = HL_TABLE()[id - 1].sg_rgb_fg; } else if (sp) { - n = HL_TABLE()[id - 1].sg_rgb_sp; + n = HL_TABLE()[id - 1].sg_rgb_sp; } else { - n = HL_TABLE()[id - 1].sg_rgb_bg; + n = HL_TABLE()[id - 1].sg_rgb_bg; } if (n < 0 || n > 0xffffff) { return NULL; @@ -7393,8 +7519,8 @@ const char *highlight_color(const int id, const char *const what, /// @param id highlight group id /// @param force_newline always start a new line /// @return true when started a new line. -static bool syn_list_header(const bool did_header, const int outlen, - const int id, bool force_newline) +static bool syn_list_header(const bool did_header, const int outlen, const int id, + bool force_newline) { int endcol = 19; bool newline = true; @@ -7410,7 +7536,7 @@ static bool syn_list_header(const bool did_header, const int outlen, } else if ((ui_has(kUIMessages) || msg_silent) && !force_newline) { msg_putchar(' '); adjust = false; - } else if (msg_col + outlen + 1 >= Columns || force_newline) { + } else if (msg_col + outlen + 1 >= Columns || force_newline) { msg_putchar('\n'); if (got_int) { return true; @@ -7430,7 +7556,7 @@ static bool syn_list_header(const bool did_header, const int outlen, msg_advance(endcol); } - /* Show "xxx" with the attributes. */ + // Show "xxx" with the attributes. if (!did_header) { msg_puts_attr("xxx", syn_id2attr(id)); msg_putchar(' '); @@ -7445,7 +7571,7 @@ static bool syn_list_header(const bool did_header, const int outlen, static void set_hl_attr(int idx) { HlAttrs at_en = HLATTRS_INIT; - struct hl_group *sgp = HL_TABLE() + idx; + struct hl_group *sgp = HL_TABLE() + idx; at_en.cterm_ae_attr = sgp->sg_cterm; at_en.cterm_fg_color = sgp->sg_cterm_fg; @@ -7525,8 +7651,9 @@ int highlight_exists(const char_u *name) */ char_u *syn_id2name(int id) { - if (id <= 0 || id > highlight_ga.ga_len) + if (id <= 0 || id > highlight_ga.ga_len) { return (char_u *)""; + } return HL_TABLE()[id - 1].sg_name; } @@ -7554,15 +7681,15 @@ int syn_check_group(const char_u *name, int len) /// @see syn_check_group syn_unadd_group static int syn_add_group(char_u *name) { - char_u *p; + char_u *p; - /* Check that the name is ASCII letters, digits and underscore. */ + // Check that the name is ASCII letters, digits and underscore. for (p = name; *p != NUL; ++p) { if (!vim_isprintc(*p)) { EMSG(_("E669: Unprintable character in group name")); xfree(name); return 0; - } else if (!ASCII_ISALNUM(*p) && *p != '_') { + } else if (!ASCII_ISALNUM(*p) && *p != '_') { /* This is an error, but since there previously was no check only * give a warning. */ msg_source(HL_ATTR(HLF_W)); @@ -7588,7 +7715,7 @@ static int syn_add_group(char_u *name) char *const name_up = (char *)vim_strsave_up(name); // Append another syntax_highlight entry. - struct hl_group* hlgp = GA_APPEND_VIA_PTR(struct hl_group, &highlight_ga); + struct hl_group * hlgp = GA_APPEND_VIA_PTR(struct hl_group, &highlight_ga); memset(hlgp, 0, sizeof(*hlgp)); hlgp->sg_name = name; hlgp->sg_rgb_bg = -1; @@ -7640,9 +7767,9 @@ int syn_get_final_id(int hl_id) { int count; - if (hl_id > highlight_ga.ga_len || hl_id < 1) - return 0; /* Can be called from eval!! */ - + if (hl_id > highlight_ga.ga_len || hl_id < 1) { + return 0; // Can be called from eval!! + } /* * Follow links until there is no more. * Look out for loops! Break after 100 links. @@ -7690,8 +7817,7 @@ void highlight_attr_set_all(void) } // Apply difference between User[1-9] and HLF_S to HLF_SNC. -static void combine_stl_hlt(int id, int id_S, int id_alt, int hlcnt, int i, - int hlf, int *table) +static void combine_stl_hlt(int id, int id_S, int id_alt, int hlcnt, int i, int hlf, int *table) FUNC_ATTR_NONNULL_ALL { struct hl_group *const hlt = HL_TABLE(); @@ -7808,7 +7934,7 @@ void set_context_in_highlight_cmd(expand_T *xp, const char *arg) include_link = 2; include_default = 1; - /* (part of) subcommand already typed */ + // (part of) subcommand already typed if (*arg != NUL) { const char *p = (const char *)skiptowhite((const char_u *)arg); if (*p != NUL) { // Past "default" or group name. @@ -7818,7 +7944,7 @@ void set_context_in_highlight_cmd(expand_T *xp, const char *arg) xp->xp_pattern = (char_u *)arg; p = (const char *)skiptowhite((const char_u *)arg); } - if (*p != NUL) { /* past group name */ + if (*p != NUL) { // past group name include_link = 0; if (arg[1] == 'i' && arg[0] == 'N') { highlight_list(); @@ -8597,7 +8723,6 @@ color_name_table_T color_name_table[] = { /// return the hex value or -1 if could not find a correct value RgbValue name_to_color(const char *name) { - if (name[0] == '#' && isxdigit(name[1]) && isxdigit(name[2]) && isxdigit(name[3]) && isxdigit(name[4]) && isxdigit(name[5]) && isxdigit(name[6]) && name[7] == NUL) { @@ -8620,5 +8745,5 @@ RgbValue name_to_color(const char *name) /************************************** -* End of Highlighting stuff * +* End of Highlighting stuff * **************************************/ diff --git a/src/nvim/testdir/test_breakindent.vim b/src/nvim/testdir/test_breakindent.vim index 5542746a04..97b570e64f 100644 --- a/src/nvim/testdir/test_breakindent.vim +++ b/src/nvim/testdir/test_breakindent.vim @@ -67,7 +67,8 @@ endfunc func Test_breakindent02() " simple breakindent test with showbreak set - call s:test_windows('setl briopt=min:0 sbr=>>') + set sbr=>> + call s:test_windows('setl briopt=min:0 sbr=') let lines = s:screen_lines(line('.'),8) let expect = [ \ " abcd", @@ -127,7 +128,8 @@ endfunc func Test_breakindent04() " breakindent set with min width 18 - call s:test_windows('setl sbr= briopt=min:18') + set sbr=<<< + call s:test_windows('setl sbr=NONE briopt=min:18') let lines = s:screen_lines(line('.'),8) let expect = [ \ " abcd", @@ -137,6 +139,7 @@ func Test_breakindent04() call s:compare_lines(expect, lines) " clean up call s:close_windows('set sbr=') + set sbr= endfunc func Test_breakindent04_vartabs() @@ -868,4 +871,22 @@ func Test_breakindent20_list() call s:close_windows('set breakindent& briopt& linebreak& list& listchars& showbreak&') endfunc +" The following used to crash Vim. This is fixed by 8.2.3391. +" This is a regression introduced by 8.2.2903. +func Test_window_resize_with_linebreak() + new + 53vnew + set linebreak + set showbreak=>> + set breakindent + set breakindentopt=shift:4 + call setline(1, "\naaaaaaaaa\n\na\naaaaa\n¯aaaaaaaaaa\naaaaaaaaaaaa\naaa\n\"a:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - aaaaaaaa\"\naaaaaaaa\n\"a") + redraw! + call assert_equal([" >>aa^@\"a: "], ScreenLines(2, 14)) + vertical resize 52 + redraw! + call assert_equal([" >>aaa^@\"a:"], ScreenLines(2, 14)) + %bw! +endfunc + " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_display.vim b/src/nvim/testdir/test_display.vim index c702b44b88..12327f34d6 100644 --- a/src/nvim/testdir/test_display.vim +++ b/src/nvim/testdir/test_display.vim @@ -262,3 +262,21 @@ func Test_display_scroll_at_topline() call StopVimInTerminal(buf) endfunc + +func Test_display_linebreak_breakat() + new + vert resize 25 + let _breakat = &breakat + setl signcolumn=yes linebreak breakat=) showbreak=+\ + call setline(1, repeat('x', winwidth(0) - 2) .. ')abc') + let lines = ScreenLines([1, 2], 25) + let expected = [ + \ ' xxxxxxxxxxxxxxxxxxxxxxx', + \ ' + )abc ' + \ ] + call assert_equal(expected, lines) + %bw! + let &breakat=_breakat +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_eval_stuff.vim b/src/nvim/testdir/test_eval_stuff.vim index 4870b9a60a..084c856ba0 100644 --- a/src/nvim/testdir/test_eval_stuff.vim +++ b/src/nvim/testdir/test_eval_stuff.vim @@ -33,6 +33,24 @@ func Test_for_invalid() redraw endfunc +func Test_readfile_binary() + new + call setline(1, ['one', 'two', 'three']) + setlocal ff=dos + silent write XReadfile + let lines = readfile('XReadfile') + call assert_equal(['one', 'two', 'three'], lines) + let lines = readfile('XReadfile', '', 2) + call assert_equal(['one', 'two'], lines) + let lines = readfile('XReadfile', 'b') + call assert_equal(["one\r", "two\r", "three\r", ""], lines) + let lines = readfile('XReadfile', 'b', 2) + call assert_equal(["one\r", "two\r"], lines) + + bwipe! + call delete('XReadfile') +endfunc + func Test_mkdir_p() call mkdir('Xmkdir/nested', 'p') call assert_true(isdirectory('Xmkdir/nested')) @@ -90,6 +108,15 @@ func Test_string_concatenation() call assert_equal('ab', a) endfunc +" Test fix for issue #4507 +func Test_skip_after_throw() + try + throw 'something' + let x = wincol() || &ts + catch /something/ + endtry +endfunc + func Test_nocatch_restore_silent_emsg() silent! try throw 1 @@ -111,15 +138,6 @@ func Test_let_errmsg() let v:errmsg = '' endfunc -" Test fix for issue #4507 -func Test_skip_after_throw() - try - throw 'something' - let x = wincol() || &ts - catch /something/ - endtry -endfunc - func Test_number_max_min_size() " This will fail on systems without 64 bit number support or when not " configured correctly. diff --git a/src/nvim/testdir/test_expr.vim b/src/nvim/testdir/test_expr.vim index 0b41a1127a..c49285621a 100644 --- a/src/nvim/testdir/test_expr.vim +++ b/src/nvim/testdir/test_expr.vim @@ -502,6 +502,17 @@ func Test_empty_concatenate() call assert_equal('b', 'b' . 'a'[4:0]) endfunc +func Test_broken_number() + let X = 'bad' + call assert_fails('echo 1X', 'E15:') + call assert_fails('echo 0b1X', 'E15:') + call assert_fails('echo 0b12', 'E15:') + call assert_fails('echo 0x1X', 'E15:') + call assert_fails('echo 011X', 'E15:') + call assert_equal(2, str2nr('2a')) + call assert_fails('inoremap <Char-0b1z> b', 'E474:') +endfunc + func Test_eval_after_if() let s:val = '' func SetVal(x) diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim index 4d29d18330..5326d3460f 100644 --- a/src/nvim/testdir/test_filetype.vim +++ b/src/nvim/testdir/test_filetype.vim @@ -295,6 +295,7 @@ let s:filename_checks = { \ 'lss': ['file.lss'], \ 'lua': ['file.lua', 'file.rockspec', 'file.nse'], \ 'lynx': ['lynx.cfg'], + \ 'matlab': ['file.m'], \ 'm3build': ['m3makefile', 'm3overrides'], \ 'm3quake': ['file.quake', 'cm3.cfg'], \ 'm4': ['file.at'], @@ -350,6 +351,7 @@ let s:filename_checks = { \ 'obj': ['file.obj'], \ 'ocaml': ['file.ml', 'file.mli', 'file.mll', 'file.mly', '.ocamlinit', 'file.mlt', 'file.mlp', 'file.mlip', 'file.mli.cppo', 'file.ml.cppo'], \ 'occam': ['file.occ'], + \ 'octave': ['octaverc', '.octaverc', 'octave.conf'], \ 'omnimark': ['file.xom', 'file.xin'], \ 'opam': ['opam', 'file.opam', 'file.opam.template'], \ 'openroad': ['file.or'], @@ -825,4 +827,96 @@ func Test_dsl_file() filetype off endfunc +func Test_m_file() + filetype on + + call writefile(['looks like Matlab'], 'Xfile.m') + split Xfile.m + call assert_equal('matlab', &filetype) + bwipe! + + let g:filetype_m = 'octave' + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + unlet g:filetype_m + + " Test dist#ft#FTm() + + " Objective-C + + call writefile(['// Objective-C line comment'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + call writefile(['/* Objective-C block comment */'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + call writefile(['#import "test.m"'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + " Octave + + call writefile(['# Octave line comment'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['#{', 'Octave block comment', '#}'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['%{', 'Octave block comment', '%}'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['%!test "Octave test"'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['unwind_protect'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['function test(); 42; endfunction'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + " Mathematica + + call writefile(['(* Mathematica comment'], 'Xfile.m') + split Xfile.m + call assert_equal('mma', &filetype) + bwipe! + + " Murphi + + call writefile(['-- Murphi comment'], 'Xfile.m') + split Xfile.m + call assert_equal('murphi', &filetype) + bwipe! + + call writefile(['/* Murphi block comment */', 'Type'], 'Xfile.m') + split Xfile.m + call assert_equal('murphi', &filetype) + bwipe! + + call writefile(['Type'], 'Xfile.m') + split Xfile.m + call assert_equal('murphi', &filetype) + bwipe! + + call delete('Xfile.m') + filetype off +endfunc " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim index b35a210055..e82fefc7fc 100644 --- a/src/nvim/testdir/test_functions.vim +++ b/src/nvim/testdir/test_functions.vim @@ -152,6 +152,10 @@ func Test_str2nr() call assert_equal(65, str2nr('0101', 8)) call assert_equal(-65, str2nr('-101', 8)) call assert_equal(-65, str2nr('-0101', 8)) + call assert_equal(65, str2nr('0o101', 8)) + call assert_equal(65, str2nr('0O0101', 8)) + call assert_equal(-65, str2nr('-0O101', 8)) + call assert_equal(-65, str2nr('-0o0101', 8)) call assert_equal(11259375, str2nr('abcdef', 16)) call assert_equal(11259375, str2nr('ABCDEF', 16)) @@ -161,8 +165,16 @@ func Test_str2nr() call assert_equal(11259375, str2nr('0XABCDEF', 16)) call assert_equal(-11259375, str2nr('-0xABCDEF', 16)) + call assert_equal(1, str2nr("1'000'000", 10, 0)) + call assert_equal(256, str2nr("1'0000'0000", 2, 1)) + call assert_equal(262144, str2nr("1'000'000", 8, 1)) + call assert_equal(1000000, str2nr("1'000'000", 10, 1)) + call assert_equal(1000, str2nr("1'000''000", 10, 1)) + call assert_equal(65536, str2nr("1'00'00", 16, 1)) + call assert_equal(0, str2nr('0x10')) call assert_equal(0, str2nr('0b10')) + call assert_equal(0, str2nr('0o10')) call assert_equal(1, str2nr('12', 2)) call assert_equal(1, str2nr('18', 8)) call assert_equal(1, str2nr('1g', 16)) diff --git a/src/nvim/testdir/test_highlight.vim b/src/nvim/testdir/test_highlight.vim index 24c9c3580e..6fd9477ce9 100644 --- a/src/nvim/testdir/test_highlight.vim +++ b/src/nvim/testdir/test_highlight.vim @@ -426,6 +426,7 @@ func Test_highlight_eol_with_cursorline_breakindent() let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() call NewWindow('topleft 5', 10) + set showbreak=xxx setlocal breakindent breakindentopt=min:0,shift:1 showbreak=> call setline(1, ' ' . repeat('a', 9) . 'bcd') call matchadd('Search', '\n') @@ -483,6 +484,7 @@ func Test_highlight_eol_with_cursorline_breakindent() call CloseWindow() set showbreak= + setlocal showbreak= exe hiCursorLine endfunc diff --git a/src/nvim/testdir/test_ins_complete.vim b/src/nvim/testdir/test_ins_complete.vim index 0fb026f6b0..ce75799551 100644 --- a/src/nvim/testdir/test_ins_complete.vim +++ b/src/nvim/testdir/test_ins_complete.vim @@ -497,6 +497,133 @@ func Test_ins_compl_tag_sft() %bwipe! endfunc +" Test for completing special characters +func Test_complete_special_chars() + new + call setline(1, 'int .*[-\^$ func float') + call feedkeys("oin\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>", 'xt') + call assert_equal('int .*[-\^$ func float', getline(2)) + close! +endfunc + +" Test for completion when text is wrapped across lines. +func Test_complete_across_line() + new + call setline(1, ['red green blue', 'one two three']) + setlocal textwidth=20 + exe "normal 2G$a re\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>" + call assert_equal(['one two three red', 'green blue one'], getline(2, '$')) + close! +endfunc + +" Test for using CTRL-L to add one character when completing matching +func Test_complete_add_onechar() + new + call setline(1, ['wool', 'woodwork']) + call feedkeys("Gowoo\<C-P>\<C-P>\<C-P>\<C-L>f", 'xt') + call assert_equal('woof', getline(3)) + + " use 'ignorecase' and backspace to erase characters from the prefix string + " and then add letters using CTRL-L + %d + set ignorecase backspace=2 + setlocal complete=. + call setline(1, ['workhorse', 'workload']) + normal Go + exe "normal aWOR\<C-P>\<bs>\<bs>\<bs>\<bs>\<bs>\<bs>\<C-L>r\<C-L>\<C-L>" + call assert_equal('workh', getline(3)) + set ignorecase& backspace& + close! +endfunc + +" Test insert completion with 'cindent' (adjust the indent) +func Test_complete_with_cindent() + new + setlocal cindent + call setline(1, ['if (i == 1)', " j = 2;"]) + exe "normal Go{\<CR>i\<C-X>\<C-L>\<C-X>\<C-L>\<CR>}" + call assert_equal(['{', "\tif (i == 1)", "\t\tj = 2;", '}'], getline(3, '$')) + + %d + call setline(1, ['when while', '{', '']) + setlocal cinkeys+==while + exe "normal Giwh\<C-P> " + call assert_equal("\twhile ", getline('$')) + close! +endfunc + +" Test for <CTRL-X> <CTRL-V> completion. Complete commands and functions +func Test_complete_cmdline() + new + exe "normal icaddb\<C-X>\<C-V>" + call assert_equal('caddbuffer', getline(1)) + exe "normal ocall getqf\<C-X>\<C-V>" + call assert_equal('call getqflist(', getline(2)) + exe "normal oabcxyz(\<C-X>\<C-V>" + call assert_equal('abcxyz(', getline(3)) + com! -buffer TestCommand1 echo 'TestCommand1' + com! -buffer TestCommand2 echo 'TestCommand2' + write TestCommand1Test + write TestCommand2Test + " Test repeating <CTRL-X> <CTRL-V> and switching to another CTRL-X mode + exe "normal oT\<C-X>\<C-V>\<C-X>\<C-V>\<C-X>\<C-F>\<Esc>" + call assert_equal('TestCommand2Test', getline(4)) + call delete('TestCommand1Test') + call delete('TestCommand2Test') + delcom TestCommand1 + delcom TestCommand2 + close! +endfunc + +" Test for <CTRL-X> <CTRL-Z> stopping completion without changing the match +func Test_complete_stop() + new + func Save_mode1() + let g:mode1 = mode(1) + return '' + endfunc + func Save_mode2() + let g:mode2 = mode(1) + return '' + endfunc + inoremap <F1> <C-R>=Save_mode1()<CR> + inoremap <F2> <C-R>=Save_mode2()<CR> + call setline(1, ['aaa bbb ccc ']) + exe "normal A\<C-N>\<C-P>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc ', getline(1)) + exe "normal A\<C-N>\<Down>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc aaa', getline(1)) + set completeopt+=noselect + exe "normal A \<C-N>\<Down>\<Down>\<C-L>\<C-L>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc aaa bb', getline(1)) + set completeopt& + exe "normal A d\<C-N>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc aaa bb d', getline(1)) + com! -buffer TestCommand1 echo 'TestCommand1' + com! -buffer TestCommand2 echo 'TestCommand2' + exe "normal oT\<C-X>\<C-V>\<C-X>\<C-V>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('TestCommand2', getline(2)) + delcom TestCommand1 + delcom TestCommand2 + unlet g:mode1 + unlet g:mode2 + iunmap <F1> + iunmap <F2> + delfunc Save_mode1 + delfunc Save_mode2 + close! +endfunc + " Test to ensure 'Scanning...' messages are not recorded in messages history func Test_z1_complete_no_history() new diff --git a/src/nvim/testdir/test_syntax.vim b/src/nvim/testdir/test_syntax.vim index 2344bac498..914d9c2782 100644 --- a/src/nvim/testdir/test_syntax.vim +++ b/src/nvim/testdir/test_syntax.vim @@ -116,7 +116,7 @@ func Test_syntime() let a = execute('syntime report') call assert_equal("\nNo Syntax items defined for this buffer", a) - view ../memfile_test.c + view samples/memfile_test.c setfiletype cpp redraw let a = execute('syntime report') diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c index e9d82ca87d..f5bd5479c4 100644 --- a/src/nvim/viml/parser/expressions.c +++ b/src/nvim/viml/parser/expressions.c @@ -351,7 +351,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags) } if (exp_start) { vim_str2nr(pline.data + exp_start, NULL, NULL, 0, NULL, &exp_part, - (int)(ret.len - exp_start)); + (int)(ret.len - exp_start), false); } if (exp_negative) { exp_part += frac_size; @@ -369,7 +369,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags) int len; int prep; vim_str2nr(pline.data, &prep, &len, STR2NR_ALL, NULL, - &ret.data.num.val.integer, (int)pline.size); + &ret.data.num.val.integer, (int)pline.size, false); ret.len = (size_t)len; const uint8_t bases[] = { [0] = 10, diff --git a/src/nvim/window.c b/src/nvim/window.c index eddbe14da2..55a7882401 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -6,9 +6,7 @@ #include <stdbool.h> #include "nvim/api/private/helpers.h" -#include "nvim/vim.h" #include "nvim/ascii.h" -#include "nvim/window.h" #include "nvim/buffer.h" #include "nvim/charset.h" #include "nvim/cursor.h" @@ -20,8 +18,10 @@ #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" #include "nvim/ex_getln.h" +#include "nvim/file_search.h" #include "nvim/fileio.h" #include "nvim/fold.h" +#include "nvim/garray.h" #include "nvim/getchar.h" #include "nvim/hashtab.h" #include "nvim/main.h" @@ -30,15 +30,14 @@ #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/misc1.h" -#include "nvim/plines.h" -#include "nvim/file_search.h" -#include "nvim/garray.h" -#include "nvim/move.h" #include "nvim/mouse.h" +#include "nvim/move.h" #include "nvim/normal.h" #include "nvim/option.h" +#include "nvim/os/os.h" #include "nvim/os_unix.h" #include "nvim/path.h" +#include "nvim/plines.h" #include "nvim/quickfix.h" #include "nvim/regexp.h" #include "nvim/screen.h" @@ -47,10 +46,11 @@ #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/terminal.h" -#include "nvim/undo.h" #include "nvim/ui.h" #include "nvim/ui_compositor.h" -#include "nvim/os/os.h" +#include "nvim/undo.h" +#include "nvim/vim.h" +#include "nvim/window.h" #ifdef INCLUDE_GENERATED_DECLARATIONS @@ -60,26 +60,21 @@ -#define NOWIN (win_T *)-1 /* non-existing window */ +#define NOWIN (win_T *)-1 // non-existing window # define ROWS_AVAIL (Rows - p_ch - tabline_height()) static char *m_onlyone = N_("Already only one window"); -/* - * all CTRL-W window commands are handled here, called from normal_cmd(). - */ -void -do_window( - int nchar, - long Prenum, - int xchar /* extra char from ":wincmd gx" or NUL */ -) +/// all CTRL-W window commands are handled here, called from normal_cmd(). +/// +/// @param xchar extra char from ":wincmd gx" or NUL +void do_window(int nchar, long Prenum, int xchar) { long Prenum1; - win_T *wp; - char_u *ptr; + win_T *wp; + char_u *ptr; linenr_T lnum = -1; int type = FIND_DEFINE; size_t len; @@ -96,7 +91,7 @@ do_window( } while (0) switch (nchar) { - /* split current window in two parts, horizontally */ + // split current window in two parts, horizontally case 'S': case Ctrl_S: case 's': @@ -110,7 +105,7 @@ do_window( (void)win_split((int)Prenum, 0); break; - /* split current window in two parts, vertically */ + // split current window in two parts, vertically case Ctrl_V: case 'v': CHECK_CMDWIN; @@ -123,7 +118,7 @@ do_window( (void)win_split((int)Prenum, WSP_VERT); break; - /* split current window and edit alternate file */ + // split current window and edit alternate file case Ctrl_HAT: case '^': CHECK_CMDWIN; @@ -144,17 +139,18 @@ do_window( } break; - /* open new window */ + // open new window case Ctrl_N: case 'n': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode newwindow: - if (Prenum) - /* window height */ + if (Prenum) { + // window height vim_snprintf(cbuf, sizeof(cbuf) - 5, "%" PRId64, (int64_t)Prenum); - else + } else { cbuf[0] = NUL; + } if (nchar == 'v' || nchar == Ctrl_V) { xstrlcat(cbuf, "v", sizeof(cbuf)); } @@ -162,23 +158,23 @@ newwindow: do_cmdline_cmd(cbuf); break; - /* quit current window */ + // quit current window case Ctrl_Q: case 'q': - reset_VIsual_and_resel(); /* stop Visual mode */ + reset_VIsual_and_resel(); // stop Visual mode cmd_with_count("quit", (char_u *)cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; - /* close current window */ + // close current window case Ctrl_C: case 'c': - reset_VIsual_and_resel(); /* stop Visual mode */ + reset_VIsual_and_resel(); // stop Visual mode cmd_with_count("close", (char_u *)cbuf, sizeof(cbuf), Prenum); do_cmdline_cmd(cbuf); break; - /* close preview window */ + // close preview window case Ctrl_Z: case 'z': CHECK_CMDWIN; @@ -186,7 +182,7 @@ newwindow: do_cmdline_cmd("pclose"); break; - /* cursor to preview window */ + // cursor to preview window case 'P': wp = NULL; FOR_ALL_WINDOWS_IN_TAB(wp2, curtab) { @@ -202,7 +198,7 @@ newwindow: } break; - /* close all but current window */ + // close all but current window case Ctrl_O: case 'o': CHECK_CMDWIN; @@ -211,10 +207,10 @@ newwindow: do_cmdline_cmd(cbuf); break; - /* cursor to next window with wrap around */ + // cursor to next window with wrap around case Ctrl_W: case 'w': - /* cursor to previous window with wrap around */ + // cursor to previous window with wrap around case 'W': CHECK_CMDWIN; if (ONE_WINDOW && Prenum != 1) { // just one window @@ -222,10 +218,11 @@ newwindow: } else { if (Prenum) { // go to specified window for (wp = firstwin; --Prenum > 0; ) { - if (wp->w_next == NULL) + if (wp->w_next == NULL) { break; - else + } else { wp = wp->w_next; + } } } else { if (nchar == 'W') { // go to previous window @@ -252,7 +249,7 @@ newwindow: } break; - /* cursor to window below */ + // cursor to window below case 'j': case K_DOWN: case Ctrl_J: @@ -260,7 +257,7 @@ newwindow: win_goto_ver(false, Prenum1); break; - /* cursor to window above */ + // cursor to window above case 'k': case K_UP: case Ctrl_K: @@ -268,7 +265,7 @@ newwindow: win_goto_ver(true, Prenum1); break; - /* cursor to left window */ + // cursor to left window case 'h': case K_LEFT: case Ctrl_H: @@ -277,7 +274,7 @@ newwindow: win_goto_hor(true, Prenum1); break; - /* cursor to right window */ + // cursor to right window case 'l': case K_RIGHT: case Ctrl_L: @@ -285,13 +282,13 @@ newwindow: win_goto_hor(false, Prenum1); break; - /* move window to new tab page */ + // move window to new tab page case 'T': - if (one_window()) + if (one_window()) { MSG(_(m_onlyone)); - else { - tabpage_T *oldtab = curtab; - tabpage_T *newtab; + } else { + tabpage_T *oldtab = curtab; + tabpage_T *newtab; /* First create a new tab with the window, then go back to * the old tab and close the window there. */ @@ -311,19 +308,19 @@ newwindow: } break; - /* cursor to top-left window */ + // cursor to top-left window case 't': case Ctrl_T: win_goto(firstwin); break; - /* cursor to bottom-right window */ + // cursor to bottom-right window case 'b': case Ctrl_B: win_goto(lastwin_nofloating()); break; - /* cursor to last accessed (previous) window */ + // cursor to last accessed (previous) window case 'p': case Ctrl_P: if (!win_valid(prevwin)) { @@ -333,14 +330,14 @@ newwindow: } break; - /* exchange current and next window */ + // exchange current and next window case 'x': case Ctrl_X: CHECK_CMDWIN; win_exchange(Prenum); break; - /* rotate windows downwards */ + // rotate windows downwards case Ctrl_R: case 'r': CHECK_CMDWIN; @@ -348,14 +345,14 @@ newwindow: win_rotate(false, (int)Prenum1); // downwards break; - /* rotate windows upwards */ + // rotate windows upwards case 'R': CHECK_CMDWIN; reset_VIsual_and_resel(); // stop Visual mode win_rotate(true, (int)Prenum1); // upwards break; - /* move window to the very top/bottom/left/right */ + // move window to the very top/bottom/left/right case 'K': case 'J': case 'H': @@ -366,43 +363,43 @@ newwindow: | ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT)); break; - /* make all windows the same height */ + // make all windows the same height case '=': win_equal(NULL, false, 'b'); break; - /* increase current window height */ + // increase current window height case '+': win_setheight(curwin->w_height + (int)Prenum1); break; - /* decrease current window height */ + // decrease current window height case '-': win_setheight(curwin->w_height - (int)Prenum1); break; - /* set current window height */ + // set current window height case Ctrl__: case '_': win_setheight(Prenum ? (int)Prenum : Rows-1); break; - /* increase current window width */ + // increase current window width case '>': win_setwidth(curwin->w_width + (int)Prenum1); break; - /* decrease current window width */ + // decrease current window width case '<': win_setwidth(curwin->w_width - (int)Prenum1); break; - /* set current window width */ + // set current window width case '|': win_setwidth(Prenum != 0 ? (int)Prenum : Columns); break; - /* jump to tag and split window if tag exists (in preview window) */ + // jump to tag and split window if tag exists (in preview window) case '}': CHECK_CMDWIN; if (Prenum) { @@ -415,10 +412,11 @@ newwindow: case Ctrl_RSB: CHECK_CMDWIN; // Keep visual mode, can select words to use as a tag. - if (Prenum) + if (Prenum) { postponed_split = Prenum; - else + } else { postponed_split = -1; + } if (nchar != '}') { g_do_tagpreview = 0; @@ -429,7 +427,7 @@ newwindow: do_nv_ident(Ctrl_RSB, NUL); break; - /* edit file name under cursor in a new window */ + // edit file name under cursor in a new window case 'f': case 'F': case Ctrl_F: @@ -460,7 +458,7 @@ wingotofile: /* Go to the first occurrence of the identifier under cursor along path in a * new window -- webb */ - case 'i': /* Go to any match */ + case 'i': // Go to any match case Ctrl_I: type = FIND_ANY; FALLTHROUGH; @@ -484,7 +482,7 @@ wingotofile: break; - /* CTRL-W g extended commands */ + // CTRL-W g extended commands case 'g': case Ctrl_G: CHECK_CMDWIN; @@ -498,18 +496,20 @@ wingotofile: switch (xchar) { case '}': xchar = Ctrl_RSB; - if (Prenum) + if (Prenum) { g_do_tagpreview = Prenum; - else + } else { g_do_tagpreview = p_pvh; + } FALLTHROUGH; case ']': case Ctrl_RSB: // Keep visual mode, can select words to use as a tag. - if (Prenum) + if (Prenum) { postponed_split = Prenum; - else + } else { postponed_split = -1; + } /* Execute the command right here, required when * "wincmd g}" was used in a function. */ @@ -520,8 +520,8 @@ wingotofile: goto_tabpage_lastused(); break; - case 'f': /* CTRL-W gf: "gf" in a new tab page */ - case 'F': /* CTRL-W gF: "gF" in a new tab page */ + case 'f': // CTRL-W gf: "gf" in a new tab page + case 'F': // CTRL-W gF: "gF" in a new tab page cmdmod.tab = tabpage_index(curtab) + 1; nchar = xchar; goto wingotofile; @@ -555,13 +555,13 @@ wingotofile: } break; - default: beep_flush(); + default: + beep_flush(); break; } } -static void cmd_with_count(char *cmd, char_u *bufp, size_t bufsize, - int64_t Prenum) +static void cmd_with_count(char *cmd, char_u *bufp, size_t bufsize, int64_t Prenum) { size_t len = xstrlcpy((char *)bufp, cmd, bufsize); @@ -737,6 +737,37 @@ void win_config_float(win_T *wp, FloatConfig fconfig) redraw_later(wp, NOT_VALID); } + // compute initial position + if (wp->w_float_config.relative == kFloatRelativeWindow) { + int row = wp->w_float_config.row; + int col = wp->w_float_config.col; + Error dummy = ERROR_INIT; + win_T *parent = find_window_by_handle(wp->w_float_config.window, &dummy); + if (parent) { + row += parent->w_winrow; + col += parent->w_wincol; + ScreenGrid *grid = &parent->w_grid; + int row_off = 0, col_off = 0; + screen_adjust_grid(&grid, &row_off, &col_off); + row += row_off; + col += col_off; + } + api_clear_error(&dummy); + if (wp->w_float_config.bufpos.lnum >= 0) { + pos_T pos = { wp->w_float_config.bufpos.lnum + 1, + wp->w_float_config.bufpos.col, 0 }; + int trow, tcol, tcolc, tcole; + textpos2screenpos(wp, &pos, &trow, &tcol, &tcolc, &tcole, true); + row += trow - 1; + col += tcol - 1; + } + wp->w_winrow = row; + wp->w_wincol = col; + } else { + wp->w_winrow = fconfig.row; + wp->w_wincol = fconfig.col; + } + // changing border style while keeping border only requires redrawing border if (fconfig.border) { wp->w_redr_border = true; @@ -770,7 +801,6 @@ int win_fdccol_count(win_T *wp) } } - void ui_ext_win_position(win_T *wp) { if (!wp->w_floating) { @@ -817,6 +847,8 @@ void ui_ext_win_position(win_T *wp) int comp_row = (int)row - (south ? wp->w_height : 0); int comp_col = (int)col - (east ? wp->w_width : 0); + comp_row += grid->comp_row; + comp_col += grid->comp_col; comp_row = MAX(MIN(comp_row, Rows-wp->w_height_outer-1), 0); comp_col = MAX(MIN(comp_col, Columns-wp->w_width_outer), 0); wp->w_winrow = comp_row; @@ -834,21 +866,21 @@ void ui_ext_win_position(win_T *wp) } else { ui_call_win_external_pos(wp->w_grid_alloc.handle, wp->handle); } - } void ui_ext_win_viewport(win_T *wp) { if ((wp == curwin || ui_has(kUIMultigrid)) && wp->w_viewport_invalid) { int botline = wp->w_botline; - if (botline == wp->w_buffer->b_ml.ml_line_count+1 - && wp->w_empty_rows == 0) { + int line_count = wp->w_buffer->b_ml.ml_line_count; + if (botline == line_count+1 && wp->w_empty_rows == 0) { // TODO(bfredl): The might be more cases to consider, like how does this // interact with incomplete final line? Diff filler lines? botline = wp->w_buffer->b_ml.ml_line_count; } ui_call_win_viewport(wp->w_grid_alloc.handle, wp->handle, wp->w_topline-1, - botline, wp->w_cursor.lnum-1, wp->w_cursor.col); + botline, wp->w_cursor.lnum-1, wp->w_cursor.col, + line_count); wp->w_viewport_invalid = false; } } @@ -870,11 +902,12 @@ void ui_ext_win_viewport(win_T *wp) */ int win_split(int size, int flags) { - /* When the ":tab" modifier was used open a new tab page instead. */ - if (may_open_tabpage() == OK) + // When the ":tab" modifier was used open a new tab page instead. + if (may_open_tabpage() == OK) { return OK; + } - /* Add flags from ":vertical", ":topleft" and ":botright". */ + // Add flags from ":vertical", ":topleft" and ":botright". flags |= cmdmod.split; if ((flags & WSP_TOP) && (flags & WSP_BOT)) { EMSG(_("E442: Can't split topleft and botright at the same time")); @@ -883,10 +916,11 @@ int win_split(int size, int flags) /* When creating the help window make a snapshot of the window layout. * Otherwise clear the snapshot, it's now invalid. */ - if (flags & WSP_HELP) + if (flags & WSP_HELP) { make_snapshot(SNAP_HELP_IDX); - else + } else { clear_snapshot(curtab, SNAP_HELP_IDX); + } return win_split_ins(size, flags, NULL, 0); } @@ -899,8 +933,8 @@ int win_split(int size, int flags) */ int win_split_ins(int size, int flags, win_T *new_wp, int dir) { - win_T *wp = new_wp; - win_T *oldwin; + win_T *wp = new_wp; + win_T *oldwin; int new_size = size; int i; int need_status = 0; @@ -909,7 +943,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) int available; int oldwin_height = 0; int layout; - frame_T *frp, *curfrp, *frp2, *prevfrp; + frame_T *frp, *curfrp, *frp2, *prevfrp; int before; int minheight; int wmh1; @@ -981,8 +1015,9 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) EMSG(_(e_noroom)); return FAIL; } - if (new_size == 0) + if (new_size == 0) { new_size = oldwin->w_width / 2; + } if (new_size > available - minwidth - 1) { new_size = available - minwidth - 1; } @@ -1065,8 +1100,9 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) oldwin->w_status_height = STATUS_HEIGHT; oldwin_height -= STATUS_HEIGHT; } - if (new_size == 0) + if (new_size == 0) { new_size = oldwin_height / 2; + } if (new_size > available - minheight - STATUS_HEIGHT) { new_size = available - minheight - STATUS_HEIGHT; @@ -1090,10 +1126,11 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) did_set_fraction = true; win_setheight_win(oldwin->w_height + new_size + STATUS_HEIGHT, - oldwin); + oldwin); oldwin_height = oldwin->w_height; - if (need_status) + if (need_status) { oldwin_height -= STATUS_HEIGHT; + } } /* Only make all windows the same height if one of them (except oldwin) @@ -1138,12 +1175,13 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) } if (new_wp == NULL) { - if (wp == NULL) + if (wp == NULL) { return FAIL; + } new_frame(wp); - /* make the contents of the new window the same as the current one */ + // make the contents of the new window the same as the current one win_init(wp, curwin, flags); } else if (wp->w_floating) { new_frame(wp); @@ -1159,25 +1197,29 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) if ((topframe->fr_layout == FR_COL && (flags & WSP_VERT) == 0) || (topframe->fr_layout == FR_ROW && (flags & WSP_VERT) != 0)) { curfrp = topframe->fr_child; - if (flags & WSP_BOT) - while (curfrp->fr_next != NULL) + if (flags & WSP_BOT) { + while (curfrp->fr_next != NULL) { curfrp = curfrp->fr_next; - } else + } + } + } else { curfrp = topframe; + } before = (flags & WSP_TOP); } else { curfrp = oldwin->w_frame; - if (flags & WSP_BELOW) + if (flags & WSP_BELOW) { before = FALSE; - else if (flags & WSP_ABOVE) + } else if (flags & WSP_ABOVE) { before = TRUE; - else if (flags & WSP_VERT) + } else if (flags & WSP_VERT) { before = !p_spr; - else + } else { before = !p_sb; + } } if (curfrp->fr_parent == NULL || curfrp->fr_parent->fr_layout != layout) { - /* Need to create a new frame in the tree to make a branch. */ + // Need to create a new frame in the tree to make a branch. frp = xcalloc(1, sizeof(frame_T)); *frp = *curfrp; curfrp->fr_layout = layout; @@ -1196,17 +1238,19 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) } } - if (new_wp == NULL) + if (new_wp == NULL) { frp = wp->w_frame; - else + } else { frp = new_wp->w_frame; + } frp->fr_parent = curfrp->fr_parent; - /* Insert the new frame at the right place in the frame list. */ - if (before) + // Insert the new frame at the right place in the frame list. + if (before) { frame_insert(curfrp, frp); - else + } else { frame_append(curfrp, frp); + } /* Set w_fraction now so that the cursor keeps the same relative * vertical position. */ @@ -1223,12 +1267,12 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) oldwin->w_status_height = need_status; } if (flags & (WSP_TOP | WSP_BOT)) { - /* set height and row of new window to full height */ + // set height and row of new window to full height wp->w_winrow = tabline_height(); win_new_height(wp, curfrp->fr_height - (p_ls > 0)); wp->w_status_height = (p_ls > 0); } else { - /* height and row of new window is same as current window */ + // height and row of new window is same as current window wp->w_winrow = oldwin->w_winrow; win_new_height(wp, oldwin->w_height); wp->w_status_height = oldwin->w_status_height; @@ -1238,16 +1282,17 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) /* "new_size" of the current window goes to the new window, use * one column for the vertical separator */ win_new_width(wp, new_size); - if (before) + if (before) { wp->w_vsep_width = 1; - else { + } else { wp->w_vsep_width = oldwin->w_vsep_width; oldwin->w_vsep_width = 1; } if (flags & (WSP_TOP | WSP_BOT)) { - if (flags & WSP_BOT) + if (flags & WSP_BOT) { frame_add_vsep(curfrp); - /* Set width of neighbor frame */ + } + // Set width of neighbor frame frame_new_width(curfrp, curfrp->fr_width - (new_size + ((flags & WSP_TOP) != 0)), flags & WSP_TOP, false); @@ -1257,12 +1302,13 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) if (before) { // new window left of current one wp->w_wincol = oldwin->w_wincol; oldwin->w_wincol += new_size + 1; - } else /* new window right of current one */ + } else { // new window right of current one wp->w_wincol = oldwin->w_wincol + oldwin->w_width + 1; + } frame_fix_width(oldwin); frame_fix_width(wp); } else { - /* width and column of new window is same as current window */ + // width and column of new window is same as current window if (flags & (WSP_TOP | WSP_BOT)) { wp->w_wincol = 0; win_new_width(wp, Columns); @@ -1298,14 +1344,16 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) oldwin->w_status_height = STATUS_HEIGHT; } } - if (flags & WSP_BOT) + if (flags & WSP_BOT) { frame_add_statusline(curfrp); + } frame_fix_height(wp); frame_fix_height(oldwin); } - if (flags & (WSP_TOP | WSP_BOT)) + if (flags & (WSP_TOP | WSP_BOT)) { (void)win_comp_pos(); + } // Both windows need redrawing. Update all status lines, in case they // show something related to the window count or position. @@ -1316,32 +1364,34 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir) if (need_status) { msg_row = Rows - 1; msg_col = sc_col; - msg_clr_eos_force(); /* Old command/ruler may still be there */ + msg_clr_eos_force(); // Old command/ruler may still be there comp_col(); msg_row = Rows - 1; - msg_col = 0; /* put position back at start of line */ + msg_col = 0; // put position back at start of line } /* * equalize the window sizes. */ - if (do_equal || dir != 0) + if (do_equal || dir != 0) { win_equal(wp, true, - (flags & WSP_VERT) ? (dir == 'v' ? 'b' : 'h') - : dir == 'h' ? 'b' : - 'v'); + (flags & WSP_VERT) ? (dir == 'v' ? 'b' : 'h') + : dir == 'h' ? 'b' : + 'v'); + } /* Don't change the window height/width to 'winheight' / 'winwidth' if a * size was given. */ if (flags & WSP_VERT) { i = p_wiw; - if (size != 0) + if (size != 0) { p_wiw = size; - + } } else { i = p_wh; - if (size != 0) + if (size != 0) { p_wh = size; + } } // Keep same changelist position in new window. @@ -1397,7 +1447,7 @@ static void win_init(win_T *newp, win_T *oldp, int flags) newp->w_prev_fraction_row = oldp->w_prev_fraction_row; copy_jumplist(oldp, newp); if (flags & WSP_NEWLOC) { - /* Don't copy the location list. */ + // Don't copy the location list. newp->w_llist = NULL; newp->w_llist_ref = NULL; } else { @@ -1406,7 +1456,7 @@ static void win_init(win_T *newp, win_T *oldp, int flags) newp->w_localdir = (oldp->w_localdir == NULL) ? NULL : vim_strsave(oldp->w_localdir); - /* copy tagstack and folds */ + // copy tagstack and folds for (i = 0; i < oldp->w_tagstacklen; i++) { taggy_T *tag = &newp->w_tagstack[i]; *tag = oldp->w_tagstack[i]; @@ -1432,12 +1482,12 @@ static void win_init(win_T *newp, win_T *oldp, int flags) */ static void win_init_some(win_T *newp, win_T *oldp) { - /* Use the same argument list. */ + // Use the same argument list. newp->w_alist = oldp->w_alist; ++newp->w_alist->al_refcount; newp->w_arg_idx = oldp->w_arg_idx; - /* copy options from existing window */ + // copy options from existing window win_copy_options(oldp, newp); } @@ -1543,10 +1593,12 @@ int make_windows(int count, bool vertical) - (p_wh - p_wmh)) / (p_wmh + STATUS_HEIGHT); } - if (maxcount < 2) + if (maxcount < 2) { maxcount = 2; - if (count > maxcount) + } + if (count > maxcount) { count = maxcount; + } /* * add status line now, otherwise first window will be too big @@ -1561,22 +1613,25 @@ int make_windows(int count, bool vertical) */ block_autocmds(); - /* todo is number of windows left to create */ - for (todo = count - 1; todo > 0; --todo) + // todo is number of windows left to create + for (todo = count - 1; todo > 0; --todo) { if (vertical) { if (win_split(curwin->w_width - (curwin->w_width - todo) - / (todo + 1) - 1, WSP_VERT | WSP_ABOVE) == FAIL) + / (todo + 1) - 1, WSP_VERT | WSP_ABOVE) == FAIL) { break; + } } else { if (win_split(curwin->w_height - (curwin->w_height - todo * STATUS_HEIGHT) / (todo + 1) - - STATUS_HEIGHT, WSP_ABOVE) == FAIL) + - STATUS_HEIGHT, WSP_ABOVE) == FAIL) { break; + } } + } unblock_autocmds(); - /* return actual number of windows */ + // return actual number of windows return count - todo; } @@ -1585,10 +1640,10 @@ int make_windows(int count, bool vertical) */ static void win_exchange(long Prenum) { - frame_T *frp; - frame_T *frp2; - win_T *wp; - win_T *wp2; + frame_T *frp; + frame_T *frp2; + win_T *wp; + win_T *wp2; int temp; if (curwin->w_floating) { @@ -1608,17 +1663,20 @@ static void win_exchange(long Prenum) */ if (Prenum) { frp = curwin->w_frame->fr_parent->fr_child; - while (frp != NULL && --Prenum > 0) + while (frp != NULL && --Prenum > 0) { frp = frp->fr_next; - } else if (curwin->w_frame->fr_next != NULL) /* Swap with next */ + } + } else if (curwin->w_frame->fr_next != NULL) { // Swap with next frp = curwin->w_frame->fr_next; - else /* Swap last window in row/col with previous */ + } else { // Swap last window in row/col with previous frp = curwin->w_frame->fr_prev; + } /* We can only exchange a window with another window, not with a frame * containing windows. */ - if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin) + if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin) { return; + } wp = frp->fr_win; /* @@ -1641,10 +1699,11 @@ static void win_exchange(long Prenum) win_remove(wp, NULL); frame_remove(wp->w_frame); win_append(wp2, wp); - if (frp2 == NULL) + if (frp2 == NULL) { frame_insert(wp->w_frame->fr_parent->fr_child, wp->w_frame); - else + } else { frame_append(frp2, wp->w_frame); + } } temp = curwin->w_status_height; curwin->w_status_height = wp->w_status_height; @@ -1669,7 +1728,7 @@ static void win_exchange(long Prenum) frame_fix_width(wp); } - (void)win_comp_pos(); /* recompute window positions */ + (void)win_comp_pos(); // recompute window positions win_enter(wp, true); redraw_later(curwin, NOT_VALID); @@ -1680,9 +1739,9 @@ static void win_exchange(long Prenum) // if upwards false the first window becomes the second one static void win_rotate(bool upwards, int count) { - win_T *wp1; - win_T *wp2; - frame_T *frp; + win_T *wp1; + win_T *wp2; + frame_T *frp; int n; if (curwin->w_floating) { @@ -1705,8 +1764,8 @@ static void win_rotate(bool upwards, int count) } while (count--) { - if (upwards) { /* first window becomes last window */ - /* remove first window/frame from the list */ + if (upwards) { // first window becomes last window + // remove first window/frame from the list frp = curwin->w_frame->fr_parent->fr_child; assert(frp != NULL); wp1 = frp->fr_win; @@ -1714,30 +1773,32 @@ static void win_rotate(bool upwards, int count) frame_remove(frp); assert(frp->fr_parent->fr_child); - /* find last frame and append removed window/frame after it */ - for (; frp->fr_next != NULL; frp = frp->fr_next) + // find last frame and append removed window/frame after it + for (; frp->fr_next != NULL; frp = frp->fr_next) { ; + } win_append(frp->fr_win, wp1); frame_append(frp, wp1->w_frame); - wp2 = frp->fr_win; /* previously last window */ - } else { /* last window becomes first window */ - /* find last window/frame in the list and remove it */ + wp2 = frp->fr_win; // previously last window + } else { // last window becomes first window + // find last window/frame in the list and remove it for (frp = curwin->w_frame; frp->fr_next != NULL; - frp = frp->fr_next) + frp = frp->fr_next) { ; + } wp1 = frp->fr_win; - wp2 = wp1->w_prev; /* will become last window */ + wp2 = wp1->w_prev; // will become last window win_remove(wp1, NULL); frame_remove(frp); assert(frp->fr_parent->fr_child); - /* append the removed window/frame before the first in the list */ + // append the removed window/frame before the first in the list win_append(frp->fr_parent->fr_child->fr_win->w_prev, wp1); frame_insert(frp->fr_parent->fr_child, frp); } - /* exchange status height and vsep width of old and new last window */ + // exchange status height and vsep width of old and new last window n = wp2->w_status_height; wp2->w_status_height = wp1->w_status_height; wp1->w_status_height = n; @@ -1749,7 +1810,7 @@ static void win_rotate(bool upwards, int count) frame_fix_width(wp1); frame_fix_width(wp2); - /* recompute w_winrow and w_wincol for all windows */ + // recompute w_winrow and w_wincol for all windows (void)win_comp_pos(); } @@ -1789,14 +1850,14 @@ static void win_totop(int size, int flags) last_status(false); // may need to remove last status line (void)win_comp_pos(); // recompute window positions - /* Split a window on the desired side and put the window there. */ + // Split a window on the desired side and put the window there. (void)win_split_ins(size, flags, curwin, dir); if (!(flags & WSP_VERT)) { win_setheight(height); - if (p_ea) + if (p_ea) { win_equal(curwin, true, 'v'); + } } - } /* @@ -1807,11 +1868,12 @@ void win_move_after(win_T *win1, win_T *win2) { int height; - /* check if the arguments are reasonable */ - if (win1 == win2) + // check if the arguments are reasonable + if (win1 == win2) { return; + } - /* check if there is something to do */ + // check if there is something to do if (win2->w_next != win1) { /* may need move the status line/vertical separator of the last window * */ @@ -1854,46 +1916,42 @@ void win_move_after(win_T *win1, win_T *win2) win2->w_pos_changed = true; } -/* - * Make all windows the same height. - * 'next_curwin' will soon be the current window, make sure it has enough - * rows. - */ -void win_equal( - win_T *next_curwin, // pointer to current window to be or NULL - bool current, // do only frame with current window - int dir // 'v' for vertically, 'h' for horizontally, - // 'b' for both, 0 for using p_ead -) -{ - if (dir == 0) +/// Make all windows the same height. +///'next_curwin' will soon be the current window, make sure it has enough rows. +/// +/// @param next_curwin pointer to current window to be or NULL +/// @param current do only frame with current window +/// @param dir 'v' for vertically, 'h' for horizontally, 'b' for both, 0 for using p_ead +void win_equal(win_T *next_curwin, bool current, int dir) +{ + if (dir == 0) { dir = *p_ead; + } win_equal_rec(next_curwin == NULL ? curwin : next_curwin, current, topframe, dir, 0, tabline_height(), Columns, topframe->fr_height); } -/* - * Set a frame to a new position and height, spreading the available room - * equally over contained frames. - * The window "next_curwin" (if not NULL) should at least get the size from - * 'winheight' and 'winwidth' if possible. - */ -static void win_equal_rec( - win_T *next_curwin, /* pointer to current window to be or NULL */ - bool current, /* do only frame with current window */ - frame_T *topfr, /* frame to set size off */ - int dir, /* 'v', 'h' or 'b', see win_equal() */ - int col, /* horizontal position for frame */ - int row, /* vertical position for frame */ - int width, /* new width of frame */ - int height /* new height of frame */ -) +/// Set a frame to a new position and height, spreading the available room +/// equally over contained frames. +/// The window "next_curwin" (if not NULL) should at least get the size from +/// 'winheight' and 'winwidth' if possible. +/// +/// @param next_curwin pointer to current window to be or NULL +/// @param current do only frame with current window +/// @param topfr frame to set size off +/// @param dir 'v', 'h' or 'b', see win_equal() +/// @param col horizontal position for frame +/// @param row vertical position for frame +/// @param width new width of frame +/// @param height new height of frame +static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int dir, int col, + int row, int width, int height) { int n, m; int extra_sep = 0; int wincount, totwincount = 0; - frame_T *fr; + frame_T *fr; int next_curwin_size = 0; int room = 0; int new_size; @@ -1904,8 +1962,8 @@ static void win_equal_rec( /* Set the width/height of this frame. * Redraw when size or position changes */ if (topfr->fr_height != height || topfr->fr_win->w_winrow != row - || topfr->fr_width != width || topfr->fr_win->w_wincol != col - ) { + || topfr->fr_width != width || + topfr->fr_win->w_wincol != col) { topfr->fr_win->w_winrow = row; frame_new_height(topfr, height, false, false); topfr->fr_win->w_wincol = col; @@ -1916,15 +1974,16 @@ static void win_equal_rec( topfr->fr_width = width; topfr->fr_height = height; - if (dir != 'v') { /* equalize frame widths */ + if (dir != 'v') { // equalize frame widths /* Compute the maximum number of windows horizontally in this * frame. */ n = frame_minwidth(topfr, NOWIN); - /* add one for the rightmost window, it doesn't have a separator */ - if (col + width == Columns) + // add one for the rightmost window, it doesn't have a separator + if (col + width == Columns) { extra_sep = 1; - else + } else { extra_sep = 0; + } totwincount = (n + extra_sep) / (p_wmw + 1); has_next_curwin = frame_has_win(topfr, next_curwin); @@ -1952,12 +2011,14 @@ static void win_equal_rec( if (frame_has_win(fr, next_curwin)) { room += p_wiw - p_wmw; next_curwin_size = 0; - if (new_size < p_wiw) + if (new_size < p_wiw) { new_size = p_wiw; - } else - /* These windows don't use up room. */ + } + } else { + // These windows don't use up room. totwincount -= (n + (fr->fr_next == NULL ? extra_sep : 0)) / (p_wmw + 1); + } room -= new_size - n; if (room < 0) { new_size += room; @@ -1966,38 +2027,40 @@ static void win_equal_rec( fr->fr_newwidth = new_size; } if (next_curwin_size == -1) { - if (!has_next_curwin) + if (!has_next_curwin) { next_curwin_size = 0; - else if (totwincount > 1 - && (room + (totwincount - 2)) - / (totwincount - 1) > p_wiw) { + } else if (totwincount > 1 + && (room + (totwincount - 2)) + / (totwincount - 1) > p_wiw) { /* Can make all windows wider than 'winwidth', spread * the room equally. */ next_curwin_size = (room + p_wiw + (totwincount - 1) * p_wmw + (totwincount - 1)) / totwincount; room -= next_curwin_size - p_wiw; - } else + } else { next_curwin_size = p_wiw; + } } } - if (has_next_curwin) - --totwincount; /* don't count curwin */ + if (has_next_curwin) { + --totwincount; // don't count curwin + } } FOR_ALL_FRAMES(fr, topfr->fr_child) { wincount = 1; - if (fr->fr_next == NULL) - /* last frame gets all that remains (avoid roundoff error) */ + if (fr->fr_next == NULL) { + // last frame gets all that remains (avoid roundoff error) new_size = width; - else if (dir == 'v') + } else if (dir == 'v') { new_size = fr->fr_width; - else if (frame_fixed_width(fr)) { + } else if (frame_fixed_width(fr)) { new_size = fr->fr_newwidth; - wincount = 0; /* doesn't count as a sizeable window */ + wincount = 0; // doesn't count as a sizeable window } else { - /* Compute the maximum number of windows horiz. in "fr". */ + // Compute the maximum number of windows horiz. in "fr". n = frame_minwidth(fr, NOWIN); wincount = (n + (fr->fr_next == NULL ? extra_sep : 0)) / (p_wmw + 1); @@ -2019,8 +2082,9 @@ static void win_equal_rec( next_curwin_size -= p_wiw - (m - n); new_size += next_curwin_size; room -= new_size - next_curwin_size; - } else + } else { room -= new_size; + } new_size += n; } @@ -2028,25 +2092,27 @@ static void win_equal_rec( * window, unless equalizing all frames. */ if (!current || dir != 'v' || topfr->fr_parent != NULL || (new_size != fr->fr_width) - || frame_has_win(fr, next_curwin)) + || frame_has_win(fr, next_curwin)) { win_equal_rec(next_curwin, current, fr, dir, col, row, - new_size, height); + new_size, height); + } col += new_size; width -= new_size; totwincount -= wincount; } - } else { /* topfr->fr_layout == FR_COL */ + } else { // topfr->fr_layout == FR_COL topfr->fr_width = width; topfr->fr_height = height; - if (dir != 'h') { /* equalize frame heights */ - /* Compute maximum number of windows vertically in this frame. */ + if (dir != 'h') { // equalize frame heights + // 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 */ - if (row + height == cmdline_row && p_ls == 0) + // add one for the bottom window if it doesn't have a statusline + if (row + height == cmdline_row && p_ls == 0) { extra_sep = 1; - else + } else { extra_sep = 0; + } totwincount = (n + extra_sep) / (p_wmh + 1); has_next_curwin = frame_has_win(topfr, next_curwin); @@ -2076,12 +2142,14 @@ static void win_equal_rec( if (frame_has_win(fr, next_curwin)) { room += p_wh - p_wmh; next_curwin_size = 0; - if (new_size < p_wh) + if (new_size < p_wh) { new_size = p_wh; - } else - /* These windows don't use up room. */ + } + } else { + // These windows don't use up room. totwincount -= (n + (fr->fr_next == NULL ? extra_sep : 0)) / (p_wmh + 1); + } room -= new_size - n; if (room < 0) { new_size += room; @@ -2090,38 +2158,40 @@ static void win_equal_rec( fr->fr_newheight = new_size; } if (next_curwin_size == -1) { - if (!has_next_curwin) + if (!has_next_curwin) { next_curwin_size = 0; - else if (totwincount > 1 - && (room + (totwincount - 2)) - / (totwincount - 1) > p_wh) { + } else if (totwincount > 1 + && (room + (totwincount - 2)) + / (totwincount - 1) > p_wh) { /* can make all windows higher than 'winheight', * spread the room equally. */ next_curwin_size = (room + p_wh + (totwincount - 1) * p_wmh + (totwincount - 1)) / totwincount; room -= next_curwin_size - p_wh; - } else + } else { next_curwin_size = p_wh; + } } } - if (has_next_curwin) - --totwincount; /* don't count curwin */ + if (has_next_curwin) { + --totwincount; // don't count curwin + } } FOR_ALL_FRAMES(fr, topfr->fr_child) { wincount = 1; - if (fr->fr_next == NULL) - /* last frame gets all that remains (avoid roundoff error) */ + if (fr->fr_next == NULL) { + // last frame gets all that remains (avoid roundoff error) new_size = height; - else if (dir == 'h') + } else if (dir == 'h') { new_size = fr->fr_height; - else if (frame_fixed_height(fr)) { + } else if (frame_fixed_height(fr)) { new_size = fr->fr_newheight; - wincount = 0; /* doesn't count as a sizeable window */ + wincount = 0; // doesn't count as a sizeable window } else { - /* Compute the maximum number of windows vert. in "fr". */ + // Compute the maximum number of windows vert. in "fr". n = frame_minheight(fr, NOWIN); wincount = (n + (fr->fr_next == NULL ? extra_sep : 0)) / (p_wmh + 1); @@ -2143,17 +2213,19 @@ static void win_equal_rec( next_curwin_size -= p_wh - (m - n); new_size += next_curwin_size; room -= new_size - next_curwin_size; - } else + } else { room -= new_size; + } new_size += n; } /* Skip frame that is full width when splitting or closing a * window, unless equalizing all frames. */ if (!current || dir != 'h' || topfr->fr_parent != NULL || (new_size != fr->fr_height) - || frame_has_win(fr, next_curwin)) + || frame_has_win(fr, next_curwin)) { win_equal_rec(next_curwin, current, fr, dir, col, row, - width, new_size); + width, new_size); + } row += new_size; height -= new_size; totwincount -= wincount; @@ -2166,7 +2238,7 @@ static void win_equal_rec( /// @param keep_curwin don't close `curwin` void close_windows(buf_T *buf, int keep_curwin) { - tabpage_T *tp, *nexttp; + tabpage_T *tp, *nexttp; int h = tabline_height(); ++RedrawingDisabled; @@ -2179,13 +2251,14 @@ void close_windows(buf_T *buf, int keep_curwin) break; } - /* Start all over, autocommands may change the window layout. */ + // Start all over, autocommands may change the window layout. wp = firstwin; - } else + } else { wp = wp->w_next; + } } - /* Also check windows in other tab pages. */ + // Also check windows in other tab pages. for (tp = first_tabpage; tp != NULL; tp = nexttp) { nexttp = tp->tp_next; if (tp != curtab) { @@ -2259,14 +2332,13 @@ bool last_nonfloat(win_T *wp) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT /// last window in the tabpage /// /// @return true when the window was closed already. -static bool close_last_window_tabpage(win_T *win, bool free_buf, - tabpage_T *prev_curtab) +static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev_curtab) FUNC_ATTR_NONNULL_ARG(1) { if (!ONE_WINDOW) { return false; } - buf_T *old_curbuf = curbuf; + buf_T *old_curbuf = curbuf; Terminal *term = win->w_buffer ? win->w_buffer->terminal : NULL; if (term) { @@ -2295,8 +2367,9 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, int h = tabline_height(); win_close_othertab(win, free_buf, prev_curtab); - if (h != tabline_height()) + if (h != tabline_height()) { shell_new_rows(); + } } // Since goto_tabpage_tp above did not trigger *Enter autocommands, do @@ -2316,12 +2389,12 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, // Returns FAIL when the window was not closed. int win_close(win_T *win, bool free_buf) { - win_T *wp; + win_T *wp; bool other_buffer = false; bool close_curwin = false; int dir; bool help_window = false; - tabpage_T *prev_curtab = curtab; + tabpage_T *prev_curtab = curtab; frame_T *win_frame = win->w_floating ? NULL : win->w_frame->fr_parent; const bool had_diffmode = win->w_p_diff; @@ -2352,8 +2425,9 @@ int win_close(win_T *win, bool free_buf) /* When closing the last window in a tab page first go to another tab page * and then close the window and the tab page to avoid that curwin and * curtab are invalid while we are freeing memory. */ - if (close_last_window_tabpage(win, free_buf, prev_curtab)) + if (close_last_window_tabpage(win, free_buf, prev_curtab)) { return FAIL; + } /* When closing the help window, try restoring a snapshot after closing * the window. Otherwise clear the snapshot, it's now invalid. */ @@ -2386,11 +2460,13 @@ int win_close(win_T *win, bool free_buf) other_buffer = true; win->w_closing = true; apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf); - if (!win_valid(win)) + if (!win_valid(win)) { return FAIL; + } win->w_closing = false; - if (last_window()) + if (last_window()) { return FAIL; + } } win->w_closing = true; apply_autocmds(EVENT_WINLEAVE, NULL, NULL, false, curbuf); @@ -2398,11 +2474,13 @@ int win_close(win_T *win, bool free_buf) return FAIL; } win->w_closing = false; - if (last_window()) + if (last_window()) { return FAIL; - /* autocmds may abort script processing */ - if (aborting()) + } + // autocmds may abort script processing + if (aborting()) { return FAIL; + } } bool was_floating = win->w_floating; @@ -2509,12 +2587,14 @@ int win_close(win_T *win, bool free_buf) * finding another window to go to. */ for (;; ) { - if (wp->w_next == NULL) + if (wp->w_next == NULL) { wp = firstwin; - else + } else { wp = wp->w_next; - if (wp == curwin) + } + if (wp == curwin) { break; + } if (!wp->w_p_pvw && !bt_quickfix(wp->w_buffer)) { curwin = wp; break; @@ -2555,8 +2635,9 @@ int win_close(win_T *win, bool free_buf) /* After closing the help window, try restoring the window layout from * before it was opened. */ - if (help_window) + if (help_window) { restore_snapshot(SNAP_HELP_IDX, close_curwin); + } // If the window had 'diff' set and now there is only one window left in // the tab page with 'diff' set, and "closeoff" is in 'diffopt', then @@ -2603,7 +2684,7 @@ static void do_autocmd_winclosed(win_T *win) void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) { int dir; - tabpage_T *ptp = NULL; + tabpage_T *ptp = NULL; bool free_tp = false; // Get here with win->w_buffer == NULL when win_close() detects the tab page @@ -2627,26 +2708,28 @@ void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) /* Careful: Autocommands may have closed the tab page or made it the * current tab page. */ - for (ptp = first_tabpage; ptp != NULL && ptp != tp; ptp = ptp->tp_next) + for (ptp = first_tabpage; ptp != NULL && ptp != tp; ptp = ptp->tp_next) { ; - if (ptp == NULL || tp == curtab) + } + if (ptp == NULL || tp == curtab) { return; + } - /* Autocommands may have closed the window already. */ + // Autocommands may have closed the window already. { bool found_window = false; FOR_ALL_WINDOWS_IN_TAB(wp, tp) { if (wp == win) { - found_window = true; - break; + found_window = true; + break; } } if (!found_window) { - return; + return; } } - /* When closing the last window in a tab page remove the tab page. */ + // When closing the last window in a tab page remove the tab page. if (tp->tp_firstwin == tp->tp_lastwin) { char_u prev_idx[NUMBUFLEN]; if (has_event(EVENT_TABCLOSED)) { @@ -2673,23 +2756,24 @@ void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp) } } - /* Free the memory used for the window. */ + // Free the memory used for the window. win_free_mem(win, &dir, tp); - if (free_tp) + if (free_tp) { free_tabpage(tp); + } } -// Free the memory used for a window. -// Returns a pointer to the window that got the freed up space. -static win_T *win_free_mem( - win_T *win, - int *dirp, // set to 'v' or 'h' for direction if 'ea' - tabpage_T *tp // tab page "win" is in, NULL for current -) +/// Free the memory used for a window. +/// +/// @param dirp set to 'v' or 'h' for direction if 'ea' +/// @param tp tab page "win" is in, NULL for current +/// +/// @return a pointer to the window that got the freed up space. +static win_T *win_free_mem(win_T *win, int *dirp, tabpage_T *tp) { - frame_T *frp; - win_T *wp; + frame_T *frp; + win_T *wp; if (!win->w_floating) { // Remove the window and its frame from the tree of frames. @@ -2724,8 +2808,9 @@ void win_free_all(void) { int dummy; - while (first_tabpage->tp_next != NULL) + while (first_tabpage->tp_next != NULL) { tabpage_close(TRUE); + } while (lastwin != NULL && lastwin->w_floating) { win_T *wp = lastwin; @@ -2741,8 +2826,9 @@ void win_free_all(void) aucmd_win = NULL; } - while (firstwin != NULL) + while (firstwin != NULL) { (void)win_free_mem(firstwin, &dummy, NULL); + } // No window should be used after this. Set curwin to NULL to crash // instead of using freed memory. @@ -2751,26 +2837,24 @@ void win_free_all(void) #endif -/* - * Remove a window and its frame from the tree of frames. - * Returns a pointer to the window that got the freed up space. - */ -win_T * -winframe_remove ( - win_T *win, - int *dirp, /* set to 'v' or 'h' for direction if 'ea' */ - tabpage_T *tp /* tab page "win" is in, NULL for current */ -) +/// Remove a window and its frame from the tree of frames. +/// +/// @param dirp set to 'v' or 'h' for direction if 'ea' +/// @param tp tab page "win" is in, NULL for current +/// +/// @return a pointer to the window that got the freed up space. +win_T *winframe_remove(win_T *win, int *dirp, tabpage_T *tp) { - frame_T *frp, *frp2, *frp3; - frame_T *frp_close = win->w_frame; - win_T *wp; + frame_T *frp, *frp2, *frp3; + frame_T *frp_close = win->w_frame; + win_T *wp; /* * If there is only one window there is nothing to remove. */ - if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin) + if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin) { return NULL; + } /* * Remove the window from its frame. @@ -2778,7 +2862,7 @@ winframe_remove ( frp2 = win_altframe(win, tp); wp = frame2win(frp2); - /* Remove this frame from the list of frames. */ + // Remove this frame from the list of frames. frame_remove(frp_close); if (frp_close->fr_parent->fr_layout == FR_COL) { @@ -2859,8 +2943,9 @@ winframe_remove ( frp->fr_parent = frp2->fr_parent; } frp2->fr_parent->fr_win = frp2->fr_win; - if (frp2->fr_win != NULL) + if (frp2->fr_win != NULL) { frp2->fr_win->w_frame = frp2->fr_parent; + } frp = frp2->fr_parent; if (topframe->fr_child == frp2) { topframe->fr_child = frp; @@ -2871,18 +2956,21 @@ winframe_remove ( if (frp2 != NULL && frp2->fr_layout == frp->fr_layout) { /* The frame above the parent has the same layout, have to merge * the frames into this list. */ - if (frp2->fr_child == frp) + if (frp2->fr_child == frp) { frp2->fr_child = frp->fr_child; + } assert(frp->fr_child); frp->fr_child->fr_prev = frp->fr_prev; - if (frp->fr_prev != NULL) + if (frp->fr_prev != NULL) { frp->fr_prev->fr_next = frp->fr_child; + } for (frp3 = frp->fr_child;; frp3 = frp3->fr_next) { frp3->fr_parent = frp2; if (frp3->fr_next == NULL) { frp3->fr_next = frp->fr_next; - if (frp->fr_next != NULL) + if (frp->fr_next != NULL) { frp->fr_next->fr_prev = frp3; + } break; } } @@ -2896,21 +2984,19 @@ winframe_remove ( return wp; } -// Return a pointer to the frame that will receive the empty screen space that -// is left over after "win" is closed. -// -// If 'splitbelow' or 'splitright' is set, the space goes above or to the left -// by default. Otherwise, the free space goes below or to the right. The -// result is that opening a window and then immediately closing it will -// preserve the initial window layout. The 'wfh' and 'wfw' settings are -// respected when possible. -static frame_T * -win_altframe ( - win_T *win, - tabpage_T *tp /* tab page "win" is in, NULL for current */ -) -{ - frame_T *frp; +/// If 'splitbelow' or 'splitright' is set, the space goes above or to the left +/// by default. Otherwise, the free space goes below or to the right. The +/// result is that opening a window and then immediately closing it will +/// preserve the initial window layout. The 'wfh' and 'wfw' settings are +/// respected when possible. +/// +/// @param tp tab page "win" is in, NULL for current +/// +/// @return a pointer to the frame that will receive the empty screen space that +/// is left over after "win" is closed. +static frame_T *win_altframe(win_T *win, tabpage_T *tp) +{ + frame_T *frp; if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin) { return alt_tabpage()->tp_curwin->w_frame; @@ -2952,15 +3038,17 @@ win_altframe ( */ static tabpage_T *alt_tabpage(void) { - tabpage_T *tp; + tabpage_T *tp; - /* Use the next tab page if possible. */ - if (curtab->tp_next != NULL) + // Use the next tab page if possible. + if (curtab->tp_next != NULL) { return curtab->tp_next; + } - /* Find the last but one tab page. */ - for (tp = first_tabpage; tp->tp_next != curtab; tp = tp->tp_next) + // Find the last but one tab page. + for (tp = first_tabpage; tp->tp_next != curtab; tp = tp->tp_next) { ; + } return tp; } @@ -2969,8 +3057,9 @@ static tabpage_T *alt_tabpage(void) */ static win_T *frame2win(frame_T *frp) { - while (frp->fr_win == NULL) + while (frp->fr_win == NULL) { frp = frp->fr_child; + } return frp->fr_win; } @@ -2999,11 +3088,10 @@ static bool frame_has_win(const frame_T *frp, const win_T *wp) /// @param topfirst resize topmost contained frame first. /// @param wfh obey 'winfixheight' when there is a choice; /// may cause the height not to be set. -static void frame_new_height(frame_T *topfrp, int height, bool topfirst, - bool wfh) +static void frame_new_height(frame_T *topfrp, int height, bool topfirst, bool wfh) FUNC_ATTR_NONNULL_ALL { - frame_T *frp; + frame_T *frp; int extra_lines; int h; @@ -3017,37 +3105,42 @@ static void frame_new_height(frame_T *topfrp, int height, bool topfirst, FOR_ALL_FRAMES(frp, topfrp->fr_child) { frame_new_height(frp, height, topfirst, wfh); if (frp->fr_height > height) { - /* Could not fit the windows, make the whole row higher. */ + // Could not fit the windows, make the whole row higher. height = frp->fr_height; break; } } } while (frp != NULL); - } else { /* fr_layout == FR_COL */ + } else { // fr_layout == FR_COL /* Complicated case: Resize a column of frames. Resize the bottom * frame first, frames above that when needed. */ frp = topfrp->fr_child; - if (wfh) - /* Advance past frames with one window with 'wfh' set. */ + if (wfh) { + // Advance past frames with one window with 'wfh' set. while (frame_fixed_height(frp)) { frp = frp->fr_next; - if (frp == NULL) - return; /* no frame without 'wfh', give up */ + if (frp == NULL) { + return; // no frame without 'wfh', give up + } } + } if (!topfirst) { - /* Find the bottom frame of this column */ - while (frp->fr_next != NULL) + // Find the bottom frame of this column + while (frp->fr_next != NULL) { frp = frp->fr_next; - if (wfh) - /* Advance back for frames with one window with 'wfh' set. */ - while (frame_fixed_height(frp)) + } + if (wfh) { + // Advance back for frames with one window with 'wfh' set. + while (frame_fixed_height(frp)) { frp = frp->fr_prev; + } + } } extra_lines = height - topfrp->fr_height; if (extra_lines < 0) { - /* reduce height of contained frames, bottom or top frame first */ + // reduce height of contained frames, bottom or top frame first while (frp != NULL) { h = frame_minheight(frp, NULL); if (frp->fr_height + extra_lines < h) { @@ -3055,7 +3148,7 @@ static void frame_new_height(frame_T *topfrp, int height, bool topfirst, frame_new_height(frp, h, topfirst, wfh); } else { frame_new_height(frp, frp->fr_height + extra_lines, - topfirst, wfh); + topfirst, wfh); break; } if (topfirst) { @@ -3067,12 +3160,13 @@ static void frame_new_height(frame_T *topfrp, int height, bool topfirst, frp = frp->fr_prev; while (wfh && frp != NULL && frame_fixed_height(frp)); } - /* Increase "height" if we could not reduce enough frames. */ - if (frp == NULL) + // Increase "height" if we could not reduce enough frames. + if (frp == NULL) { height -= extra_lines; + } } } else if (extra_lines > 0) { - /* increase height of bottom or top frame */ + // increase height of bottom or top frame frame_new_height(frp, frp->fr_height + extra_lines, topfirst, wfh); } } @@ -3153,13 +3247,14 @@ static bool frame_fixed_width(frame_T *frp) */ static void frame_add_statusline(frame_T *frp) { - win_T *wp; + win_T *wp; if (frp->fr_layout == FR_LEAF) { wp = frp->fr_win; if (wp->w_status_height == 0) { - if (wp->w_height > 0) /* don't make it negative */ + if (wp->w_height > 0) { // don't make it negative --wp->w_height; + } wp->w_status_height = STATUS_HEIGHT; } } else if (frp->fr_layout == FR_ROW) { @@ -3182,23 +3277,25 @@ static void frame_add_statusline(frame_T *frp) /// @param leftfirst resize leftmost contained frame first. /// @param wfw obey 'winfixwidth' when there is a choice; /// may cause the width not to be set. -static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, - bool wfw) +static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, bool wfw) { - frame_T *frp; + frame_T *frp; int extra_cols; int w; - win_T *wp; + win_T *wp; if (topfrp->fr_layout == FR_LEAF) { - /* Simple case: just one window. */ + // Simple case: just one window. wp = topfrp->fr_win; - /* Find out if there are any windows right of this one. */ - for (frp = topfrp; frp->fr_parent != NULL; frp = frp->fr_parent) - if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_next != NULL) + // Find out if there are any windows right of this one. + for (frp = topfrp; frp->fr_parent != NULL; frp = frp->fr_parent) { + if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_next != NULL) { break; - if (frp->fr_parent == NULL) + } + } + if (frp->fr_parent == NULL) { wp->w_vsep_width = 0; + } win_new_width(wp, width - wp->w_vsep_width); } else if (topfrp->fr_layout == FR_COL) { do { @@ -3206,37 +3303,42 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, FOR_ALL_FRAMES(frp, topfrp->fr_child) { frame_new_width(frp, width, leftfirst, wfw); if (frp->fr_width > width) { - /* Could not fit the windows, make whole column wider. */ + // Could not fit the windows, make whole column wider. width = frp->fr_width; break; } } } while (frp != NULL); - } else { /* fr_layout == FR_ROW */ + } else { // fr_layout == FR_ROW /* Complicated case: Resize a row of frames. Resize the rightmost * frame first, frames left of it when needed. */ frp = topfrp->fr_child; - if (wfw) - /* Advance past frames with one window with 'wfw' set. */ + if (wfw) { + // Advance past frames with one window with 'wfw' set. while (frame_fixed_width(frp)) { frp = frp->fr_next; - if (frp == NULL) - return; /* no frame without 'wfw', give up */ + if (frp == NULL) { + return; // no frame without 'wfw', give up + } } + } if (!leftfirst) { - /* Find the rightmost frame of this row */ - while (frp->fr_next != NULL) + // Find the rightmost frame of this row + while (frp->fr_next != NULL) { frp = frp->fr_next; - if (wfw) - /* Advance back for frames with one window with 'wfw' set. */ - while (frame_fixed_width(frp)) + } + if (wfw) { + // Advance back for frames with one window with 'wfw' set. + while (frame_fixed_width(frp)) { frp = frp->fr_prev; + } + } } extra_cols = width - topfrp->fr_width; if (extra_cols < 0) { - /* reduce frame width, rightmost frame first */ + // reduce frame width, rightmost frame first while (frp != NULL) { w = frame_minwidth(frp, NULL); if (frp->fr_width + extra_cols < w) { @@ -3244,7 +3346,7 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, frame_new_width(frp, w, leftfirst, wfw); } else { frame_new_width(frp, frp->fr_width + extra_cols, - leftfirst, wfw); + leftfirst, wfw); break; } if (leftfirst) { @@ -3256,12 +3358,13 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, frp = frp->fr_prev; while (wfw && frp != NULL && frame_fixed_width(frp)); } - /* Increase "width" if we could not reduce enough frames. */ - if (frp == NULL) + // Increase "width" if we could not reduce enough frames. + if (frp == NULL) { width -= extra_cols; + } } } else if (extra_cols > 0) { - /* increase width of rightmost frame */ + // increase width of rightmost frame frame_new_width(frp, frp->fr_width + extra_cols, leftfirst, wfw); } } @@ -3275,13 +3378,14 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, static void frame_add_vsep(const frame_T *frp) FUNC_ATTR_NONNULL_ARG(1) { - win_T *wp; + win_T *wp; if (frp->fr_layout == FR_LEAF) { wp = frp->fr_win; if (wp->w_vsep_width == 0) { - if (wp->w_width > 0) /* don't make it negative */ + if (wp->w_width > 0) { // don't make it negative --wp->w_width; + } wp->w_vsep_width = 1; } } else if (frp->fr_layout == FR_COL) { @@ -3293,8 +3397,9 @@ static void frame_add_vsep(const frame_T *frp) assert(frp->fr_layout == FR_ROW); // Only need to handle the last frame in the row. frp = frp->fr_child; - while (frp->fr_next != NULL) + while (frp->fr_next != NULL) { frp = frp->fr_next; + } frame_add_vsep(frp); } } @@ -3325,7 +3430,7 @@ static void frame_fix_height(win_T *wp) */ static int frame_minheight(frame_T *topfrp, win_T *next_curwin) { - frame_T *frp; + frame_T *frp; int m; int n; @@ -3343,15 +3448,16 @@ static int frame_minheight(frame_T *topfrp, win_T *next_curwin) } } } else if (topfrp->fr_layout == FR_ROW) { - /* get the minimal height from each frame in this row */ + // get the minimal height from each frame in this row m = 0; FOR_ALL_FRAMES(frp, topfrp->fr_child) { n = frame_minheight(frp, next_curwin); - if (n > m) + if (n > m) { m = n; + } } } else { - /* Add up the minimal heights for all frames in this column. */ + // Add up the minimal heights for all frames in this column. m = 0; FOR_ALL_FRAMES(frp, topfrp->fr_child) { m += frame_minheight(frp, next_curwin); @@ -3361,41 +3467,39 @@ static int frame_minheight(frame_T *topfrp, win_T *next_curwin) return m; } -/* - * Compute the minimal width for frame "topfrp". - * When "next_curwin" isn't NULL, use p_wiw for this window. - * When "next_curwin" is NOWIN, don't use at least one column for the current - * window. - */ -static int -frame_minwidth ( - frame_T *topfrp, - win_T *next_curwin /* use p_wh and p_wiw for next_curwin */ -) +/// Compute the minimal width for frame "topfrp". +/// When "next_curwin" isn't NULL, use p_wiw for this window. +/// When "next_curwin" is NOWIN, don't use at least one column for the current +/// window. +/// +/// @param next_curwin use p_wh and p_wiw for next_curwin +static int frame_minwidth(frame_T *topfrp, win_T *next_curwin) { - frame_T *frp; + frame_T *frp; int m, n; if (topfrp->fr_win != NULL) { - if (topfrp->fr_win == next_curwin) + if (topfrp->fr_win == next_curwin) { m = p_wiw + topfrp->fr_win->w_vsep_width; - else { - /* window: minimal width of the window plus separator column */ + } else { + // window: minimal width of the window plus separator column m = p_wmw + topfrp->fr_win->w_vsep_width; - /* Current window is minimal one column wide */ - if (p_wmw == 0 && topfrp->fr_win == curwin && next_curwin == NULL) + // Current window is minimal one column wide + if (p_wmw == 0 && topfrp->fr_win == curwin && next_curwin == NULL) { ++m; + } } } else if (topfrp->fr_layout == FR_COL) { - /* get the minimal width from each frame in this column */ + // get the minimal width from each frame in this column m = 0; FOR_ALL_FRAMES(frp, topfrp->fr_child) { n = frame_minwidth(frp, next_curwin); - if (n > m) + if (n > m) { m = n; + } } } else { - /* Add up the minimal widths for all frames in this row. */ + // Add up the minimal widths for all frames in this row. m = 0; FOR_ALL_FRAMES(frp, topfrp->fr_child) { m += frame_minwidth(frp, next_curwin); @@ -3406,21 +3510,17 @@ frame_minwidth ( } -/* - * Try to close all windows except current one. - * Buffers in the other windows become hidden if 'hidden' is set, or '!' is - * used and the buffer was modified. - * - * Used by ":bdel" and ":only". - */ -void -close_others ( - int message, - int forceit /* always hide all other windows */ -) -{ - win_T *wp; - win_T *nextwp; +/// Try to close all windows except current one. +/// Buffers in the other windows become hidden if 'hidden' is set, or '!' is +/// used and the buffer was modified. +/// +/// Used by ":bdel" and ":only". +/// +/// @param forceit always hide all other windows +void close_others(int message, int forceit) +{ + win_T *wp; + win_T *nextwp; int r; if (curwin->w_floating) { @@ -3432,23 +3532,22 @@ close_others ( if (one_window() && !lastwin->w_floating) { if (message - && !autocmd_busy - ) { + && !autocmd_busy) { MSG(_(m_onlyone)); } return; } - /* Be very careful here: autocommands may change the window layout. */ + // Be very careful here: autocommands may change the window layout. for (wp = firstwin; win_valid(wp); wp = nextwp) { nextwp = wp->w_next; - if (wp == curwin) { /* don't close current window */ + if (wp == curwin) { // don't close current window continue; } - /* Check if it's allowed to abandon this window */ + // Check if it's allowed to abandon this window r = can_abandon(wp->w_buffer, forceit); - if (!win_valid(wp)) { /* autocommands messed wp up */ + if (!win_valid(wp)) { // autocommands messed wp up nextwp = firstwin; continue; } @@ -3460,14 +3559,16 @@ close_others ( continue; } } - if (bufIsChanged(wp->w_buffer)) + if (bufIsChanged(wp->w_buffer)) { continue; + } } win_close(wp, !buf_hide(wp->w_buffer) && !bufIsChanged(wp->w_buffer)); } - if (message && !ONE_WINDOW) + if (message && !ONE_WINDOW) { EMSG(_("E445: Other window contains changes")); + } } @@ -3487,7 +3588,7 @@ void win_init_empty(win_T *wp) wp->w_cursor.lnum = 1; wp->w_curswant = wp->w_cursor.col = 0; wp->w_cursor.coladd = 0; - wp->w_pcmark.lnum = 1; /* pcmark not cleared but set to line 1 */ + wp->w_pcmark.lnum = 1; // pcmark not cleared but set to line 1 wp->w_pcmark.col = 0; wp->w_prev_pcmark.lnum = 0; wp->w_prev_pcmark.col = 0; @@ -3505,8 +3606,9 @@ void win_init_empty(win_T *wp) */ int win_alloc_first(void) { - if (win_alloc_firstwin(NULL) == FAIL) + if (win_alloc_firstwin(NULL) == FAIL) { return FAIL; + } first_tabpage = alloc_tabpage(); first_tabpage->tp_topframe = topframe; @@ -3550,14 +3652,14 @@ static int win_alloc_firstwin(win_T *oldwin) } curwin->w_buffer = curbuf; curwin->w_s = &(curbuf->b_s); - curbuf->b_nwindows = 1; /* there is one window */ + curbuf->b_nwindows = 1; // there is one window curwin->w_alist = &global_alist; - curwin_init(); /* init current window */ + curwin_init(); // init current window } else { - /* First window in new tab page, initialize it from "oldwin". */ + // First window in new tab page, initialize it from "oldwin". win_init(curwin, oldwin, 0); - /* We don't want cursor- and scroll-binding in the first window. */ + // We don't want cursor- and scroll-binding in the first window. RESET_BINDING(curwin); } @@ -3621,9 +3723,10 @@ void free_tabpage(tabpage_T *tp) pmap_del(handle_T)(&tabpage_handles, tp->handle); diff_clear(tp); - for (idx = 0; idx < SNAP_COUNT; ++idx) + for (idx = 0; idx < SNAP_COUNT; ++idx) { clear_snapshot(tp, idx); - vars_clear(&tp->tp_vars->dv_hashtab); /* free all t: variables */ + } + vars_clear(&tp->tp_vars->dv_hashtab); // free all t: variables hash_init(&tp->tp_vars->dv_hashtab); unref_var_dict(tp->tp_vars); @@ -3645,8 +3748,8 @@ void free_tabpage(tabpage_T *tp) /// @return Was the new tabpage created successfully? FAIL or OK. int win_new_tabpage(int after, char_u *filename) { - tabpage_T *old_curtab = curtab; - tabpage_T *newtp; + tabpage_T *old_curtab = curtab; + tabpage_T *newtp; int n; newtp = alloc_tabpage(); @@ -3670,14 +3773,15 @@ int win_new_tabpage(int after, char_u *filename) newtp->tp_next = first_tabpage; first_tabpage = newtp; } else { - tabpage_T *tp = old_curtab; + tabpage_T *tp = old_curtab; if (after > 0) { // Put new tab page before tab page "after". n = 2; for (tp = first_tabpage; tp->tp_next != NULL - && n < after; tp = tp->tp_next) + && n < after; tp = tp->tp_next) { ++n; + } } newtp->tp_next = tp->tp_next; tp->tp_next = newtp; @@ -3720,7 +3824,7 @@ int may_open_tabpage(void) int n = (cmdmod.tab == 0) ? postponed_split_tab : cmdmod.tab; if (n != 0) { - cmdmod.tab = 0; /* reset it to avoid doing it twice */ + cmdmod.tab = 0; // reset it to avoid doing it twice postponed_split_tab = 0; return win_new_tabpage(n, NULL); } @@ -3736,9 +3840,10 @@ int make_tabpages(int maxcount) int count = maxcount; int todo; - /* Limit to 'tabpagemax' tabs. */ - if (count > p_tpm) + // Limit to 'tabpagemax' tabs. + if (count > p_tpm) { count = p_tpm; + } /* * Don't execute autocommands while creating the tab pages. Must do that @@ -3754,7 +3859,7 @@ int make_tabpages(int maxcount) unblock_autocmds(); - /* return actual number of tab pages */ + // return actual number of tab pages return count - todo; } @@ -3815,11 +3920,12 @@ void close_tabpage(tabpage_T *tab) */ tabpage_T *find_tabpage(int n) { - tabpage_T *tp; + tabpage_T *tp; int i = 1; - for (tp = first_tabpage; tp != NULL && i != n; tp = tp->tp_next) + for (tp = first_tabpage; tp != NULL && i != n; tp = tp->tp_next) { ++i; + } return tp; } @@ -3830,10 +3936,11 @@ tabpage_T *find_tabpage(int n) int tabpage_index(tabpage_T *ftp) { int i = 1; - tabpage_T *tp; + tabpage_T *tp; - for (tp = first_tabpage; tp != NULL && tp != ftp; tp = tp->tp_next) + for (tp = first_tabpage; tp != NULL && tp != ftp; tp = tp->tp_next) { ++i; + } return i; } @@ -3847,21 +3954,24 @@ int tabpage_index(tabpage_T *ftp) /// @param trigger_leave_autocmds when true trigger *Leave autocommands. static int leave_tabpage(buf_T *new_curbuf, bool trigger_leave_autocmds) { - tabpage_T *tp = curtab; + tabpage_T *tp = curtab; - reset_VIsual_and_resel(); /* stop Visual mode */ + reset_VIsual_and_resel(); // stop Visual mode if (trigger_leave_autocmds) { if (new_curbuf != curbuf) { apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf); - if (curtab != tp) + if (curtab != tp) { return FAIL; + } } apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf); - if (curtab != tp) + if (curtab != tp) { return FAIL; + } apply_autocmds(EVENT_TABLEAVE, NULL, NULL, FALSE, curbuf); - if (curtab != tp) + if (curtab != tp) { return FAIL; + } } tp->tp_curwin = curwin; tp->tp_prevwin = prevwin; @@ -3879,12 +3989,11 @@ static int leave_tabpage(buf_T *new_curbuf, bool trigger_leave_autocmds) /// /// @param trigger_enter_autocmds when true trigger *Enter autocommands. /// @param trigger_leave_autocmds when true trigger *Leave autocommands. -static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, - bool trigger_enter_autocmds, +static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, bool trigger_enter_autocmds, bool trigger_leave_autocmds) { int old_off = tp->tp_firstwin->w_winrow; - win_T *next_prevwin = tp->tp_prevwin; + win_T *next_prevwin = tp->tp_prevwin; tabpage_T *old_curtab = curtab; curtab = tp; @@ -3893,7 +4002,7 @@ static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, topframe = tp->tp_topframe; if (old_curtab != curtab) { - tabpage_check_windows(old_curtab); + tabpage_check_windows(old_curtab); } /* We would like doing the TabEnter event first, but we don't have a @@ -3936,8 +4045,9 @@ static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, * 'columns' have been set correctly. */ if (trigger_enter_autocmds) { apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf); - if (old_curbuf != curbuf) + if (old_curbuf != curbuf) { apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); + } } redraw_all_later(NOT_VALID); @@ -3978,8 +4088,8 @@ static void tabpage_check_windows(tabpage_T *old_curtab) */ void goto_tabpage(int n) { - tabpage_T *tp = NULL; // shut up compiler - tabpage_T *ttp; + tabpage_T *tp = NULL; // shut up compiler + tabpage_T *ttp; int i; if (text_locked()) { @@ -3988,35 +4098,39 @@ void goto_tabpage(int n) return; } - /* If there is only one it can't work. */ + // If there is only one it can't work. if (first_tabpage->tp_next == NULL) { - if (n > 1) + if (n > 1) { beep_flush(); + } return; } if (n == 0) { - /* No count, go to next tab page, wrap around end. */ - if (curtab->tp_next == NULL) + // No count, go to next tab page, wrap around end. + if (curtab->tp_next == NULL) { tp = first_tabpage; - else + } else { tp = curtab->tp_next; + } } else if (n < 0) { /* "gT": go to previous tab page, wrap around end. "N gT" repeats * this N times. */ ttp = curtab; for (i = n; i < 0; ++i) { for (tp = first_tabpage; tp->tp_next != ttp && tp->tp_next != NULL; - tp = tp->tp_next) + tp = tp->tp_next) { ; + } ttp = tp; } } else if (n == 9999) { - /* Go to last tab page. */ - for (tp = first_tabpage; tp->tp_next != NULL; tp = tp->tp_next) + // Go to last tab page. + for (tp = first_tabpage; tp->tp_next != NULL; tp = tp->tp_next) { ; + } } else { - /* Go to tab page "n". */ + // Go to tab page "n". tp = find_tabpage(n); if (tp == NULL) { beep_flush(); @@ -4032,20 +4146,20 @@ void goto_tabpage(int n) /// /// @param trigger_enter_autocmds when true trigger *Enter autocommands. /// @param trigger_leave_autocmds when true trigger *Leave autocommands. -void goto_tabpage_tp(tabpage_T *tp, bool trigger_enter_autocmds, - bool trigger_leave_autocmds) +void goto_tabpage_tp(tabpage_T *tp, bool trigger_enter_autocmds, bool trigger_leave_autocmds) { - /* Don't repeat a message in another tab page. */ + // Don't repeat a message in another tab page. set_keep_msg(NULL, 0); if (tp != curtab && leave_tabpage(tp->tp_curwin->w_buffer, - trigger_leave_autocmds) == OK) { - if (valid_tabpage(tp)) + trigger_leave_autocmds) == OK) { + if (valid_tabpage(tp)) { enter_tabpage(tp, curbuf, trigger_enter_autocmds, - trigger_leave_autocmds); - else + trigger_leave_autocmds); + } else { enter_tabpage(curtab, curbuf, trigger_enter_autocmds, - trigger_leave_autocmds); + trigger_leave_autocmds); + } } } @@ -4134,20 +4248,22 @@ void tabpage_move(int nr) */ void win_goto(win_T *wp) { - win_T *owp = curwin; + win_T *owp = curwin; if (text_locked()) { beep_flush(); text_locked_msg(); return; } - if (curbuf_locked()) + if (curbuf_locked()) { return; + } - if (wp->w_buffer != curbuf) + if (wp->w_buffer != curbuf) { reset_VIsual_and_resel(); - else if (VIsual_active) + } else if (VIsual_active) { wp->w_cursor = curwin->w_cursor; + } win_enter(wp, true); @@ -4185,9 +4301,9 @@ tabpage_T *win_find_tabpage(win_T *win) /// @return found window win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count) { - frame_T *fr; - frame_T *nfr; - frame_T *foundfr; + frame_T *fr; + frame_T *nfr; + frame_T *foundfr; foundfr = wp->w_frame; @@ -4233,9 +4349,11 @@ win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count) fr = fr->fr_next; } } - if (nfr->fr_layout == FR_COL && up) - while (fr->fr_next != NULL) + if (nfr->fr_layout == FR_COL && up) { + while (fr->fr_next != NULL) { fr = fr->fr_next; + } + } nfr = fr; } } @@ -4266,9 +4384,9 @@ static void win_goto_ver(bool up, long count) /// @return found window win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count) { - frame_T *fr; - frame_T *nfr; - frame_T *foundfr; + frame_T *fr; + frame_T *nfr; + frame_T *foundfr; foundfr = wp->w_frame; @@ -4307,15 +4425,18 @@ win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count) } fr = nfr->fr_child; if (nfr->fr_layout == FR_COL) { - /* Find the frame at the cursor row. */ + // Find the frame at the cursor row. while (fr->fr_next != NULL && frame2win(fr)->w_winrow + fr->fr_height - <= wp->w_winrow + wp->w_wrow) + <= wp->w_winrow + wp->w_wrow) { fr = fr->fr_next; + } } - if (nfr->fr_layout == FR_ROW && left) - while (fr->fr_next != NULL) + if (nfr->fr_layout == FR_ROW && left) { + while (fr->fr_next != NULL) { fr = fr->fr_next; + } + } nfr = fr; } } @@ -4348,15 +4469,14 @@ void win_enter(win_T *wp, bool undo_sync) /// /// @param curwin_invalid curwin has just been closed and /// isn't valid when true. -static void win_enter_ext(win_T *wp, bool undo_sync, bool curwin_invalid, - bool trigger_new_autocmds, - bool trigger_enter_autocmds, - bool trigger_leave_autocmds) +static void win_enter_ext(win_T *wp, bool undo_sync, bool curwin_invalid, bool trigger_new_autocmds, + bool trigger_enter_autocmds, bool trigger_leave_autocmds) { int other_buffer = FALSE; - if (wp == curwin && !curwin_invalid) /* nothing to do */ + if (wp == curwin && !curwin_invalid) { // nothing to do return; + } if (!curwin_invalid && trigger_leave_autocmds) { /* @@ -4365,15 +4485,18 @@ static void win_enter_ext(win_T *wp, bool undo_sync, bool curwin_invalid, if (wp->w_buffer != curbuf) { apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf); other_buffer = TRUE; - if (!win_valid(wp)) + if (!win_valid(wp)) { return; + } } apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf); - if (!win_valid(wp)) + if (!win_valid(wp)) { return; - /* autocmds may abort script processing */ - if (aborting()) + } + // autocmds may abort script processing + if (aborting()) { return; + } } // sync undo before leaving the current buffer @@ -4390,16 +4513,17 @@ static void win_enter_ext(win_T *wp, bool undo_sync, bool curwin_invalid, buf_copy_options(wp->w_buffer, BCO_ENTER | BCO_NOHELP); } if (!curwin_invalid) { - prevwin = curwin; /* remember for CTRL-W p */ + prevwin = curwin; // remember for CTRL-W p curwin->w_redr_status = TRUE; } curwin = wp; curbuf = wp->w_buffer; check_cursor(); - if (!virtual_active()) + if (!virtual_active()) { curwin->w_cursor.coladd = 0; - changed_line_abv_curs(); /* assume cursor position needs updating */ + } + changed_line_abv_curs(); // assume cursor position needs updating // New directory is either the local directory of the window, tab or NULL. char *new_dir = (char *)(curwin->w_localdir @@ -4474,9 +4598,9 @@ static void win_enter_ext(win_T *wp, bool undo_sync, bool curwin_invalid, win_setwidth((int)p_wiw); } - setmouse(); /* in case jumped to/from help buffer */ + setmouse(); // in case jumped to/from help buffer - /* Change directories when the 'acd' option is set. */ + // Change directories when the 'acd' option is set. do_autochdir(); } @@ -4505,12 +4629,12 @@ win_T *buf_jump_open_win(buf_T *buf) /// @return the found window, or NULL. win_T *buf_jump_open_tab(buf_T *buf) { - // First try the current tab page. { win_T *wp = buf_jump_open_win(buf); - if (wp != NULL) + if (wp != NULL) { return wp; + } } FOR_ALL_TABS(tp) { @@ -4563,13 +4687,14 @@ static win_T *win_alloc(win_T *after, bool hidden) /* * link the window in the window list */ - if (!hidden) + if (!hidden) { win_append(after, new_wp); + } new_wp->w_wincol = 0; new_wp->w_width = Columns; - /* position the display and the cursor at the top of the file. */ + // position the display and the cursor at the top of the file. new_wp->w_topline = 1; new_wp->w_topfill = 0; new_wp->w_botline = 2; @@ -4583,7 +4708,7 @@ static win_T *win_alloc(win_T *after, bool hidden) new_wp->w_p_so = -1; new_wp->w_p_siso = -1; - /* We won't calculate w_fraction until resizing the window */ + // We won't calculate w_fraction until resizing the window new_wp->w_fraction = 0; new_wp->w_prev_fraction_row = -1; @@ -4596,8 +4721,7 @@ static win_T *win_alloc(win_T *after, bool hidden) // Free one wininfo_T. -void -free_wininfo(wininfo_T *wip, buf_T *bp) +void free_wininfo(wininfo_T *wip, buf_T *bp) { if (wip->wi_optset) { clear_winopt(&wip->wi_opt); @@ -4607,22 +4731,18 @@ free_wininfo(wininfo_T *wip, buf_T *bp) } -/* - * Remove window 'wp' from the window list and free the structure. - */ -static void -win_free ( - win_T *wp, - tabpage_T *tp /* tab page "win" is in, NULL for current */ -) +/// Remove window 'wp' from the window list and free the structure. +/// +/// @param tp tab page "win" is in, NULL for current +static void win_free(win_T *wp, tabpage_T *tp) { int i; - wininfo_T *wip; + wininfo_T *wip; pmap_del(handle_T)(&window_handles, wp->handle); clearFolding(wp); - /* reduce the reference count to the argument list. */ + // reduce the reference count to the argument list. alist_unlink(wp->w_alist); /* Don't execute autocommands while the window is halfway being deleted. @@ -4632,7 +4752,7 @@ win_free ( clear_winopt(&wp->w_onebuf_opt); clear_winopt(&wp->w_allbuf_opt); - vars_clear(&wp->w_vars->dv_hashtab); /* free all w: variables */ + vars_clear(&wp->w_vars->dv_hashtab); // free all w: variables hash_init(&wp->w_vars->dv_hashtab); unref_var_dict(wp->w_vars); @@ -4695,8 +4815,9 @@ win_free ( win_free_grid(wp, false); - if (wp != aucmd_win) + if (wp != aucmd_win) { win_remove(wp, tp); + } if (autocmd_busy) { wp->w_next = au_pending_free_win; au_pending_free_win = wp; @@ -4725,33 +4846,32 @@ void win_free_grid(win_T *wp, bool reinit) */ void win_append(win_T *after, win_T *wp) { - win_T *before; + win_T *before; - if (after == NULL) /* after NULL is in front of the first */ + if (after == NULL) { // after NULL is in front of the first before = firstwin; - else + } else { before = after->w_next; + } wp->w_next = before; wp->w_prev = after; - if (after == NULL) + if (after == NULL) { firstwin = wp; - else + } else { after->w_next = wp; - if (before == NULL) + } + if (before == NULL) { lastwin = wp; - else + } else { before->w_prev = wp; + } } -/* - * Remove a window from the window list. - */ -void -win_remove ( - win_T *wp, - tabpage_T *tp /* tab page "win" is in, NULL for current */ -) +/// Remove a window from the window list. +/// +/// @param tp tab page "win" is in, NULL for current +void win_remove(win_T *wp, tabpage_T *tp) { if (wp->w_prev != NULL) { wp->w_prev->w_next = wp->w_next; @@ -4776,8 +4896,9 @@ static void frame_append(frame_T *after, frame_T *frp) { frp->fr_next = after->fr_next; after->fr_next = frp; - if (frp->fr_next != NULL) + if (frp->fr_next != NULL) { frp->fr_next->fr_prev = frp; + } frp->fr_prev = after; } @@ -4789,10 +4910,11 @@ static void frame_insert(frame_T *before, frame_T *frp) frp->fr_next = before; frp->fr_prev = before->fr_prev; before->fr_prev = frp; - if (frp->fr_prev != NULL) + if (frp->fr_prev != NULL) { frp->fr_prev->fr_next = frp; - else + } else { frp->fr_parent->fr_child = frp; + } } /* @@ -4823,10 +4945,12 @@ void shell_new_rows(void) { int h = (int)ROWS_AVAIL; - if (firstwin == NULL) /* not initialized yet */ + if (firstwin == NULL) { // not initialized yet return; - if (h < frame_minheight(topframe, NULL)) + } + if (h < frame_minheight(topframe, NULL)) { h = frame_minheight(topframe, NULL); + } /* First try setting the heights of windows with 'winfixheight'. If * that doesn't result in the right height, forget about that option. */ @@ -4839,7 +4963,6 @@ void shell_new_rows(void) win_reconfig_floats(); // The size of floats might change compute_cmdrow(); curtab->tp_ch_used = p_ch; - } /* @@ -4847,8 +4970,9 @@ void shell_new_rows(void) */ void shell_new_columns(void) { - if (firstwin == NULL) /* not initialized yet */ + if (firstwin == NULL) { // not initialized yet return; + } /* First try setting the widths of windows with 'winfixwidth'. If that * doesn't result in the right width, forget about that option. */ @@ -4921,7 +5045,7 @@ void win_size_restore(garray_T *gap) } } } - /* recompute the window positions */ + // recompute the window positions (void)win_comp_pos(); } } @@ -4963,17 +5087,16 @@ void win_reconfig_floats(void) */ static void frame_comp_pos(frame_T *topfrp, int *row, int *col) { - win_T *wp; - frame_T *frp; + win_T *wp; + frame_T *frp; int startcol; int startrow; wp = topfrp->fr_win; if (wp != NULL) { if (wp->w_winrow != *row - || wp->w_wincol != *col - ) { - /* position changed, redraw */ + || wp->w_wincol != *col) { + // position changed, redraw wp->w_winrow = *row; wp->w_wincol = *col; redraw_later(wp, NOT_VALID); @@ -5044,7 +5167,6 @@ void win_setheight_win(int height, win_T *win) msg_col = 0; redraw_all_later(NOT_VALID); } - } @@ -5063,22 +5185,24 @@ void win_setheight_win(int height, win_T *win) */ static void frame_setheight(frame_T *curfrp, int height) { - int room; /* total number of lines available */ - int take; /* number of lines taken from other windows */ - int room_cmdline; /* lines available from cmdline */ + int room; // total number of lines available + int take; // number of lines taken from other windows + int room_cmdline; // lines available from cmdline int run; - frame_T *frp; + frame_T *frp; int h; int room_reserved; - /* If the height already is the desired value, nothing to do. */ - if (curfrp->fr_height == height) + // If the height already is the desired value, nothing to do. + if (curfrp->fr_height == height) { return; + } if (curfrp->fr_parent == NULL) { - /* topframe: can only change the command line */ - if (height > ROWS_AVAIL) + // topframe: can only change the command line + if (height > ROWS_AVAIL) { height = ROWS_AVAIL; + } if (height > 0) { frame_new_height(curfrp, height, false, false); } @@ -5086,8 +5210,9 @@ static void frame_setheight(frame_T *curfrp, int height) /* Row of frames: Also need to resize frames left and right of this * one. First check for the minimal height of these. */ h = frame_minheight(curfrp->fr_parent, NULL); - if (height < h) + if (height < h) { height = h; + } frame_setheight(curfrp->fr_parent, height); } else { /* @@ -5119,7 +5244,7 @@ static void frame_setheight(frame_T *curfrp, int height) } else { win_T *wp = lastwin_nofloating(); room_cmdline = Rows - p_ch - - (wp->w_winrow + wp->w_height + wp->w_status_height); + - (wp->w_winrow + wp->w_height + wp->w_status_height); if (room_cmdline < 0) { room_cmdline = 0; } @@ -5133,8 +5258,8 @@ static void frame_setheight(frame_T *curfrp, int height) break; } frame_setheight(curfrp->fr_parent, height - + frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1); - /*NOTREACHED*/ + + frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1); + //NOTREACHED } /* @@ -5145,17 +5270,20 @@ static void frame_setheight(frame_T *curfrp, int height) /* If there is not enough room, also reduce the height of a window * with 'winfixheight' set. */ - if (height > room + room_cmdline - room_reserved) + if (height > room + room_cmdline - room_reserved) { room_reserved = room + room_cmdline - height; + } /* If there is only a 'winfixheight' window and making the * window smaller, need to make the other window taller. */ - if (take < 0 && room - curfrp->fr_height < room_reserved) + if (take < 0 && room - curfrp->fr_height < room_reserved) { room_reserved = 0; + } if (take > 0 && room_cmdline > 0) { - /* use lines from cmdline first */ - if (take < room_cmdline) + // use lines from cmdline first + if (take < room_cmdline) { room_cmdline = take; + } take -= room_cmdline; topframe->fr_height += room_cmdline; } @@ -5171,20 +5299,22 @@ static void frame_setheight(frame_T *curfrp, int height) * frame. */ for (run = 0; run < 2; ++run) { - if (run == 0) - frp = curfrp->fr_next; /* 1st run: start with next window */ - else - frp = curfrp->fr_prev; /* 2nd run: start with prev window */ + if (run == 0) { + frp = curfrp->fr_next; // 1st run: start with next window + } else { + frp = curfrp->fr_prev; // 2nd run: start with prev window + } while (frp != NULL && take != 0) { h = frame_minheight(frp, NULL); if (room_reserved > 0 && frp->fr_win != NULL && frp->fr_win->w_p_wfh) { - if (room_reserved >= frp->fr_height) + if (room_reserved >= frp->fr_height) { room_reserved -= frp->fr_height; - else { - if (frp->fr_height - room_reserved > take) + } else { + if (frp->fr_height - room_reserved > take) { room_reserved = frp->fr_height - take; + } take -= frp->fr_height - room_reserved; frame_new_height(frp, room_reserved, false, false); room_reserved = 0; @@ -5198,10 +5328,11 @@ static void frame_setheight(frame_T *curfrp, int height) take = 0; } } - if (run == 0) + if (run == 0) { frp = frp->fr_next; - else + } else { frp = frp->fr_prev; + } } } } @@ -5221,10 +5352,12 @@ void win_setwidth_win(int width, win_T *wp) /* Always keep current window at least one column wide, even when * 'winminwidth' is zero. */ if (wp == curwin) { - if (width < p_wmw) + if (width < p_wmw) { width = p_wmw; - if (width == 0) + } + if (width == 0) { width = 1; + } } else if (width < 0) { width = 0; } @@ -5239,7 +5372,6 @@ void win_setwidth_win(int width, win_T *wp) (void)win_comp_pos(); redraw_all_later(NOT_VALID); } - } /* @@ -5251,27 +5383,30 @@ void win_setwidth_win(int width, win_T *wp) */ static void frame_setwidth(frame_T *curfrp, int width) { - int room; /* total number of lines available */ - int take; /* number of lines taken from other windows */ + int room; // total number of lines available + int take; // number of lines taken from other windows int run; - frame_T *frp; + frame_T *frp; int w; int room_reserved; - /* If the width already is the desired value, nothing to do. */ - if (curfrp->fr_width == width) + // If the width already is the desired value, nothing to do. + if (curfrp->fr_width == width) { return; + } - if (curfrp->fr_parent == NULL) - /* topframe: can't change width */ + if (curfrp->fr_parent == NULL) { + // topframe: can't change width return; + } if (curfrp->fr_parent->fr_layout == FR_COL) { /* Column of frames: Also need to resize frames above and below of * this one. First check for the minimal width of these. */ w = frame_minwidth(curfrp->fr_parent, NULL); - if (width < w) + if (width < w) { width = w; + } frame_setwidth(curfrp->fr_parent, width); } else { /* @@ -5297,14 +5432,15 @@ static void frame_setwidth(frame_T *curfrp, int width) } } - if (width <= room) + if (width <= room) { break; + } if (run == 2 || curfrp->fr_height >= ROWS_AVAIL) { width = room; break; } frame_setwidth(curfrp->fr_parent, width - + frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1); + + frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1); } /* @@ -5315,12 +5451,14 @@ static void frame_setwidth(frame_T *curfrp, int width) /* If there is not enough room, also reduce the width of a window * with 'winfixwidth' set. */ - if (width > room - room_reserved) + if (width > room - room_reserved) { room_reserved = room - width; + } /* If there is only a 'winfixwidth' window and making the * window smaller, need to make the other window narrower. */ - if (take < 0 && room - curfrp->fr_width < room_reserved) + if (take < 0 && room - curfrp->fr_width < room_reserved) { room_reserved = 0; + } /* * set the current frame to the new width @@ -5333,20 +5471,22 @@ static void frame_setwidth(frame_T *curfrp, int width) * frame. */ for (run = 0; run < 2; ++run) { - if (run == 0) - frp = curfrp->fr_next; /* 1st run: start with next window */ - else - frp = curfrp->fr_prev; /* 2nd run: start with prev window */ + if (run == 0) { + frp = curfrp->fr_next; // 1st run: start with next window + } else { + frp = curfrp->fr_prev; // 2nd run: start with prev window + } while (frp != NULL && take != 0) { w = frame_minwidth(frp, NULL); if (room_reserved > 0 && frp->fr_win != NULL && frp->fr_win->w_p_wfw) { - if (room_reserved >= frp->fr_width) + if (room_reserved >= frp->fr_width) { room_reserved -= frp->fr_width; - else { - if (frp->fr_width - room_reserved > take) + } else { + if (frp->fr_width - room_reserved > take) { room_reserved = frp->fr_width - take; + } take -= frp->fr_width - room_reserved; frame_new_width(frp, room_reserved, false, false); room_reserved = 0; @@ -5360,10 +5500,11 @@ static void frame_setwidth(frame_T *curfrp, int width) take = 0; } } - if (run == 0) + if (run == 0) { frp = frp->fr_next; - else + } else { frp = frp->fr_prev; + } } } } @@ -5412,8 +5553,8 @@ void win_setminwidth(void) /// Status line of dragwin is dragged "offset" lines down (negative is up). void win_drag_status_line(win_T *dragwin, int offset) { - frame_T *curfr; - frame_T *fr; + frame_T *curfr; + frame_T *fr; int room; int row; bool up; // if true, drag status line up, otherwise down @@ -5421,40 +5562,44 @@ void win_drag_status_line(win_T *dragwin, int offset) fr = dragwin->w_frame; curfr = fr; - if (fr != topframe) { /* more than one window */ + if (fr != topframe) { // more than one window fr = fr->fr_parent; /* When the parent frame is not a column of frames, its parent should * be. */ if (fr->fr_layout != FR_COL) { curfr = fr; - if (fr != topframe) /* only a row of windows, may drag statusline */ + if (fr != topframe) { // only a row of windows, may drag statusline fr = fr->fr_parent; + } } } /* If this is the last frame in a column, may want to resize the parent * frame instead (go two up to skip a row of frames). */ while (curfr != topframe && curfr->fr_next == NULL) { - if (fr != topframe) + if (fr != topframe) { fr = fr->fr_parent; + } curfr = fr; - if (fr != topframe) + if (fr != topframe) { fr = fr->fr_parent; + } } if (offset < 0) { // drag up up = true; offset = -offset; - /* sum up the room of the current frame and above it */ + // sum up the room of the current frame and above it if (fr == curfr) { - /* only one window */ + // only one window room = fr->fr_height - frame_minheight(fr, NULL); } else { room = 0; for (fr = fr->fr_child;; fr = fr->fr_next) { room += fr->fr_height - frame_minheight(fr, NULL); - if (fr == curfr) + if (fr == curfr) { break; + } } } fr = curfr->fr_next; // put fr at frame that grows @@ -5462,12 +5607,14 @@ void win_drag_status_line(win_T *dragwin, int offset) up = false; // Only dragging the last status line can reduce p_ch. room = Rows - cmdline_row; - if (curfr->fr_next == NULL) + if (curfr->fr_next == NULL) { room -= 1; - else + } else { room -= p_ch; - if (room < 0) + } + if (room < 0) { room = 0; + } // sum up the room of frames below of the current one FOR_ALL_FRAMES(fr, curfr->fr_next) { room += fr->fr_height - frame_minheight(fr, NULL); @@ -5475,10 +5622,12 @@ void win_drag_status_line(win_T *dragwin, int offset) fr = curfr; // put fr at window that grows } - if (room < offset) /* Not enough room */ - offset = room; /* Move as far as we can */ - if (offset <= 0) + if (room < offset) { // Not enough room + offset = room; // Move as far as we can + } + if (offset <= 0) { return; + } /* * Grow frame fr by "offset" lines. @@ -5488,11 +5637,11 @@ void win_drag_status_line(win_T *dragwin, int offset) frame_new_height(fr, fr->fr_height + offset, up, false); } - if (up) - fr = curfr; /* current frame gets smaller */ - else - fr = curfr->fr_next; /* next frame gets smaller */ - + if (up) { + fr = curfr; // current frame gets smaller + } else { + fr = curfr->fr_next; // next frame gets smaller + } /* * Now make the other frames smaller. */ @@ -5505,10 +5654,11 @@ void win_drag_status_line(win_T *dragwin, int offset) frame_new_height(fr, fr->fr_height - offset, !up, false); break; } - if (up) + if (up) { fr = fr->fr_prev; - else + } else { fr = fr->fr_next; + } } row = win_comp_pos(); grid_fill(&default_grid, row, cmdline_row, 0, Columns, ' ', ' ', 0); @@ -5517,8 +5667,9 @@ void win_drag_status_line(win_T *dragwin, int offset) } cmdline_row = row; p_ch = Rows - cmdline_row; - if (p_ch < 1) + if (p_ch < 1) { p_ch = 1; + } curtab->tp_ch_used = p_ch; redraw_all_later(SOME_VALID); showmode(); @@ -5529,21 +5680,23 @@ void win_drag_status_line(win_T *dragwin, int offset) */ void win_drag_vsep_line(win_T *dragwin, int offset) { - frame_T *curfr; - frame_T *fr; + frame_T *curfr; + frame_T *fr; int room; bool left; // if true, drag separator line left, otherwise right int n; fr = dragwin->w_frame; - if (fr == topframe) /* only one window (cannot happen?) */ + if (fr == topframe) { // only one window (cannot happen?) return; + } curfr = fr; fr = fr->fr_parent; - /* When the parent frame is not a row of frames, its parent should be. */ + // When the parent frame is not a row of frames, its parent should be. if (fr->fr_layout != FR_ROW) { - if (fr == topframe) /* only a column of windows (cannot happen?) */ + if (fr == topframe) { // only a column of windows (cannot happen?) return; + } curfr = fr; fr = fr->fr_parent; } @@ -5551,8 +5704,9 @@ void win_drag_vsep_line(win_T *dragwin, int offset) /* If this is the last frame in a row, may want to resize a parent * frame instead. */ while (curfr->fr_next == NULL) { - if (fr == topframe) + if (fr == topframe) { break; + } curfr = fr; fr = fr->fr_parent; if (fr != topframe) { @@ -5564,12 +5718,13 @@ void win_drag_vsep_line(win_T *dragwin, int offset) if (offset < 0) { // drag left left = true; offset = -offset; - /* sum up the room of the current frame and left of it */ + // sum up the room of the current frame and left of it room = 0; for (fr = fr->fr_child;; fr = fr->fr_next) { room += fr->fr_width - frame_minwidth(fr, NULL); - if (fr == curfr) + if (fr == curfr) { break; + } } fr = curfr->fr_next; // put fr at frame that grows } else { // drag right @@ -5600,12 +5755,12 @@ void win_drag_vsep_line(win_T *dragwin, int offset) // grow frame fr by offset lines frame_new_width(fr, fr->fr_width + offset, left, false); - /* shrink other frames: current and at the left or at the right */ - if (left) - fr = curfr; /* current frame gets smaller */ - else - fr = curfr->fr_next; /* next frame gets smaller */ - + // shrink other frames: current and at the left or at the right + if (left) { + fr = curfr; // current frame gets smaller + } else { + fr = curfr->fr_next; // next frame gets smaller + } while (fr != NULL && offset > 0) { n = frame_minwidth(fr, NULL); if (fr->fr_width - offset <= n) { @@ -5615,10 +5770,11 @@ void win_drag_vsep_line(win_T *dragwin, int offset) frame_new_width(fr, fr->fr_width - offset, !left, false); break; } - if (left) + if (left) { fr = fr->fr_prev; - else + } else { fr = fr->fr_next; + } } (void)win_comp_pos(); redraw_all_later(NOT_VALID); @@ -5636,7 +5792,7 @@ void set_fraction(win_T *wp) // it's halfway that line. Thus with two lines it is 25%, with three // lines 17%, etc. Similarly for the last line: 75%, 83%, etc. wp->w_fraction = ((long)wp->w_wrow * FRACTION_MULT + FRACTION_MULT / 2) - / (long)wp->w_height_inner; + / (long)wp->w_height_inner; } } @@ -5662,9 +5818,9 @@ void win_new_height(win_T *wp, int height) void scroll_to_fraction(win_T *wp, int prev_height) { - linenr_T lnum; - int sline, line_size; - int height = wp->w_height_inner; + linenr_T lnum; + int sline, line_size; + int height = wp->w_height_inner; // Don't change w_topline in any of these cases: // - window height is 0 @@ -5673,15 +5829,16 @@ void scroll_to_fraction(win_T *wp, int prev_height) // is visible. if (height > 0 && (!wp->w_p_scb || wp == curwin) - && (height < wp->w_buffer->b_ml.ml_line_count || wp->w_topline > 1) - ) { + && (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). */ lnum = wp->w_cursor.lnum; - if (lnum < 1) /* can happen when starting up */ + if (lnum < 1) { // can happen when starting up lnum = 1; + } wp->w_wrow = ((long)wp->w_fraction * (long)height - 1L) / FRACTION_MULT; line_size = plines_win_col(wp, lnum, (long)(wp->w_cursor.col)) - 1; sline = wp->w_wrow - line_size; @@ -5717,7 +5874,7 @@ void scroll_to_fraction(win_T *wp, int prev_height) while (sline > 0 && lnum > 1) { (void)hasFoldingWin(wp, lnum, &lnum, NULL, true, NULL); if (lnum == 1) { - /* first line in buffer is folded */ + // first line in buffer is folded line_size = 1; --sline; break; @@ -5856,7 +6013,7 @@ void win_comp_scroll(win_T *wp) void command_height(void) { int h; - frame_T *frp; + frame_T *frp; int old_p_ch = curtab->tp_ch_used; /* Use the value of p_ch that we remembered. This is needed for when the @@ -5870,15 +6027,16 @@ void command_height(void) frp = frp->fr_parent; } - /* Avoid changing the height of a window with 'winfixheight' set. */ + // Avoid changing the height of a window with 'winfixheight' set. while (frp->fr_prev != NULL && frp->fr_layout == FR_LEAF - && frp->fr_win->w_p_wfh) + && frp->fr_win->w_p_wfh) { frp = frp->fr_prev; + } if (starting != NO_SCREEN) { cmdline_row = Rows - p_ch; - if (p_ch > old_p_ch) { /* p_ch got bigger */ + if (p_ch > old_p_ch) { // p_ch got bigger while (p_ch > old_p_ch) { if (frp == NULL) { EMSG(_(e_noroom)); @@ -5888,14 +6046,15 @@ void command_height(void) break; } h = frp->fr_height - frame_minheight(frp, NULL); - if (h > p_ch - old_p_ch) + if (h > p_ch - old_p_ch) { h = p_ch - old_p_ch; + } old_p_ch += h; frame_add_height(frp, -h); frp = frp->fr_prev; } - /* Recompute window positions. */ + // Recompute window positions. (void)win_comp_pos(); // clear the lines added to cmdline @@ -5907,15 +6066,17 @@ void command_height(void) return; } - if (msg_row < cmdline_row) + if (msg_row < cmdline_row) { msg_row = cmdline_row; + } redraw_cmdline = true; } frame_add_height(frp, (int)(old_p_ch - p_ch)); - /* Recompute window positions. */ - if (frp != lastwin->w_frame) + // Recompute window positions. + if (frp != lastwin->w_frame) { (void)win_comp_pos(); + } } /* @@ -5927,8 +6088,9 @@ static void frame_add_height(frame_T *frp, int n) frame_new_height(frp, frp->fr_height + n, false, false); for (;; ) { frp = frp->fr_parent; - if (frp == NULL) + if (frp == NULL) { break; + } frp->fr_height += n; } } @@ -5943,9 +6105,10 @@ char_u *grab_file_name(long count, linenr_T *file_lnum) int options = FNAME_MESS | FNAME_EXP | FNAME_REL | FNAME_UNESC; if (VIsual_active) { size_t len; - char_u *ptr; - if (get_visual_text(NULL, &ptr, &len) == FAIL) + char_u *ptr; + if (get_visual_text(NULL, &ptr, &len) == FAIL) { return NULL; + } // Only recognize ":123" here if (file_lnum != NULL && ptr[len] == ':' && isdigit(ptr[len + 1])) { char_u *p = ptr + len + 1; @@ -5965,33 +6128,26 @@ char_u *grab_file_name(long count, linenr_T *file_lnum) * 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" + * 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(get_cursor_line_ptr(), - curwin->w_cursor.col, options, count, curbuf->b_ffname, - file_lnum); + curwin->w_cursor.col, options, count, curbuf->b_ffname, + file_lnum); } -/* - * Return the name of the file under or after ptr[col]. - * Otherwise like file_name_at_cursor(). - */ -char_u * -file_name_in_line ( - char_u *line, - int col, - int options, - long count, - char_u *rel_fname, /* file we are searching relative to */ - linenr_T *file_lnum /* line number after the file name */ -) -{ - char_u *ptr; +/// @param rel_fname file we are searching relative to +/// @param file_lnum line number after the file name +/// +/// @return the name of the file under or after ptr[col]. Otherwise like file_name_at_cursor(). +char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u *rel_fname, + linenr_T *file_lnum) +{ + char_u *ptr; size_t len; bool in_type = true; bool is_url = false; @@ -6056,8 +6212,9 @@ file_name_in_line ( * But don't remove "..", could be a directory name. */ if (len > 2 && vim_strchr((char_u *)".,:;!", ptr[len - 1]) != NULL - && ptr[len - 2] != '.') + && ptr[len - 2] != '.') { --len; + } if (file_lnum != NULL) { char_u *p; @@ -6095,25 +6252,25 @@ file_name_in_line ( /// @param morewin pretend there are two or more windows if true. void last_status(bool morewin) { - /* Don't make a difference between horizontal or vertical split. */ + // Don't make a difference between horizontal or vertical split. last_status_rec(topframe, (p_ls == 2 || (p_ls == 1 && (morewin || !one_window())))); } static void last_status_rec(frame_T *fr, bool statusline) { - frame_T *fp; - win_T *wp; + frame_T *fp; + win_T *wp; if (fr->fr_layout == FR_LEAF) { wp = fr->fr_win; if (wp->w_status_height != 0 && !statusline) { - /* remove status line */ + // remove status line win_new_height(wp, wp->w_height + 1); wp->w_status_height = 0; comp_col(); } else if (wp->w_status_height == 0 && statusline) { - /* Find a frame to take a line from. */ + // Find a frame to take a line from. fp = fr; while (fp->fr_height <= frame_minheight(fp, NULL)) { if (fp == topframe) { @@ -6122,18 +6279,20 @@ static void last_status_rec(frame_T *fr, bool statusline) } /* In a column of frames: go to frame above. If already at * the top or in a row of frames: go to parent. */ - if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL) + if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL) { fp = fp->fr_prev; - else + } else { fp = fp->fr_parent; + } } wp->w_status_height = 1; if (fp != fr) { frame_new_height(fp, fp->fr_height - 1, false, false); frame_fix_height(wp); (void)win_comp_pos(); - } else + } else { win_new_height(wp, wp->w_height - 1); + } comp_col(); redraw_all_later(SOME_VALID); } @@ -6143,9 +6302,10 @@ static void last_status_rec(frame_T *fr, bool statusline) last_status_rec(fp, statusline); } } else { - /* horizontally split window, set status line for last one */ - for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next) + // horizontally split window, set status line for last one + for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next) { ; + } last_status_rec(fp, statusline); } } @@ -6160,8 +6320,10 @@ int tabline_height(void) } assert(first_tabpage); switch (p_stal) { - case 0: return 0; - case 1: return (first_tabpage->tp_next == NULL) ? 0 : 1; + case 0: + return 0; + case 1: + return (first_tabpage->tp_next == NULL) ? 0 : 1; } return 1; } @@ -6172,8 +6334,9 @@ int tabline_height(void) */ int min_rows(void) { - if (firstwin == NULL) /* not initialized yet */ + if (firstwin == NULL) { // not initialized yet return MIN_LINES; + } int total = 0; FOR_ALL_TABS(tp) { @@ -6183,7 +6346,7 @@ int min_rows(void) } } total += tabline_height(); - total += 1; /* count the room for the command line */ + total += 1; // count the room for the command line return total; } @@ -6278,12 +6441,15 @@ static void make_snapshot_rec(frame_T *fr, frame_T **frp) (*frp)->fr_layout = fr->fr_layout; (*frp)->fr_width = fr->fr_width; (*frp)->fr_height = fr->fr_height; - if (fr->fr_next != NULL) + if (fr->fr_next != NULL) { make_snapshot_rec(fr->fr_next, &((*frp)->fr_next)); - if (fr->fr_child != NULL) + } + if (fr->fr_child != NULL) { make_snapshot_rec(fr->fr_child, &((*frp)->fr_child)); - if (fr->fr_layout == FR_LEAF && fr->fr_win == curwin) + } + if (fr->fr_layout == FR_LEAF && fr->fr_win == curwin) { (*frp)->fr_win = curwin; + } } /* @@ -6304,18 +6470,14 @@ static void clear_snapshot_rec(frame_T *fr) } } -/* - * Restore a previously created snapshot, if there is any. - * This is only done if the screen size didn't change and the window layout is - * still the same. - */ -void -restore_snapshot ( - int idx, - int close_curwin /* closing current window */ -) +/// Restore a previously created snapshot, if there is any. +/// This is only done if the screen size didn't change and the window layout is +/// still the same. +/// +/// @param close_curwin closing current window +void restore_snapshot(int idx, int close_curwin) { - win_T *wp; + win_T *wp; if (curtab->tp_snapshot[idx] != NULL && curtab->tp_snapshot[idx]->fr_width == topframe->fr_width @@ -6342,8 +6504,9 @@ static int check_snapshot_rec(frame_T *sn, frame_T *fr) && check_snapshot_rec(sn->fr_next, fr->fr_next) == FAIL) || (sn->fr_child != NULL && check_snapshot_rec(sn->fr_child, fr->fr_child) == FAIL) - || (sn->fr_win != NULL && !win_valid(sn->fr_win))) + || (sn->fr_win != NULL && !win_valid(sn->fr_win))) { return FAIL; + } return OK; } @@ -6354,8 +6517,8 @@ static int check_snapshot_rec(frame_T *sn, frame_T *fr) */ static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr) { - win_T *wp = NULL; - win_T *wp2; + win_T *wp = NULL; + win_T *wp2; fr->fr_height = sn->fr_height; fr->fr_width = sn->fr_width; @@ -6366,13 +6529,15 @@ static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr) } if (sn->fr_next != NULL) { wp2 = restore_snapshot_rec(sn->fr_next, fr->fr_next); - if (wp2 != NULL) + if (wp2 != NULL) { wp = wp2; + } } if (sn->fr_child != NULL) { wp2 = restore_snapshot_rec(sn->fr_child, fr->fr_child); - if (wp2 != NULL) + if (wp2 != NULL) { wp = wp2; + } } return wp; } @@ -6407,16 +6572,16 @@ static win_T *get_snapshot_focus(int idx) /// triggered, another tabpage access is limited. /// /// @return FAIL if switching to "win" failed. -int switch_win(win_T **save_curwin, tabpage_T **save_curtab, win_T *win, - tabpage_T *tp, bool no_display) +int switch_win(win_T **save_curwin, tabpage_T **save_curtab, win_T *win, tabpage_T *tp, + bool no_display) { block_autocmds(); return switch_win_noblock(save_curwin, save_curtab, win, tp, no_display); } // As switch_win() but without blocking autocommands. -int switch_win_noblock(win_T **save_curwin, tabpage_T **save_curtab, - win_T *win, tabpage_T *tp, bool no_display) +int switch_win_noblock(win_T **save_curwin, tabpage_T **save_curtab, win_T *win, tabpage_T *tp, + bool no_display) { *save_curwin = curwin; if (tp != NULL) { @@ -6449,8 +6614,7 @@ void restore_win(win_T *save_curwin, tabpage_T *save_curtab, bool no_display) } // As restore_win() but without unblocking autocommands. -void restore_win_noblock(win_T *save_curwin, tabpage_T *save_curtab, - bool no_display) +void restore_win_noblock(win_T *save_curwin, tabpage_T *save_curtab, bool no_display) { if (save_curtab != NULL && valid_tabpage(save_curtab)) { if (no_display) { @@ -6506,16 +6670,15 @@ void restore_buffer(bufref_T *save_curbuf) /// particular ID is desired /// @param[in] conceal_char pointer to conceal replacement char /// @return ID of added match, -1 on failure. -int match_add(win_T *wp, const char *const grp, const char *const pat, - int prio, int id, list_T *pos_list, - const char *const conceal_char) +int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, int id, + list_T *pos_list, const char *const conceal_char) FUNC_ATTR_NONNULL_ARG(1, 2) { matchitem_T *cur; matchitem_T *prev; matchitem_T *m; int hlg_id; - regprog_T *regprog = NULL; + regprog_T *regprog = NULL; int rtype = SOME_VALID; if (*grp == NUL || (pat != NULL && *pat == NUL)) { @@ -6548,10 +6711,12 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, // Find available match ID. while (id == -1) { cur = wp->w_match_head; - while (cur != NULL && cur->id != wp->w_next_match_id) + while (cur != NULL && cur->id != wp->w_next_match_id) { cur = cur->next; - if (cur == NULL) + } + if (cur == NULL) { id = wp->w_next_match_id; + } wp->w_next_match_id++; } @@ -6643,8 +6808,8 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, } }); - // Calculate top and bottom lines for redrawing area - if (toplnum != 0){ + // Calculate top and bottom lines for redrawing area + if (toplnum != 0) { if (wp->w_buffer->b_mod_set) { if (wp->w_buffer->b_mod_top > toplnum) { wp->w_buffer->b_mod_top = toplnum; @@ -6672,10 +6837,11 @@ int match_add(win_T *wp, const char *const grp, const char *const pat, prev = cur; cur = cur->next; } - if (cur == prev) + if (cur == prev) { wp->w_match_head = m; - else + } else { prev->next = m; + } m->next = cur; redraw_later(wp, rtype); @@ -6714,10 +6880,11 @@ int match_delete(win_T *wp, int id, bool perr) } return -1; } - if (cur == prev) + if (cur == prev) { wp->w_match_head = cur->next; - else + } else { prev->next = cur->next; + } vim_regfree(cur->match.regprog); xfree(cur->pattern); if (cur->pos.toplnum != 0) { @@ -6766,8 +6933,9 @@ matchitem_T *get_match(win_T *wp, int id) { matchitem_T *cur = wp->w_match_head; - while (cur != NULL && cur->id != id) + while (cur != NULL && cur->id != id) { cur = cur->next; + } return cur; } diff --git a/src/nvim/xdiff/COPYING b/src/xdiff/COPYING index f3f1b3b65e..f3f1b3b65e 100644 --- a/src/nvim/xdiff/COPYING +++ b/src/xdiff/COPYING diff --git a/src/nvim/xdiff/README.txt b/src/xdiff/README.txt index 1afe74095b..95b2242b87 100644 --- a/src/nvim/xdiff/README.txt +++ b/src/xdiff/README.txt @@ -1,6 +1,6 @@ The files in this directory come from the xdiff implementation in git. You can find it here: https://github.com/git/git/tree/master/xdiff -The files were last updated 2018 September 10. +The files were last updated August 31, 2021 from git release v.2.33.0 This is originally based on libxdiff, which can be found here: http://www.xmailserver.org/xdiff-lib.html diff --git a/src/nvim/xdiff/xdiff.h b/src/xdiff/xdiff.h index 8ff4a05bfb..49985a0e9a 100644 --- a/src/nvim/xdiff/xdiff.h +++ b/src/xdiff/xdiff.h @@ -25,9 +25,9 @@ #ifdef __cplusplus extern "C" { -#endif // #ifdef __cplusplus +#endif /* #ifdef __cplusplus */ -// xpparm_t.flags +/* xpparm_t.flags */ #define XDF_NEED_MINIMAL (1 << 0) #define XDF_IGNORE_WHITESPACE (1 << 1) @@ -48,22 +48,23 @@ extern "C" { #define XDF_INDENT_HEURISTIC (1 << 23) -// xdemitconf_t.flags +/* xdemitconf_t.flags */ #define XDL_EMIT_FUNCNAMES (1 << 0) +#define XDL_EMIT_NO_HUNK_HDR (1 << 1) #define XDL_EMIT_FUNCCONTEXT (1 << 2) -// merge simplification levels +/* merge simplification levels */ #define XDL_MERGE_MINIMAL 0 #define XDL_MERGE_EAGER 1 #define XDL_MERGE_ZEALOUS 2 #define XDL_MERGE_ZEALOUS_ALNUM 3 -// merge favor modes +/* merge favor modes */ #define XDL_MERGE_FAVOR_OURS 1 #define XDL_MERGE_FAVOR_THEIRS 2 #define XDL_MERGE_FAVOR_UNION 3 -// merge output styles +/* merge output styles */ #define XDL_MERGE_DIFF3 1 typedef struct s_mmfile { @@ -79,14 +80,24 @@ typedef struct s_mmbuffer { typedef struct s_xpparam { unsigned long flags; - // See Documentation/diff-options.txt. + /* -I<regex> */ + #if 0 // unused by Vim + regex_t **ignore_regex; + size_t ignore_regex_nr; +#endif + + /* See Documentation/diff-options.txt. */ char **anchors; size_t anchors_nr; } xpparam_t; typedef struct s_xdemitcb { void *priv; - int (*outf)(void *, mmbuffer_t *, int); + int (*out_hunk)(void *, + long old_begin, long old_nr, + long new_begin, long new_nr, + const char *func, long funclen); + int (*out_line)(void *, mmbuffer_t *, int); } xdemitcb_t; typedef long (*find_func_t)(const char *line, long line_len, char *buffer, long buffer_size, void *priv); @@ -108,7 +119,7 @@ typedef struct s_bdiffparam { long bsize; } bdiffparam_t; -#include "../memory.h" +#include "../nvim/memory.h" #define xdl_malloc(x) xmalloc((x)) #define xdl_free(ptr) xfree(ptr) @@ -126,9 +137,9 @@ typedef struct s_xmparam { int level; int favor; int style; - const char *ancestor; // label for orig - const char *file1; // label for mf1 - const char *file2; // label for mf2 + const char *ancestor; /* label for orig */ + const char *file1; /* label for mf1 */ + const char *file2; /* label for mf2 */ } xmparam_t; #define DEFAULT_CONFLICT_MARKER_SIZE 7 @@ -138,6 +149,6 @@ int xdl_merge(mmfile_t *orig, mmfile_t *mf1, mmfile_t *mf2, #ifdef __cplusplus } -#endif // #ifdef __cplusplus +#endif /* #ifdef __cplusplus */ -#endif // #if !defined(XDIFF_H) +#endif /* #if !defined(XDIFF_H) */ diff --git a/src/nvim/xdiff/xdiffi.c b/src/xdiff/xdiffi.c index 3806903986..cfcbb5d982 100644 --- a/src/nvim/xdiff/xdiffi.c +++ b/src/xdiff/xdiffi.c @@ -38,9 +38,9 @@ typedef struct s_xdpsplit { * Basically considers a "box" (off1, off2, lim1, lim2) and scan from both * the forward diagonal starting from (off1, off2) and the backward diagonal * starting from (lim1, lim2). If the K values on the same diagonal crosses - * returns the furthest point of reach. We might end up having to expensive - * cases using this algorithm is full, so a little bit of heuristic is needed - * to cut the search and to return a suboptimal point. + * returns the furthest point of reach. We might encounter expensive edge cases + * using this algorithm, so a little bit of heuristic is needed to cut the + * search and to return a suboptimal point. */ static long xdl_split(unsigned long const *ha1, long off1, long lim1, unsigned long const *ha2, long off2, long lim2, @@ -63,11 +63,13 @@ static long xdl_split(unsigned long const *ha1, long off1, long lim1, int got_snake = 0; /* - * We need to extent the diagonal "domain" by one. If the next + * We need to extend the diagonal "domain" by one. If the next * values exits the box boundaries we need to change it in the - * opposite direction because (max - min) must be a power of two. + * opposite direction because (max - min) must be a power of + * two. + * * Also we initialize the external K value to -1 so that we can - * avoid extra conditions check inside the core loop. + * avoid extra conditions in the check inside the core loop. */ if (fmin > dmin) kvdf[--fmin - 1] = -1; @@ -98,11 +100,13 @@ static long xdl_split(unsigned long const *ha1, long off1, long lim1, } /* - * We need to extent the diagonal "domain" by one. If the next + * We need to extend the diagonal "domain" by one. If the next * values exits the box boundaries we need to change it in the - * opposite direction because (max - min) must be a power of two. + * opposite direction because (max - min) must be a power of + * two. + * * Also we initialize the external K value to -1 so that we can - * avoid extra conditions check inside the core loop. + * avoid extra conditions in the check inside the core loop. */ if (bmin > dmin) kvdb[--bmin - 1] = XDL_LINE_MAX; @@ -138,7 +142,7 @@ static long xdl_split(unsigned long const *ha1, long off1, long lim1, /* * If the edit cost is above the heuristic trigger and if * we got a good snake, we sample current diagonals to see - * if some of the, have reached an "interesting" path. Our + * if some of them have reached an "interesting" path. Our * measure is a function of the distance from the diagonal * corner (i1 + i2) penalized with the distance from the * mid diagonal itself. If this value is above the current @@ -196,8 +200,9 @@ static long xdl_split(unsigned long const *ha1, long off1, long lim1, } /* - * Enough is enough. We spent too much time here and now we collect - * the furthest reaching path using the (i1 + i2) measure. + * Enough is enough. We spent too much time here and now we + * collect the furthest reaching path using the (i1 + i2) + * measure. */ if (ec >= xenv->mxcost) { long fbest, fbest1, bbest, bbest1; @@ -244,9 +249,9 @@ static long xdl_split(unsigned long const *ha1, long off1, long lim1, /* - * Rule: "Divide et Impera". Recursively split the box in sub-boxes by calling - * the box splitting function. Note that the real job (marking changed lines) - * is done in the two boundary reaching checks. + * Rule: "Divide et Impera" (divide & conquer). Recursively split the box in + * sub-boxes by calling the box splitting function. Note that the real job + * (marking changed lines) is done in the two boundary reaching checks. */ int xdl_recs_cmp(diffdata_t *dd1, long off1, long lim1, diffdata_t *dd2, long off2, long lim2, @@ -323,7 +328,9 @@ int xdl_do_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, } /* - * Allocate and setup K vectors to be used by the differential algorithm. + * Allocate and setup K vectors to be used by the differential + * algorithm. + * * One is to store the forward path and one to store the backward path. */ ndiags = xe->xdf1.nreff + xe->xdf2.nreff + 3; @@ -418,13 +425,13 @@ static int xget_indent(xrecord_t *rec) ret += 1; else if (c == '\t') ret += 8 - ret % 8; - // ignore other whitespace characters + /* ignore other whitespace characters */ if (ret >= MAX_INDENT) return MAX_INDENT; } - // The line contains only whitespace. + /* The line contains only whitespace. */ return -1; } @@ -435,7 +442,7 @@ static int xget_indent(xrecord_t *rec) */ #define MAX_BLANKS 20 -// Characteristics measured about a hypothetical split position. +/* Characteristics measured about a hypothetical split position. */ struct split_measurement { /* * Is the split at the end of the file (aside from any blank lines)? @@ -443,8 +450,8 @@ struct split_measurement { int end_of_file; /* - * How much is the line immediately following the split indented (or -1 if - * the line is blank): + * How much is the line immediately following the split indented (or -1 + * if the line is blank): */ int indent; @@ -454,8 +461,8 @@ struct split_measurement { int pre_blank; /* - * How much is the nearest non-blank line above the split indented (or -1 - * if there is no such line)? + * How much is the nearest non-blank line above the split indented (or + * -1 if there is no such line)? */ int pre_indent; @@ -472,10 +479,10 @@ struct split_measurement { }; struct split_score { - // The effective indent of this split (smaller is preferred). + /* The effective indent of this split (smaller is preferred). */ int effective_indent; - // Penalty for this split (smaller is preferred). + /* Penalty for this split (smaller is preferred). */ int penalty; }; @@ -534,16 +541,16 @@ static void measure_split(const xdfile_t *xdf, long split, * integer math. */ -// Penalty if there are no non-blank lines before the split +/* Penalty if there are no non-blank lines before the split */ #define START_OF_FILE_PENALTY 1 -// Penalty if there are no non-blank lines after the split +/* Penalty if there are no non-blank lines after the split */ #define END_OF_FILE_PENALTY 21 -// Multiplier for the number of blank lines around the split +/* Multiplier for the number of blank lines around the split */ #define TOTAL_BLANK_WEIGHT (-30) -// Multiplier for the number of blank lines after the split +/* Multiplier for the number of blank lines after the split */ #define POST_BLANK_WEIGHT 6 /* @@ -581,13 +588,13 @@ static void measure_split(const xdfile_t *xdf, long split, /* * Compute a badness score for the hypothetical split whose measurements are - * stored in m. The weight factors were determined empirically using the tools and - * corpus described in + * stored in m. The weight factors were determined empirically using the tools + * and corpus described in * * https://github.com/mhagger/diff-slider-tools * - * Also see that project if you want to improve the weights based on, for example, - * a larger or more diverse corpus. + * Also see that project if you want to improve the weights based on, for + * example, a larger or more diverse corpus. */ static void score_add_split(const struct split_measurement *m, struct split_score *s) { @@ -610,7 +617,7 @@ static void score_add_split(const struct split_measurement *m, struct split_scor post_blank = (m->indent == -1) ? 1 + m->post_blank : 0; total_blank = m->pre_blank + post_blank; - // Penalties based on nearby blank lines: + /* Penalties based on nearby blank lines: */ s->penalty += TOTAL_BLANK_WEIGHT * total_blank; s->penalty += POST_BLANK_WEIGHT * post_blank; @@ -621,13 +628,13 @@ static void score_add_split(const struct split_measurement *m, struct split_scor any_blanks = (total_blank != 0); - // Note that the effective indent is -1 at the end of the file: + /* Note that the effective indent is -1 at the end of the file: */ s->effective_indent += indent; if (indent == -1) { - // No additional adjustments needed. + /* No additional adjustments needed. */ } else if (m->pre_indent == -1) { - // No additional adjustments needed. + /* No additional adjustments needed. */ } else if (indent > m->pre_indent) { /* * The line is indented more than its predecessor. @@ -669,7 +676,7 @@ static void score_add_split(const struct split_measurement *m, struct split_scor static int score_cmp(struct split_score *s1, struct split_score *s2) { - // -1 if s1.effective_indent < s2->effective_indent, etc. + /* -1 if s1.effective_indent < s2->effective_indent, etc. */ int cmp_indents = ((s1->effective_indent > s2->effective_indent) - (s1->effective_indent < s2->effective_indent)); @@ -809,13 +816,16 @@ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { group_init(xdfo, &go); while (1) { - // If the group is empty in the to-be-compacted file, skip it: + /* + * If the group is empty in the to-be-compacted file, skip it: + */ if (g.end == g.start) goto next; /* * Now shift the change up and then down as far as possible in - * each direction. If it bumps into any other changes, merge them. + * each direction. If it bumps into any other changes, merge + * them. */ do { groupsize = g.end - g.start; @@ -828,7 +838,7 @@ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { */ end_matching_other = -1; - // Shift the group backward as much as possible: + /* Shift the group backward as much as possible: */ while (!group_slide_up(xdf, &g, flags)) if (group_previous(xdfo, &go)) xdl_bug("group sync broken sliding up"); @@ -842,7 +852,7 @@ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { if (go.end > go.start) end_matching_other = g.end; - // Now shift the group forward as far as possible: + /* Now shift the group forward as far as possible: */ while (1) { if (group_slide_down(xdf, &g, flags)) break; @@ -858,17 +868,17 @@ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { * If the group can be shifted, then we can possibly use this * freedom to produce a more intuitive diff. * - * The group is currently shifted as far down as possible, so the - * heuristics below only have to handle upwards shifts. + * The group is currently shifted as far down as possible, so + * the heuristics below only have to handle upwards shifts. */ if (g.end == earliest_end) { - // no shifting was possible + /* no shifting was possible */ } else if (end_matching_other != -1) { /* - * Move the possibly merged group of changes back to line - * up with the last group of changes from the other file - * that it can align with. + * Move the possibly merged group of changes back to + * line up with the last group of changes from the + * other file that it can align with. */ while (go.end == go.start) { if (group_slide_up(xdf, &g, flags)) @@ -879,14 +889,15 @@ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { } else if (flags & XDF_INDENT_HEURISTIC) { /* * Indent heuristic: a group of pure add/delete lines - * implies two splits, one between the end of the "before" - * context and the start of the group, and another between - * the end of the group and the beginning of the "after" - * context. Some splits are aesthetically better and some - * are worse. We compute a badness "score" for each split, - * and add the scores for the two splits to define a - * "score" for each position that the group can be shifted - * to. Then we pick the shift with the lowest score. + * implies two splits, one between the end of the + * "before" context and the start of the group, and + * another between the end of the group and the + * beginning of the "after" context. Some splits are + * aesthetically better and some are worse. We compute + * a badness "score" for each split, and add the scores + * for the two splits to define a "score" for each + * position that the group can be shifted to. Then we + * pick the shift with the lowest score. */ long shift, best_shift = -1; struct split_score best_score; @@ -921,7 +932,7 @@ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { } next: - // Move past the just-processed group: + /* Move past the just-processed group: */ if (group_next(xdf, &g)) break; if (group_next(xdfo, &go)) @@ -987,7 +998,7 @@ static int xdl_call_hunk_func(xdfenv_t *xe UNUSED, xdchange_t *xscr, xdemitcb_t return 0; } -static void xdl_mark_ignorable(xdchange_t *xscr, xdfenv_t *xe, long flags) +static void xdl_mark_ignorable_lines(xdchange_t *xscr, xdfenv_t *xe, long flags) { xdchange_t *xch; @@ -1008,6 +1019,48 @@ static void xdl_mark_ignorable(xdchange_t *xscr, xdfenv_t *xe, long flags) } } +#if 0 // unused by Vim +static int record_matches_regex(xrecord_t *rec, xpparam_t const *xpp) { + regmatch_t regmatch; + int i; + + for (i = 0; i < xpp->ignore_regex_nr; i++) + if (!regexec_buf(xpp->ignore_regex[i], rec->ptr, rec->size, 1, + ®match, 0)) + return 1; + + return 0; +} + +static void xdl_mark_ignorable_regex(xdchange_t *xscr, const xdfenv_t *xe, + xpparam_t const *xpp) +{ + xdchange_t *xch; + + for (xch = xscr; xch; xch = xch->next) { + xrecord_t **rec; + int ignore = 1; + long i; + + /* + * Do not override --ignore-blank-lines. + */ + if (xch->ignore) + continue; + + rec = &xe->xdf1.recs[xch->i1]; + for (i = 0; i < xch->chg1 && ignore; i++) + ignore = record_matches_regex(rec[i], xpp); + + rec = &xe->xdf2.recs[xch->i2]; + for (i = 0; i < xch->chg2 && ignore; i++) + ignore = record_matches_regex(rec[i], xpp); + + xch->ignore = ignore; + } +} +#endif + int xdl_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdemitconf_t const *xecfg, xdemitcb_t *ecb) { xdchange_t *xscr; @@ -1027,7 +1080,12 @@ int xdl_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, } if (xscr) { if (xpp->flags & XDF_IGNORE_BLANK_LINES) - xdl_mark_ignorable(xscr, &xe, xpp->flags); + xdl_mark_ignorable_lines(xscr, &xe, xpp->flags); + +#if 0 + if (xpp->ignore_regex) + xdl_mark_ignorable_regex(xscr, &xe, xpp); +#endif if (ef(&xe, xscr, ecb, xecfg) < 0) { diff --git a/src/nvim/xdiff/xdiffi.h b/src/xdiff/xdiffi.h index 467a1e85cd..8f1c7c8b04 100644 --- a/src/nvim/xdiff/xdiffi.h +++ b/src/xdiff/xdiffi.h @@ -61,4 +61,4 @@ int xdl_do_patience_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, int xdl_do_histogram_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *env); -#endif // #if !defined(XDIFFI_H) +#endif /* #if !defined(XDIFFI_H) */ diff --git a/src/nvim/xdiff/xemit.c b/src/xdiff/xemit.c index f1a45139cc..a0078f928c 100644 --- a/src/nvim/xdiff/xemit.c +++ b/src/xdiff/xemit.c @@ -31,7 +31,7 @@ static long xdl_get_rec(xdfile_t *xdf, long ri, char const **rec) { static int xdl_emit_record(xdfile_t *xdf, long ri, char const *pre, xdemitcb_t *ecb) { - long size, psize = (long)strlen(pre); + long size, psize = strlen(pre); char const *rec; size = xdl_get_rec(xdf, ri, &rec); @@ -54,9 +54,9 @@ xdchange_t *xdl_get_hunk(xdchange_t **xscr, xdemitconf_t const *xecfg) xdchange_t *xch, *xchp, *lxch; long max_common = 2 * xecfg->ctxlen + xecfg->interhunkctxlen; long max_ignorable = xecfg->ctxlen; - unsigned long ignored = 0; // number of ignored blank lines + unsigned long ignored = 0; /* number of ignored blank lines */ - // remove ignorable changes that are too far before other changes + /* remove ignorable changes that are too far before other changes */ for (xchp = *xscr; xchp && xchp->ignore; xchp = xchp->next) { xch = xchp->next; @@ -99,9 +99,9 @@ xdchange_t *xdl_get_hunk(xdchange_t **xscr, xdemitconf_t const *xecfg) static long def_ff(const char *rec, long len, char *buf, long sz, void *priv UNUSED) { if (len > 0 && - (isalpha((unsigned char)*rec) || // identifier? - *rec == '_' || // also identifier? - *rec == '$')) { // identifiers from VMS and other esoterico + (isalpha((unsigned char)*rec) || /* identifier? */ + *rec == '_' || /* also identifier? */ + *rec == '$')) { /* identifiers from VMS and other esoterico */ if (len > sz) len = sz; while (0 < len && isspace((unsigned char)rec[len - 1])) @@ -197,7 +197,7 @@ int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, if (xecfg->flags & XDL_EMIT_FUNCCONTEXT) { long fs1, i1 = xch->i1; - // Appended chunk? + /* Appended chunk? */ if (i1 >= xe->xdf1.nrec) { long i2 = xch->i2; @@ -225,8 +225,23 @@ int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, if (fs1 < 0) fs1 = 0; if (fs1 < s1) { - s2 -= s1 - fs1; + s2 = XDL_MAX(s2 - (s1 - fs1), 0); s1 = fs1; + + /* + * Did we extend context upwards into an + * ignored change? + */ + while (xchp != xch && + xchp->i1 + xchp->chg1 <= s1 && + xchp->i2 + xchp->chg2 <= s2) + xchp = xchp->next; + + /* If so, show it after all. */ + if (xchp != xch) { + xch = xchp; + goto pre_context_calculation; + } } } @@ -249,7 +264,7 @@ int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, if (fe1 < 0) fe1 = xe->xdf1.nrec; if (fe1 > e1) { - e2 += fe1 - e1; + e2 = XDL_MIN(e2 + (fe1 - e1), xe->xdf2.nrec); e1 = fe1; } @@ -281,7 +296,8 @@ int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, funclineprev = s1 - 1; } #endif - if (xdl_emit_hunk_hdr(s1 + 1, e1 - s1, s2 + 1, e2 - s2, + if (!(xecfg->flags & XDL_EMIT_NO_HUNK_HDR) && + xdl_emit_hunk_hdr(s1 + 1, e1 - s1, s2 + 1, e2 - s2, func_line.buf, func_line.len, ecb) < 0) return -1; diff --git a/src/nvim/xdiff/xemit.h b/src/xdiff/xemit.h index 3ce7e3dd50..1b9887e670 100644 --- a/src/nvim/xdiff/xemit.h +++ b/src/xdiff/xemit.h @@ -33,4 +33,4 @@ int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, -#endif // #if !defined(XEMIT_H) +#endif /* #if !defined(XEMIT_H) */ diff --git a/src/nvim/xdiff/xhistogram.c b/src/xdiff/xhistogram.c index 28cf8258e5..8598a8550d 100644 --- a/src/nvim/xdiff/xhistogram.c +++ b/src/xdiff/xhistogram.c @@ -42,8 +42,6 @@ */ #include "xinclude.h" -#include "xtypes.h" -#include "xdiff.h" #define MAX_PTR INT_MAX #define MAX_CNT INT_MAX @@ -55,8 +53,8 @@ struct histindex { struct record { unsigned int ptr, cnt; struct record *next; - } **records, // an occurrence - **line_map; // map of line to record chain + } **records, /* an occurrence */ + **line_map; /* map of line to record chain */ chastore_t rcha; unsigned int *next_ptrs; unsigned int table_bits, @@ -128,7 +126,7 @@ static int scanA(struct histindex *index, int line1, int count1) */ NEXT_PTR(index, ptr) = rec->ptr; rec->ptr = ptr; - // cap rec->cnt at MAX_CNT + /* cap rec->cnt at MAX_CNT */ rec->cnt = XDL_MIN(MAX_CNT, rec->cnt + 1); LINE_MAP(index, ptr) = rec; goto continue_scan; @@ -154,7 +152,7 @@ static int scanA(struct histindex *index, int line1, int count1) LINE_MAP(index, ptr) = rec; continue_scan: - ; // no op + ; /* no op */ } return 0; @@ -237,6 +235,8 @@ static int fall_back_to_classic_diff(xpparam_t const *xpp, xdfenv_t *env, int line1, int count1, int line2, int count2) { xpparam_t xpparam; + + memset(&xpparam, 0, sizeof(xpparam)); xpparam.flags = xpp->flags & ~XDF_DIFF_ALGORITHM_MASK; return xdl_fall_back_diff(env, &xpparam, @@ -266,7 +266,7 @@ static int find_lcs(xpparam_t const *xpp, xdfenv_t *env, index.records = NULL; index.line_map = NULL; - // in case of early xdl_cha_free() + /* in case of early xdl_cha_free() */ index.rcha.head = NULL; index.table_bits = xdl_hashbits(count1); @@ -288,7 +288,7 @@ static int find_lcs(xpparam_t const *xpp, xdfenv_t *env, goto cleanup; memset(index.next_ptrs, 0, sz); - // lines / 4 + 1 comes from xprepare.c:xdl_prepare_ctx() + /* lines / 4 + 1 comes from xprepare.c:xdl_prepare_ctx() */ if (xdl_cha_init(&index.rcha, sizeof(struct record), count1 / 4 + 1) < 0) goto cleanup; diff --git a/src/nvim/xdiff/xinclude.h b/src/xdiff/xinclude.h index 5a359d1431..a412404bfe 100644 --- a/src/nvim/xdiff/xinclude.h +++ b/src/xdiff/xinclude.h @@ -40,6 +40,7 @@ #if !defined(XINCLUDE_H) #define XINCLUDE_H +// This effectively re-verts b46054b3746271d23feab0 from git #include <ctype.h> #include <stdio.h> #include <stdlib.h> @@ -48,7 +49,10 @@ #endif #include <string.h> #include <limits.h> - +// This include comes from git, so uncomment it +#if 0 +#include "git-compat-util.h" +#endif #include "xmacros.h" #include "xdiff.h" #include "xtypes.h" @@ -58,4 +62,4 @@ #include "xemit.h" -#endif // #if !defined(XINCLUDE_H) +#endif /* #if !defined(XINCLUDE_H) */ diff --git a/src/nvim/xdiff/xmacros.h b/src/xdiff/xmacros.h index 1167ebbb05..2809a28ca9 100644 --- a/src/nvim/xdiff/xmacros.h +++ b/src/xdiff/xmacros.h @@ -51,4 +51,4 @@ do { \ } while (0) -#endif // #if !defined(XMACROS_H) +#endif /* #if !defined(XMACROS_H) */ diff --git a/src/nvim/xdiff/xpatience.c b/src/xdiff/xpatience.c index f6c84c67d8..f78c897ad8 100644 --- a/src/nvim/xdiff/xpatience.c +++ b/src/xdiff/xpatience.c @@ -20,8 +20,6 @@ * */ #include "xinclude.h" -#include "xtypes.h" -#include "xdiff.h" /* * The basic idea of patience diff is to find lines that are unique in @@ -69,7 +67,7 @@ struct hashmap { */ unsigned anchor : 1; } *entries, *first, *last; - // were common records found? + /* were common records found? */ unsigned long has_matches; mmfile_t *file1, *file2; xdfenv_t *env; @@ -78,21 +76,21 @@ struct hashmap { static int is_anchor(xpparam_t const *xpp, const char *line) { - size_t i; - for (i = 0; i < xpp->anchors_nr; i++) { + int i; + for (i = 0; i < (int)xpp->anchors_nr; i++) { if (!strncmp(line, xpp->anchors[i], strlen(xpp->anchors[i]))) return 1; } return 0; } -// The argument "pass" is 1 for the first file, 2 for the second. +/* The argument "pass" is 1 for the first file, 2 for the second. */ static void insert_record(xpparam_t const *xpp, int line, struct hashmap *map, int pass) { xrecord_t **records = pass == 1 ? map->env->xdf1.recs : map->env->xdf2.recs; - xrecord_t *record = records[line - 1], *other; + xrecord_t *record = records[line - 1]; /* * After xdl_prepare_env() (or more precisely, due to * xdl_classify_record()), the "ha" member of the records (AKA lines) @@ -106,11 +104,7 @@ static void insert_record(xpparam_t const *xpp, int line, struct hashmap *map, int index = (int)((record->ha << 1) % map->alloc); while (map->entries[index].line1) { - other = map->env->xdf1.recs[map->entries[index].line1 - 1]; - if (map->entries[index].hash != record->ha || - !xdl_recmatch(record->ptr, record->size, - other->ptr, other->size, - map->xpp->flags)) { + if (map->entries[index].hash != record->ha) { if (++index >= map->alloc) index = 0; continue; @@ -155,7 +149,7 @@ static int fill_hashmap(mmfile_t *file1, mmfile_t *file2, result->xpp = xpp; result->env = env; - // We know exactly how large we want the hash map + /* We know exactly how large we want the hash map */ result->alloc = count1 * 2; result->entries = (struct entry *) xdl_malloc(result->alloc * sizeof(struct entry)); @@ -163,11 +157,11 @@ static int fill_hashmap(mmfile_t *file1, mmfile_t *file2, return -1; memset(result->entries, 0, result->alloc * sizeof(struct entry)); - // First, fill with entries from the first file + /* First, fill with entries from the first file */ while (count1--) insert_record(xpp, line1++, result, 1); - // Then search for matches in the second file + /* Then search for matches in the second file */ while (count2--) insert_record(xpp, line2++, result, 2); @@ -185,13 +179,13 @@ static int binary_search(struct entry **sequence, int longest, while (left + 1 < right) { int middle = left + (right - left) / 2; - // by construction, no two entries can be equal + /* by construction, no two entries can be equal */ if (sequence[middle]->line2 > entry->line2) right = middle; else left = middle; } - // return the index in "sequence", _not_ the sequence length + /* return the index in "sequence", _not_ the sequence length */ return left; } @@ -206,9 +200,10 @@ static int binary_search(struct entry **sequence, int longest, */ static struct entry *find_longest_common_sequence(struct hashmap *map) { - struct entry **sequence = (struct entry **)xdl_malloc(map->nr * sizeof(struct entry *)); + struct entry **sequence = xdl_malloc(map->nr * sizeof(struct entry *)); int longest = 0, i; struct entry *entry; + /* * If not -1, this entry in sequence must never be overridden. * Therefore, overriding entries before this has no effect, so @@ -237,13 +232,13 @@ static struct entry *find_longest_common_sequence(struct hashmap *map) } } - // No common unique lines were found + /* No common unique lines were found */ if (!longest) { xdl_free(sequence); return NULL; } - // Iterate starting at the last element, adjusting the "next" members + /* Iterate starting at the last element, adjusting the "next" members */ entry = sequence[longest - 1]; entry->next = NULL; while (entry->previous) { @@ -258,8 +253,7 @@ static int match(struct hashmap *map, int line1, int line2) { xrecord_t *record1 = map->env->xdf1.recs[line1 - 1]; xrecord_t *record2 = map->env->xdf2.recs[line2 - 1]; - return xdl_recmatch(record1->ptr, record1->size, - record2->ptr, record2->size, map->xpp->flags); + return record1->ha == record2->ha; } static int patience_diff(mmfile_t *file1, mmfile_t *file2, @@ -273,7 +267,7 @@ static int walk_common_sequence(struct hashmap *map, struct entry *first, int next1, next2; for (;;) { - // Try to grow the line ranges of common lines + /* Try to grow the line ranges of common lines */ if (first) { next1 = first->line1; next2 = first->line2; @@ -292,11 +286,8 @@ static int walk_common_sequence(struct hashmap *map, struct entry *first, line2++; } - // Recurse + /* Recurse */ if (next1 > line1 || next2 > line2) { - struct hashmap submap; - - memset(&submap, 0, sizeof(submap)); if (patience_diff(map->file1, map->file2, map->xpp, map->env, line1, next1 - line1, @@ -323,6 +314,8 @@ static int fall_back_to_classic_diff(struct hashmap *map, int line1, int count1, int line2, int count2) { xpparam_t xpp; + + memset(&xpp, 0, sizeof(xpp)); xpp.flags = map->xpp->flags & ~XDF_DIFF_ALGORITHM_MASK; return xdl_fall_back_diff(map->env, &xpp, @@ -343,7 +336,7 @@ static int patience_diff(mmfile_t *file1, mmfile_t *file2, struct entry *first; int result = 0; - // trivial case: one side is empty + /* trivial case: one side is empty */ if (!count1) { while(count2--) env->xdf2.rchg[line2++ - 1] = 1; @@ -359,7 +352,7 @@ static int patience_diff(mmfile_t *file1, mmfile_t *file2, line1, count1, line2, count2)) return -1; - // are there any matching lines at all? + /* are there any matching lines at all? */ if (!map.has_matches) { while(count1--) env->xdf1.rchg[line1++ - 1] = 1; @@ -387,7 +380,7 @@ int xdl_do_patience_diff(mmfile_t *file1, mmfile_t *file2, if (xdl_prepare_env(file1, file2, xpp, env) < 0) return -1; - // environment is cleaned up in xdl_diff() + /* environment is cleaned up in xdl_diff() */ return patience_diff(file1, file2, xpp, env, 1, env->xdf1.nrec, 1, env->xdf2.nrec); } diff --git a/src/nvim/xdiff/xprepare.c b/src/xdiff/xprepare.c index abeb8fb84e..abeb8fb84e 100644 --- a/src/nvim/xdiff/xprepare.c +++ b/src/xdiff/xprepare.c diff --git a/src/nvim/xdiff/xprepare.h b/src/xdiff/xprepare.h index b67b3b25ab..947d9fc1bb 100644 --- a/src/nvim/xdiff/xprepare.h +++ b/src/xdiff/xprepare.h @@ -31,4 +31,4 @@ void xdl_free_env(xdfenv_t *xe); -#endif // #if !defined(XPREPARE_H) +#endif /* #if !defined(XPREPARE_H) */ diff --git a/src/nvim/xdiff/xtypes.h b/src/xdiff/xtypes.h index 026999c1bf..8442bd436e 100644 --- a/src/nvim/xdiff/xtypes.h +++ b/src/xdiff/xtypes.h @@ -64,4 +64,4 @@ typedef struct s_xdfenv { -#endif // #if !defined(XTYPES_H) +#endif /* #if !defined(XTYPES_H) */ diff --git a/src/nvim/xdiff/xutils.c b/src/xdiff/xutils.c index e8c7d2f884..5ef519155d 100644 --- a/src/nvim/xdiff/xutils.c +++ b/src/xdiff/xutils.c @@ -20,13 +20,9 @@ * */ -#include <limits.h> -#include <assert.h> #include "xinclude.h" - - long xdl_bogosqrt(long n) { long i; @@ -51,10 +47,10 @@ int xdl_emit_diffrec(char const *rec, long size, char const *pre, long psize, mb[1].size = size; if (size > 0 && rec[size - 1] != '\n') { mb[2].ptr = (char *) "\n\\ No newline at end of file\n"; - mb[2].size = (long)strlen(mb[2].ptr); + mb[2].size = strlen(mb[2].ptr); i++; } - if (ecb->outf(ecb->priv, mb, i) < 0) { + if (ecb->out_line(ecb->priv, mb, i) < 0) { return -1; } @@ -168,7 +164,7 @@ static int ends_with_optional_cr(const char *l, long s, long i) s--; if (s == i) return 1; - // do not ignore CR at the end of an incomplete line + /* do not ignore CR at the end of an incomplete line */ if (complete && s == i + 1 && l[i] == '\r') return 1; return 0; @@ -208,7 +204,7 @@ int xdl_recmatch(const char *l1, long s1, const char *l2, long s2, long flags) } else if (flags & XDF_IGNORE_WHITESPACE_CHANGE) { while (i1 < s1 && i2 < s2) { if (XDL_ISSPACE(l1[i1]) && XDL_ISSPACE(l2[i2])) { - // Skip matching spaces and try again + /* Skip matching spaces and try again */ while (i1 < s1 && XDL_ISSPACE(l1[i1])) i1++; while (i2 < s2 && XDL_ISSPACE(l2[i2])) @@ -224,7 +220,7 @@ int xdl_recmatch(const char *l1, long s1, const char *l2, long s2, long flags) i2++; } } else if (flags & XDF_IGNORE_CR_AT_EOL) { - // Find the first difference and see how the line ends + /* Find the first difference and see how the line ends */ while (i1 < s1 && i2 < s2 && l1[i1] == l2[i2]) { i1++; i2++; @@ -261,7 +257,7 @@ static unsigned long xdl_hash_record_with_whitespace(char const **data, for (; ptr < top && *ptr != '\n'; ptr++) { if (cr_at_eol_only) { - // do not ignore CR at the end of an incomplete line + /* do not ignore CR at the end of an incomplete line */ if (*ptr == '\r' && (ptr + 1 < top && ptr[1] == '\n')) continue; @@ -274,7 +270,7 @@ static unsigned long xdl_hash_record_with_whitespace(char const **data, ptr++; at_eol = (top <= ptr + 1 || ptr[1] == '\n'); if (flags & XDF_IGNORE_WHITESPACE) - ; // already handled + ; /* already handled */ else if (flags & XDF_IGNORE_WHITESPACE_CHANGE && !at_eol) { ha += (ha << 5); @@ -344,8 +340,9 @@ int xdl_num_out(char *out, long val) { return str - out; } -int xdl_emit_hunk_hdr(long s1, long c1, long s2, long c2, - const char *func, long funclen, xdemitcb_t *ecb) { +static int xdl_format_hunk_hdr(long s1, long c1, long s2, long c2, + const char *func, long funclen, + xdemitcb_t *ecb) { int nb = 0; mmbuffer_t mb; char buf[128]; @@ -387,9 +384,21 @@ int xdl_emit_hunk_hdr(long s1, long c1, long s2, long c2, mb.ptr = buf; mb.size = nb; - if (ecb->outf(ecb->priv, &mb, 1) < 0) + if (ecb->out_line(ecb->priv, &mb, 1) < 0) return -1; + return 0; +} +int xdl_emit_hunk_hdr(long s1, long c1, long s2, long c2, + const char *func, long funclen, + xdemitcb_t *ecb) { + if (!ecb->out_hunk) + return xdl_format_hunk_hdr(s1, c1, s2, c2, func, funclen, ecb); + if (ecb->out_hunk(ecb->priv, + c1 ? s1 : s1 - 1, c1, + c2 ? s2 : s2 - 1, c2, + func, funclen) < 0) + return -1; return 0; } diff --git a/src/nvim/xdiff/xutils.h b/src/xdiff/xutils.h index 0bebd93022..fba7bae03c 100644 --- a/src/nvim/xdiff/xutils.h +++ b/src/xdiff/xutils.h @@ -44,4 +44,4 @@ int xdl_fall_back_diff(xdfenv_t *diff_env, xpparam_t const *xpp, -#endif // #if !defined(XUTILS_H) +#endif /* #if !defined(XUTILS_H) */ |