aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.builds/freebsd.yml45
-rw-r--r--.builds/openbsd.yml49
-rw-r--r--.cirrus.yml29
-rw-r--r--.git-blame-ignore-revs3
-rw-r--r--.github/labeler.yml1
-rw-r--r--.github/scripts/reviews.js10
-rwxr-xr-x.github/workflows/env.sh2
-rw-r--r--.luacheckrc7
-rw-r--r--.mailmap5
-rw-r--r--CMakeLists.txt22
-rw-r--r--CONTRIBUTING.md21
-rw-r--r--README.md1
-rw-r--r--cmake.deps/CMakeLists.txt36
-rw-r--r--cmake.deps/cmake/BuildGettext.cmake4
-rw-r--r--cmake.deps/cmake/BuildLibiconv.cmake4
-rw-r--r--cmake.deps/cmake/BuildLibtermkey.cmake58
-rw-r--r--cmake.deps/cmake/BuildLibvterm.cmake64
-rw-r--r--cmake.deps/cmake/BuildLua.cmake57
-rw-r--r--cmake.deps/cmake/BuildLuarocks.cmake83
-rw-r--r--cmake.deps/cmake/BuildLuv.cmake96
-rw-r--r--cmake.deps/cmake/BuildMsgpack.cmake55
-rw-r--r--cmake.deps/cmake/BuildTreesitter.cmake71
-rw-r--r--cmake.deps/cmake/BuildTreesitterParsers.cmake52
-rw-r--r--cmake.deps/cmake/BuildUnibilium.cmake71
-rw-r--r--cmake.deps/cmake/TreesitterParserCMakeLists.txt8
-rw-r--r--cmake.deps/patches/libvterm-Remove-VLAs-for-MSVC.patch50
-rw-r--r--cmake/GenerateVersion.cmake10
-rw-r--r--cmake/RunTests.cmake5
-rw-r--r--cmake/Util.cmake40
-rw-r--r--runtime/CMakeLists.txt2
-rw-r--r--runtime/autoload/dist/ft.vim19
-rw-r--r--runtime/autoload/man.vim529
-rw-r--r--runtime/colors/blue.vim16
-rw-r--r--runtime/colors/darkblue.vim6
-rw-r--r--runtime/colors/delek.vim10
-rw-r--r--runtime/colors/desert.vim6
-rw-r--r--runtime/colors/elflord.vim4
-rw-r--r--runtime/colors/evening.vim39
-rw-r--r--runtime/colors/habamax.vim6
-rw-r--r--runtime/colors/industry.vim14
-rw-r--r--runtime/colors/koehler.vim4
-rw-r--r--runtime/colors/lunaperche.vim95
-rw-r--r--runtime/colors/morning.vim6
-rw-r--r--runtime/colors/murphy.vim6
-rw-r--r--runtime/colors/pablo.vim22
-rw-r--r--runtime/colors/peachpuff.vim6
-rw-r--r--runtime/colors/quiet.vim4
-rw-r--r--runtime/colors/ron.vim4
-rw-r--r--runtime/colors/shine.vim6
-rw-r--r--runtime/colors/slate.vim6
-rw-r--r--runtime/colors/torte.vim6
-rw-r--r--runtime/colors/zellner.vim6
-rw-r--r--runtime/doc/api.txt12
-rw-r--r--runtime/doc/autocmd.txt2
-rw-r--r--runtime/doc/builtin.txt81
-rw-r--r--runtime/doc/eval.txt393
-rw-r--r--runtime/doc/filetype.txt4
-rw-r--r--runtime/doc/help.txt1
-rw-r--r--runtime/doc/lsp.txt10
-rw-r--r--runtime/doc/lua.txt22
-rw-r--r--runtime/doc/options.txt15
-rw-r--r--runtime/doc/quickref.txt1
-rw-r--r--runtime/doc/tagsrch.txt8
-rw-r--r--runtime/doc/treesitter.txt134
-rw-r--r--runtime/doc/ui.txt1
-rw-r--r--runtime/doc/userfunc.txt429
-rw-r--r--runtime/doc/usr_41.txt1
-rw-r--r--runtime/doc/vim_diff.txt2
-rw-r--r--runtime/doc/windows.txt4
-rw-r--r--runtime/filetype.lua2
-rw-r--r--runtime/filetype.vim36
-rw-r--r--runtime/ftplugin/gitattributes.vim13
-rw-r--r--runtime/ftplugin/gitignore.vim13
-rw-r--r--runtime/ftplugin/jsonnet.vim17
-rw-r--r--runtime/ftplugin/lua.lua3
-rw-r--r--runtime/ftplugin/lua.vim38
-rw-r--r--runtime/ftplugin/lynx.vim29
-rw-r--r--runtime/ftplugin/man.vim4
-rw-r--r--runtime/ftplugin/sh.vim53
-rw-r--r--runtime/ftplugin/vim.vim2
-rw-r--r--runtime/ftplugin/zimbu.vim4
-rw-r--r--runtime/ftplugin/zsh.vim2
-rw-r--r--runtime/indent/json.vim3
-rw-r--r--runtime/indent/testdir/runtest.vim15
-rw-r--r--runtime/indent/testdir/vim.in7
-rw-r--r--runtime/indent/testdir/vim.ok7
-rw-r--r--runtime/indent/vim.vim44
-rw-r--r--runtime/indent/yaml.vim10
-rw-r--r--runtime/lua/man.lua601
-rw-r--r--runtime/lua/vim/_meta.lua3
-rw-r--r--runtime/lua/vim/diagnostic.lua4
-rw-r--r--runtime/lua/vim/filetype.lua26
-rw-r--r--runtime/lua/vim/filetype/detect.lua13
-rw-r--r--runtime/lua/vim/lsp.lua44
-rw-r--r--runtime/lua/vim/lsp/buf.lua82
-rw-r--r--runtime/lua/vim/lsp/rpc.lua3
-rw-r--r--runtime/lua/vim/shared.lua25
-rw-r--r--runtime/lua/vim/treesitter.lua152
-rw-r--r--runtime/lua/vim/treesitter/highlighter.lua32
-rw-r--r--runtime/lua/vim/treesitter/query.lua46
-rw-r--r--runtime/plugin/man.lua34
-rw-r--r--runtime/plugin/man.vim15
-rw-r--r--runtime/queries/c/highlights.scm2
-rw-r--r--runtime/queries/c/injections.scm3
-rw-r--r--runtime/queries/lua/highlights.scm194
-rw-r--r--runtime/queries/lua/injections.scm22
-rw-r--r--runtime/queries/vim/highlights.scm259
-rw-r--r--runtime/queries/vim/injections.scm26
-rw-r--r--runtime/syntax/gdresource.vim3
-rw-r--r--runtime/syntax/gdscript.vim3
-rw-r--r--runtime/syntax/gitattributes.vim63
-rw-r--r--runtime/syntax/gitignore.vim29
-rw-r--r--runtime/syntax/lua.vim70
-rw-r--r--runtime/syntax/sh.vim6
-rw-r--r--runtime/syntax/syntax.vim6
-rw-r--r--runtime/syntax/vim.vim2
-rw-r--r--runtime/syntax/zsh.vim163
-rwxr-xr-xsrc/clint.py7
-rwxr-xr-xsrc/nvim/CMakeLists.txt7
-rw-r--r--src/nvim/api/buffer.c6
-rw-r--r--src/nvim/api/command.c28
-rw-r--r--src/nvim/api/extmark.c65
-rw-r--r--src/nvim/api/keysets.lua10
-rw-r--r--src/nvim/api/private/converter.c9
-rw-r--r--src/nvim/api/private/helpers.c4
-rw-r--r--src/nvim/api/ui.c2
-rw-r--r--src/nvim/api/vim.c8
-rw-r--r--src/nvim/arglist.c171
-rw-r--r--src/nvim/autocmd.c8
-rw-r--r--src/nvim/buffer.c8
-rw-r--r--src/nvim/buffer_defs.h358
-rw-r--r--src/nvim/change.c16
-rw-r--r--src/nvim/charset.c54
-rw-r--r--src/nvim/cmdexpand.c163
-rw-r--r--src/nvim/cmdhist.c26
-rw-r--r--src/nvim/cmdhist.h2
-rw-r--r--src/nvim/cursor.c15
-rw-r--r--src/nvim/debugger.c2
-rw-r--r--src/nvim/decoration.c12
-rw-r--r--src/nvim/decoration.h7
-rw-r--r--src/nvim/decoration_provider.c33
-rw-r--r--src/nvim/decoration_provider.h1
-rw-r--r--src/nvim/diff.c49
-rw-r--r--src/nvim/digraph.c30
-rw-r--r--src/nvim/drawline.c63
-rw-r--r--src/nvim/drawscreen.c2
-rw-r--r--src/nvim/edit.c497
-rw-r--r--src/nvim/eval.c67
-rw-r--r--src/nvim/eval.h52
-rw-r--r--src/nvim/eval.lua1
-rw-r--r--src/nvim/eval/decode.c4
-rw-r--r--src/nvim/eval/funcs.c150
-rw-r--r--src/nvim/eval/typval.c45
-rw-r--r--src/nvim/eval/typval.h26
-rw-r--r--src/nvim/eval/userfunc.c344
-rw-r--r--src/nvim/eval/userfunc.h14
-rw-r--r--src/nvim/eval/vars.c2
-rw-r--r--src/nvim/ex_cmds.c468
-rw-r--r--src/nvim/ex_docmd.c79
-rw-r--r--src/nvim/ex_eval.c380
-rw-r--r--src/nvim/ex_getln.c234
-rw-r--r--src/nvim/ex_getln.h2
-rw-r--r--src/nvim/extmark.c3
-rw-r--r--src/nvim/file_search.c501
-rw-r--r--src/nvim/fileio.c776
-rw-r--r--src/nvim/fold.c8
-rw-r--r--src/nvim/fold.h6
-rw-r--r--src/nvim/garray.c2
-rw-r--r--src/nvim/generators/gen_options.lua2
-rw-r--r--src/nvim/getchar.c306
-rw-r--r--src/nvim/globals.h4
-rw-r--r--src/nvim/grid.c12
-rw-r--r--src/nvim/grid.h16
-rw-r--r--src/nvim/grid_defs.h2
-rw-r--r--src/nvim/hardcopy.c494
-rw-r--r--src/nvim/hardcopy.h12
-rw-r--r--src/nvim/help.c77
-rw-r--r--src/nvim/highlight_group.c19
-rw-r--r--src/nvim/if_cscope.c151
-rw-r--r--src/nvim/indent.c20
-rw-r--r--src/nvim/indent_c.c1209
-rw-r--r--src/nvim/insexpand.c228
-rw-r--r--src/nvim/keycodes.c8
-rw-r--r--src/nvim/lua/converter.c13
-rw-r--r--src/nvim/lua/converter.h8
-rw-r--r--src/nvim/lua/executor.c37
-rw-r--r--src/nvim/lua/stdlib.c8
-rw-r--r--src/nvim/lua/treesitter.c8
-rw-r--r--src/nvim/macros.h2
-rw-r--r--src/nvim/main.c61
-rw-r--r--src/nvim/mapping.c84
-rw-r--r--src/nvim/mapping.h2
-rw-r--r--src/nvim/mark.c179
-rw-r--r--src/nvim/mark_defs.h8
-rw-r--r--src/nvim/match.c32
-rw-r--r--src/nvim/mbyte.c342
-rw-r--r--src/nvim/mbyte.h10
-rw-r--r--src/nvim/memfile.c12
-rw-r--r--src/nvim/memfile_defs.h2
-rw-r--r--src/nvim/memline.c850
-rw-r--r--src/nvim/memline_defs.h2
-rw-r--r--src/nvim/memory.c36
-rw-r--r--src/nvim/menu.c152
-rw-r--r--src/nvim/message.c176
-rw-r--r--src/nvim/message.h10
-rw-r--r--src/nvim/mouse.c2
-rw-r--r--src/nvim/move.c443
-rw-r--r--src/nvim/normal.c88
-rw-r--r--src/nvim/normal.h8
-rw-r--r--src/nvim/ops.c333
-rw-r--r--src/nvim/ops.h16
-rw-r--r--src/nvim/option.c379
-rw-r--r--src/nvim/option_defs.h22
-rw-r--r--src/nvim/options.lua12
-rw-r--r--src/nvim/optionstr.c20
-rw-r--r--src/nvim/os/env.c12
-rw-r--r--src/nvim/os/input.c6
-rw-r--r--src/nvim/os/shell.c34
-rw-r--r--src/nvim/os/users.c6
-rw-r--r--src/nvim/path.c461
-rw-r--r--src/nvim/path.h4
-rw-r--r--src/nvim/plines.c9
-rw-r--r--src/nvim/plines.h1
-rw-r--r--src/nvim/popupmenu.c7
-rw-r--r--src/nvim/profile.c10
-rw-r--r--src/nvim/quickfix.c73
-rw-r--r--src/nvim/regexp.c78
-rw-r--r--src/nvim/regexp_bt.c24
-rw-r--r--src/nvim/regexp_defs.h6
-rw-r--r--src/nvim/regexp_nfa.c20
-rw-r--r--src/nvim/runtime.c6
-rw-r--r--src/nvim/screen.c2
-rw-r--r--src/nvim/search.c450
-rw-r--r--src/nvim/shada.c22
-rw-r--r--src/nvim/sign.c12
-rw-r--r--src/nvim/sign_defs.h8
-rw-r--r--src/nvim/spell.c212
-rw-r--r--src/nvim/spell_defs.h6
-rw-r--r--src/nvim/spellfile.c243
-rw-r--r--src/nvim/spellsuggest.c157
-rw-r--r--src/nvim/state.c2
-rw-r--r--src/nvim/statusline.c22
-rw-r--r--src/nvim/strings.c124
-rw-r--r--src/nvim/syntax.c1133
-rw-r--r--src/nvim/tag.c542
-rw-r--r--src/nvim/tag.h2
-rw-r--r--src/nvim/terminal.c42
-rw-r--r--src/nvim/testdir/test_cmdline.vim12
-rw-r--r--src/nvim/testdir/test_cursor_func.vim22
-rw-r--r--src/nvim/testdir/test_eval_stuff.vim40
-rw-r--r--src/nvim/testdir/test_filetype.vim60
-rw-r--r--src/nvim/testdir/test_fnamemodify.vim6
-rw-r--r--src/nvim/testdir/test_functions.vim21
-rw-r--r--src/nvim/testdir/test_listdict.vim7
-rw-r--r--src/nvim/testdir/test_profile.vim6
-rw-r--r--src/nvim/testdir/test_window_cmd.vim15
-rw-r--r--src/nvim/testing.c2
-rw-r--r--src/nvim/textformat.c42
-rw-r--r--src/nvim/textobject.c8
-rw-r--r--src/nvim/tui/input.c7
-rw-r--r--src/nvim/tui/tui.c27
-rw-r--r--src/nvim/ui_compositor.c2
-rw-r--r--src/nvim/undo.c26
-rw-r--r--src/nvim/undo_defs.h4
-rw-r--r--src/nvim/usercmd.c4
-rw-r--r--src/nvim/vim.h19
-rw-r--r--src/nvim/viml/parser/expressions.c9
-rw-r--r--src/nvim/window.c620
-rw-r--r--src/nvim/window.h10
-rw-r--r--test/functional/api/command_spec.lua41
-rw-r--r--test/functional/api/server_notifications_spec.lua4
-rw-r--r--test/functional/api/vim_spec.lua28
-rw-r--r--test/functional/core/fileio_spec.lua7
-rw-r--r--test/functional/ex_cmds/source_spec.lua4
-rw-r--r--test/functional/ex_cmds/write_spec.lua7
-rw-r--r--test/functional/helpers.lua10
-rw-r--r--test/functional/lua/diagnostic_spec.lua9
-rw-r--r--test/functional/lua/vim_spec.lua18
-rw-r--r--test/functional/plugin/lsp_spec.lua84
-rw-r--r--test/functional/plugin/man_spec.lua15
-rw-r--r--test/functional/terminal/altscreen_spec.lua10
-rw-r--r--test/functional/terminal/ex_terminal_spec.lua4
-rw-r--r--test/functional/terminal/tui_spec.lua52
-rw-r--r--test/functional/treesitter/highlight_spec.lua25
-rw-r--r--test/functional/treesitter/language_spec.lua12
-rw-r--r--test/functional/treesitter/node_spec.lua5
-rw-r--r--test/functional/treesitter/parser_spec.lua3
-rw-r--r--test/functional/treesitter/utils_spec.lua2
-rw-r--r--test/functional/ui/decorations_spec.lua86
-rw-r--r--test/functional/ui/mouse_spec.lua15
-rw-r--r--test/functional/ui/options_spec.lua7
-rw-r--r--test/functional/ui/popupmenu_spec.lua111
-rw-r--r--test/functional/vimscript/executable_spec.lua6
-rw-r--r--test/functional/vimscript/exepath_spec.lua6
-rw-r--r--test/helpers.lua5
-rw-r--r--test/unit/message_spec.lua2
296 files changed, 10379 insertions, 10782 deletions
diff --git a/.builds/freebsd.yml b/.builds/freebsd.yml
deleted file mode 100644
index 4be49fd153..0000000000
--- a/.builds/freebsd.yml
+++ /dev/null
@@ -1,45 +0,0 @@
-image: freebsd/latest
-
-packages:
-- cmake
-- gmake
-- ninja
-- libtool
-- automake
-- pkgconf
-- unzip
-- wget
-- gettext
-- python
-- libffi
-- gdb
-
-sources:
-- https://github.com/neovim/neovim
-
-environment:
- SOURCEHUT: 1
- LANG: en_US.UTF-8
- CMAKE_EXTRA_FLAGS: -DCI_BUILD=ON -DMIN_LOG_LEVEL=3
-
-tasks:
-- should-run: |
- if ! git -C neovim diff --name-only HEAD^! | grep -E -v "^(.github|runtime/doc/.*)" >/dev/null; then
- echo "Skipping build because only ignored files were changed"
- complete-build
- fi
-- build-deps: |
- cd neovim
- gmake deps
-- build: |
- cd neovim
- gmake CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXTRA_FLAGS="${CMAKE_EXTRA_FLAGS}" nvim
-- functionaltest: |
- cd neovim
- gmake functionaltest
-- unittest: |
- cd neovim
- gmake unittest
-- oldtest: |
- cd neovim
- gmake oldtest
diff --git a/.builds/openbsd.yml b/.builds/openbsd.yml
deleted file mode 100644
index b5799e424b..0000000000
--- a/.builds/openbsd.yml
+++ /dev/null
@@ -1,49 +0,0 @@
-# sourcehut CI: https://builds.sr.ht/~jmk/neovim
-
-image: openbsd/latest
-
-packages:
-- autoconf-2.71
-- automake-1.16.3
-- cmake
-- gettext-runtime
-- gettext-tools
-- gmake
-- libtool
-- ninja
-- unzip-6.0p14
-- gdb
-
-sources:
-- https://github.com/neovim/neovim
-
-environment:
- SOURCEHUT: 1
- LC_CTYPE: en_US.UTF-8
- CMAKE_EXTRA_FLAGS: -DCI_BUILD=ON -DMIN_LOG_LEVEL=3
-
-tasks:
-- should-run: |
- if ! git -C neovim diff --name-only HEAD^! | grep -E -v "^(.github|runtime/doc/.*)" >/dev/null; then
- echo "Skipping build because only ignored files were changed"
- complete-build
- fi
-- build-deps: |
- export AUTOCONF_VERSION=2.71
- export AUTOMAKE_VERSION=1.16
- mkdir neovim/.deps
- cd neovim/.deps
- cmake -G Ninja ../cmake.deps/
- cmake --build . --config RelWithDebInfo
-- build: |
- mkdir neovim/build
- cd neovim/build
- cmake -G Ninja $CMAKE_EXTRA_FLAGS ..
- cmake --build . --config RelWithDebInfo
- ./bin/nvim --version
-- functionaltest: |
- cd neovim/build
- cmake --build . --config RelWithDebInfo --target functionaltest
-- oldtest: |
- cd neovim
- gmake oldtest
diff --git a/.cirrus.yml b/.cirrus.yml
new file mode 100644
index 0000000000..af67170235
--- /dev/null
+++ b/.cirrus.yml
@@ -0,0 +1,29 @@
+env:
+ CIRRUS_CLONE_DEPTH: '1'
+ LANG: en_US.UTF-8
+ CMAKE_EXTRA_FLAGS: -DCI_BUILD=ON -DMIN_LOG_LEVEL=3
+
+freebsd_task:
+ name: FreeBSD
+ only_if: $BRANCH != "master"
+ freebsd_instance:
+ image_family: freebsd-13-1
+ timeout_in: 30m
+ install_script:
+ - pkg update -f
+ - pkg install -y cmake gmake ninja libtool automake pkgconf unzip wget gettext python libffi git
+ build_deps_script:
+ - gmake deps
+ build_script:
+ - gmake CMAKE_EXTRA_FLAGS="${CMAKE_EXTRA_FLAGS}" nvim
+ workaround_script:
+ # Run tests as user "cirrus" instead of root. This is required for the
+ # permission-related tests to work correctly.
+ - pw useradd cirrus -m
+ - chown -R cirrus:cirrus .
+ functionaltest_script:
+ - sudo -u cirrus gmake functionaltest
+ unittest_script:
+ - sudo -u cirrus gmake unittest
+ oldtest_script:
+ - sudo -u cirrus gmake oldtest
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
index 23c7862b99..b9830dd2fd 100644
--- a/.git-blame-ignore-revs
+++ b/.git-blame-ignore-revs
@@ -50,6 +50,9 @@ ee031eb5256bb83e0d6add2bae6fd943a4186ffe
aefdc6783cb77f09786542c90901a9e7120bea42
aa4f9c5341f5280f16cce0630ea54b84eef717b3
0adc66171a355a12494d87ebb767d509540c7ef9
+93f24403f8cc760ff47979c596976b53a8b16358
+1ffd527c837fb2465c9659273bbe5447a1352db2
+2498e9feb025361576603a0101c86393d211e31e
# typos
d238b8f6003d34cae7f65ff7585b48a2cd9449fb
diff --git a/.github/labeler.yml b/.github/labeler.yml
index e86c7aabe8..b4f6f054cb 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -13,6 +13,7 @@
- src/nvim/lua/treesitter.*
- runtime/lua/vim/treesitter.lua
- runtime/lua/vim/treesitter/*
+ - runtime/queries/**/*
"diagnostic":
- runtime/lua/vim/diagnostic.lua
diff --git a/.github/scripts/reviews.js b/.github/scripts/reviews.js
index 6e9a829353..c76f25b7da 100644
--- a/.github/scripts/reviews.js
+++ b/.github/scripts/reviews.js
@@ -9,15 +9,16 @@ module.exports = async ({github, context}) => {
const reviewers = new Set()
if (labels.includes('api')) {
reviewers.add("bfredl")
- reviewers.add("gpanders")
reviewers.add("muniter")
}
if (labels.includes('build')) {
reviewers.add("jamessan")
+ reviewers.add("justinmk")
}
if (labels.includes('ci')) {
+ reviewers.add("dundargoc")
reviewers.add("jamessan")
}
@@ -54,17 +55,14 @@ module.exports = async ({github, context}) => {
reviewers.add("gpanders")
}
- if (labels.includes('gui')) {
- reviewers.add("glacambre")
- reviewers.add("smolck")
- }
-
if (labels.includes('lsp')) {
reviewers.add("mfussenegger")
+ reviewers.add("glepnir")
}
if (labels.includes('treesitter')) {
reviewers.add("bfredl")
+ reviewers.add("clason")
reviewers.add("vigoux")
}
diff --git a/.github/workflows/env.sh b/.github/workflows/env.sh
index 061588da1a..da70d358a9 100755
--- a/.github/workflows/env.sh
+++ b/.github/workflows/env.sh
@@ -57,7 +57,7 @@ EOF
functionaltest-lua)
BUILD_FLAGS="$BUILD_FLAGS -DPREFER_LUA=ON"
FUNCTIONALTEST=functionaltest-lua
- DEPS_CMAKE_FLAGS="$DEPS_CMAKE_FLAGS -DUSE_BUNDLED_LUAJIT=OFF -DUSE_BUNDLED_TS_PARSERS=OFF"
+ DEPS_CMAKE_FLAGS="$DEPS_CMAKE_FLAGS -DUSE_BUNDLED_LUAJIT=OFF"
;;
*)
;;
diff --git a/.luacheckrc b/.luacheckrc
index 9bbd323e84..8c1f4cf41c 100644
--- a/.luacheckrc
+++ b/.luacheckrc
@@ -28,6 +28,13 @@ read_globals = {
globals = {
"vim.g",
+ "vim.b",
+ "vim.w",
+ "vim.o",
+ "vim.bo",
+ "vim.wo",
+ "vim.go",
+ "vim.env"
}
exclude_files = {
diff --git a/.mailmap b/.mailmap
index 7e154b4644..ffef9f280b 100644
--- a/.mailmap
+++ b/.mailmap
@@ -15,6 +15,8 @@ Christian Clason <c.clason@uni-graz.at> <christian.clason@uni-due.de>
Cédric Barreteau <> <cbarrete@users.noreply.github.com>
Dan Aloni <alonid@gmail.com> <dan@kernelim.com>
Daniel Hahler <git@thequod.de> <github@thequod.de>
+dundargoc <gocdundar@gmail.com> <33953936+dundargoc@users.noreply.github.com>
+dundargoc <gocdundar@gmail.com> Dundar Goc
Eisuke Kawashima <e-kwsm@users.noreply.github.com> E Kawashima
ElPiloto <luis.r.piloto@gmail.com> Luis Piloto
Eliseo Martínez <eliseomarmol@gmail.com> Eliseo Martínez
@@ -52,6 +54,7 @@ Jurica Bradaric <jbradaric@gmail.com> <jbradaric@users.noreply.github.com>
Jurica Bradaric <jbradaric@gmail.com> <jurica.bradaric@avl.com>
KillTheMule <KillTheMule@users.noreply.github.com> <github@pipsfrank.de>
Kwon-Young Choi <kwon-young.choi@hotmail.fr> Kwon-Young
+Lewis Russell <lewis6991@gmail.com> <me@lewisr.dev>
Lucas Hoffmann <l-m-h@web.de> <lucc@posteo.de>
Lucas Hoffmann <l-m-h@web.de> <lucc@users.noreply.github.com>
Marco Hinz <mh.codebro@gmail.com> <mh.codebro+github@gmail.com>
@@ -92,7 +95,7 @@ Steven Sojka <Steven.Sojka@tdameritrade.com> <steelsojka@gmail.com>
Steven Sojka <steelsojka@gmail.com> <steelsojka@users.noreply.github.com>
TJ DeVries <devries.timothyj@gmail.com> <timothydvrs1234@gmail.com>
Thomas Fehér <thomas.feher@yahoo.de> <thomasfeher@web.de>
-Thomas Vigouroux <tomvig38@gmail.com> <39092278+vigoux@users.noreply.github.com>
+Thomas Vigouroux <thomas.vigouroux@protonmail.com> <tomvig38@gmail.com> <39092278+vigoux@users.noreply.github.com>
Utkarsh Maheshwari <UtkarshME96@gmail.com> UTkarsh Maheshwari
Utkarsh Maheshwari <utkarshme96@gmail.com> <UtkarshME96@gmail.com>
VVKot <volodymyr.kot.ua@gmail.com> Volodymyr Kot
diff --git a/CMakeLists.txt b/CMakeLists.txt
index caf9658699..d3764f4a99 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -6,12 +6,6 @@
cmake_minimum_required(VERSION 3.10)
project(nvim C)
-if(POLICY CMP0065)
- cmake_policy(SET CMP0065 NEW)
-endif()
-if(POLICY CMP0060)
- cmake_policy(SET CMP0060 NEW)
-endif()
if(POLICY CMP0075)
cmake_policy(SET CMP0075 NEW)
endif()
@@ -102,7 +96,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
# Work around some old, broken detection by CMake for knowing when to use the
# isystem flag. Apple's compilers have supported this for quite some time
# now.
- if(CMAKE_COMPILER_IS_GNUCC)
+ if(CMAKE_C_COMPILER_ID MATCHES "GNU")
set(CMAKE_INCLUDE_SYSTEM_FLAG_C "-isystem ")
endif()
endif()
@@ -127,22 +121,12 @@ endif()
message(STATUS "CMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}")
-# Build type.
-if(NOT CMAKE_BUILD_TYPE)
- message(STATUS "CMAKE_BUILD_TYPE not specified, default is 'Debug'")
- set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Choose the type of build" FORCE)
-else()
- message(STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
-endif()
+set_default_buildtype()
if(CMAKE_BUILD_TYPE MATCHES Debug)
set(DEBUG 1)
else()
set(DEBUG 0)
endif()
-# Set available build types for CMake GUIs.
-# Other build types can still be set by -DCMAKE_BUILD_TYPE=...
-set_property(CACHE CMAKE_BUILD_TYPE PROPERTY
- STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
# If not in a git repo (e.g., a tarball) these tokens define the complete
# version string, else they are combined with the result of `git describe`.
@@ -186,7 +170,7 @@ if(CMAKE_C_FLAGS_RELEASE MATCHES "-O3")
string(REPLACE "-O3" "-O2" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
endif()
-if(CMAKE_COMPILER_IS_GNUCC)
+if(CMAKE_C_COMPILER_ID MATCHES "GNU")
check_c_compiler_flag(-Og HAS_OG_FLAG)
else()
set(HAS_OG_FLAG 0)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 582d5fbdd4..b3adf13318 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -10,7 +10,7 @@ low-risk/isolated tasks:
- Try a [complexity:low] issue.
- Fix bugs found by [Clang](#clang-scan-build), [PVS](#pvs-studio) or
[Coverity](#coverity).
-- [Improve documentation][wiki-contribute-help]
+- [Improve documentation](#documenting)
- [Merge a Vim patch] (familiarity with Vim is *strongly* recommended)
Reporting problems
@@ -111,7 +111,7 @@ the VCS/git logs more valuable. The general structure of a commit message is:
### Automated builds (CI)
-Each pull request must pass the automated builds on [sourcehut] and [GitHub Actions].
+Each pull request must pass the automated builds on [Cirrus CI] and [GitHub Actions].
- CI builds are compiled with [`-Werror`][gcc-warnings], so compiler warnings
will fail the build.
@@ -125,20 +125,7 @@ Each pull request must pass the automated builds on [sourcehut] and [GitHub Acti
- The [lint](#lint) build checks modified lines _and their immediate
neighbors_, to encourage incrementally updating the legacy style to meet our
[style](#style). (See [#3174][3174] for background.)
-- CI for freebsd and openbsd runs on [sourcehut].
- - To get a backtrace on freebsd (after connecting via ssh):
- ```sh
- sudo pkg install tmux # If you want tmux.
- lldb build/bin/nvim -c nvim.core
-
- # To get a full backtrace:
- # 1. Rebuild with debug info.
- rm -rf nvim.core build
- gmake CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXTRA_FLAGS="-DCI_BUILD=ON -DMIN_LOG_LEVEL=3" nvim
- # 2. Run the failing test to generate a new core file.
- TEST_FILE=test/functional/foo.lua gmake functionaltest
- lldb build/bin/nvim -c nvim.core
- ```
+- CI for FreeBSD runs on [Cirrus CI].
### Clang scan-build
@@ -321,6 +308,7 @@ as context, use the `-W` argument as well.
[1820]: https://github.com/neovim/neovim/pull/1820
[3174]: https://github.com/neovim/neovim/issues/3174
[ASan]: http://clang.llvm.org/docs/AddressSanitizer.html
+[Cirrus CI]: https://cirrus-ci.com/github/neovim/neovim
[Clang report]: https://neovim.io/doc/reports/clang/
[GitHub Actions]: https://github.com/neovim/neovim/actions
[clangd]: https://clangd.llvm.org
@@ -345,7 +333,6 @@ as context, use the `-W` argument as well.
[pr-ready]: https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request
[review-checklist]: https://github.com/neovim/neovim/wiki/Code-review-checklist
[run-tests]: https://github.com/neovim/neovim/blob/master/test/README.md#running-tests
-[sourcehut]: https://builds.sr.ht/~jmk
[style-guide]: https://neovim.io/doc/user/dev_style.html#dev-style
[uncrustify]: http://uncrustify.sourceforge.net/
[wiki-contribute-help]: https://github.com/neovim/neovim/wiki/contribute-%3Ahelp
diff --git a/README.md b/README.md
index e3c3c12104..7be8dc77b1 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,6 @@
[Twitter](https://twitter.com/Neovim)
[![GitHub CI](https://github.com/neovim/neovim/workflows/CI/badge.svg)](https://github.com/neovim/neovim/actions?query=workflow%3ACI+branch%3Amaster+event%3Apush)
-[![Codecov coverage](https://img.shields.io/codecov/c/github/neovim/neovim.svg)](https://codecov.io/gh/neovim/neovim)
[![Coverity Scan analysis](https://scan.coverity.com/projects/2227/badge.svg)](https://scan.coverity.com/projects/2227)
[![Clang analysis](https://neovim.io/doc/reports/clang/badge.svg)](https://neovim.io/doc/reports/clang)
[![PVS-Studio analysis](https://neovim.io/doc/reports/pvs/badge.svg)](https://neovim.io/doc/reports/pvs/PVS-studio.html.d)
diff --git a/cmake.deps/CMakeLists.txt b/cmake.deps/CMakeLists.txt
index 27659b2a56..5ca610ba1f 100644
--- a/cmake.deps/CMakeLists.txt
+++ b/cmake.deps/CMakeLists.txt
@@ -2,22 +2,18 @@
cmake_minimum_required (VERSION 3.10)
project(NVIM_DEPS C)
-# Needed for: check_c_compiler_flag()
-include(CheckCCompilerFlag)
-
# Point CMake at any custom modules we may ship
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake" "${PROJECT_SOURCE_DIR}/../cmake")
+include(CheckCCompilerFlag)
+include(Util)
+
get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT isMultiConfig)
set(BUILD_TYPE_STRING -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE})
endif()
-# In Windows/MSVC CMAKE_BUILD_TYPE changes the paths/linking of the build
-# recipes (libuv, msgpack), make sure it is set
-if(NOT CMAKE_BUILD_TYPE)
- set(CMAKE_BUILD_TYPE Release)
-endif()
+set_default_buildtype()
set(DEFAULT_MAKE_CFLAGS CFLAGS+=-g)
@@ -177,12 +173,12 @@ set(UNIBILIUM_SHA256 29815283c654277ef77a3adcc8840db79ddbb20a0f0b0c8f648bd8cd49a
set(LIBTERMKEY_URL https://www.leonerd.org.uk/code/libtermkey/libtermkey-0.22.tar.gz)
set(LIBTERMKEY_SHA256 6945bd3c4aaa83da83d80a045c5563da4edd7d0374c62c0d35aec09eb3014600)
-set(LIBVTERM_URL https://www.leonerd.org.uk/code/libvterm/libvterm-0.1.4.tar.gz)
-set(LIBVTERM_SHA256 bc70349e95559c667672fc8c55b9527d9db9ada0fb80a3beda533418d782d3dd)
+set(LIBVTERM_URL https://www.leonerd.org.uk/code/libvterm/libvterm-0.3-RC1.tar.gz)
+set(LIBVTERM_SHA256 441d1c372b84a0df12525100ab06c0366260fb4f6252abd1665ee4fa571b5134)
-set(LUV_VERSION 1.44.2-0)
-set(LUV_URL https://github.com/luvit/luv/archive/1.44.2-0.tar.gz)
-set(LUV_SHA256 44ccda27035bfe683e6325a2a93f2c254be1eb76bde6efc2bd37c56a7af7b00a)
+set(LUV_VERSION 1.44.2-1)
+set(LUV_URL https://github.com/luvit/luv/archive/1.44.2-1.tar.gz)
+set(LUV_SHA256 f8c69908e17ec8ab370253d1508e23deaecfc0c4752d2efb77e427e579501104)
set(LUA_COMPAT53_URL https://github.com/keplerproject/lua-compat-5.3/archive/v0.9.tar.gz)
set(LUA_COMPAT53_SHA256 ad05540d2d96a48725bb79a1def35cf6652a4e2ec26376e2617c8ce2baa6f416)
@@ -205,11 +201,17 @@ set(GETTEXT_SHA256 66415634c6e8c3fa8b71362879ec7575e27da43da562c798a8a2f223e6e47
set(LIBICONV_URL https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.15.tar.gz)
set(LIBICONV_SHA256 ccf536620a45458d26ba83887a983b96827001e92a13847b45e4925cc8913178)
-set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.1.tar.gz)
-set(TREESITTER_C_SHA256 ffcc2ef0eded59ad1acec9aec4f9b0c7dd209fc1a85d85f8b0e81298e3dddcc2)
+set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.2.tar.gz)
+set(TREESITTER_C_SHA256 af66fde03feb0df4faf03750102a0d265b007e5d957057b6b293c13116a70af2 )
+
+set(TREESITTER_LUA_URL https://github.com/MunifTanjim/tree-sitter-lua/archive/v0.0.12.tar.gz)
+set(TREESITTER_LUA_SHA256 b6d7c6d04e9101a2e589d25f1d61668301e776c0b8defa6eae8dd86272e9e7c3)
+
+set(TREESITTER_VIM_URL https://github.com/vigoux/tree-sitter-viml/archive/v0.2.0.tar.gz)
+set(TREESITTER_VIM_SHA256 608dcc31a7948cb66ae7f45494620e2e9face1af75598205541f80d782ec4501)
-set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/1f1b1eb4501ed0a2d195d37f7de15f72aa10acd0.tar.gz)
-set(TREESITTER_SHA256 a324bdb7ff507cd5157a36b908224d60ba638f8e3363070dd51aa383c7cbd790)
+set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.7.tar.gz)
+set(TREESITTER_SHA256 b355e968ec2d0241bbd96748e00a9038f83968f85d822ecb9940cbe4c42e182e)
if(USE_BUNDLED_UNIBILIUM)
include(BuildUnibilium)
diff --git a/cmake.deps/cmake/BuildGettext.cmake b/cmake.deps/cmake/BuildGettext.cmake
index f36c00c559..d903fbc737 100644
--- a/cmake.deps/cmake/BuildGettext.cmake
+++ b/cmake.deps/cmake/BuildGettext.cmake
@@ -23,8 +23,8 @@ if(MSVC)
-DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DLIBICONV_INCLUDE_DIRS=${DEPS_INSTALL_DIR}/include
-DLIBICONV_LIBRARIES=${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}libcharset${CMAKE_STATIC_LIBRARY_SUFFIX}$<SEMICOLON>${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}libiconv${CMAKE_STATIC_LIBRARY_SUFFIX}
- BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
- INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
+ BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>
+ INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>)
else()
message(FATAL_ERROR "Trying to build gettext in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}")
endif()
diff --git a/cmake.deps/cmake/BuildLibiconv.cmake b/cmake.deps/cmake/BuildLibiconv.cmake
index 434bfd6979..29168340a1 100644
--- a/cmake.deps/cmake/BuildLibiconv.cmake
+++ b/cmake.deps/cmake/BuildLibiconv.cmake
@@ -21,8 +21,8 @@ if(MSVC)
${BUILD_TYPE_STRING}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
-DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
- BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
- INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
+ BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>
+ INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>)
else()
message(FATAL_ERROR "Trying to build libiconv in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}")
endif()
diff --git a/cmake.deps/cmake/BuildLibtermkey.cmake b/cmake.deps/cmake/BuildLibtermkey.cmake
index 66bac57d23..ee35112823 100644
--- a/cmake.deps/cmake/BuildLibtermkey.cmake
+++ b/cmake.deps/cmake/BuildLibtermkey.cmake
@@ -1,18 +1,6 @@
if(WIN32)
-ExternalProject_Add(libtermkey
- PREFIX ${DEPS_BUILD_DIR}
- URL ${LIBTERMKEY_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/libtermkey
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/libtermkey
- -DURL=${LIBTERMKEY_URL}
- -DEXPECTED_SHA256=${LIBTERMKEY_SHA256}
- -DTARGET=libtermkey
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/libtermkeyCMakeLists.txt
+ set(LIBTERMKEY_CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_SOURCE_DIR}/cmake/libtermkeyCMakeLists.txt
${DEPS_BUILD_DIR}/src/libtermkey/CMakeLists.txt
COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/libtermkey
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
@@ -24,34 +12,32 @@ ExternalProject_Add(libtermkey
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
-DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DUNIBILIUM_INCLUDE_DIRS=${DEPS_INSTALL_DIR}/include
- -DUNIBILIUM_LIBRARIES=${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}unibilium${CMAKE_STATIC_LIBRARY_SUFFIX}
- BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
- INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
+ -DUNIBILIUM_LIBRARIES=${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}unibilium${CMAKE_STATIC_LIBRARY_SUFFIX})
+ set(LIBTERMKEY_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>)
+ set(LIBTERMKEY_INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>)
else()
-find_package(PkgConfig REQUIRED)
+ find_package(PkgConfig REQUIRED)
+
+ set(LIBTERMKEY_BUILD_COMMAND "" BUILD_IN_SOURCE 1)
+ set(LIBTERMKEY_INSTALL_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER}
+ PREFIX=${DEPS_INSTALL_DIR} PKG_CONFIG_PATH=${DEPS_LIB_DIR}/pkgconfig
+ CFLAGS=-fPIC LDFLAGS+=-static ${DEFAULT_MAKE_CFLAGS} install)
+endif()
ExternalProject_Add(libtermkey
PREFIX ${DEPS_BUILD_DIR}
URL ${LIBTERMKEY_URL}
DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/libtermkey
DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/libtermkey
- -DURL=${LIBTERMKEY_URL}
- -DEXPECTED_SHA256=${LIBTERMKEY_SHA256}
- -DTARGET=libtermkey
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- CONFIGURE_COMMAND ""
- BUILD_IN_SOURCE 1
- BUILD_COMMAND ""
- INSTALL_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER}
- PREFIX=${DEPS_INSTALL_DIR}
- PKG_CONFIG_PATH=${DEPS_LIB_DIR}/pkgconfig
- CFLAGS=-fPIC
- LDFLAGS+=-static
- ${DEFAULT_MAKE_CFLAGS}
- install)
-endif()
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/libtermkey
+ -DURL=${LIBTERMKEY_URL}
+ -DEXPECTED_SHA256=${LIBTERMKEY_SHA256}
+ -DTARGET=libtermkey
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ CONFIGURE_COMMAND "${LIBTERMKEY_CONFIGURE_COMMAND}"
+ BUILD_COMMAND "${LIBTERMKEY_BUILD_COMMAND}"
+ INSTALL_COMMAND "${LIBTERMKEY_INSTALL_COMMAND}")
list(APPEND THIRD_PARTY_DEPS libtermkey)
diff --git a/cmake.deps/cmake/BuildLibvterm.cmake b/cmake.deps/cmake/BuildLibvterm.cmake
index a905733abc..8ab81e9bbe 100644
--- a/cmake.deps/cmake/BuildLibvterm.cmake
+++ b/cmake.deps/cmake/BuildLibvterm.cmake
@@ -1,43 +1,4 @@
-# BuildLibvterm(CONFIGURE_COMMAND ... BUILD_COMMAND ... INSTALL_COMMAND ...)
-# Failing to pass a command argument will result in no command being run
-function(BuildLibvterm)
- cmake_parse_arguments(_libvterm
- ""
- ""
- "PATCH_COMMAND;CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND"
- ${ARGN})
-
- if(NOT _libvterm_CONFIGURE_COMMAND AND NOT _libvterm_BUILD_COMMAND
- AND NOT _libvterm_INSTALL_COMMAND)
- message(FATAL_ERROR "Must pass at least one of CONFIGURE_COMMAND, BUILD_COMMAND, INSTALL_COMMAND")
- endif()
-
- ExternalProject_Add(libvterm
- PREFIX ${DEPS_BUILD_DIR}
- URL ${LIBVTERM_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/libvterm
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/libvterm
- -DURL=${LIBVTERM_URL}
- -DEXPECTED_SHA256=${LIBVTERM_SHA256}
- -DTARGET=libvterm
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- PATCH_COMMAND "${_libvterm_PATCH_COMMAND}"
- BUILD_IN_SOURCE 1
- CONFIGURE_COMMAND "${_libvterm_CONFIGURE_COMMAND}"
- BUILD_COMMAND "${_libvterm_BUILD_COMMAND}"
- INSTALL_COMMAND "${_libvterm_INSTALL_COMMAND}")
-endfunction()
-
if(WIN32)
- if(MSVC)
- set(LIBVTERM_PATCH_COMMAND
- ${GIT_EXECUTABLE} -C ${DEPS_BUILD_DIR}/src/libvterm init
- COMMAND ${GIT_EXECUTABLE} -C ${DEPS_BUILD_DIR}/src/libvterm apply --ignore-whitespace
- ${CMAKE_CURRENT_SOURCE_DIR}/patches/libvterm-Remove-VLAs-for-MSVC.patch)
- endif()
set(LIBVTERM_CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/cmake/LibvtermCMakeLists.txt
${DEPS_BUILD_DIR}/src/libvterm/CMakeLists.txt
@@ -49,14 +10,13 @@ if(WIN32)
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR})
-
if(MSVC)
list(APPEND LIBVTERM_CONFIGURE_COMMAND "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_COMPILER_ARG1}")
else()
list(APPEND LIBVTERM_CONFIGURE_COMMAND "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_COMPILER_ARG1} -fPIC")
endif()
- set(LIBVTERM_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE})
- set(LIBVTERM_INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
+ set(LIBVTERM_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>)
+ set(LIBVTERM_INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>)
else()
set(LIBVTERM_INSTALL_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER}
PREFIX=${DEPS_INSTALL_DIR}
@@ -66,9 +26,21 @@ else()
install)
endif()
-BuildLibvterm(PATCH_COMMAND ${LIBVTERM_PATCH_COMMAND}
- CONFIGURE_COMMAND ${LIBVTERM_CONFIGURE_COMMAND}
- BUILD_COMMAND ${LIBVTERM_BUILD_COMMAND}
- INSTALL_COMMAND ${LIBVTERM_INSTALL_COMMAND})
+ExternalProject_Add(libvterm
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${LIBVTERM_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/libvterm
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/libvterm
+ -DURL=${LIBVTERM_URL}
+ -DEXPECTED_SHA256=${LIBVTERM_SHA256}
+ -DTARGET=libvterm
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ BUILD_IN_SOURCE 1
+ CONFIGURE_COMMAND "${LIBVTERM_CONFIGURE_COMMAND}"
+ BUILD_COMMAND "${LIBVTERM_BUILD_COMMAND}"
+ INSTALL_COMMAND "${LIBVTERM_INSTALL_COMMAND}")
list(APPEND THIRD_PARTY_DEPS libvterm)
diff --git a/cmake.deps/cmake/BuildLua.cmake b/cmake.deps/cmake/BuildLua.cmake
index a40cb7dcb2..58131a4ba7 100644
--- a/cmake.deps/cmake/BuildLua.cmake
+++ b/cmake.deps/cmake/BuildLua.cmake
@@ -1,36 +1,3 @@
-# BuildLua(CONFIGURE_COMMAND ... BUILD_COMMAND ... INSTALL_COMMAND ...)
-# Reusable function to build lua, wraps ExternalProject_Add.
-# Failing to pass a command argument will result in no command being run
-function(BuildLua)
- cmake_parse_arguments(_lua
- ""
- ""
- "CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND"
- ${ARGN})
-
- if(NOT _lua_CONFIGURE_COMMAND AND NOT _lua_BUILD_COMMAND
- AND NOT _lua_INSTALL_COMMAND)
- message(FATAL_ERROR "Must pass at least one of CONFIGURE_COMMAND, BUILD_COMMAND, INSTALL_COMMAND")
- endif()
-
- ExternalProject_Add(lua
- PREFIX ${DEPS_BUILD_DIR}
- URL ${LUA_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/lua
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/lua
- -DURL=${LUA_URL}
- -DEXPECTED_SHA256=${LUA_SHA256}
- -DTARGET=lua
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- CONFIGURE_COMMAND "${_lua_CONFIGURE_COMMAND}"
- BUILD_IN_SOURCE 1
- BUILD_COMMAND "${_lua_BUILD_COMMAND}"
- INSTALL_COMMAND "${_lua_INSTALL_COMMAND}")
-endfunction()
-
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(LUA_TARGET linux)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
@@ -72,16 +39,26 @@ set(LUA_CONFIGURE_COMMAND
-e "s@\\(#define LUA_ROOT[ ]*\"\\)/usr/local@\\1${DEPS_INSTALL_DIR}@"
-i ${DEPS_BUILD_DIR}/src/lua/src/luaconf.h)
set(LUA_INSTALL_TOP_ARG "INSTALL_TOP=${DEPS_INSTALL_DIR}")
-set(LUA_BUILD_COMMAND
- ${MAKE_PRG} ${LUA_INSTALL_TOP_ARG} ${LUA_TARGET})
-set(LUA_INSTALL_COMMAND
- ${MAKE_PRG} ${LUA_INSTALL_TOP_ARG} install)
message(STATUS "Lua target is ${LUA_TARGET}")
-BuildLua(CONFIGURE_COMMAND ${LUA_CONFIGURE_COMMAND}
- BUILD_COMMAND ${LUA_BUILD_COMMAND}
- INSTALL_COMMAND ${LUA_INSTALL_COMMAND})
+ExternalProject_Add(lua
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${LUA_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/lua
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/lua
+ -DURL=${LUA_URL}
+ -DEXPECTED_SHA256=${LUA_SHA256}
+ -DTARGET=lua
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ CONFIGURE_COMMAND "${LUA_CONFIGURE_COMMAND}"
+ BUILD_IN_SOURCE 1
+ BUILD_COMMAND ${MAKE_PRG} ${LUA_INSTALL_TOP_ARG} ${LUA_TARGET}
+ INSTALL_COMMAND ${MAKE_PRG} ${LUA_INSTALL_TOP_ARG} install)
+
list(APPEND THIRD_PARTY_DEPS lua)
set(BUSTED ${DEPS_INSTALL_DIR}/bin/busted)
diff --git a/cmake.deps/cmake/BuildLuarocks.cmake b/cmake.deps/cmake/BuildLuarocks.cmake
index 73f3331176..838653e7cb 100644
--- a/cmake.deps/cmake/BuildLuarocks.cmake
+++ b/cmake.deps/cmake/BuildLuarocks.cmake
@@ -9,39 +9,6 @@
option(USE_BUNDLED_BUSTED "Use the bundled version of busted to run tests." ON)
-# BuildLuarocks(CONFIGURE_COMMAND ... BUILD_COMMAND ... INSTALL_COMMAND ...)
-# Reusable function to build luarocks, wraps ExternalProject_Add.
-# Failing to pass a command argument will result in no command being run
-function(BuildLuarocks)
- cmake_parse_arguments(_luarocks
- ""
- ""
- "CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND"
- ${ARGN})
-
- if(NOT _luarocks_CONFIGURE_COMMAND AND NOT _luarocks_BUILD_COMMAND
- AND NOT _luarocks_INSTALL_COMMAND)
- message(FATAL_ERROR "Must pass at least one of CONFIGURE_COMMAND, BUILD_COMMAND, INSTALL_COMMAND")
- endif()
-
- ExternalProject_Add(luarocks
- PREFIX ${DEPS_BUILD_DIR}
- URL ${LUAROCKS_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/luarocks
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/luarocks
- -DURL=${LUAROCKS_URL}
- -DEXPECTED_SHA256=${LUAROCKS_SHA256}
- -DTARGET=luarocks
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- BUILD_IN_SOURCE 1
- CONFIGURE_COMMAND "${_luarocks_CONFIGURE_COMMAND}"
- BUILD_COMMAND "${_luarocks_BUILD_COMMAND}"
- INSTALL_COMMAND "${_luarocks_INSTALL_COMMAND}")
-endfunction()
-
# The luarocks binary location
set(LUAROCKS_BINARY ${HOSTDEPS_BIN_DIR}/luarocks)
@@ -90,10 +57,9 @@ if(UNIX)
endif()
endif()
- BuildLuarocks(
- CONFIGURE_COMMAND ${DEPS_BUILD_DIR}/src/luarocks/configure
- --prefix=${HOSTDEPS_INSTALL_DIR} --force-config ${LUAROCKS_OPTS}
- INSTALL_COMMAND ${MAKE_PRG} -j1 bootstrap)
+ set(LUAROCKS_CONFIGURE_COMMAND ${DEPS_BUILD_DIR}/src/luarocks/configure
+ --prefix=${HOSTDEPS_INSTALL_DIR} --force-config ${LUAROCKS_OPTS})
+ set(LUAROCKS_INSTALL_COMMAND ${MAKE_PRG} -j1 bootstrap)
elseif(MSVC OR MINGW)
if(MINGW)
@@ -103,7 +69,7 @@ elseif(MSVC OR MINGW)
endif()
# Ignore USE_BUNDLED_LUAJIT - always ON for native Win32
- BuildLuarocks(INSTALL_COMMAND install.bat /FORCECONFIG /NOREG /NOADMIN /Q /F
+ set(LUAROCKS_INSTALL_COMMAND install.bat /FORCECONFIG /NOREG /NOADMIN /Q /F
/LUA ${DEPS_INSTALL_DIR}
/LIB ${DEPS_LIB_DIR}
/BIN ${DEPS_BIN_DIR}
@@ -119,6 +85,23 @@ else()
message(FATAL_ERROR "Trying to build luarocks in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}")
endif()
+ExternalProject_Add(luarocks
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${LUAROCKS_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/luarocks
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/luarocks
+ -DURL=${LUAROCKS_URL}
+ -DEXPECTED_SHA256=${LUAROCKS_SHA256}
+ -DTARGET=luarocks
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ BUILD_IN_SOURCE 1
+ CONFIGURE_COMMAND "${LUAROCKS_CONFIGURE_COMMAND}"
+ BUILD_COMMAND ""
+ INSTALL_COMMAND "${LUAROCKS_INSTALL_COMMAND}")
+
list(APPEND THIRD_PARTY_DEPS luarocks)
if(USE_BUNDLED_LUAJIT)
@@ -130,16 +113,14 @@ set(ROCKS_DIR ${HOSTDEPS_LIB_DIR}/luarocks/rocks-${LUA_VERSION})
# mpack
add_custom_command(OUTPUT ${ROCKS_DIR}/mpack
- COMMAND ${LUAROCKS_BINARY}
- ARGS build mpack 1.0.8-0 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build mpack 1.0.8-0 ${LUAROCKS_BUILDARGS}
DEPENDS luarocks)
add_custom_target(mpack DEPENDS ${ROCKS_DIR}/mpack)
list(APPEND THIRD_PARTY_DEPS mpack)
# lpeg
add_custom_command(OUTPUT ${ROCKS_DIR}/lpeg
- COMMAND ${LUAROCKS_BINARY}
- ARGS build lpeg 1.0.2-1 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build lpeg 1.0.2-1 ${LUAROCKS_BUILDARGS}
DEPENDS mpack)
add_custom_target(lpeg DEPENDS ${ROCKS_DIR}/lpeg)
list(APPEND THIRD_PARTY_DEPS lpeg)
@@ -147,8 +128,7 @@ list(APPEND THIRD_PARTY_DEPS lpeg)
if((NOT USE_BUNDLED_LUAJIT) AND USE_BUNDLED_LUA)
# luabitop
add_custom_command(OUTPUT ${ROCKS_DIR}/luabitop
- COMMAND ${LUAROCKS_BINARY}
- ARGS build luabitop 1.0.2-3 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build luabitop 1.0.2-3 ${LUAROCKS_BUILDARGS}
DEPENDS lpeg)
add_custom_target(luabitop DEPENDS ${ROCKS_DIR}/luabitop)
list(APPEND THIRD_PARTY_DEPS luabitop)
@@ -163,8 +143,7 @@ if(USE_BUNDLED_BUSTED)
# penlight
add_custom_command(OUTPUT ${ROCKS_DIR}/penlight
- COMMAND ${LUAROCKS_BINARY}
- ARGS build penlight 1.5.4-1 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build penlight 1.5.4-1 ${LUAROCKS_BUILDARGS}
DEPENDS ${PENLIGHT_DEPENDS})
add_custom_target(penlight DEPENDS ${ROCKS_DIR}/penlight)
@@ -177,15 +156,13 @@ if(USE_BUNDLED_BUSTED)
set(LUACHECK_EXE "${HOSTDEPS_BIN_DIR}/luacheck")
endif()
add_custom_command(OUTPUT ${BUSTED_EXE}
- COMMAND ${LUAROCKS_BINARY}
- ARGS build busted 2.0.0 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build busted 2.0.0 ${LUAROCKS_BUILDARGS}
DEPENDS penlight)
add_custom_target(busted DEPENDS ${BUSTED_EXE})
# luacheck
add_custom_command(OUTPUT ${LUACHECK_EXE}
- COMMAND ${LUAROCKS_BINARY}
- ARGS build luacheck 0.23.0-1 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build luacheck 0.23.0-1 ${LUAROCKS_BUILDARGS}
DEPENDS busted)
add_custom_target(luacheck DEPENDS ${LUACHECK_EXE})
@@ -195,8 +172,7 @@ if(USE_BUNDLED_BUSTED)
set(NVIM_CLIENT_DEPS luacheck luv-static lua-compat-5.3)
else()
add_custom_command(OUTPUT ${ROCKS_DIR}/luv
- COMMAND ${LUAROCKS_BINARY}
- ARGS build luv ${LUV_VERSION} ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build luv ${LUV_VERSION} ${LUAROCKS_BUILDARGS}
DEPENDS luacheck)
add_custom_target(luv DEPENDS ${ROCKS_DIR}/luv)
set(NVIM_CLIENT_DEPS luv)
@@ -204,8 +180,7 @@ if(USE_BUNDLED_BUSTED)
# nvim-client: https://github.com/neovim/lua-client
add_custom_command(OUTPUT ${ROCKS_DIR}/nvim-client
- COMMAND ${LUAROCKS_BINARY}
- ARGS build nvim-client 0.2.4-1 ${LUAROCKS_BUILDARGS}
+ COMMAND ${LUAROCKS_BINARY} build nvim-client 0.2.4-1 ${LUAROCKS_BUILDARGS}
DEPENDS ${NVIM_CLIENT_DEPS})
add_custom_target(nvim-client DEPENDS ${ROCKS_DIR}/nvim-client)
diff --git a/cmake.deps/cmake/BuildLuv.cmake b/cmake.deps/cmake/BuildLuv.cmake
index f960b24992..9aafd9239a 100644
--- a/cmake.deps/cmake/BuildLuv.cmake
+++ b/cmake.deps/cmake/BuildLuv.cmake
@@ -1,57 +1,3 @@
-# BuildLuv(PATCH_COMMAND ... CONFIGURE_COMMAND ... BUILD_COMMAND ... INSTALL_COMMAND ...)
-# Reusable function to build luv, wraps ExternalProject_Add.
-# Failing to pass a command argument will result in no command being run
-function(BuildLuv)
- cmake_parse_arguments(_luv
- ""
- ""
- "PATCH_COMMAND;CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND"
- ${ARGN})
-
- if(NOT _luv_CONFIGURE_COMMAND AND NOT _luv_BUILD_COMMAND
- AND NOT _luv_INSTALL_COMMAND)
- message(FATAL_ERROR "Must pass at least one of CONFIGURE_COMMAND, BUILD_COMMAND, INSTALL_COMMAND")
- endif()
-
- ExternalProject_Add(lua-compat-5.3
- PREFIX ${DEPS_BUILD_DIR}
- URL ${LUA_COMPAT53_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/lua-compat-5.3
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/lua-compat-5.3
- -DURL=${LUA_COMPAT53_URL}
- -DEXPECTED_SHA256=${LUA_COMPAT53_SHA256}
- -DTARGET=lua-compat-5.3
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- PATCH_COMMAND ""
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND "")
-
- ExternalProject_Add(luv-static
- PREFIX ${DEPS_BUILD_DIR}
- DEPENDS lua-compat-5.3
- URL ${LUV_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/luv
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/luv
- -DURL=${LUV_URL}
- -DEXPECTED_SHA256=${LUV_SHA256}
- -DTARGET=luv-static
- # The source is shared with BuildLuarocks (with USE_BUNDLED_LUV).
- -DSRC_DIR=${DEPS_BUILD_DIR}/src/luv
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- PATCH_COMMAND "${_luv_PATCH_COMMAND}"
- CONFIGURE_COMMAND "${_luv_CONFIGURE_COMMAND}"
- BUILD_COMMAND "${_luv_BUILD_COMMAND}"
- INSTALL_COMMAND "${_luv_INSTALL_COMMAND}"
- LIST_SEPARATOR |)
-endfunction()
-
set(LUV_SRC_DIR ${DEPS_BUILD_DIR}/src/luv)
set(LUV_INCLUDE_FLAGS
"-I${DEPS_INSTALL_DIR}/include -I${DEPS_INSTALL_DIR}/include/luajit-2.1")
@@ -110,15 +56,41 @@ else()
endif()
endif()
-set(LUV_BUILD_COMMAND
- ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE})
-set(LUV_INSTALL_COMMAND
- ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
+ExternalProject_Add(lua-compat-5.3
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${LUA_COMPAT53_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/lua-compat-5.3
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/lua-compat-5.3
+ -DURL=${LUA_COMPAT53_URL}
+ -DEXPECTED_SHA256=${LUA_COMPAT53_SHA256}
+ -DTARGET=lua-compat-5.3
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ""
+ INSTALL_COMMAND "")
-BuildLuv(PATCH_COMMAND ${LUV_PATCH_COMMAND}
- CONFIGURE_COMMAND ${LUV_CONFIGURE_COMMAND}
- BUILD_COMMAND ${LUV_BUILD_COMMAND}
- INSTALL_COMMAND ${LUV_INSTALL_COMMAND})
+ExternalProject_Add(luv-static
+ PREFIX ${DEPS_BUILD_DIR}
+ DEPENDS lua-compat-5.3
+ URL ${LUV_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/luv
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/luv
+ -DURL=${LUV_URL}
+ -DEXPECTED_SHA256=${LUV_SHA256}
+ -DTARGET=luv-static
+ # The source is shared with BuildLuarocks (with USE_BUNDLED_LUV).
+ -DSRC_DIR=${DEPS_BUILD_DIR}/src/luv
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ CONFIGURE_COMMAND "${LUV_CONFIGURE_COMMAND}"
+ BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>
+ INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>
+ LIST_SEPARATOR |)
list(APPEND THIRD_PARTY_DEPS luv-static)
if(USE_BUNDLED_LUAJIT)
diff --git a/cmake.deps/cmake/BuildMsgpack.cmake b/cmake.deps/cmake/BuildMsgpack.cmake
index ea3fa84d7b..f79117e4b1 100644
--- a/cmake.deps/cmake/BuildMsgpack.cmake
+++ b/cmake.deps/cmake/BuildMsgpack.cmake
@@ -1,36 +1,3 @@
-# BuildMsgpack(CONFIGURE_COMMAND ... BUILD_COMMAND ... INSTALL_COMMAND ...)
-# Reusable function to build msgpack, wraps ExternalProject_Add.
-# Failing to pass a command argument will result in no command being run
-function(BuildMsgpack)
- cmake_parse_arguments(_msgpack
- ""
- ""
- "CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND"
- ${ARGN})
-
- if(NOT _msgpack_CONFIGURE_COMMAND AND NOT _msgpack_BUILD_COMMAND
- AND NOT _msgpack_INSTALL_COMMAND)
- message(FATAL_ERROR "Must pass at least one of CONFIGURE_COMMAND, BUILD_COMMAND, INSTALL_COMMAND")
- endif()
-
- ExternalProject_Add(msgpack
- PREFIX ${DEPS_BUILD_DIR}
- URL ${MSGPACK_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/msgpack
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/msgpack
- -DURL=${MSGPACK_URL}
- -DEXPECTED_SHA256=${MSGPACK_SHA256}
- -DTARGET=msgpack
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- CONFIGURE_COMMAND "${_msgpack_CONFIGURE_COMMAND}"
- BUILD_COMMAND "${_msgpack_BUILD_COMMAND}"
- INSTALL_COMMAND "${_msgpack_INSTALL_COMMAND}"
- LIST_SEPARATOR |)
-endfunction()
-
set(MSGPACK_CONFIGURE_COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/msgpack
-DMSGPACK_BUILD_TESTS=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
@@ -40,9 +7,6 @@ set(MSGPACK_CONFIGURE_COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/msgpack
"-DCMAKE_C_FLAGS:STRING=${CMAKE_C_COMPILER_ARG1} -fPIC"
-DCMAKE_GENERATOR=${CMAKE_GENERATOR})
-set(MSGPACK_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE})
-set(MSGPACK_INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
-
if(MSVC)
# Same as Unix without fPIC
set(MSGPACK_CONFIGURE_COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/msgpack
@@ -58,8 +22,21 @@ if(MSVC)
-DCMAKE_GENERATOR=${CMAKE_GENERATOR})
endif()
-BuildMsgpack(CONFIGURE_COMMAND ${MSGPACK_CONFIGURE_COMMAND}
- BUILD_COMMAND ${MSGPACK_BUILD_COMMAND}
- INSTALL_COMMAND ${MSGPACK_INSTALL_COMMAND})
+ExternalProject_Add(msgpack
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${MSGPACK_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/msgpack
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/msgpack
+ -DURL=${MSGPACK_URL}
+ -DEXPECTED_SHA256=${MSGPACK_SHA256}
+ -DTARGET=msgpack
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ CONFIGURE_COMMAND "${MSGPACK_CONFIGURE_COMMAND}"
+ BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>
+ INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>
+ LIST_SEPARATOR |)
list(APPEND THIRD_PARTY_DEPS msgpack)
diff --git a/cmake.deps/cmake/BuildTreesitter.cmake b/cmake.deps/cmake/BuildTreesitter.cmake
index 6d98f6179c..fe4e9e2c93 100644
--- a/cmake.deps/cmake/BuildTreesitter.cmake
+++ b/cmake.deps/cmake/BuildTreesitter.cmake
@@ -1,42 +1,5 @@
-# BuildTreeSitter(TARGET targetname CONFIGURE_COMMAND ... BUILD_COMMAND ... INSTALL_COMMAND ...)
-function(BuildTreeSitter)
- cmake_parse_arguments(_treesitter
- "BUILD_IN_SOURCE"
- "TARGET"
- "CONFIGURE_COMMAND;BUILD_COMMAND;INSTALL_COMMAND"
- ${ARGN})
-
- if(NOT _treesitter_CONFIGURE_COMMAND AND NOT _treesitter_BUILD_COMMAND
- AND NOT _treesitter_INSTALL_COMMAND)
- message(FATAL_ERROR "Must pass at least one of CONFIGURE_COMMAND, BUILD_COMMAND, INSTALL_COMMAND")
- endif()
- if(NOT _treesitter_TARGET)
- set(_treesitter_TARGET "tree-sitter")
- endif()
-
- ExternalProject_Add(tree-sitter
- PREFIX ${DEPS_BUILD_DIR}
- URL ${TREESITTER_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/tree-sitter
- INSTALL_DIR ${DEPS_INSTALL_DIR}
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/tree-sitter
- -DURL=${TREESITTER_URL}
- -DEXPECTED_SHA256=${TREESITTER_SHA256}
- -DTARGET=tree-sitter
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- BUILD_IN_SOURCE ${_treesitter_BUILD_IN_SOURCE}
- PATCH_COMMAND ""
- CONFIGURE_COMMAND "${_treesitter_CONFIGURE_COMMAND}"
- BUILD_COMMAND "${_treesitter_BUILD_COMMAND}"
- INSTALL_COMMAND "${_treesitter_INSTALL_COMMAND}")
-endfunction()
-
if(MSVC)
- BuildTreeSitter(BUILD_IN_SOURCE
- CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
+ set(TREESITTER_CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/cmake/TreesitterCMakeLists.txt
${DEPS_BUILD_DIR}/src/tree-sitter/CMakeLists.txt
COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/tree-sitter/CMakeLists.txt
@@ -44,16 +7,32 @@ if(MSVC)
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
-DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
${BUILD_TYPE_STRING}
- -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
- BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
- INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE}
- )
+ -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR})
+ set(TREESITTER_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>)
+ set(TREESITTER_INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>)
else()
set(TS_CFLAGS "-O3 -Wall -Wextra")
- BuildTreeSitter(BUILD_IN_SOURCE
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER} CFLAGS=${TS_CFLAGS}
- INSTALL_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER} PREFIX=${DEPS_INSTALL_DIR} install)
+ set(TREESITTER_BUILD_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER} CFLAGS=${TS_CFLAGS})
+ set(TREESITTER_INSTALL_COMMAND
+ ${MAKE_PRG} CC=${DEPS_C_COMPILER} PREFIX=${DEPS_INSTALL_DIR} install)
endif()
+ExternalProject_Add(tree-sitter
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${TREESITTER_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/tree-sitter
+ INSTALL_DIR ${DEPS_INSTALL_DIR}
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/tree-sitter
+ -DURL=${TREESITTER_URL}
+ -DEXPECTED_SHA256=${TREESITTER_SHA256}
+ -DTARGET=tree-sitter
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ BUILD_IN_SOURCE 1
+ CONFIGURE_COMMAND "${TREESITTER_CONFIGURE_COMMAND}"
+ BUILD_COMMAND "${TREESITTER_BUILD_COMMAND}"
+ INSTALL_COMMAND "${TREESITTER_INSTALL_COMMAND}")
+
list(APPEND THIRD_PARTY_DEPS tree-sitter)
diff --git a/cmake.deps/cmake/BuildTreesitterParsers.cmake b/cmake.deps/cmake/BuildTreesitterParsers.cmake
index 1ff86e89b9..dd3f4eb308 100644
--- a/cmake.deps/cmake/BuildTreesitterParsers.cmake
+++ b/cmake.deps/cmake/BuildTreesitterParsers.cmake
@@ -1,29 +1,25 @@
-ExternalProject_Add(treesitter-c
-PREFIX ${DEPS_BUILD_DIR}
-URL ${TREESITTER_C_URL}
-DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/treesitter-c
-DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/treesitter-c
- -DURL=${TREESITTER_C_URL}
- -DEXPECTED_SHA256=${TREESITTER_C_SHA256}
- -DTARGET=treesitter-c
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
-PATCH_COMMAND ${CMAKE_COMMAND} -E copy
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/TreesitterParserCMakeLists.txt
- ${DEPS_BUILD_DIR}/src/treesitter-c/CMakeLists.txt
-CMAKE_ARGS
- -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
- -DCMAKE_GENERATOR=${CMAKE_GENERATOR}
- -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
- ${BUILD_TYPE_STRING}
- -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
- -DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES_ALT_SEP}
- # Pass toolchain
- -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
- -DPARSERLANG=c
+function(BuildTSParser LANG TS_URL TS_SHA256 TS_CMAKE_FILE)
+ set(NAME treesitter-${LANG})
+ ExternalProject_Add(${NAME}
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${TREESITTER_C_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/${NAME}
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/${NAME}
+ -DURL=${TS_URL}
+ -DEXPECTED_SHA256=${TS_SHA256}
+ -DTARGET=${NAME}
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ PATCH_COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${TS_CMAKE_FILE}
+ ${DEPS_BUILD_DIR}/src/${NAME}/CMakeLists.txt
+ CMAKE_ARGS
+ -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
+ -DPARSERLANG=${LANG})
+endfunction()
-BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
-INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE}
-LIST_SEPARATOR |)
+BuildTSParser(c ${TREESITTER_C_URL} ${TREESITTER_C_SHA256} TreesitterParserCMakeLists.txt)
+BuildTSParser(lua ${TREESITTER_LUA_URL} ${TREESITTER_LUA_SHA256} TreesitterParserCMakeLists.txt)
+BuildTSParser(vim ${TREESITTER_VIM_URL} ${TREESITTER_VIM_SHA256} TreesitterParserCMakeLists.txt)
diff --git a/cmake.deps/cmake/BuildUnibilium.cmake b/cmake.deps/cmake/BuildUnibilium.cmake
index fd5d68f9a8..020f01ba0b 100644
--- a/cmake.deps/cmake/BuildUnibilium.cmake
+++ b/cmake.deps/cmake/BuildUnibilium.cmake
@@ -1,48 +1,37 @@
if(WIN32)
- ExternalProject_Add(unibilium
- PREFIX ${DEPS_BUILD_DIR}
- URL ${UNIBILIUM_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/unibilium
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/unibilium
- -DURL=${UNIBILIUM_URL}
- -DEXPECTED_SHA256=${UNIBILIUM_SHA256}
- -DTARGET=unibilium
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
+ set(UNIBILIUM_CONFIGURE_COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/cmake/UnibiliumCMakeLists.txt
${DEPS_BUILD_DIR}/src/unibilium/CMakeLists.txt
- COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/unibilium
- -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
- # Pass toolchain
- -DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN}
- -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
- ${BUILD_TYPE_STRING}
- -DCMAKE_GENERATOR=${CMAKE_GENERATOR}
- BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
- INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
+ COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/unibilium
+ -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
+ # Pass toolchain
+ -DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
+ ${BUILD_TYPE_STRING}
+ -DCMAKE_GENERATOR=${CMAKE_GENERATOR})
+ set(UNIBILIUM_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config $<CONFIG>)
+ set(UNIBILIUM_INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config $<CONFIG>)
else()
- ExternalProject_Add(unibilium
- PREFIX ${DEPS_BUILD_DIR}
- URL ${UNIBILIUM_URL}
- DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/unibilium
- DOWNLOAD_COMMAND ${CMAKE_COMMAND}
- -DPREFIX=${DEPS_BUILD_DIR}
- -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/unibilium
- -DURL=${UNIBILIUM_URL}
- -DEXPECTED_SHA256=${UNIBILIUM_SHA256}
- -DTARGET=unibilium
- -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
- CONFIGURE_COMMAND ""
- BUILD_IN_SOURCE 1
- BUILD_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER}
- PREFIX=${DEPS_INSTALL_DIR}
- CFLAGS=-fPIC
- LDFLAGS+=-static
- INSTALL_COMMAND ${MAKE_PRG} PREFIX=${DEPS_INSTALL_DIR} install)
+ set(UNIBILIUM_BUILD_COMMAND ${MAKE_PRG} CC=${DEPS_C_COMPILER}
+ PREFIX=${DEPS_INSTALL_DIR} CFLAGS=-fPIC LDFLAGS+=-static
+ BUILD_IN_SOURCE 1)
+ set(UNIBILIUM_INSTALL_COMMAND ${MAKE_PRG} PREFIX=${DEPS_INSTALL_DIR} install)
endif()
+ExternalProject_Add(unibilium
+ PREFIX ${DEPS_BUILD_DIR}
+ URL ${UNIBILIUM_URL}
+ DOWNLOAD_DIR ${DEPS_DOWNLOAD_DIR}/unibilium
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND}
+ -DPREFIX=${DEPS_BUILD_DIR}
+ -DDOWNLOAD_DIR=${DEPS_DOWNLOAD_DIR}/unibilium
+ -DURL=${UNIBILIUM_URL}
+ -DEXPECTED_SHA256=${UNIBILIUM_SHA256}
+ -DTARGET=unibilium
+ -DUSE_EXISTING_SRC_DIR=${USE_EXISTING_SRC_DIR}
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadAndExtractFile.cmake
+ CONFIGURE_COMMAND "${UNIBILIUM_CONFIGURE_COMMAND}"
+ BUILD_COMMAND "${UNIBILIUM_BUILD_COMMAND}"
+ INSTALL_COMMAND "${UNIBILIUM_INSTALL_COMMAND}")
+
list(APPEND THIRD_PARTY_DEPS unibilium)
diff --git a/cmake.deps/cmake/TreesitterParserCMakeLists.txt b/cmake.deps/cmake/TreesitterParserCMakeLists.txt
index 54bc35fb8a..be07f00a37 100644
--- a/cmake.deps/cmake/TreesitterParserCMakeLists.txt
+++ b/cmake.deps/cmake/TreesitterParserCMakeLists.txt
@@ -1,10 +1,12 @@
cmake_minimum_required(VERSION 3.10)
-# some parsers have c++ scanner, problem?
-project(parser C) # CXX
+project(parser C)
+
+set(CMAKE_C_STANDARD 99)
+file(GLOB source_files src/*.c)
add_library(parser
MODULE
- src/parser.c
+ ${source_files}
)
set_target_properties(
parser
diff --git a/cmake.deps/patches/libvterm-Remove-VLAs-for-MSVC.patch b/cmake.deps/patches/libvterm-Remove-VLAs-for-MSVC.patch
deleted file mode 100644
index e999c0fa9b..0000000000
--- a/cmake.deps/patches/libvterm-Remove-VLAs-for-MSVC.patch
+++ /dev/null
@@ -1,50 +0,0 @@
-From eb386b1d82f7d07363c9133b7aa06902ccd555fe Mon Sep 17 00:00:00 2001
-Date: Tue, 27 Feb 2018 17:54:20 -0600
-Subject: [PATCH] Remove VLAs for MSVC
-
-VLAs are replaced with calls to _alloca() because MSVC does not support them.
----
- src/state.c | 7 ++++---
- 1 file changed, 4 insertions(+), 3 deletions(-)
-
-diff --git a/src/state.c b/src/state.c
-index 84299df..f9aabb3 100644
---- a/src/state.c
-+++ b/src/state.c
-@@ -1,5 +1,6 @@
- #include "vterm_internal.h"
-
-+#include <malloc.h>
- #include <stdio.h>
- #include <string.h>
-
-@@ -236,7 +237,7 @@ static int on_text(const char bytes[], size_t len, void *user)
- VTermPos oldpos = state->pos;
-
- // We'll have at most len codepoints
-- uint32_t codepoints[len];
-+ uint32_t* codepoints = _alloca(len * sizeof(uint32_t));
- int npoints = 0;
- size_t eaten = 0;
-
-@@ -313,7 +314,7 @@ static int on_text(const char bytes[], size_t len, void *user)
-
- int width = 0;
-
-- uint32_t chars[glyph_ends - glyph_starts + 1];
-+ uint32_t* chars = _alloca((glyph_ends - glyph_starts + 1) * sizeof(uint32_t));
-
- for( ; i < glyph_ends; i++) {
- chars[i - glyph_starts] = codepoints[i];
-@@ -512,7 +513,7 @@ static int settermprop_int(VTermState *state, VTermProp prop, int v)
-
- static int settermprop_string(VTermState *state, VTermProp prop, const char *str, size_t len)
- {
-- char strvalue[len+1];
-+ char* strvalue = _alloca(len+1);
- strncpy(strvalue, str, len);
- strvalue[len] = 0;
-
---
-2.16.1.windows.4
-
diff --git a/cmake/GenerateVersion.cmake b/cmake/GenerateVersion.cmake
index 6118d8cba7..a7a72fe0bb 100644
--- a/cmake/GenerateVersion.cmake
+++ b/cmake/GenerateVersion.cmake
@@ -7,15 +7,11 @@ set(NVIM_VERSION_MEDIUM
"v${NVIM_VERSION_MAJOR}.${NVIM_VERSION_MINOR}.${NVIM_VERSION_PATCH}${NVIM_VERSION_PRERELEASE}")
execute_process(
- COMMAND git describe --first-parent --dirty
+ COMMAND git describe --first-parent --dirty --always
OUTPUT_VARIABLE GIT_TAG
- ERROR_VARIABLE ERR
- RESULT_VARIABLE RES
-)
+ RESULT_VARIABLE RES)
-if(NOT RES EQUAL 0)
- message(STATUS "Git tag extraction failed:\n" " ${GIT_TAG}${ERR}" )
- # This will only be executed once since the file will get generated afterwards.
+if(RES AND NOT RES EQUAL 0)
message(STATUS "Using NVIM_VERSION_MEDIUM: ${NVIM_VERSION_MEDIUM}")
file(WRITE "${OUTPUT}" "${NVIM_VERSION_STRING}")
return()
diff --git a/cmake/RunTests.cmake b/cmake/RunTests.cmake
index e07c6dd174..86ce22de72 100644
--- a/cmake/RunTests.cmake
+++ b/cmake/RunTests.cmake
@@ -1,11 +1,6 @@
# Set LC_ALL to meet expectations of some locale-sensitive tests.
set(ENV{LC_ALL} "en_US.UTF-8")
-if(POLICY CMP0012)
- # Handle CI=true, without dev warnings.
- cmake_policy(SET CMP0012 NEW)
-endif()
-
set(ENV{VIMRUNTIME} ${WORKING_DIR}/runtime)
set(ENV{NVIM_RPLUGIN_MANIFEST} ${BUILD_DIR}/Xtest_rplugin_manifest)
set(ENV{XDG_CONFIG_HOME} ${BUILD_DIR}/Xtest_xdg/config)
diff --git a/cmake/Util.cmake b/cmake/Util.cmake
index b485f4606b..343a729305 100644
--- a/cmake/Util.cmake
+++ b/cmake/Util.cmake
@@ -143,3 +143,43 @@ function(add_glob_targets)
add_custom_target(${ARG_TARGET} DEPENDS ${touch_list})
endfunction()
+
+# Set default build type to Debug. Also limit the list of allowable build types
+# to the ones defined in variable allowableBuildTypes.
+#
+# The correct way to specify build type (for example Release) for
+# single-configuration generators (Make and Ninja) is to run
+#
+# cmake -B build -D CMAKE_BUILD_TYPE=Release
+# cmake --build build
+#
+# while for multi-configuration generators (Visual Studio, Xcode and Ninja
+# Multi-Config) is to run
+#
+# cmake -B build
+# cmake --build build --config Release
+#
+# Passing CMAKE_BUILD_TYPE for multi-config generators will now not only
+# not be used, but also generate a warning for the user.
+function(set_default_buildtype)
+ set(allowableBuildTypes Debug Release MinSizeRel RelWithDebInfo)
+
+ get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+ if(isMultiConfig)
+ set(CMAKE_CONFIGURATION_TYPES ${allowableBuildTypes} PARENT_SCOPE)
+ if(CMAKE_BUILD_TYPE)
+ message(WARNING "CMAKE_BUILD_TYPE specified which is ignored on \
+ multi-configuration generators. Defaulting to Debug build type.")
+ endif()
+ else()
+ set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "${allowableBuildTypes}")
+ if(NOT CMAKE_BUILD_TYPE)
+ message(STATUS "CMAKE_BUILD_TYPE not specified, default is 'Debug'")
+ set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build" FORCE)
+ elseif(NOT CMAKE_BUILD_TYPE IN_LIST allowableBuildTypes)
+ message(FATAL_ERROR "Invalid build type: ${CMAKE_BUILD_TYPE}")
+ else()
+ message(STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
+ endif()
+ endif()
+endfunction()
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e0a0b34d28..b42b1de54b 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -123,7 +123,7 @@ foreach(PROG ${RUNTIME_PROGRAMS})
endforeach()
globrecurse_wrapper(RUNTIME_FILES ${CMAKE_CURRENT_SOURCE_DIR}
- *.vim *.lua *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json)
+ *.vim *.lua *.scm *.dict *.py *.rb *.ps *.spl *.tutor *.tutor.json)
foreach(F ${RUNTIME_FILES})
get_filename_component(BASEDIR ${F} DIRECTORY)
diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim
index 77140d62b1..7333e5a7e7 100644
--- a/runtime/autoload/dist/ft.vim
+++ b/runtime/autoload/dist/ft.vim
@@ -468,7 +468,7 @@ endfunc
" Returns true if file content looks like LambdaProlog module
func IsLProlog()
- " skip apparent comments and blank lines, what looks like
+ " skip apparent comments and blank lines, what looks like
" LambdaProlog comment may be RAPID header
let l = nextnonblank(1)
while l > 0 && l < line('$') && getline(l) =~ '^\s*%' " LambdaProlog comment
@@ -877,6 +877,23 @@ func dist#ft#FTsig()
endif
endfunc
+" This function checks the first 100 lines of files matching "*.sil" to
+" resolve detection between Swift Intermediate Language and SILE.
+func dist#ft#FTsil()
+ for lnum in range(1, [line('$'), 100]->min())
+ let line = getline(lnum)
+ if line =~ '^\s*[\\%]'
+ setf sile
+ return
+ elseif line =~ '^\s*\S'
+ setf sil
+ return
+ endif
+ endfor
+ " no clue, default to "sil"
+ setf sil
+endfunc
+
func dist#ft#FTsys()
if exists("g:filetype_sys")
exe "setf " .. g:filetype_sys
diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim
deleted file mode 100644
index b8a73a64c9..0000000000
--- a/runtime/autoload/man.vim
+++ /dev/null
@@ -1,529 +0,0 @@
-" Maintainer: Anmol Sethi <hi@nhooyr.io>
-
-if exists('s:loaded_man')
- finish
-endif
-let s:loaded_man = 1
-
-let s:find_arg = '-w'
-let s:localfile_arg = v:true " Always use -l if possible. #6683
-
-function! man#init() abort
- try
- " Check for -l support.
- call s:get_page(s:get_path('', 'man'))
- catch /command error .*/
- let s:localfile_arg = v:false
- endtry
-endfunction
-
-function! man#open_page(count, mods, ...) abort
- if a:0 > 2
- call s:error('too many arguments')
- return
- elseif a:0 == 0
- let ref = &filetype ==# 'man' ? expand('<cWORD>') : expand('<cword>')
- if empty(ref)
- call s:error('no identifier under cursor')
- return
- endif
- elseif a:0 ==# 1
- let ref = a:1
- else
- " Combine the name and sect into a manpage reference so that all
- " verification/extraction can be kept in a single function.
- " If a:2 is a reference as well, that is fine because it is the only
- " reference that will match.
- let ref = a:2.'('.a:1.')'
- endif
- try
- let [sect, name] = s:extract_sect_and_name_ref(ref)
- if a:count >= 0
- let sect = string(a:count)
- endif
- let path = s:verify_exists(sect, name)
- let [sect, name] = s:extract_sect_and_name_path(path)
- catch
- call s:error(v:exception)
- return
- endtry
-
- let [l:buf, l:save_tfu] = [bufnr(), &tagfunc]
- try
- setlocal tagfunc=man#goto_tag
- let l:target = l:name . '(' . l:sect . ')'
- if a:mods !~# 'tab' && s:find_man()
- execute 'silent keepalt tag' l:target
- else
- execute 'silent keepalt' a:mods 'stag' l:target
- endif
- call s:set_options(v:false)
- finally
- call setbufvar(l:buf, '&tagfunc', l:save_tfu)
- endtry
-
- let b:man_sect = sect
-endfunction
-
-" Called when a man:// buffer is opened.
-function! man#read_page(ref) abort
- try
- let [sect, name] = s:extract_sect_and_name_ref(a:ref)
- let path = s:verify_exists(sect, name)
- let [sect, name] = s:extract_sect_and_name_path(path)
- let page = s:get_page(path)
- catch
- call s:error(v:exception)
- return
- endtry
- let b:man_sect = sect
- call s:put_page(page)
-endfunction
-
-" Handler for s:system() function.
-function! s:system_handler(jobid, data, event) dict abort
- if a:event is# 'stdout' || a:event is# 'stderr'
- let self[a:event] .= join(a:data, "\n")
- else
- let self.exit_code = a:data
- endif
-endfunction
-
-" Run a system command and timeout after 30 seconds.
-function! s:system(cmd, ...) abort
- let opts = {
- \ 'stdout': '',
- \ 'stderr': '',
- \ 'exit_code': 0,
- \ 'on_stdout': function('s:system_handler'),
- \ 'on_stderr': function('s:system_handler'),
- \ 'on_exit': function('s:system_handler'),
- \ }
- let jobid = jobstart(a:cmd, opts)
-
- if jobid < 1
- throw printf('command error %d: %s', jobid, join(a:cmd))
- endif
-
- let res = jobwait([jobid], 30000)
- if res[0] == -1
- try
- call jobstop(jobid)
- throw printf('command timed out: %s', join(a:cmd))
- catch /^Vim(call):E900:/
- endtry
- elseif res[0] == -2
- throw printf('command interrupted: %s', join(a:cmd))
- endif
- if opts.exit_code != 0
- throw printf("command error (%d) %s: %s", jobid, join(a:cmd), substitute(opts.stderr, '\_s\+$', '', &gdefault ? '' : 'g'))
- endif
-
- return opts.stdout
-endfunction
-
-function! s:set_options(pager) abort
- setlocal noswapfile buftype=nofile bufhidden=hide
- setlocal nomodified readonly nomodifiable
- let b:pager = a:pager
- setlocal filetype=man
-endfunction
-
-function! s:get_page(path) abort
- " Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065).
- " Soft-wrap: ftplugin/man.vim sets wrap/breakindent/….
- " Hard-wrap: driven by `man`.
- let manwidth = !get(g:, 'man_hardwrap', 1) ? 999 : (empty($MANWIDTH) ? winwidth(0) : $MANWIDTH)
- " Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db).
- " http://comments.gmane.org/gmane.editors.vim.devel/29085
- " Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces.
- let cmd = ['env', 'MANPAGER=cat', 'MANWIDTH='.manwidth, 'MAN_KEEP_FORMATTING=1', 'man']
- return s:system(cmd + (s:localfile_arg ? ['-l', a:path] : [a:path]))
-endfunction
-
-function! s:put_page(page) abort
- setlocal modifiable noreadonly noswapfile
- silent keepjumps %delete _
- silent put =a:page
- while getline(1) =~# '^\s*$'
- silent keepjumps 1delete _
- endwhile
- " XXX: nroff justifies text by filling it with whitespace. That interacts
- " badly with our use of $MANWIDTH=999. Hack around this by using a fixed
- " size for those whitespace regions.
- silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g
- 1
- lua require("man").highlight_man_page()
- call s:set_options(v:false)
-endfunction
-
-function! man#show_toc() abort
- let bufname = bufname('%')
- let info = getloclist(0, {'winid': 1})
- if !empty(info) && getwinvar(info.winid, 'qf_toc') ==# bufname
- lopen
- return
- endif
-
- let toc = []
- let lnum = 2
- let last_line = line('$') - 1
- while lnum && lnum < last_line
- let text = getline(lnum)
- if text =~# '^\%( \{3\}\)\=\S.*$'
- " if text is a section title
- call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text})
- elseif text =~# '^\s\+\%(+\|-\)\S\+'
- " if text is a flag title. we strip whitespaces and prepend two
- " spaces to have a consistent format in the loclist.
- let text = ' ' .. substitute(text, '^\s*\(.\{-}\)\s*$', '\1', '')
- call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text})
- endif
- let lnum = nextnonblank(lnum + 1)
- endwhile
-
- call setloclist(0, toc, ' ')
- call setloclist(0, [], 'a', {'title': 'Man TOC'})
- lopen
- let w:qf_toc = bufname
-endfunction
-
-" attempt to extract the name and sect out of 'name(sect)'
-" otherwise just return the largest string of valid characters in ref
-function! s:extract_sect_and_name_ref(ref) abort
- if a:ref[0] ==# '-' " try ':Man -pandoc' with this disabled.
- throw 'manpage name cannot start with ''-'''
- endif
- let ref = matchstr(a:ref, '[^()]\+([^()]\+)')
- if empty(ref)
- let name = matchstr(a:ref, '[^()]\+')
- if empty(name)
- throw 'manpage reference cannot contain only parentheses'
- endif
- return ['', s:spaces_to_underscores(name)]
- endif
- let left = split(ref, '(')
- " see ':Man 3X curses' on why tolower.
- " TODO(nhooyr) Not sure if this is portable across OSs
- " but I have not seen a single uppercase section.
- return [tolower(split(left[1], ')')[0]), s:spaces_to_underscores(left[0])]
-endfunction
-
-" replace spaces in a man page name with underscores
-" intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)';
-" while editing SQL source code, it's nice to visually select 'CREATE TABLE'
-" and hit 'K', which requires this transformation
-function! s:spaces_to_underscores(str)
- return substitute(a:str, ' ', '_', 'g')
-endfunction
-
-function! s:get_path(sect, name) abort
- " Some man implementations (OpenBSD) return all available paths from the
- " search command. Previously, this function would simply select the first one.
- "
- " However, some searches will report matches that are incorrect:
- " man -w strlen may return string.3 followed by strlen.3, and therefore
- " selecting the first would get us the wrong page. Thus, we must find the
- " first matching one.
- "
- " There's yet another special case here. Consider the following:
- " If you run man -w strlen and string.3 comes up first, this is a problem. We
- " should search for a matching named one in the results list.
- " However, if you search for man -w clock_gettime, you will *only* get
- " clock_getres.2, which is the right page. Searching the resuls for
- " clock_gettime will no longer work. In this case, we should just use the
- " first one that was found in the correct section.
- "
- " Finally, we can avoid relying on -S or -s here since they are very
- " inconsistently supported. Instead, call -w with a section and a name.
- if empty(a:sect)
- let results = split(s:system(['man', s:find_arg, a:name]))
- else
- let results = split(s:system(['man', s:find_arg, a:sect, a:name]))
- endif
-
- if empty(results)
- return ''
- endif
-
- " find any that match the specified name
- let namematches = filter(copy(results), 'fnamemodify(v:val, ":t") =~ a:name')
- let sectmatches = []
-
- if !empty(namematches) && !empty(a:sect)
- let sectmatches = filter(copy(namematches), 'fnamemodify(v:val, ":e") == a:sect')
- endif
-
- return substitute(get(sectmatches, 0, get(namematches, 0, results[0])), '\n\+$', '', '')
-endfunction
-
-" s:verify_exists attempts to find the path to a manpage
-" based on the passed section and name.
-"
-" 1. If the passed section is empty, b:man_default_sects is used.
-" 2. If manpage could not be found with the given sect and name,
-" then another attempt is made with b:man_default_sects.
-" 3. If it still could not be found, then we try again without a section.
-" 4. If still not found but $MANSECT is set, then we try again with $MANSECT
-" unset.
-"
-" This function is careful to avoid duplicating a search if a previous
-" step has already done it. i.e if we use b:man_default_sects in step 1,
-" then we don't do it again in step 2.
-function! s:verify_exists(sect, name) abort
- let sect = a:sect
-
- if empty(sect)
- " no section specified, so search with b:man_default_sects
- if exists('b:man_default_sects')
- let sects = split(b:man_default_sects, ',')
- for sec in sects
- try
- let res = s:get_path(sec, a:name)
- if !empty(res)
- return res
- endif
- catch /^command error (/
- endtry
- endfor
- endif
- else
- " try with specified section
- try
- let res = s:get_path(sect, a:name)
- if !empty(res)
- return res
- endif
- catch /^command error (/
- endtry
-
- " try again with b:man_default_sects
- if exists('b:man_default_sects')
- let sects = split(b:man_default_sects, ',')
- for sec in sects
- try
- let res = s:get_path(sec, a:name)
- if !empty(res)
- return res
- endif
- catch /^command error (/
- endtry
- endfor
- endif
- endif
-
- " if none of the above worked, we will try with no section
- try
- let res = s:get_path('', a:name)
- if !empty(res)
- return res
- endif
- catch /^command error (/
- endtry
-
- " if that still didn't work, we will check for $MANSECT and try again with it
- " unset
- if !empty($MANSECT)
- try
- let MANSECT = $MANSECT
- call setenv('MANSECT', v:null)
- let res = s:get_path('', a:name)
- if !empty(res)
- return res
- endif
- catch /^command error (/
- finally
- call setenv('MANSECT', MANSECT)
- endtry
- endif
-
- " finally, if that didn't work, there is no hope
- throw 'no manual entry for ' . a:name
-endfunction
-
-" Extracts the name/section from the 'path/name.sect', because sometimes the actual section is
-" more specific than what we provided to `man` (try `:Man 3 App::CLI`).
-" Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we
-" still want the name of the buffer to be 'printf'.
-function! s:extract_sect_and_name_path(path) abort
- let tail = fnamemodify(a:path, ':t')
- if a:path =~# '\.\%([glx]z\|bz2\|lzma\|Z\)$' " valid extensions
- let tail = fnamemodify(tail, ':r')
- endif
- let sect = matchstr(tail, '\.\zs[^.]\+$')
- let name = matchstr(tail, '^.\+\ze\.')
- return [sect, name]
-endfunction
-
-function! s:find_man() abort
- let l:win = 1
- while l:win <= winnr('$')
- let l:buf = winbufnr(l:win)
- if getbufvar(l:buf, '&filetype', '') ==# 'man'
- execute l:win.'wincmd w'
- return 1
- endif
- let l:win += 1
- endwhile
- return 0
-endfunction
-
-function! s:error(msg) abort
- redraw
- echohl ErrorMsg
- echon 'man.vim: ' a:msg
- echohl None
-endfunction
-
-" see s:extract_sect_and_name_ref on why tolower(sect)
-function! man#complete(arg_lead, cmd_line, cursor_pos) abort
- let args = split(a:cmd_line)
- let cmd_offset = index(args, 'Man')
- if cmd_offset > 0
- " Prune all arguments up to :Man itself. Otherwise modifier commands like
- " :tab, :vertical, etc. would lead to a wrong length.
- let args = args[cmd_offset:]
- endif
- let l = len(args)
- if l > 3
- return
- elseif l ==# 1
- let name = ''
- let sect = ''
- elseif a:arg_lead =~# '^[^()]\+([^()]*$'
- " cursor (|) is at ':Man printf(|' or ':Man 1 printf(|'
- " The later is is allowed because of ':Man pri<TAB>'.
- " It will offer 'priclass.d(1m)' even though section is specified as 1.
- let tmp = split(a:arg_lead, '(')
- let name = tmp[0]
- let sect = tolower(get(tmp, 1, ''))
- return s:complete(sect, '', name)
- elseif args[1] !~# '^[^()]\+$'
- " cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|'
- " or ':Man 3() pri |'
- return
- elseif l ==# 2
- if empty(a:arg_lead)
- " cursor (|) is at ':Man 1 |'
- let name = ''
- let sect = tolower(args[1])
- else
- " cursor (|) is at ':Man pri|'
- if a:arg_lead =~# '\/'
- " if the name is a path, complete files
- " TODO(nhooyr) why does this complete the last one automatically
- return glob(a:arg_lead.'*', 0, 1)
- endif
- let name = a:arg_lead
- let sect = ''
- endif
- elseif a:arg_lead !~# '^[^()]\+$'
- " cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|'
- return
- else
- " cursor (|) is at ':Man 3 pri|'
- let name = a:arg_lead
- let sect = tolower(args[1])
- endif
- return s:complete(sect, sect, name)
-endfunction
-
-function! s:get_paths(sect, name, do_fallback) abort
- " callers must try-catch this, as some `man` implementations don't support `s:find_arg`
- try
- let mandirs = join(split(s:system(['man', s:find_arg]), ':\|\n'), ',')
- let paths = globpath(mandirs, 'man?/'.a:name.'*.'.a:sect.'*', 0, 1)
- try
- " Prioritize the result from verify_exists as it obeys b:man_default_sects.
- let first = s:verify_exists(a:sect, a:name)
- let paths = filter(paths, 'v:val !=# first')
- let paths = [first] + paths
- catch
- endtry
- return paths
- catch
- if !a:do_fallback
- throw v:exception
- endif
-
- " Fallback to a single path, with the page we're trying to find.
- try
- return [s:verify_exists(a:sect, a:name)]
- catch
- return []
- endtry
- endtry
-endfunction
-
-function! s:complete(sect, psect, name) abort
- let pages = s:get_paths(a:sect, a:name, v:false)
- " We remove duplicates in case the same manpage in different languages was found.
- return uniq(sort(map(pages, 's:format_candidate(v:val, a:psect)'), 'i'))
-endfunction
-
-function! s:format_candidate(path, psect) abort
- if a:path =~# '\.\%(pdf\|in\)$' " invalid extensions
- return
- endif
- let [sect, name] = s:extract_sect_and_name_path(a:path)
- if sect ==# a:psect
- return name
- elseif sect =~# a:psect.'.\+$'
- " We include the section if the user provided section is a prefix
- " of the actual section.
- return name.'('.sect.')'
- endif
-endfunction
-
-" Called when Nvim is invoked as $MANPAGER.
-function! man#init_pager() abort
- if getline(1) =~# '^\s*$'
- silent keepjumps 1delete _
- else
- keepjumps 1
- endif
- lua require("man").highlight_man_page()
- " Guess the ref from the heading (which is usually uppercase, so we cannot
- " know the correct casing, cf. `man glDrawArraysInstanced`).
- let ref = substitute(matchstr(getline(1), '^[^)]\+)'), ' ', '_', 'g')
- try
- let b:man_sect = s:extract_sect_and_name_ref(ref)[0]
- catch
- let b:man_sect = ''
- endtry
- if -1 == match(bufname('%'), 'man:\/\/') " Avoid duplicate buffers, E95.
- execute 'silent file man://'.tolower(fnameescape(ref))
- endif
-
- call s:set_options(v:true)
-endfunction
-
-function! man#goto_tag(pattern, flags, info) abort
- let [l:sect, l:name] = s:extract_sect_and_name_ref(a:pattern)
-
- let l:paths = s:get_paths(l:sect, l:name, v:true)
- let l:structured = []
-
- for l:path in l:paths
- let [l:sect, l:name] = s:extract_sect_and_name_path(l:path)
- let l:structured += [{
- \ 'name': l:name,
- \ 'title': l:name . '(' . l:sect . ')'
- \ }]
- endfor
-
- if &cscopetag
- " return only a single entry so we work well with :cstag (#11675)
- let l:structured = l:structured[:0]
- endif
-
- return map(l:structured, {
- \ _, entry -> {
- \ 'name': entry.name,
- \ 'filename': 'man://' . entry.title,
- \ 'cmd': '1'
- \ }
- \ })
-endfunction
-
-call man#init()
diff --git a/runtime/colors/blue.vim b/runtime/colors/blue.vim
index 2fbce09b67..652046b561 100644
--- a/runtime/colors/blue.vim
+++ b/runtime/colors/blue.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Steven Vertigan <steven@vertigan.wattle.id.au>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:34 MSK
+" Last Updated: Fri 02 Sep 2022 09:41:44 MSK
" Generated by Colortemplate v2.2.0
@@ -57,7 +57,7 @@ hi ToolbarLine guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NO
hi VertSplit guifg=#008787 guibg=NONE gui=NONE cterm=NONE
hi Visual guifg=#ffffff guibg=#008787 gui=NONE cterm=NONE
hi VisualNOS guifg=#008787 guibg=#ffffff gui=NONE cterm=NONE
-hi WarningMsg guifg=#d70000 guibg=NONE gui=NONE cterm=NONE
+hi WarningMsg guifg=#d787d7 guibg=NONE gui=NONE cterm=NONE
hi WildMenu guifg=#000087 guibg=#ffd700 gui=NONE cterm=NONE
hi debugBreakpoint guifg=#00ff00 guibg=#000087 gui=reverse cterm=reverse
hi debugPC guifg=#5fffff guibg=#000087 gui=reverse cterm=reverse
@@ -120,6 +120,8 @@ hi! link Structure Type
hi! link Tag Special
hi! link Typedef Type
hi! link Terminal Normal
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi DiffAdd guifg=#ffffff guibg=#5f875f gui=NONE cterm=NONE
hi DiffChange guifg=#ffffff guibg=#5f87af gui=NONE cterm=NONE
hi DiffText guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE
@@ -165,7 +167,7 @@ if s:t_Co >= 256
hi VertSplit ctermfg=30 ctermbg=NONE cterm=NONE
hi Visual ctermfg=231 ctermbg=30 cterm=NONE
hi VisualNOS ctermfg=30 ctermbg=231 cterm=NONE
- hi WarningMsg ctermfg=160 ctermbg=NONE cterm=NONE
+ hi WarningMsg ctermfg=176 ctermbg=NONE cterm=NONE
hi WildMenu ctermfg=18 ctermbg=220 cterm=NONE
hi debugBreakpoint ctermfg=46 ctermbg=18 cterm=reverse
hi debugPC ctermfg=87 ctermbg=18 cterm=reverse
@@ -228,6 +230,8 @@ if s:t_Co >= 256
hi! link Tag Special
hi! link Typedef Type
hi! link Terminal Normal
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi DiffAdd ctermfg=231 ctermbg=65 cterm=NONE
hi DiffChange ctermfg=231 ctermbg=67 cterm=NONE
hi DiffText ctermfg=16 ctermbg=251 cterm=NONE
@@ -276,7 +280,7 @@ if s:t_Co >= 16
hi VertSplit ctermfg=darkcyan ctermbg=NONE cterm=NONE
hi Visual ctermfg=white ctermbg=darkcyan cterm=NONE
hi VisualNOS ctermfg=darkcyan ctermbg=white cterm=NONE
- hi WarningMsg ctermfg=red ctermbg=NONE cterm=NONE
+ hi WarningMsg ctermfg=magenta ctermbg=NONE cterm=NONE
hi WildMenu ctermfg=darkblue ctermbg=yellow cterm=NONE
hi debugBreakpoint ctermfg=green ctermbg=darkblue cterm=reverse
hi debugPC ctermfg=cyan ctermbg=darkblue cterm=reverse
@@ -339,6 +343,8 @@ if s:t_Co >= 16
hi! link Tag Special
hi! link Typedef Type
hi! link Terminal Normal
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi DiffAdd ctermfg=white ctermbg=darkgreen cterm=NONE
hi DiffChange ctermfg=white ctermbg=blue cterm=NONE
hi DiffText ctermfg=black ctermbg=grey cterm=NONE
@@ -449,6 +455,8 @@ if s:t_Co >= 8
hi! link Tag Special
hi! link Typedef Type
hi! link Terminal Normal
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi DiffAdd ctermfg=white ctermbg=darkgreen cterm=NONE
hi DiffChange ctermfg=white ctermbg=darkblue cterm=NONE
hi DiffText ctermfg=black ctermbg=grey cterm=NONE
diff --git a/runtime/colors/darkblue.vim b/runtime/colors/darkblue.vim
index 9e96a4638c..4ce8687415 100644
--- a/runtime/colors/darkblue.vim
+++ b/runtime/colors/darkblue.vim
@@ -4,7 +4,7 @@
" Maintainer: Original author Bohdan Vlasyuk <bohdan@vstu.edu.ua>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:35 MSK
+" Last Updated: Fri 02 Sep 2022 09:40:36 MSK
" Generated by Colortemplate v2.2.0
@@ -65,6 +65,8 @@ hi! link diffCommon WarningMsg
hi! link diffBDiffer WarningMsg
hi! link lCursor Cursor
hi! link CurSearch Search
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#c0c0c0 guibg=#000040 gui=NONE cterm=NONE
hi Conceal guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE
hi ColorColumn guifg=#c0c0c0 guibg=#8b0000 gui=NONE cterm=NONE
@@ -171,6 +173,8 @@ if s:t_Co >= 256
hi! link diffBDiffer WarningMsg
hi! link lCursor Cursor
hi! link CurSearch Search
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=252 ctermbg=17 cterm=NONE
hi Conceal ctermfg=NONE ctermbg=NONE cterm=NONE
hi ColorColumn ctermfg=252 ctermbg=88 cterm=NONE
diff --git a/runtime/colors/delek.vim b/runtime/colors/delek.vim
index e21adf2795..38f21d7156 100644
--- a/runtime/colors/delek.vim
+++ b/runtime/colors/delek.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer David Schweikert <david@schweikert.ch>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:36 MSK
+" Last Updated: Sun 04 Sep 2022 09:31:26 MSK
" Generated by Colortemplate v2.2.0
@@ -25,6 +25,8 @@ hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link ErrorMsg Error
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE
hi EndOfBuffer guifg=#bcbcbc guibg=NONE gui=NONE cterm=NONE
hi StatusLine guifg=#ffff00 guibg=#00008b gui=bold cterm=bold
@@ -57,7 +59,7 @@ hi Error guifg=#ff0000 guibg=#ffffff gui=reverse cterm=reverse
hi WarningMsg guifg=#cd00cd guibg=#ffffff gui=NONE cterm=NONE
hi MoreMsg guifg=#000000 guibg=#ffffff gui=bold cterm=bold
hi ModeMsg guifg=#000000 guibg=#ffffff gui=bold cterm=bold
-hi Question guifg=#00cd00 guibg=NONE gui=bold cterm=bold
+hi Question guifg=#008700 guibg=NONE gui=bold cterm=bold
hi Todo guifg=#000000 guibg=#ffff00 gui=NONE cterm=NONE
hi MatchParen guifg=#ffffff guibg=#ff1493 gui=NONE cterm=NONE
hi Search guifg=#ffffff guibg=#cd00cd gui=NONE cterm=NONE
@@ -97,6 +99,8 @@ if s:t_Co >= 256
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link ErrorMsg Error
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=16 ctermbg=231 cterm=NONE
hi EndOfBuffer ctermfg=250 ctermbg=NONE cterm=NONE
hi StatusLine ctermfg=226 ctermbg=18 cterm=bold
@@ -129,7 +133,7 @@ if s:t_Co >= 256
hi WarningMsg ctermfg=164 ctermbg=231 cterm=NONE
hi MoreMsg ctermfg=16 ctermbg=231 cterm=bold
hi ModeMsg ctermfg=16 ctermbg=231 cterm=bold
- hi Question ctermfg=40 ctermbg=NONE cterm=bold
+ hi Question ctermfg=28 ctermbg=NONE cterm=bold
hi Todo ctermfg=16 ctermbg=226 cterm=NONE
hi MatchParen ctermfg=231 ctermbg=198 cterm=NONE
hi Search ctermfg=231 ctermbg=164 cterm=NONE
diff --git a/runtime/colors/desert.vim b/runtime/colors/desert.vim
index 510c2ee263..4bfdf7eabd 100644
--- a/runtime/colors/desert.vim
+++ b/runtime/colors/desert.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Hans Fugal <hans@fugal.net>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:37 MSK
+" Last Updated: Fri 02 Sep 2022 09:39:21 MSK
" Generated by Colortemplate v2.2.0
@@ -25,6 +25,8 @@ hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link EndOfBuffer NonText
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#ffffff guibg=#333333 gui=NONE cterm=NONE
hi StatusLine guifg=#333333 guibg=#c2bfa5 gui=NONE cterm=NONE
hi StatusLineNC guifg=#7f7f8c guibg=#c2bfa5 gui=NONE cterm=NONE
@@ -97,6 +99,8 @@ if s:t_Co >= 256
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link EndOfBuffer NonText
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=231 ctermbg=236 cterm=NONE
hi StatusLine ctermfg=236 ctermbg=144 cterm=NONE
hi StatusLineNC ctermfg=242 ctermbg=144 cterm=NONE
diff --git a/runtime/colors/elflord.vim b/runtime/colors/elflord.vim
index dc0327b5fe..a9bdac7a1d 100644
--- a/runtime/colors/elflord.vim
+++ b/runtime/colors/elflord.vim
@@ -3,7 +3,7 @@
" Maintainer: original maintainer Ron Aaron <ron@ronware.org>
" Website: https://www.github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:37 MSK
+" Last Updated: Fri 02 Sep 2022 09:44:22 MSK
" Generated by Colortemplate v2.2.0
@@ -43,6 +43,8 @@ hi! link lCursor Cursor
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
if (has('termguicolors') && &termguicolors) || has('gui_running')
let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff']
diff --git a/runtime/colors/evening.vim b/runtime/colors/evening.vim
index 978444d79f..23ff8421e8 100644
--- a/runtime/colors/evening.vim
+++ b/runtime/colors/evening.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Steven Vertigan <steven@vertigan.wattle.id.au>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:38 MSK
+" Last Updated: Sun 04 Sep 2022 09:48:34 MSK
" Generated by Colortemplate v2.2.0
@@ -16,7 +16,7 @@ let g:colors_name = 'evening'
let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1
if (has('termguicolors') && &termguicolors) || has('gui_running')
- let g:terminal_ansi_colors = ['#000000', '#ffa500', '#2e8b57', '#ffff00', '#006faf', '#8b008b', '#008b8b', '#bebebe', '#4d4d4d', '#ff5f5f', '#00ff00', '#ffff60', '#0087ff', '#ff80ff', '#00ffff', '#ffffff']
+ let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0087ff', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff']
endif
hi! link VertSplit StatusLineNC
hi! link StatusLineTerm StatusLine
@@ -64,6 +64,8 @@ hi! link String Constant
hi! link Structure Type
hi! link Tag Special
hi! link Typedef Type
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#ffffff guibg=#333333 gui=NONE cterm=NONE
hi ColorColumn guifg=NONE guibg=#8b0000 gui=NONE cterm=NONE
hi CursorLine guifg=NONE guibg=#666666 gui=NONE cterm=NONE
@@ -98,7 +100,7 @@ hi ToolbarButton guifg=NONE guibg=#999999 gui=bold cterm=bold
hi ToolbarLine guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE
hi Visual guifg=#ffffff guibg=#999999 gui=NONE cterm=NONE
hi VisualNOS guifg=NONE guibg=NONE gui=bold,underline ctermfg=NONE ctermbg=NONE cterm=bold,underline
-hi WarningMsg guifg=#8b0000 guibg=NONE gui=NONE cterm=NONE
+hi WarningMsg guifg=#ff0000 guibg=NONE gui=NONE cterm=NONE
hi WildMenu guifg=#000000 guibg=#ffff00 gui=bold cterm=bold
hi debugBreakpoint guifg=#00008b guibg=#ff0000 gui=NONE cterm=NONE
hi debugPC guifg=#00008b guibg=#0000ff gui=NONE cterm=NONE
@@ -170,6 +172,8 @@ if s:t_Co >= 256
hi! link Structure Type
hi! link Tag Special
hi! link Typedef Type
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=231 ctermbg=236 cterm=NONE
hi ColorColumn ctermfg=NONE ctermbg=88 cterm=NONE
hi CursorLine ctermfg=NONE ctermbg=241 cterm=NONE
@@ -204,7 +208,7 @@ if s:t_Co >= 256
hi ToolbarLine ctermfg=NONE ctermbg=NONE cterm=NONE
hi Visual ctermfg=231 ctermbg=246 cterm=NONE
hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=bold,underline
- hi WarningMsg ctermfg=88 ctermbg=NONE cterm=NONE
+ hi WarningMsg ctermfg=196 ctermbg=NONE cterm=NONE
hi WildMenu ctermfg=16 ctermbg=226 cterm=bold
hi debugBreakpoint ctermfg=18 ctermbg=196 cterm=NONE
hi debugPC ctermfg=18 ctermbg=21 cterm=NONE
@@ -279,6 +283,8 @@ if s:t_Co >= 16
hi! link Structure Type
hi! link Tag Special
hi! link Typedef Type
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=white ctermbg=black cterm=NONE
hi ColorColumn ctermfg=white ctermbg=darkred cterm=NONE
hi CursorLine ctermfg=NONE ctermbg=NONE cterm=underline
@@ -313,7 +319,7 @@ if s:t_Co >= 16
hi ToolbarLine ctermfg=NONE ctermbg=NONE cterm=NONE
hi Visual ctermfg=white ctermbg=darkgray cterm=NONE
hi VisualNOS ctermfg=NONE ctermbg=NONE cterm=bold,underline
- hi WarningMsg ctermfg=darkred ctermbg=NONE cterm=NONE
+ hi WarningMsg ctermfg=red ctermbg=NONE cterm=NONE
hi WildMenu ctermfg=black ctermbg=darkyellow cterm=bold
hi debugBreakpoint ctermfg=darkblue ctermbg=red cterm=NONE
hi debugPC ctermfg=darkblue ctermbg=blue cterm=NONE
@@ -494,13 +500,26 @@ endif
" Color: grey30 #4d4d4d 239 darkgray
" Color: grey40 #666666 241 darkgray
" Color: grey60 #999999 246 darkgray
-" Color: xtermblue #0087ff 33 blue
-" Color: xtermdarkblue #006faf 25 darkblue
-" Color: xtermred #ff5f5f 203 red
" Color: comment #80a0ff 111 lightblue
" Color: darkred #8b0000 88 darkred
-" Term colors: black orange seagreen yellow xtermdarkblue darkmagenta darkcyan grey
-" Term colors: grey30 xtermred green lightyellow xtermblue magenta cyan white
+" Color: x_black #000000 16 black
+" Color: x_darkred #cd0000 160 darkred
+" Color: x_darkgreen #00cd00 40 darkgreen
+" Color: x_darkyellow #cdcd00 184 darkyellow
+" Color: x_darkblue_m #0087ff 33 darkblue
+" Color: x_darkmagenta #cd00cd 164 darkmagenta
+" Color: x_darkcyan #00cdcd 44 darkcyan
+" Color: x_gray #e5e5e5 254 gray
+" Color: x_darkgray #7f7f7f 244 darkgray
+" Color: x_red #ff0000 196 red
+" Color: x_green #00ff00 46 green
+" Color: x_yellow #ffff00 226 yellow
+" Color: x_blue #5c5cff 63 blue
+" Color: x_magenta #ff00ff 201 magenta
+" Color: x_cyan #00ffff 51 cyan
+" Color: x_white #ffffff 231 white
+" Term colors: x_black x_darkred x_darkgreen x_darkyellow x_darkblue_m x_darkmagenta x_darkcyan x_gray
+" Term colors: x_darkgray x_red x_green x_yellow x_blue x_magenta x_cyan x_white
" Color: bgDiffA #5F875F 65 darkgreen
" Color: bgDiffC #5F87AF 67 blue
" Color: bgDiffD #AF5FAF 133 magenta
diff --git a/runtime/colors/habamax.vim b/runtime/colors/habamax.vim
index b356260102..049413beef 100644
--- a/runtime/colors/habamax.vim
+++ b/runtime/colors/habamax.vim
@@ -4,7 +4,7 @@
" Maintainer: Maxim Kim <habamax@gmail.com>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:38 MSK
+" Last Updated: Fri 02 Sep 2022 09:45:11 MSK
" Generated by Colortemplate v2.2.0
@@ -21,6 +21,8 @@ endif
hi! link Terminal Normal
hi! link StatuslineTerm Statusline
hi! link StatuslineTermNC StatuslineNC
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi! link javaScriptFunction Statement
hi! link javaScriptIdentifier Statement
hi! link sqlKeyword Statement
@@ -142,6 +144,8 @@ if s:t_Co >= 256
hi! link Terminal Normal
hi! link StatuslineTerm Statusline
hi! link StatuslineTermNC StatuslineNC
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi! link javaScriptFunction Statement
hi! link javaScriptIdentifier Statement
hi! link sqlKeyword Statement
diff --git a/runtime/colors/industry.vim b/runtime/colors/industry.vim
index c627d8c826..3f6726038e 100644
--- a/runtime/colors/industry.vim
+++ b/runtime/colors/industry.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Shian Lee.
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:39 MSK
+" Last Updated: Sun 04 Sep 2022 09:50:04 MSK
" Generated by Colortemplate v2.2.0
@@ -51,7 +51,7 @@ hi Underlined guifg=#87afff guibg=NONE gui=underline cterm=underline
hi Error guifg=#ffffff guibg=#ff0000 gui=NONE cterm=NONE
hi ErrorMsg guifg=#ffffff guibg=#ff0000 gui=NONE cterm=NONE
hi ModeMsg guifg=#ffffff guibg=NONE gui=bold cterm=bold
-hi WarningMsg guifg=#870000 guibg=NONE gui=bold cterm=bold
+hi WarningMsg guifg=#ff0000 guibg=NONE gui=bold cterm=bold
hi MoreMsg guifg=#5fd75f guibg=NONE gui=bold cterm=bold
hi Question guifg=#00ff00 guibg=NONE gui=bold cterm=bold
hi Todo guifg=#005fff guibg=#ffff00 gui=NONE cterm=NONE
@@ -84,6 +84,8 @@ hi! link LineNrBelow LineNr
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi DiffAdd guifg=#ffffff guibg=#5f875f gui=NONE cterm=NONE
hi DiffChange guifg=#ffffff guibg=#5f87af gui=NONE cterm=NONE
hi DiffText guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE
@@ -123,7 +125,7 @@ if s:t_Co >= 256
hi Error ctermfg=231 ctermbg=196 cterm=NONE
hi ErrorMsg ctermfg=231 ctermbg=196 cterm=NONE
hi ModeMsg ctermfg=231 ctermbg=NONE cterm=bold
- hi WarningMsg ctermfg=88 ctermbg=NONE cterm=bold
+ hi WarningMsg ctermfg=196 ctermbg=NONE cterm=bold
hi MoreMsg ctermfg=77 ctermbg=NONE cterm=bold
hi Question ctermfg=46 ctermbg=NONE cterm=bold
hi Todo ctermfg=27 ctermbg=226 cterm=NONE
@@ -156,6 +158,8 @@ if s:t_Co >= 256
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi DiffAdd ctermfg=231 ctermbg=65 cterm=NONE
hi DiffChange ctermfg=231 ctermbg=67 cterm=NONE
hi DiffText ctermfg=16 ctermbg=251 cterm=NONE
@@ -198,7 +202,7 @@ if s:t_Co >= 16
hi Error ctermfg=white ctermbg=red cterm=NONE
hi ErrorMsg ctermfg=white ctermbg=red cterm=NONE
hi ModeMsg ctermfg=white ctermbg=NONE cterm=bold
- hi WarningMsg ctermfg=darkred ctermbg=NONE cterm=bold
+ hi WarningMsg ctermfg=red ctermbg=NONE cterm=bold
hi MoreMsg ctermfg=darkgreen ctermbg=NONE cterm=bold
hi Question ctermfg=green ctermbg=NONE cterm=bold
hi Todo ctermfg=blue ctermbg=yellow cterm=NONE
@@ -231,6 +235,8 @@ if s:t_Co >= 16
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi DiffAdd ctermfg=white ctermbg=darkgreen cterm=NONE
hi DiffChange ctermfg=white ctermbg=blue cterm=NONE
hi DiffText ctermfg=black ctermbg=grey cterm=NONE
diff --git a/runtime/colors/koehler.vim b/runtime/colors/koehler.vim
index cc4eff6cdf..f414eeb3e6 100644
--- a/runtime/colors/koehler.vim
+++ b/runtime/colors/koehler.vim
@@ -3,7 +3,7 @@
" Maintainer: original maintainer Ron Aaron <ron@ronware.org>
" Website: https://www.github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:39 MSK
+" Last Updated: Fri 02 Sep 2022 09:23:56 MSK
" Generated by Colortemplate v2.2.0
@@ -49,6 +49,8 @@ hi! link lCursor Cursor
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
if (has('termguicolors') && &termguicolors) || has('gui_running')
let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff']
diff --git a/runtime/colors/lunaperche.vim b/runtime/colors/lunaperche.vim
index 2f2d4d949b..b717ca7855 100644
--- a/runtime/colors/lunaperche.vim
+++ b/runtime/colors/lunaperche.vim
@@ -4,7 +4,7 @@
" Maintainer: Maxim Kim <habamax@gmail.com>
" Website: https://www.github.com/vim/colorschemes
" License: Vim License (see `:help license`)
-" Last Updated: Tue 23 Aug 2022 16:50:40 MSK
+" Last Updated: Sat 03 Sep 2022 14:31:51 MSK
" Generated by Colortemplate v2.2.0
@@ -81,18 +81,31 @@ hi! link shOption Normal
hi! link shCommandSub Normal
hi! link shDerefPattern shQuote
hi! link shDerefOp Special
+hi! link phpStorageClass Statement
+hi! link phpStructure Statement
+hi! link phpInclude Statement
+hi! link phpDefine Statement
+hi! link phpSpecialFunction Normal
+hi! link phpParent Normal
+hi! link phpComparison Normal
+hi! link phpOperator Normal
+hi! link phpVarSelector Special
+hi! link phpMemberSelector Special
+hi! link phpDocCustomTags phpDocTags
hi! link Terminal Normal
hi! link StatuslineTerm Statusline
hi! link StatuslineTermNC StatuslineNC
hi! link LineNrAbove LineNr
hi! link LineNrBelow LineNr
+hi! link MessageWindow PMenu
+hi! link PopupNotification Todo
if &background ==# 'dark'
if (has('termguicolors') && &termguicolors) || has('gui_running')
let g:terminal_ansi_colors = ['#000000', '#af5f5f', '#5faf5f', '#af875f', '#5f87af', '#d787af', '#5fafaf', '#c6c6c6', '#767676', '#ff5f5f', '#5fd75f', '#ffd787', '#87afd7', '#ffafd7', '#5fd7d7', '#ffffff']
endif
hi Normal guifg=#c6c6c6 guibg=#000000 gui=NONE cterm=NONE
- hi Statusline guifg=#000000 guibg=#c6c6c6 gui=bold cterm=bold
- hi StatuslineNC guifg=#000000 guibg=#767676 gui=NONE cterm=NONE
+ hi Statusline guifg=#c6c6c6 guibg=#000000 gui=bold,reverse cterm=bold,reverse
+ hi StatuslineNC guifg=#767676 guibg=#000000 gui=reverse cterm=reverse
hi VertSplit guifg=#767676 guibg=#767676 gui=NONE cterm=NONE
hi TabLine guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE
hi TabLineFill guifg=NONE guibg=#767676 gui=NONE cterm=NONE
@@ -107,7 +120,7 @@ if &background ==# 'dark'
hi EndOfBuffer guifg=#585858 guibg=NONE gui=NONE cterm=NONE
hi SpecialKey guifg=#585858 guibg=NONE gui=NONE cterm=NONE
hi Pmenu guifg=NONE guibg=#1c1c1c gui=NONE cterm=NONE
- hi PmenuSel guifg=NONE guibg=#005f00 gui=NONE cterm=NONE
+ hi PmenuSel guifg=NONE guibg=#444444 gui=NONE cterm=NONE
hi PmenuThumb guifg=NONE guibg=#c6c6c6 gui=NONE cterm=NONE
hi PmenuSbar guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE
hi SignColumn guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -169,7 +182,6 @@ if &background ==# 'dark'
hi dirFilterMenuBookmarkPath guifg=#878787 guibg=NONE gui=NONE cterm=NONE
hi dirFilterMenuHistoryPath guifg=#878787 guibg=NONE gui=NONE cterm=NONE
hi FilterMenuLineNr guifg=#878787 guibg=NONE gui=NONE cterm=NONE
- hi CocMenuSel guifg=NONE guibg=#005f00 gui=NONE cterm=NONE
hi CocSearch guifg=#ffd787 guibg=NONE gui=NONE cterm=NONE
else
" Light background
@@ -193,7 +205,7 @@ else
hi EndOfBuffer guifg=#9e9e9e guibg=NONE gui=NONE cterm=NONE
hi SpecialKey guifg=#9e9e9e guibg=NONE gui=NONE cterm=NONE
hi Pmenu guifg=NONE guibg=#eeeeee gui=NONE cterm=NONE
- hi PmenuSel guifg=NONE guibg=#afd7af gui=NONE cterm=NONE
+ hi PmenuSel guifg=NONE guibg=#c6c6c6 gui=NONE cterm=NONE
hi PmenuThumb guifg=NONE guibg=#767676 gui=NONE cterm=NONE
hi PmenuSbar guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE
hi SignColumn guifg=NONE guibg=NONE gui=NONE ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -256,7 +268,6 @@ else
hi dirFilterMenuHistoryPath guifg=#626262 guibg=NONE gui=NONE cterm=NONE
hi FilterMenuDirectorySubtle guifg=#626262 guibg=NONE gui=NONE cterm=NONE
hi FilterMenuLineNr guifg=#626262 guibg=NONE gui=NONE cterm=NONE
- hi CocMenuSel guifg=NONE guibg=#afd7af gui=NONE cterm=NONE
hi CocSearch guifg=#870000 guibg=NONE gui=NONE cterm=NONE
endif
@@ -329,15 +340,28 @@ if s:t_Co >= 256
hi! link shCommandSub Normal
hi! link shDerefPattern shQuote
hi! link shDerefOp Special
+ hi! link phpStorageClass Statement
+ hi! link phpStructure Statement
+ hi! link phpInclude Statement
+ hi! link phpDefine Statement
+ hi! link phpSpecialFunction Normal
+ hi! link phpParent Normal
+ hi! link phpComparison Normal
+ hi! link phpOperator Normal
+ hi! link phpVarSelector Special
+ hi! link phpMemberSelector Special
+ hi! link phpDocCustomTags phpDocTags
hi! link Terminal Normal
hi! link StatuslineTerm Statusline
hi! link StatuslineTermNC StatuslineNC
hi! link LineNrAbove LineNr
hi! link LineNrBelow LineNr
+ hi! link MessageWindow PMenu
+ hi! link PopupNotification Todo
if &background ==# 'dark'
hi Normal ctermfg=251 ctermbg=16 cterm=NONE
- hi Statusline ctermfg=16 ctermbg=251 cterm=bold
- hi StatuslineNC ctermfg=16 ctermbg=243 cterm=NONE
+ hi Statusline ctermfg=251 ctermbg=16 cterm=bold,reverse
+ hi StatuslineNC ctermfg=243 ctermbg=16 cterm=reverse
hi VertSplit ctermfg=243 ctermbg=243 cterm=NONE
hi TabLine ctermfg=16 ctermbg=251 cterm=NONE
hi TabLineFill ctermfg=NONE ctermbg=243 cterm=NONE
@@ -352,7 +376,7 @@ if s:t_Co >= 256
hi EndOfBuffer ctermfg=240 ctermbg=NONE cterm=NONE
hi SpecialKey ctermfg=240 ctermbg=NONE cterm=NONE
hi Pmenu ctermfg=NONE ctermbg=234 cterm=NONE
- hi PmenuSel ctermfg=NONE ctermbg=22 cterm=NONE
+ hi PmenuSel ctermfg=NONE ctermbg=238 cterm=NONE
hi PmenuThumb ctermfg=NONE ctermbg=251 cterm=NONE
hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE
hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -412,7 +436,6 @@ if s:t_Co >= 256
hi dirFilterMenuBookmarkPath ctermfg=102 ctermbg=NONE cterm=NONE
hi dirFilterMenuHistoryPath ctermfg=102 ctermbg=NONE cterm=NONE
hi FilterMenuLineNr ctermfg=102 ctermbg=NONE cterm=NONE
- hi CocMenuSel ctermfg=NONE ctermbg=22 cterm=NONE
hi CocSearch ctermfg=222 ctermbg=NONE cterm=NONE
else
" Light background
@@ -433,7 +456,7 @@ if s:t_Co >= 256
hi EndOfBuffer ctermfg=247 ctermbg=NONE cterm=NONE
hi SpecialKey ctermfg=247 ctermbg=NONE cterm=NONE
hi Pmenu ctermfg=NONE ctermbg=255 cterm=NONE
- hi PmenuSel ctermfg=NONE ctermbg=151 cterm=NONE
+ hi PmenuSel ctermfg=NONE ctermbg=251 cterm=NONE
hi PmenuThumb ctermfg=NONE ctermbg=243 cterm=NONE
hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE
hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -494,7 +517,6 @@ if s:t_Co >= 256
hi dirFilterMenuHistoryPath ctermfg=241 ctermbg=NONE cterm=NONE
hi FilterMenuDirectorySubtle ctermfg=241 ctermbg=NONE cterm=NONE
hi FilterMenuLineNr ctermfg=241 ctermbg=NONE cterm=NONE
- hi CocMenuSel ctermfg=NONE ctermbg=151 cterm=NONE
hi CocSearch ctermfg=88 ctermbg=NONE cterm=NONE
endif
unlet s:t_Co
@@ -504,8 +526,8 @@ endif
if s:t_Co >= 16
if &background ==# 'dark'
hi Normal ctermfg=grey ctermbg=black cterm=NONE
- hi Statusline ctermfg=black ctermbg=grey cterm=bold
- hi StatuslineNC ctermfg=black ctermbg=darkgrey cterm=NONE
+ hi Statusline ctermfg=grey ctermbg=black cterm=bold,reverse
+ hi StatuslineNC ctermfg=darkgrey ctermbg=black cterm=reverse
hi VertSplit ctermfg=darkgrey ctermbg=darkgrey cterm=NONE
hi TabLine ctermfg=black ctermbg=grey cterm=NONE
hi TabLineFill ctermfg=NONE ctermbg=darkgrey cterm=NONE
@@ -520,7 +542,7 @@ if s:t_Co >= 16
hi EndOfBuffer ctermfg=grey ctermbg=NONE cterm=NONE
hi SpecialKey ctermfg=grey ctermbg=NONE cterm=NONE
hi Pmenu ctermfg=black ctermbg=darkgrey cterm=NONE
- hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE
+ hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE
hi PmenuThumb ctermfg=NONE ctermbg=grey cterm=NONE
hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE
hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -567,6 +589,20 @@ if s:t_Co >= 16
hi diffAdded ctermfg=green ctermbg=NONE cterm=NONE
hi diffRemoved ctermfg=darkred ctermbg=NONE cterm=NONE
hi diffSubname ctermfg=magenta ctermbg=NONE cterm=NONE
+ hi dirType ctermfg=darkmagenta ctermbg=NONE cterm=NONE
+ hi dirPermissionUser ctermfg=darkgreen ctermbg=NONE cterm=NONE
+ hi dirPermissionGroup ctermfg=darkyellow ctermbg=NONE cterm=NONE
+ hi dirPermissionOther ctermfg=darkcyan ctermbg=NONE cterm=NONE
+ hi dirOwner ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi dirGroup ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi dirTime ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi dirSize ctermfg=yellow ctermbg=NONE cterm=NONE
+ hi dirSizeMod ctermfg=darkmagenta ctermbg=NONE cterm=NONE
+ hi FilterMenuDirectorySubtle ctermfg=grey ctermbg=NONE cterm=NONE
+ hi dirFilterMenuBookmarkPath ctermfg=grey ctermbg=NONE cterm=NONE
+ hi dirFilterMenuHistoryPath ctermfg=grey ctermbg=NONE cterm=NONE
+ hi FilterMenuLineNr ctermfg=grey ctermbg=NONE cterm=NONE
+ hi CocSearch ctermfg=yellow ctermbg=NONE cterm=NONE
else
" Light background
hi Normal ctermfg=black ctermbg=white cterm=NONE
@@ -586,7 +622,7 @@ if s:t_Co >= 16
hi EndOfBuffer ctermfg=darkgrey ctermbg=NONE cterm=NONE
hi SpecialKey ctermfg=darkgrey ctermbg=NONE cterm=NONE
hi Pmenu ctermfg=black ctermbg=grey cterm=NONE
- hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE
+ hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE
hi PmenuThumb ctermfg=NONE ctermbg=darkgrey cterm=NONE
hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE
hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -633,6 +669,21 @@ if s:t_Co >= 16
hi diffAdded ctermfg=darkgreen ctermbg=NONE cterm=NONE
hi diffRemoved ctermfg=red ctermbg=NONE cterm=NONE
hi diffSubname ctermfg=darkmagenta ctermbg=NONE cterm=NONE
+ hi dirType ctermfg=darkcyan ctermbg=NONE cterm=NONE
+ hi dirPermissionUser ctermfg=darkyellow ctermbg=NONE cterm=NONE
+ hi dirPermissionGroup ctermfg=darkgreen ctermbg=NONE cterm=NONE
+ hi dirPermissionOther ctermfg=darkmagenta ctermbg=NONE cterm=NONE
+ hi dirOwner ctermfg=grey ctermbg=NONE cterm=NONE
+ hi dirGroup ctermfg=grey ctermbg=NONE cterm=NONE
+ hi dirTime ctermfg=grey ctermbg=NONE cterm=NONE
+ hi dirSize ctermfg=darkred ctermbg=NONE cterm=NONE
+ hi dirSizeMod ctermfg=darkcyan ctermbg=NONE cterm=NONE
+ hi dirLink ctermfg=darkgreen ctermbg=NONE cterm=bold
+ hi dirFilterMenuBookmarkPath ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi dirFilterMenuHistoryPath ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi FilterMenuDirectorySubtle ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi FilterMenuLineNr ctermfg=darkgrey ctermbg=NONE cterm=NONE
+ hi CocSearch ctermfg=darkred ctermbg=NONE cterm=NONE
endif
unlet s:t_Co
finish
@@ -659,7 +710,7 @@ if s:t_Co >= 8
hi Pmenu ctermfg=black ctermbg=grey cterm=NONE
hi PmenuThumb ctermfg=NONE ctermbg=darkgreen cterm=NONE
hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE
- hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE
+ hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE
hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
hi Error ctermfg=grey ctermbg=darkred cterm=NONE
hi ErrorMsg ctermfg=grey ctermbg=darkred cterm=NONE
@@ -688,7 +739,7 @@ if s:t_Co >= 8
hi Comment ctermfg=darkblue ctermbg=NONE cterm=NONE
hi Constant ctermfg=darkred ctermbg=NONE cterm=NONE
hi Identifier ctermfg=NONE ctermbg=NONE cterm=NONE
- hi Statement ctermfg=black ctermbg=NONE cterm=bold
+ hi Statement ctermfg=grey ctermbg=NONE cterm=bold
hi Type ctermfg=darkgreen ctermbg=NONE cterm=bold
hi PreProc ctermfg=darkyellow ctermbg=NONE cterm=NONE
hi Special ctermfg=darkcyan ctermbg=NONE cterm=NONE
@@ -722,7 +773,7 @@ if s:t_Co >= 8
hi Pmenu ctermfg=grey ctermbg=black cterm=NONE
hi PmenuThumb ctermfg=NONE ctermbg=darkgreen cterm=NONE
hi PmenuSbar ctermfg=NONE ctermbg=NONE cterm=NONE
- hi PmenuSel ctermfg=black ctermbg=darkgreen cterm=NONE
+ hi PmenuSel ctermfg=black ctermbg=darkcyan cterm=NONE
hi SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
hi Error ctermfg=grey ctermbg=darkred cterm=NONE
hi ErrorMsg ctermfg=grey ctermbg=darkred cterm=NONE
@@ -864,7 +915,7 @@ endif
" Color: colorlC #FF5FFF 207 magenta
" Color: colorV #005F87 24 darkblue
" Color: colorMP #C5E7C5 30 darkcyan
-" Color: colorPMenuSel #005F00 22 darkgreen
+" Color: colorPMenuSel #444444 238 darkcyan
" Color: colorDim #878787 102 grey
" Color: diffAdd #AF87AF 139 darkmagenta
" Color: diffDelete #D78787 174 darkred
@@ -898,7 +949,7 @@ endif
" Color: colorlC #FF00FF 201 magenta
" Color: colorV #5F87AF 67 darkblue
" Color: colorMP #C5E7C5 30 darkcyan
-" Color: colorPMenuSel #AFD7AF 151 darkgreen
+" Color: colorPMenuSel #C6C6C6 251 darkcyan
" Color: colorDim #626262 241 darkgrey
" Color: diffAdd #D7AFD7 182 darkmagenta
" Color: diffDelete #870000 88 darkred
diff --git a/runtime/colors/morning.vim b/runtime/colors/morning.vim
index 6ffecef422..a7aec49808 100644
--- a/runtime/colors/morning.vim
+++ b/runtime/colors/morning.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Bram Moolenaar <Bram@vim.org>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:41 MSK
+" Last Updated: Fri 02 Sep 2022 09:46:24 MSK
" Generated by Colortemplate v2.2.0
@@ -26,6 +26,8 @@ hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link StatuslineTerm Statusline
hi! link StatuslineTermNC StatuslineNC
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#000000 guibg=#e4e4e4 gui=NONE cterm=NONE
hi EndOfBuffer guifg=#0000ff guibg=#cccccc gui=bold cterm=bold
hi Folded guifg=#00008b guibg=#d3d3d3 gui=NONE cterm=NONE
@@ -96,6 +98,8 @@ if s:t_Co >= 256
hi! link CursorLineSign CursorLine
hi! link StatuslineTerm Statusline
hi! link StatuslineTermNC StatuslineNC
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=16 ctermbg=254 cterm=NONE
hi EndOfBuffer ctermfg=21 ctermbg=252 cterm=bold
hi Folded ctermfg=18 ctermbg=252 cterm=NONE
diff --git a/runtime/colors/murphy.vim b/runtime/colors/murphy.vim
index 7b5defd3d0..60a6aed428 100644
--- a/runtime/colors/murphy.vim
+++ b/runtime/colors/murphy.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Ron Aaron <ron@ronware.org>.
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:41 MSK
+" Last Updated: Fri 02 Sep 2022 09:47:20 MSK
" Generated by Colortemplate v2.2.0
@@ -26,6 +26,8 @@ hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#87ff87 guibg=#000000 gui=NONE cterm=NONE
hi EndOfBuffer guifg=#0000ff guibg=#000000 gui=NONE cterm=NONE
hi StatusLine guifg=#ffffff guibg=#00008b gui=NONE cterm=NONE
@@ -96,6 +98,8 @@ if s:t_Co >= 256
hi! link CursorLineSign CursorLine
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=120 ctermbg=16 cterm=NONE
hi EndOfBuffer ctermfg=21 ctermbg=16 cterm=NONE
hi StatusLine ctermfg=231 ctermbg=18 cterm=NONE
diff --git a/runtime/colors/pablo.vim b/runtime/colors/pablo.vim
index eaf6deb22b..f404951b2a 100644
--- a/runtime/colors/pablo.vim
+++ b/runtime/colors/pablo.vim
@@ -3,7 +3,7 @@
" Maintainer: Original maintainerRon Aaron <ron@ronware.org>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:42 MSK
+" Last Updated: Sun 04 Sep 2022 09:53:40 MSK
" Generated by Colortemplate v2.2.0
@@ -17,13 +17,15 @@ let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1
if (has('termguicolors') && &termguicolors) || has('gui_running')
let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff']
endif
-hi Normal guifg=#ffffff guibg=#000000 gui=NONE cterm=NONE
hi! link Terminal Normal
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
+hi Normal guifg=#ffffff guibg=#000000 gui=NONE cterm=NONE
hi Comment guifg=#808080 guibg=NONE gui=NONE cterm=NONE
hi Constant guifg=#00ffff guibg=NONE gui=NONE cterm=NONE
hi Identifier guifg=#00c0c0 guibg=NONE gui=NONE cterm=NONE
@@ -88,13 +90,15 @@ hi DiffText guifg=#000000 guibg=#c6c6c6 gui=NONE cterm=NONE
hi DiffDelete guifg=#ffffff guibg=#af5faf gui=NONE cterm=NONE
if s:t_Co >= 256
- hi Normal ctermfg=231 ctermbg=16 cterm=NONE
hi! link Terminal Normal
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
+ hi Normal ctermfg=231 ctermbg=16 cterm=NONE
hi Comment ctermfg=244 ctermbg=NONE cterm=NONE
hi Constant ctermfg=51 ctermbg=NONE cterm=NONE
hi Identifier ctermfg=37 ctermbg=NONE cterm=NONE
@@ -117,7 +121,7 @@ if s:t_Co >= 256
hi NonText ctermfg=63 ctermbg=NONE cterm=bold
hi EndOfBuffer ctermfg=63 ctermbg=NONE cterm=bold
hi ErrorMsg ctermfg=231 ctermbg=160 cterm=NONE
- hi WarningMsg ctermfg=224 ctermbg=NONE cterm=NONE
+ hi WarningMsg ctermfg=196 ctermbg=NONE cterm=NONE
hi SignColumn ctermfg=51 ctermbg=248 cterm=NONE
hi ColorColumn ctermfg=NONE ctermbg=239 cterm=NONE
hi FoldColumn ctermfg=102 ctermbg=236 cterm=NONE
@@ -163,12 +167,6 @@ endif
if s:t_Co >= 16
hi Normal ctermfg=white ctermbg=black cterm=NONE
- hi! link Terminal Normal
- hi! link StatusLineTerm StatusLine
- hi! link StatusLineTermNC StatusLineNC
- hi! link CurSearch Search
- hi! link CursorLineFold CursorLine
- hi! link CursorLineSign CursorLine
hi Comment ctermfg=darkgrey ctermbg=NONE cterm=NONE
hi Constant ctermfg=cyan ctermbg=NONE cterm=NONE
hi Identifier ctermfg=darkcyan ctermbg=NONE cterm=NONE
@@ -191,7 +189,7 @@ if s:t_Co >= 16
hi NonText ctermfg=blue ctermbg=NONE cterm=bold
hi EndOfBuffer ctermfg=blue ctermbg=NONE cterm=bold
hi ErrorMsg ctermfg=white ctermbg=darkred cterm=NONE
- hi WarningMsg ctermfg=darkred ctermbg=NONE cterm=NONE
+ hi WarningMsg ctermfg=red ctermbg=NONE cterm=NONE
hi SignColumn ctermfg=cyan ctermbg=black cterm=NONE
hi ColorColumn ctermfg=white ctermbg=darkgrey cterm=NONE
hi FoldColumn ctermfg=NONE ctermbg=NONE cterm=NONE
@@ -405,7 +403,7 @@ endif
" Color: SpecialKey #00ffff 81 cyan
" Color: StatusLineTerm #90ee90 121 darkgreen
" Color: Title #ff00ff 225 magenta
-" Color: WarningMsg #ff0000 224 darkred
+" Color: WarningMsg #ff0000 196 red
" Color: ToolbarLine #7f7f7f 242 darkgrey
" Color: ToolbarButton #d3d3d3 254 grey
" Color: Underlined #80a0ff 111 darkgreen
diff --git a/runtime/colors/peachpuff.vim b/runtime/colors/peachpuff.vim
index ad47c31e19..130eceeb18 100644
--- a/runtime/colors/peachpuff.vim
+++ b/runtime/colors/peachpuff.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer David Ne\v{c}as (Yeti) <yeti@physics.muni.cz>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:42 MSK
+" Last Updated: Fri 02 Sep 2022 09:50:02 MSK
" Generated by Colortemplate v2.2.0
@@ -24,6 +24,8 @@ hi! link LineNrBelow LineNr
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#000000 guibg=#ffdab9 gui=NONE cterm=NONE
hi Folded guifg=#000000 guibg=#e3c1a5 gui=NONE cterm=NONE
hi CursorLine guifg=NONE guibg=#f5c195 gui=NONE cterm=NONE
@@ -94,6 +96,8 @@ if s:t_Co >= 256
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=16 ctermbg=223 cterm=NONE
hi Folded ctermfg=16 ctermbg=252 cterm=NONE
hi CursorLine ctermfg=NONE ctermbg=180 cterm=NONE
diff --git a/runtime/colors/quiet.vim b/runtime/colors/quiet.vim
index 9f265726cc..9e81ba3857 100644
--- a/runtime/colors/quiet.vim
+++ b/runtime/colors/quiet.vim
@@ -4,7 +4,7 @@
" Maintainer: neutaaaaan <neutaaaaan-gh@protonmail.com>
" Website: https://github.com/vim/colorschemes
" License: Vim License (see `:help license`)`
-" Last Updated: Tue 23 Aug 2022 16:50:43 MSK
+" Last Updated: Fri 02 Sep 2022 09:55:30 MSK
" Generated by Colortemplate v2.2.0
@@ -16,6 +16,8 @@ let s:t_Co = exists('&t_Co') && !has('gui_running') ? (&t_Co ? &t_Co : 0) : -1
hi! link Terminal Normal
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi! link Boolean Constant
hi! link Character Constant
hi! link Conditional Statement
diff --git a/runtime/colors/ron.vim b/runtime/colors/ron.vim
index f622a6f991..ea37b646a6 100644
--- a/runtime/colors/ron.vim
+++ b/runtime/colors/ron.vim
@@ -3,7 +3,7 @@
" Maintainer: original maintainer Ron Aaron <ron@ronware.org>
" Website: https://www.github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:45 MSK
+" Last Updated: Fri 02 Sep 2022 09:50:56 MSK
" Generated by Colortemplate v2.2.0
@@ -46,6 +46,8 @@ hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link LineNrAbove LineNr
hi! link LineNrBelow LineNr
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
if (has('termguicolors') && &termguicolors) || has('gui_running')
let g:terminal_ansi_colors = ['#000000', '#cd0000', '#00cd00', '#cdcd00', '#0000ee', '#cd00cd', '#00cdcd', '#e5e5e5', '#7f7f7f', '#ff0000', '#00ff00', '#ffff00', '#5c5cff', '#ff00ff', '#00ffff', '#ffffff']
diff --git a/runtime/colors/shine.vim b/runtime/colors/shine.vim
index 331ca9487c..f9b1e39324 100644
--- a/runtime/colors/shine.vim
+++ b/runtime/colors/shine.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer is Yasuhiro Matsumoto <mattn@mail.goo.ne.jp>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:46 MSK
+" Last Updated: Fri 02 Sep 2022 09:51:42 MSK
" Generated by Colortemplate v2.2.0
@@ -28,6 +28,8 @@ hi! link EndOfBuffer NonText
hi! link ErrorMsg Error
hi! link Tag Special
hi! link Operator Statement
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE
hi Folded guifg=#00008b guibg=#dadada gui=NONE cterm=NONE
hi CursorLine guifg=NONE guibg=#dadada gui=NONE cterm=NONE
@@ -104,6 +106,8 @@ if s:t_Co >= 256
hi! link ErrorMsg Error
hi! link Tag Special
hi! link Operator Statement
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=16 ctermbg=231 cterm=NONE
hi Folded ctermfg=18 ctermbg=253 cterm=NONE
hi CursorLine ctermfg=NONE ctermbg=253 cterm=NONE
diff --git a/runtime/colors/slate.vim b/runtime/colors/slate.vim
index ecdaca1e2a..04fbc6d6c8 100644
--- a/runtime/colors/slate.vim
+++ b/runtime/colors/slate.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Ralph Amissah <ralph@amissah.com>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:46 MSK
+" Last Updated: Fri 02 Sep 2022 09:52:25 MSK
" Generated by Colortemplate v2.2.0
@@ -24,6 +24,8 @@ hi! link LineNrBelow LineNr
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#ffffff guibg=#262626 gui=NONE cterm=NONE
hi EndOfBuffer guifg=#5f87d7 guibg=NONE gui=NONE cterm=NONE
hi StatusLine guifg=#000000 guibg=#afaf87 gui=NONE cterm=NONE
@@ -99,6 +101,8 @@ if s:t_Co >= 256
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=231 ctermbg=235 cterm=NONE
hi EndOfBuffer ctermfg=68 ctermbg=NONE cterm=NONE
hi StatusLine ctermfg=16 ctermbg=144 cterm=NONE
diff --git a/runtime/colors/torte.vim b/runtime/colors/torte.vim
index dbce11c921..01d5f0b4e0 100644
--- a/runtime/colors/torte.vim
+++ b/runtime/colors/torte.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Thorsten Maerz <info@netztorte.de>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:47 MSK
+" Last Updated: Fri 02 Sep 2022 09:53:21 MSK
" Generated by Colortemplate v2.2.0
@@ -26,6 +26,8 @@ hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#cccccc guibg=#000000 gui=NONE cterm=NONE
hi Comment guifg=#80a0ff guibg=NONE gui=NONE cterm=NONE
hi Constant guifg=#ffa0a0 guibg=NONE gui=NONE cterm=NONE
@@ -97,6 +99,8 @@ if s:t_Co >= 256
hi! link CursorLineSign CursorLine
hi! link StatusLineTerm StatusLine
hi! link StatusLineTermNC StatusLineNC
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=251 ctermbg=16 cterm=NONE
hi Comment ctermfg=111 ctermbg=NONE cterm=NONE
hi Constant ctermfg=217 ctermbg=NONE cterm=NONE
diff --git a/runtime/colors/zellner.vim b/runtime/colors/zellner.vim
index db500c52f2..ab794c0193 100644
--- a/runtime/colors/zellner.vim
+++ b/runtime/colors/zellner.vim
@@ -4,7 +4,7 @@
" Maintainer: Original maintainer Ron Aaron <ron@ronware.org>
" Website: https://github.com/vim/colorschemes
" License: Same as Vim
-" Last Updated: Tue 23 Aug 2022 16:50:48 MSK
+" Last Updated: Fri 02 Sep 2022 09:54:15 MSK
" Generated by Colortemplate v2.2.0
@@ -24,6 +24,8 @@ hi! link LineNrBelow LineNr
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+hi! link MessageWindow Pmenu
+hi! link PopupNotification Todo
hi Normal guifg=#000000 guibg=#ffffff gui=NONE cterm=NONE
hi Folded guifg=#00008b guibg=#d3d3d3 gui=NONE cterm=NONE
hi CursorLine guifg=NONE guibg=#e5e5e5 gui=NONE cterm=NONE
@@ -95,6 +97,8 @@ if s:t_Co >= 256
hi! link CurSearch Search
hi! link CursorLineFold CursorLine
hi! link CursorLineSign CursorLine
+ hi! link MessageWindow Pmenu
+ hi! link PopupNotification Todo
hi Normal ctermfg=16 ctermbg=231 cterm=NONE
hi Folded ctermfg=18 ctermbg=252 cterm=NONE
hi CursorLine ctermfg=NONE ctermbg=254 cterm=NONE
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt
index 82978d0b3c..00a3759936 100644
--- a/runtime/doc/api.txt
+++ b/runtime/doc/api.txt
@@ -1067,9 +1067,11 @@ nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col})
|api-fast|
Parameters: ~
- {button} Mouse button: one of "left", "right", "middle", "wheel".
+ {button} Mouse button: one of "left", "right", "middle", "wheel",
+ "move".
{action} For ordinary buttons, one of "press", "drag", "release".
For the wheel, one of "up", "down", "left", "right".
+ Ignored for "move".
{modifier} String of modifiers each represented by a single char. The
same specifiers are used as for a key press, except that
the "-" separator is optional, so "C-A-", "c-a" and "CA"
@@ -1846,7 +1848,7 @@ nvim_parse_cmd({str}, {opts}) *nvim_parse_cmd()*
• keeppatterns: (boolean) |:keeppatterns|.
• lockmarks: (boolean) |:lockmarks|.
• noswapfile: (boolean) |:noswapfile|.
- • tab: (integer) |:tab|.
+ • tab: (integer) |:tab|. -1 when omitted.
• verbose: (integer) |:verbose|. -1 when omitted.
• vertical: (boolean) |:vertical|.
• split: (string) Split modifier string, is an empty string when
@@ -2644,6 +2646,8 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts})
When a character is supplied it is used as |:syn-cchar|.
"hl_group" is used as highlight for the cchar if provided,
otherwise it defaults to |hl-Conceal|.
+ • spell: boolean indicating that spell checking should be
+ performed within this extmark
• ui_watched: boolean that indicates the mark should be
drawn by a UI. When set, the UI will receive win_extmark
events. Note: the mark is positioned by virt_text
@@ -2675,7 +2679,7 @@ nvim_get_namespaces() *nvim_get_namespaces()*
dict that maps from names to namespace ids.
*nvim_set_decoration_provider()*
-nvim_set_decoration_provider({ns_id}, {opts})
+nvim_set_decoration_provider({ns_id}, {*opts})
Set or change decoration provider for a namespace
This is a very general purpose interface for having lua callbacks being
@@ -2707,7 +2711,7 @@ nvim_set_decoration_provider({ns_id}, {opts})
Parameters: ~
{ns_id} Namespace id from |nvim_create_namespace()|
- {opts} Callbacks invoked during redraw:
+ {opts} Table of callbacks:
• on_start: called first on each screen redraw ["start",
tick]
• on_buf: called for each buffer being redrawn (before window
diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt
index 63226fe701..7a2c540ea2 100644
--- a/runtime/doc/autocmd.txt
+++ b/runtime/doc/autocmd.txt
@@ -412,6 +412,8 @@ CmdwinLeave Before leaving the command-line window.
|cmdwin-char|
*ColorScheme*
ColorScheme After loading a color scheme. |:colorscheme|
+ Not triggered if the color scheme is not
+ found.
The pattern is matched against the
colorscheme name. <afile> can be used for the
name of the actual file where this option was
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt
index a2e15142e7..c70643d12c 100644
--- a/runtime/doc/builtin.txt
+++ b/runtime/doc/builtin.txt
@@ -6,9 +6,7 @@
Builtin functions *builtin-functions*
-1. Overview |builtin-function-list|
-2. Details |builtin-function-details|
-3. Matching a pattern in a String |string-match|
+ Type |gO| to see the table of contents.
==============================================================================
1. Overview *builtin-function-list*
@@ -528,6 +526,8 @@ uniq({list} [, {func} [, {dict}]])
List remove adjacent duplicates from a list
values({dict}) List values in {dict}
virtcol({expr}) Number screen column of cursor or mark
+virtcol2col({winid}, {lnum}, {col})
+ Number byte index of a character on screen
visualmode([expr]) String last visual mode used
wait({timeout}, {condition} [, {interval}])
Number Wait until {condition} is satisfied
@@ -1276,7 +1276,7 @@ complete_info([{what}]) *complete_info()*
typed text only, or the last completion after
no item is selected when using the <Up> or
<Down> keys)
- inserted Inserted string. [NOT IMPLEMENT YET]
+ inserted Inserted string. [NOT IMPLEMENTED YET]
*complete_info_mode*
mode values are:
@@ -2507,10 +2507,11 @@ funcref({name} [, {arglist}] [, {dict}])
Can also be used as a |method|: >
GetFuncname()->funcref([arg])
<
- *function()* *E700* *E922* *E923*
+ *function()* *partial* *E700* *E922* *E923*
function({name} [, {arglist}] [, {dict}])
Return a |Funcref| variable that refers to function {name}.
- {name} can be a user defined function or an internal function.
+ {name} can be the name of a user defined function or an
+ internal function.
{name} can also be a Funcref or a partial. When it is a
partial the dict stored in it will be used and the {dict}
@@ -2529,30 +2530,56 @@ function({name} [, {arglist}] [, {dict}])
The arguments are passed to the function in front of other
arguments, but after any argument from |method|. Example: >
func Callback(arg1, arg2, name)
- ...
+ "...
let Partial = function('Callback', ['one', 'two'])
- ...
+ "...
call Partial('name')
< Invokes the function as with: >
call Callback('one', 'two', 'name')
+< With a |method|: >
+ func Callback(one, two, three)
+ "...
+ let Partial = function('Callback', ['two'])
+ "...
+ eval 'one'->Partial('three')
+< Invokes the function as with: >
+ call Callback('one', 'two', 'three')
+
+< The function() call can be nested to add more arguments to the
+ Funcref. The extra arguments are appended to the list of
+ arguments. Example: >
+ func Callback(arg1, arg2, name)
+ "...
+ let Func = function('Callback', ['one'])
+ let Func2 = function(Func, ['two'])
+ "...
+ call Func2('name')
+< Invokes the function as with: >
+ call Callback('one', 'two', 'name')
+
< The Dictionary is only useful when calling a "dict" function.
In that case the {dict} is passed in as "self". Example: >
function Callback() dict
echo "called for " .. self.name
endfunction
- ...
+ "...
let context = {"name": "example"}
let Func = function('Callback', context)
- ...
+ "...
call Func() " will echo: called for example
+< The use of function() is not needed when there are no extra
+ arguments, these two are equivalent, if Callback() is defined
+ as context.Callback(): >
+ let Func = function('Callback', context)
+ let Func = context.Callback
< The argument list and the Dictionary can be combined: >
function Callback(arg1, count) dict
- ...
+ "...
let context = {"name": "example"}
let Func = function('Callback', ['one'], context)
- ...
+ "...
call Func(500)
< Invokes the function as with: >
call context.Callback('one', 500)
@@ -5595,12 +5622,19 @@ nvim_...({...}) *E5555* *nvim_...()* *eval-api*
or({expr}, {expr}) *or()*
Bitwise OR on the two arguments. The arguments are converted
to a number. A List, Dict or Float argument causes an error.
+ Also see `and()` and `xor()`.
Example: >
:let bits = or(bits, 0x80)
< Can also be used as a |method|: >
:let bits = bits->or(0x80)
-pathshorten({expr} [, {len}]) *pathshorten()*
+< Rationale: The reason this is a function and not using the "|"
+ character like many languages, is that Vi has always used "|"
+ to separate commands. In many places it would not be clear if
+ "|" is an operator or a command separator.
+
+
+pathshorten({path} [, {len}]) *pathshorten()*
Shorten directory names in the path {path} and return the
result. The tail, the file name, is kept as-is. The other
components in the path are reduced to {len} letters in length.
@@ -8806,6 +8840,26 @@ virtcol({expr}) *virtcol()*
< Can also be used as a |method|: >
GetPos()->virtcol()
+virtcol2col({winid}, {lnum}, {col}) *virtcol2col()*
+ The result is a Number, which is the byte index of the
+ character in window {winid} at buffer line {lnum} and virtual
+ column {col}.
+
+ If {col} is greater than the last virtual column in line
+ {lnum}, then the byte index of the character at the last
+ virtual column is returned.
+
+ The {winid} argument can be the window number or the
+ |window-ID|. If this is zero, then the current window is used.
+
+ Returns -1 if the window {winid} doesn't exist or the buffer
+ line {lnum} or virtual column {col} is invalid.
+
+ See also |screenpos()|, |virtcol()| and |col()|.
+
+ Can also be used as a |method|: >
+ GetWinid()->virtcol2col(lnum, col)
+
visualmode([{expr}]) *visualmode()*
The result is a String, which describes the last Visual mode
used in the current buffer. Initially it returns an empty
@@ -9237,6 +9291,7 @@ writefile({object}, {fname} [, {flags}])
xor({expr}, {expr}) *xor()*
Bitwise XOR on the two arguments. The arguments are converted
to a number. A List, Dict or Float argument causes an error.
+ Also see `and()` and `or()`.
Example: >
:let bits = xor(bits, 0x80)
<
diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt
index 3fbf1ee136..3e068e3b4e 100644
--- a/runtime/doc/eval.txt
+++ b/runtime/doc/eval.txt
@@ -2309,397 +2309,10 @@ help file: |builtin-functions|.
5. Defining functions *user-function*
New functions can be defined. These can be called just like builtin
-functions. The function executes a sequence of Ex commands. Normal mode
-commands can be executed with the |:normal| command.
-
-The function name must start with an uppercase letter, to avoid confusion with
-builtin functions. To prevent from using the same name in different scripts
-avoid obvious, short names. A good habit is to start the function name with
-the name of the script, e.g., "HTMLcolor()".
-
-It's also possible to use curly braces, see |curly-braces-names|. And the
-|autoload| facility is useful to define a function only when it's called.
-
- *local-function*
-A function local to a script must start with "s:". A local script function
-can only be called from within the script and from functions, user commands
-and autocommands defined in the script. It is also possible to call the
-function from a mapping defined in the script, but then |<SID>| must be used
-instead of "s:" when the mapping is expanded outside of the script.
-There are only script-local functions, no buffer-local or window-local
-functions.
-
- *:fu* *:function* *E128* *E129* *E123*
-:fu[nction] List all functions and their arguments.
-
-:fu[nction][!] {name} List function {name}, annotated with line numbers
- unless "!" is given.
- {name} may be a |Dictionary| |Funcref| entry: >
- :function dict.init
-
-:fu[nction] /{pattern} List functions with a name matching {pattern}.
- Example that lists all functions ending with "File": >
- :function /File$
-<
- *:function-verbose*
-When 'verbose' is non-zero, listing a function will also display where it was
-last defined. Example: >
-
- :verbose function SetFileTypeSH
- function SetFileTypeSH(name)
- Last set from /usr/share/vim/vim-7.0/filetype.vim
-<
-See |:verbose-cmd| for more information.
-
- *E124* *E125* *E853* *E884*
-:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
- Define a new function by the name {name}. The body of
- the function follows in the next lines, until the
- matching |:endfunction|.
-
- The name must be made of alphanumeric characters and
- '_', and must start with a capital or "s:" (see
- above). Note that using "b:" or "g:" is not allowed.
- (since patch 7.4.260 E884 is given if the function
- name has a colon in the name, e.g. for "foo:bar()".
- Before that patch no error was given).
-
- {name} can also be a |Dictionary| entry that is a
- |Funcref|: >
- :function dict.init(arg)
-< "dict" must be an existing dictionary. The entry
- "init" is added if it didn't exist yet. Otherwise [!]
- is required to overwrite an existing function. The
- result is a |Funcref| to a numbered function. The
- function can only be used with a |Funcref| and will be
- deleted if there are no more references to it.
- *E127* *E122*
- When a function by this name already exists and [!] is
- not used an error message is given. There is one
- exception: When sourcing a script again, a function
- that was previously defined in that script will be
- silently replaced.
- When [!] is used, an existing function is silently
- replaced. Unless it is currently being executed, that
- is an error.
- NOTE: Use ! wisely. If used without care it can cause
- an existing function to be replaced unexpectedly,
- which is hard to debug.
-
- For the {arguments} see |function-argument|.
-
- *:func-range* *a:firstline* *a:lastline*
- When the [range] argument is added, the function is
- expected to take care of a range itself. The range is
- passed as "a:firstline" and "a:lastline". If [range]
- is excluded, ":{range}call" will call the function for
- each line in the range, with the cursor on the start
- of each line. See |function-range-example|.
- The cursor is still moved to the first line of the
- range, as is the case with all Ex commands.
- *:func-abort*
- When the [abort] argument is added, the function will
- abort as soon as an error is detected.
- *:func-dict*
- When the [dict] argument is added, the function must
- be invoked through an entry in a |Dictionary|. The
- local variable "self" will then be set to the
- dictionary. See |Dictionary-function|.
- *:func-closure* *E932*
- When the [closure] argument is added, the function
- can access variables and arguments from the outer
- scope. This is usually called a closure. In this
- example Bar() uses "x" from the scope of Foo(). It
- remains referenced even after Foo() returns: >
- :function! Foo()
- : let x = 0
- : function! Bar() closure
- : let x += 1
- : return x
- : endfunction
- : return funcref('Bar')
- :endfunction
-
- :let F = Foo()
- :echo F()
-< 1 >
- :echo F()
-< 2 >
- :echo F()
-< 3
-
- *function-search-undo*
- The last used search pattern and the redo command "."
- will not be changed by the function. This also
- implies that the effect of |:nohlsearch| is undone
- when the function returns.
-
- *:endf* *:endfunction* *E126* *E193* *W22*
-:endf[unction] [argument]
- The end of a function definition. Best is to put it
- on a line by its own, without [argument].
-
- [argument] can be:
- | command command to execute next
- \n command command to execute next
- " comment always ignored
- anything else ignored, warning given when
- 'verbose' is non-zero
- The support for a following command was added in Vim
- 8.0.0654, before that any argument was silently
- ignored.
-
- To be able to define a function inside an `:execute`
- command, use line breaks instead of |:bar|: >
- :exe "func Foo()\necho 'foo'\nendfunc"
-<
- *:delf* *:delfunction* *E131* *E933*
-:delf[unction][!] {name}
- Delete function {name}.
- {name} can also be a |Dictionary| entry that is a
- |Funcref|: >
- :delfunc dict.init
-< This will remove the "init" entry from "dict". The
- function is deleted if there are no more references to
- it.
- With the ! there is no error if the function does not
- exist.
- *:retu* *:return* *E133*
-:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
- evaluated and returned as the result of the function.
- If "[expr]" is not given, the number 0 is returned.
- When a function ends without an explicit ":return",
- the number 0 is returned.
- Note that there is no check for unreachable lines,
- thus there is no warning if commands follow ":return".
-
- If the ":return" is used after a |:try| but before the
- matching |:finally| (if present), the commands
- following the ":finally" up to the matching |:endtry|
- are executed first. This process applies to all
- nested ":try"s inside the function. The function
- returns at the outermost ":endtry".
-
- *function-argument* *a:var*
-An argument can be defined by giving its name. In the function this can then
-be used as "a:name" ("a:" for argument).
- *a:0* *a:1* *a:000* *E740* *...*
-Up to 20 arguments can be given, separated by commas. After the named
-arguments an argument "..." can be specified, which means that more arguments
-may optionally be following. In the function the extra arguments can be used
-as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
-can be 0). "a:000" is set to a |List| that contains these arguments. Note
-that "a:1" is the same as "a:000[0]".
- *E742*
-The a: scope and the variables in it cannot be changed, they are fixed.
-However, if a composite type is used, such as |List| or |Dictionary| , you can
-change their contents. Thus you can pass a |List| to a function and have the
-function add an item to it. If you want to make sure the function cannot
-change a |List| or |Dictionary| use |:lockvar|.
-
-It is also possible to define a function without any arguments. You must
-still supply the () then.
-
-It is allowed to define another function inside a function body.
-
- *optional-function-argument*
-You can provide default values for positional named arguments. This makes
-them optional for function calls. When a positional argument is not
-specified at a call, the default expression is used to initialize it.
-This only works for functions declared with |function|, not for
-lambda expressions |expr-lambda|.
-
-Example: >
- function Something(key, value = 10)
- echo a:key .. ": " .. a:value
- endfunction
- call Something('empty') "empty: 10"
- call Something('key', 20) "key: 20"
-
-The argument default expressions are evaluated at the time of the function
-call, not definition. Thus it is possible to use an expression which is
-invalid the moment the function is defined. The expressions are also only
-evaluated when arguments are not specified during a call.
-
- *E989*
-Optional arguments with default expressions must occur after any mandatory
-arguments. You can use "..." after all optional named arguments.
-
-It is possible for later argument defaults to refer to prior arguments,
-but not the other way around. They must be prefixed with "a:", as with all
-arguments.
-
-Example that works: >
- :function Okay(mandatory, optional = a:mandatory)
- :endfunction
-Example that does NOT work: >
- :function NoGood(first = a:second, second = 10)
- :endfunction
-<
-When not using "...", the number of arguments in a function call must be at
-least equal to the number of mandatory named arguments. When using "...", the
-number of arguments may be larger than the total of mandatory and optional
-arguments.
-
- *local-variables*
-Inside a function local variables can be used. These will disappear when the
-function returns. Global variables need to be accessed with "g:".
-
-Example: >
- :function Table(title, ...)
- : echohl Title
- : echo a:title
- : echohl None
- : echo a:0 .. " items:"
- : for s in a:000
- : echon ' ' .. s
- : endfor
- :endfunction
-
-This function can then be called with: >
- call Table("Table", "line1", "line2")
- call Table("Empty Table")
-
-To return more than one value, return a |List|: >
- :function Compute(n1, n2)
- : if a:n2 == 0
- : return ["fail", 0]
- : endif
- : return ["ok", a:n1 / a:n2]
- :endfunction
-
-This function can then be called with: >
- :let [success, div] = Compute(102, 6)
- :if success == "ok"
- : echo div
- :endif
-<
- *:cal* *:call* *E107* *E117*
-:[range]cal[l] {name}([arguments])
- Call a function. The name of the function and its arguments
- are as specified with `:function`. Up to 20 arguments can be
- used. The returned value is discarded.
- Without a range and for functions that accept a range, the
- function is called once. When a range is given the cursor is
- positioned at the start of the first line before executing the
- function.
- When a range is given and the function doesn't handle it
- itself, the function is executed for each line in the range,
- with the cursor in the first column of that line. The cursor
- is left at the last line (possibly moved by the last function
- call). The arguments are re-evaluated for each line. Thus
- this works:
- *function-range-example* >
- :function Mynumber(arg)
- : echo line(".") .. " " .. a:arg
- :endfunction
- :1,5call Mynumber(getline("."))
-<
- The "a:firstline" and "a:lastline" are defined anyway, they
- can be used to do something different at the start or end of
- the range.
-
- Example of a function that handles the range itself: >
-
- :function Cont() range
- : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ '
- :endfunction
- :4,8call Cont()
-<
- This function inserts the continuation character "\" in front
- of all the lines in the range, except the first one.
-
- When the function returns a composite value it can be further
- dereferenced, but the range will not be used then. Example: >
- :4,8call GetDict().method()
-< Here GetDict() gets the range but method() does not.
-
- *E132*
-The recursiveness of user functions is restricted with the |'maxfuncdepth'|
-option.
-
-It is also possible to use `:eval`. It does not support a range, but does
-allow for method chaining, e.g.: >
- eval GetList()->Filter()->append('$')
-
-
-AUTOMATICALLY LOADING FUNCTIONS ~
- *autoload-functions*
-When using many or large functions, it's possible to automatically define them
-only when they are used. There are two methods: with an autocommand and with
-the "autoload" directory in 'runtimepath'.
-
-
-Using an autocommand ~
-
-This is introduced in the user manual, section |41.14|.
-
-The autocommand is useful if you have a plugin that is a long Vim script file.
-You can define the autocommand and quickly quit the script with `:finish`.
-That makes Vim startup faster. The autocommand should then load the same file
-again, setting a variable to skip the `:finish` command.
-
-Use the FuncUndefined autocommand event with a pattern that matches the
-function(s) to be defined. Example: >
-
- :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
-
-The file "~/vim/bufnetfuncs.vim" should then define functions that start with
-"BufNet". Also see |FuncUndefined|.
-
-
-Using an autoload script ~
- *autoload* *E746*
-This is introduced in the user manual, section |41.15|.
-
-Using a script in the "autoload" directory is simpler, but requires using
-exactly the right file name. A function that can be autoloaded has a name
-like this: >
-
- :call filename#funcname()
-
-When such a function is called, and it is not defined yet, Vim will search the
-"autoload" directories in 'runtimepath' for a script file called
-"filename.vim". For example "~/.config/nvim/autoload/filename.vim". That
-file should then define the function like this: >
-
- function filename#funcname()
- echo "Done!"
- endfunction
-
-The file name and the name used before the # in the function must match
-exactly, and the defined function must have the name exactly as it will be
-called.
-
-It is possible to use subdirectories. Every # in the function name works like
-a path separator. Thus when calling a function: >
-
- :call foo#bar#func()
-
-Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
-
-This also works when reading a variable that has not been set yet: >
-
- :let l = foo#bar#lvar
-
-However, when the autoload script was already loaded it won't be loaded again
-for an unknown variable.
-
-When assigning a value to such a variable nothing special happens. This can
-be used to pass settings to the autoload script before it's loaded: >
-
- :let foo#bar#toggle = 1
- :call foo#bar#func()
-
-Note that when you make a mistake and call a function that is supposed to be
-defined in an autoload script, but the script doesn't actually define the
-function, you will get an error message for the missing function. If you fix
-the autoload script it won't be automatically loaded again. Either restart
-Vim or manually source the script.
+functions. The function takes arguments, executes a sequence of Ex commands
+and can return a value.
-Also note that if you have two script files, and one calls a function in the
-other and vice versa, before the used function is defined, it won't work.
-Avoid using the autoload functionality at the toplevel.
+You can find most information about defining functions in |userfunc.txt|.
==============================================================================
6. Curly braces names *curly-braces-names*
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt
index 7fff74a963..9f8ef248f8 100644
--- a/runtime/doc/filetype.txt
+++ b/runtime/doc/filetype.txt
@@ -586,12 +586,12 @@ Local mappings:
to the end of the file in Normal mode. This means "> " is inserted in
each line.
-MAN *ft-man-plugin* *:Man* *man.vim*
+MAN *ft-man-plugin* *:Man* *man.lua*
View manpages in Nvim. Supports highlighting, completion, locales, and
navigation. Also see |find-manpage|.
-man.vim will always attempt to reuse the closest man window (above/left) but
+man.lua will always attempt to reuse the closest man window (above/left) but
otherwise create a split.
The case sensitivity of completion is controlled by 'fileignorecase'.
diff --git a/runtime/doc/help.txt b/runtime/doc/help.txt
index 04e31e0680..34213f7512 100644
--- a/runtime/doc/help.txt
+++ b/runtime/doc/help.txt
@@ -131,6 +131,7 @@ Advanced editing ~
|autocmd.txt| automatically executing commands on an event
|eval.txt| expression evaluation, conditional commands
|builtin.txt| builtin functions
+|userfunc.txt| defining user functions
|fold.txt| hide (fold) ranges of lines
|lua.txt| Lua API
|api.txt| Nvim API via RPC, Lua and VimL
diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt
index 3393a1a1fd..00aaf759e2 100644
--- a/runtime/doc/lsp.txt
+++ b/runtime/doc/lsp.txt
@@ -1136,6 +1136,11 @@ format({options}) *vim.lsp.buf.format()*
ID (client.id) matching this field.
• name (string|nil): Restrict formatting to the client with
name (client.name) matching this field.
+ • range (table|nil) Range to format. Table must contain
+ `start` and `end` keys with {row, col} tuples using (1,0)
+ indexing. Defaults to current selection in visual mode
+ Defaults to `nil` in other modes, formatting the full
+ buffer
formatting({options}) *vim.lsp.buf.formatting()*
Formats the current buffer.
@@ -1957,8 +1962,9 @@ rpc_response_error({code}, {message}, {data})
*vim.lsp.rpc.start()*
start({cmd}, {cmd_args}, {dispatchers}, {extra_spawn_params})
Starts an LSP server process and create an LSP RPC client object to
- interact with it. Communication with the server is currently limited to
- stdio.
+ interact with it. Communication with the spawned process happens via
+ stdio. For communication via TCP, spawn a process manually and use
+ |vim.lsp.rpc.connect|
Parameters: ~
{cmd} (string) Command to start the LSP server.
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt
index a634cc1e93..35badb13b1 100644
--- a/runtime/doc/lua.txt
+++ b/runtime/doc/lua.txt
@@ -1581,6 +1581,28 @@ deepcopy({orig}) *vim.deepcopy()*
Return: ~
(table) Table of copied keys and (nested) values.
+defaulttable({create}) *vim.defaulttable()*
+ Creates a table whose members are automatically created when accessed, if
+ they don't already exist.
+
+ They mimic defaultdict in python.
+
+ If `create` is `nil`, this will create a defaulttable whose constructor
+ function is this function, effectively allowing to create nested tables on
+ the fly:
+>
+
+ local a = vim.defaulttable()
+ a.b.c = 1
+<
+
+ Parameters: ~
+ {create} (function|nil) The function called to create a missing
+ value.
+
+ Return: ~
+ (table) Empty table with metamethod
+
endswith({s}, {suffix}) *vim.endswith()*
Tests if `s` ends with `suffix`.
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt
index 9e396dd3e8..110f7400e6 100644
--- a/runtime/doc/options.txt
+++ b/runtime/doc/options.txt
@@ -4231,6 +4231,15 @@ A jump table for the options with a short description can be found at |Q_op|.
The 'mousemodel' option is set by the |:behave| command.
+ *'mousemoveevent'* *'mousemev'*
+'mousemoveevent' 'mousemev' boolean (default off)
+ global
+ When on, mouse move events are delivered to the input queue and are
+ available for mapping. The default, off, avoids the mouse movement
+ overhead except when needed.
+ Warning: Setting this option can make pending mappings to be aborted
+ when the mouse is moved.
+
*'mousescroll'*
'mousescroll' string (default "ver:3,hor:6")
global
@@ -5862,10 +5871,14 @@ A jump table for the options with a short description can be found at |Q_op|.
'spelloptions' 'spo' string (default "")
local to buffer
A comma-separated list of options for spell checking:
- camel When a word is CamelCased, assume "Cased" is a
+ camel When a word is CamelCased, assume "Cased" is a
separate word: every upper-case character in a word
that comes after a lower case character indicates the
start of a new word.
+ noplainbuffer Only spellcheck a buffer when 'syntax' is enabled,
+ or when extmarks are set within the buffer. Only
+ designated regions of the buffer are spellchecked in
+ this case.
*'spellsuggest'* *'sps'*
'spellsuggest' 'sps' string (default "best")
diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt
index 6f16db5cc2..9f3993506a 100644
--- a/runtime/doc/quickref.txt
+++ b/runtime/doc/quickref.txt
@@ -649,6 +649,7 @@ Short explanation of each option: *option-list*
'complete' 'cpt' specify how Insert mode completion works
'completefunc' 'cfu' function to be used for Insert mode completion
'completeopt' 'cot' options for Insert mode completion
+'completeslash' 'csl' like 'shellslash' for completion
'concealcursor' 'cocu' whether concealable text is hidden in cursor line
'conceallevel' 'cole' whether concealable text is shown or hidden
'confirm' 'cf' ask what to do about unsaved/read-only files
diff --git a/runtime/doc/tagsrch.txt b/runtime/doc/tagsrch.txt
index 2485290667..82deb0fa0c 100644
--- a/runtime/doc/tagsrch.txt
+++ b/runtime/doc/tagsrch.txt
@@ -870,13 +870,15 @@ like |CTRL-]|.
The function used for generating the taglist is specified by setting the
'tagfunc' option. The function will be called with three arguments:
- a:pattern The tag identifier or pattern used during the tag search.
- a:flags String containing flags to control the function behavior.
- a:info Dict containing the following entries:
+ pattern The tag identifier or pattern used during the tag search.
+ flags String containing flags to control the function behavior.
+ info Dict containing the following entries:
buf_ffname Full filename which can be used for priority.
user_data Custom data String, if stored in the tag
stack previously by tagfunc.
+Note that "a:" needs to be prepended to the argument name when using it.
+
Currently up to three flags may be passed to the tag function:
'c' The function was invoked by a normal command being processed
(mnemonic: the tag function may use the context around the
diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt
index 2c6c9e4ed8..0a48b435b6 100644
--- a/runtime/doc/treesitter.txt
+++ b/runtime/doc/treesitter.txt
@@ -187,6 +187,11 @@ Note: The predicates listed in the web page above differ from those Neovim
supports. See |lua-treesitter-predicates| for a complete list of predicates
supported by Neovim.
+By default, the first query on `runtimepath` is used (which usually implies
+that user config takes precedence over plugins, which take precedence over
+queries bundled with Neovim). If a query should extend other queries instead
+of replacing them, use the `; extends` modeline below.
+
A `query` consists of one or more patterns. A `pattern` is defined over node
types in the syntax tree. A `match` corresponds to specific elements of the
syntax tree which match a pattern. Patterns may optionally define captures
@@ -194,6 +199,32 @@ and predicates. A `capture` allows you to associate names with a specific
node in a pattern. A `predicate` adds arbitrary metadata and conditional data
to a match.
+Neovim supports to customize the behavior of the queries using a set of
+"modelines", that is comments in the queries starting with `;`. Here are the
+currently supported modeline alternatives:
+
+ `inherits: {lang}...`
+ Specifies that this query should inherit the queries from {lang}.
+ This will recursively descend in the queries of {lang} unless wrapped
+ in parentheses: `({lang})`.
+
+ `extends`
+ Specifies that this query should be used as an extension for the
+ query, i.e. that it should be merged with the others.
+ Note: the order of the extensions, and the query that will be used as
+ a base depends on your 'runtimepath' value.
+
+Note: these modeline comments must be at the top of the query, but can be
+repeated, for example, the following modeline blocks are all valid:
+>
+ ;; inherits: foo,bar
+ ;; extends
+
+ ;; extends
+ ;;
+ ;; inherits: baz
+<
+
Treesitter Query Predicates *lua-treesitter-predicates*
When writing queries for treesitter, one might use `predicates`, that is,
@@ -370,17 +401,50 @@ attribute: >
==============================================================================
Lua module: vim.treesitter *lua-treesitter-core*
+get_captures_at_cursor({winnr}) *get_captures_at_cursor()*
+ Gets a list of captures under the cursor
+
+ Parameters: ~
+ {winnr} (number|nil) Window handle or 0 for current window (default)
+
+ Return: ~
+ (table) Named node under the cursor
+
*get_captures_at_position()*
get_captures_at_position({bufnr}, {row}, {col})
Gets a list of captures for a given cursor position
Parameters: ~
- {bufnr} (number) The buffer number
- {row} (number) The position row
- {col} (number) The position column
+ {bufnr} (number) Buffer number (0 for current buffer)
+ {row} (number) Position row
+ {col} (number) Position column
Return: ~
- (table) A table of captures
+ (table) Table of captures
+
+get_node_at_cursor({winnr}) *get_node_at_cursor()*
+ Gets the smallest named node under the cursor
+
+ Parameters: ~
+ {winnr} (number|nil) Window handle or 0 for current window (default)
+
+ Return: ~
+ (string) Named node under the cursor
+
+ *get_node_at_position()*
+get_node_at_position({bufnr}, {row}, {col}, {opts})
+ Gets the smallest named node at position
+
+ Parameters: ~
+ {bufnr} (number) Buffer number (0 for current buffer)
+ {row} (number) Position row
+ {col} (number) Position column
+ {opts} (table) Optional keyword arguments:
+ • ignore_injections boolean Ignore injected languages
+ (default true)
+
+ Return: ~
+ (table) Named node under the cursor
get_node_range({node_or_range}) *get_node_range()*
Get the node's range or unpack a range table
@@ -389,7 +453,7 @@ get_node_range({node_or_range}) *get_node_range()*
{node_or_range} (table)
Return: ~
- start_row, start_col, end_row, end_col
+ (table) start_row, start_col, end_row, end_col
get_parser({bufnr}, {lang}, {opts}) *get_parser()*
Gets the parser for this bufnr / ft combination.
@@ -398,12 +462,14 @@ get_parser({bufnr}, {lang}, {opts}) *get_parser()*
callback
Parameters: ~
- {bufnr} The buffer the parser should be tied to
- {lang} The filetype of this parser
- {opts} Options object to pass to the created language tree
+ {bufnr} (number|nil) Buffer the parser should be tied to (default:
+ current buffer)
+ {lang} (string) |nil Filetype of this parser (default: buffer
+ filetype)
+ {opts} (table|nil) Options to pass to the created language tree
Return: ~
- The parser
+ (table) Parser object
get_string_parser({str}, {lang}, {opts}) *get_string_parser()*
Gets a string parser
@@ -417,8 +483,8 @@ is_ancestor({dest}, {source}) *is_ancestor()*
Determines whether a node is the ancestor of another
Parameters: ~
- {dest} (table) the possible ancestor
- {source} (table) the possible descendant node
+ {dest} (table) Possible ancestor
+ {source} (table) Possible descendant node
Return: ~
(boolean) True if dest is an ancestor of source
@@ -427,20 +493,56 @@ is_in_node_range({node}, {line}, {col}) *is_in_node_range()*
Determines whether (line, col) position is in node range
Parameters: ~
- {node} Node defining the range
- {line} A line (0-based)
- {col} A column (0-based)
+ {node} (table) Node defining the range
+ {line} (number) Line (0-based)
+ {col} (number) Column (0-based)
+
+ Return: ~
+ (boolean) True if the position is in node range
node_contains({node}, {range}) *node_contains()*
Determines if a node contains a range
Parameters: ~
- {node} (table) The node
- {range} (table) The range
+ {node} (table)
+ {range} (table)
Return: ~
(boolean) True if the node contains the range
+start({bufnr}, {lang}) *start()*
+ Start treesitter highlighting for a buffer
+
+ Can be used in an ftplugin or FileType autocommand
+
+ Note: By default, disables regex syntax highlighting, which may be
+ required for some plugins. In this case, add `vim.bo.syntax = 'on'` after
+ the call to `start`.
+
+ Example:
+>
+
+ vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
+ callback = function(args)
+ vim.treesitter.start(args.buf, 'latex')
+ vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed
+ end
+ })
+<
+
+ Parameters: ~
+ {bufnr} (number|nil) Buffer to be highlighted (default: current
+ buffer)
+ {lang} (string|nil) Language of the parser (default: buffer
+ filetype)
+
+stop({bufnr}) *stop()*
+ Stop treesitter highlighting for a buffer
+
+ Parameters: ~
+ {bufnr} (number|nil) Buffer to stop highlighting (default: current
+ buffer)
+
==============================================================================
Lua module: vim.treesitter.language *treesitter-language*
diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt
index 3fb9ed1125..955af84679 100644
--- a/runtime/doc/ui.txt
+++ b/runtime/doc/ui.txt
@@ -207,6 +207,7 @@ the editor.
'guifontwide'
'linespace'
'mousefocus'
+ 'mousemoveevent'
'pumblend'
'showtabline'
'termguicolors'
diff --git a/runtime/doc/userfunc.txt b/runtime/doc/userfunc.txt
new file mode 100644
index 0000000000..c701834383
--- /dev/null
+++ b/runtime/doc/userfunc.txt
@@ -0,0 +1,429 @@
+*userfunc.txt* Nvim
+
+
+ VIM REFERENCE MANUAL by Bram Moolenaar
+
+
+Defining and using functions.
+
+This is introduced in section |41.7| of the user manual.
+
+ Type |gO| to see the table of contents.
+
+==============================================================================
+
+1. Defining a fuction ~
+ *define-function*
+New functions can be defined. These can be called just like builtin
+functions. The function executes a sequence of Ex commands. Normal mode
+commands can be executed with the |:normal| command.
+
+The function name must start with an uppercase letter, to avoid confusion with
+builtin functions. To prevent from using the same name in different scripts
+make them script-local. If you do use a global function then avoid obvious,
+short names. A good habit is to start the function name with the name of the
+script, e.g., "HTMLcolor()".
+
+It is also possible to use curly braces, see |curly-braces-names|.
+
+The |autoload| facility is useful to define a function only when it's called.
+
+ *local-function*
+A function local to a script must start with "s:". A local script function
+can only be called from within the script and from functions, user commands
+and autocommands defined in the script. It is also possible to call the
+function from a mapping defined in the script, but then |<SID>| must be used
+instead of "s:" when the mapping is expanded outside of the script.
+There are only script-local functions, no buffer-local or window-local
+functions.
+
+ *:fu* *:function* *E128* *E129* *E123*
+:fu[nction] List all functions and their arguments.
+
+:fu[nction][!] {name} List function {name}, annotated with line numbers
+ unless "!" is given.
+ {name} may be a |Dictionary| |Funcref| entry: >
+ :function dict.init
+
+:fu[nction] /{pattern} List functions with a name matching {pattern}.
+ Example that lists all functions ending with "File": >
+ :function /File$
+<
+ *:function-verbose*
+When 'verbose' is non-zero, listing a function will also display where it was
+last defined. Example: >
+
+ :verbose function SetFileTypeSH
+ function SetFileTypeSH(name)
+ Last set from /usr/share/vim/vim-7.0/filetype.vim
+<
+See |:verbose-cmd| for more information.
+
+ *E124* *E125* *E853* *E884*
+:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
+ Define a new function by the name {name}. The body of
+ the function follows in the next lines, until the
+ matching |:endfunction|.
+
+ The name must be made of alphanumeric characters and
+ '_', and must start with a capital or "s:" (see
+ above). Note that using "b:" or "g:" is not allowed.
+ (since patch 7.4.260 E884 is given if the function
+ name has a colon in the name, e.g. for "foo:bar()".
+ Before that patch no error was given).
+
+ {name} can also be a |Dictionary| entry that is a
+ |Funcref|: >
+ :function dict.init(arg)
+< "dict" must be an existing dictionary. The entry
+ "init" is added if it didn't exist yet. Otherwise [!]
+ is required to overwrite an existing function. The
+ result is a |Funcref| to a numbered function. The
+ function can only be used with a |Funcref| and will be
+ deleted if there are no more references to it.
+ *E127* *E122*
+ When a function by this name already exists and [!] is
+ not used an error message is given. There is one
+ exception: When sourcing a script again, a function
+ that was previously defined in that script will be
+ silently replaced.
+ When [!] is used, an existing function is silently
+ replaced. Unless it is currently being executed, that
+ is an error.
+ NOTE: Use ! wisely. If used without care it can cause
+ an existing function to be replaced unexpectedly,
+ which is hard to debug.
+
+ For the {arguments} see |function-argument|.
+
+ *:func-range* *a:firstline* *a:lastline*
+ When the [range] argument is added, the function is
+ expected to take care of a range itself. The range is
+ passed as "a:firstline" and "a:lastline". If [range]
+ is excluded, ":{range}call" will call the function for
+ each line in the range, with the cursor on the start
+ of each line. See |function-range-example|.
+ The cursor is still moved to the first line of the
+ range, as is the case with all Ex commands.
+ *:func-abort*
+ When the [abort] argument is added, the function will
+ abort as soon as an error is detected.
+ *:func-dict*
+ When the [dict] argument is added, the function must
+ be invoked through an entry in a |Dictionary|. The
+ local variable "self" will then be set to the
+ dictionary. See |Dictionary-function|.
+ *:func-closure* *E932*
+ When the [closure] argument is added, the function
+ can access variables and arguments from the outer
+ scope. This is usually called a closure. In this
+ example Bar() uses "x" from the scope of Foo(). It
+ remains referenced even after Foo() returns: >
+ :function! Foo()
+ : let x = 0
+ : function! Bar() closure
+ : let x += 1
+ : return x
+ : endfunction
+ : return funcref('Bar')
+ :endfunction
+
+ :let F = Foo()
+ :echo F()
+< 1 >
+ :echo F()
+< 2 >
+ :echo F()
+< 3
+
+ *function-search-undo*
+ The last used search pattern and the redo command "."
+ will not be changed by the function. This also
+ implies that the effect of |:nohlsearch| is undone
+ when the function returns.
+
+ *:endf* *:endfunction* *E126* *E193* *W22*
+:endf[unction] [argument]
+ The end of a function definition. Best is to put it
+ on a line by its own, without [argument].
+
+ [argument] can be:
+ | command command to execute next
+ \n command command to execute next
+ " comment always ignored
+ anything else ignored, warning given when
+ 'verbose' is non-zero
+ The support for a following command was added in Vim
+ 8.0.0654, before that any argument was silently
+ ignored.
+
+ To be able to define a function inside an `:execute`
+ command, use line breaks instead of |:bar|: >
+ :exe "func Foo()\necho 'foo'\nendfunc"
+<
+ *:delf* *:delfunction* *E131* *E933*
+:delf[unction][!] {name}
+ Delete function {name}.
+ {name} can also be a |Dictionary| entry that is a
+ |Funcref|: >
+ :delfunc dict.init
+< This will remove the "init" entry from "dict". The
+ function is deleted if there are no more references to
+ it.
+ With the ! there is no error if the function does not
+ exist.
+ *:retu* *:return* *E133*
+:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
+ evaluated and returned as the result of the function.
+ If "[expr]" is not given, the number 0 is returned.
+ When a function ends without an explicit ":return",
+ the number 0 is returned.
+ Note that there is no check for unreachable lines,
+ thus there is no warning if commands follow ":return".
+
+ If the ":return" is used after a |:try| but before the
+ matching |:finally| (if present), the commands
+ following the ":finally" up to the matching |:endtry|
+ are executed first. This process applies to all
+ nested ":try"s inside the function. The function
+ returns at the outermost ":endtry".
+
+ *function-argument* *a:var*
+An argument can be defined by giving its name. In the function this can then
+be used as "a:name" ("a:" for argument).
+ *a:0* *a:1* *a:000* *E740* *...*
+Up to 20 arguments can be given, separated by commas. After the named
+arguments an argument "..." can be specified, which means that more arguments
+may optionally be following. In the function the extra arguments can be used
+as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
+can be 0). "a:000" is set to a |List| that contains these arguments. Note
+that "a:1" is the same as "a:000[0]".
+ *E742*
+The a: scope and the variables in it cannot be changed, they are fixed.
+However, if a composite type is used, such as |List| or |Dictionary| , you can
+change their contents. Thus you can pass a |List| to a function and have the
+function add an item to it. If you want to make sure the function cannot
+change a |List| or |Dictionary| use |:lockvar|.
+
+It is also possible to define a function without any arguments. You must
+still supply the () then.
+
+It is allowed to define another function inside a function body.
+
+ *optional-function-argument*
+You can provide default values for positional named arguments. This makes
+them optional for function calls. When a positional argument is not
+specified at a call, the default expression is used to initialize it.
+This only works for functions declared with |function|, not for
+lambda expressions |expr-lambda|.
+
+Example: >
+ function Something(key, value = 10)
+ echo a:key .. ": " .. a:value
+ endfunction
+ call Something('empty') "empty: 10"
+ call Something('key', 20) "key: 20"
+
+The argument default expressions are evaluated at the time of the function
+call, not definition. Thus it is possible to use an expression which is
+invalid the moment the function is defined. The expressions are also only
+evaluated when arguments are not specified during a call.
+
+ *E989*
+Optional arguments with default expressions must occur after any mandatory
+arguments. You can use "..." after all optional named arguments.
+
+It is possible for later argument defaults to refer to prior arguments,
+but not the other way around. They must be prefixed with "a:", as with all
+arguments.
+
+Example that works: >
+ :function Okay(mandatory, optional = a:mandatory)
+ :endfunction
+Example that does NOT work: >
+ :function NoGood(first = a:second, second = 10)
+ :endfunction
+<
+When not using "...", the number of arguments in a function call must be at
+least equal to the number of mandatory named arguments. When using "...", the
+number of arguments may be larger than the total of mandatory and optional
+arguments.
+
+ *local-variables*
+Inside a function local variables can be used. These will disappear when the
+function returns. Global variables need to be accessed with "g:". Inside
+functions local variables are accessed without prepending anything. But you
+can also prepend "l:" if you like. This is required for some reserved names,
+such as "version".
+
+Example: >
+ :function Table(title, ...)
+ : echohl Title
+ : echo a:title
+ : echohl None
+ : echo a:0 .. " items:"
+ : for s in a:000
+ : echon ' ' .. s
+ : endfor
+ :endfunction
+
+This function can then be called with: >
+ call Table("Table", "line1", "line2")
+ call Table("Empty Table")
+
+To return more than one value, return a |List|: >
+ :function Compute(n1, n2)
+ : if a:n2 == 0
+ : return ["fail", 0]
+ : endif
+ : return ["ok", a:n1 / a:n2]
+ :endfunction
+
+This function can then be called with: >
+ :let [success, div] = Compute(102, 6)
+ :if success == "ok"
+ : echo div
+ :endif
+<
+==============================================================================
+
+2. Calling a fuction ~
+ *:cal* *:call* *E107* *E117*
+:[range]cal[l] {name}([arguments])
+ Call a function. The name of the function and its arguments
+ are as specified with `:function`. Up to 20 arguments can be
+ used. The returned value is discarded.
+ Without a range and for functions that accept a range, the
+ function is called once. When a range is given the cursor is
+ positioned at the start of the first line before executing the
+ function.
+ When a range is given and the function doesn't handle it
+ itself, the function is executed for each line in the range,
+ with the cursor in the first column of that line. The cursor
+ is left at the last line (possibly moved by the last function
+ call). The arguments are re-evaluated for each line. Thus
+ this works:
+ *function-range-example* >
+ :function Mynumber(arg)
+ : echo line(".") .. " " .. a:arg
+ :endfunction
+ :1,5call Mynumber(getline("."))
+<
+ The "a:firstline" and "a:lastline" are defined anyway, they
+ can be used to do something different at the start or end of
+ the range.
+
+ Example of a function that handles the range itself: >
+
+ :function Cont() range
+ : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ '
+ :endfunction
+ :4,8call Cont()
+<
+ This function inserts the continuation character "\" in front
+ of all the lines in the range, except the first one.
+
+ When the function returns a composite value it can be further
+ dereferenced, but the range will not be used then. Example: >
+ :4,8call GetDict().method()
+< Here GetDict() gets the range but method() does not.
+
+ *E132*
+The recursiveness of user functions is restricted with the |'maxfuncdepth'|
+option.
+
+It is also possible to use `:eval`. It does not support a range, but does
+allow for method chaining, e.g.: >
+ eval GetList()->Filter()->append('$')
+
+A function can also be called as part of evaluating an expression or when it
+is used as a method: >
+ let x = GetList()
+ let y = GetList()->Filter()
+
+
+==============================================================================
+
+3. Automatically loading functions ~
+ *autoload-functions*
+When using many or large functions, it's possible to automatically define them
+only when they are used. There are two methods: with an autocommand and with
+the "autoload" directory in 'runtimepath'.
+
+
+Using an autocommand ~
+
+This is introduced in the user manual, section |41.14|.
+
+The autocommand is useful if you have a plugin that is a long Vim script file.
+You can define the autocommand and quickly quit the script with `:finish`.
+That makes Vim startup faster. The autocommand should then load the same file
+again, setting a variable to skip the `:finish` command.
+
+Use the FuncUndefined autocommand event with a pattern that matches the
+function(s) to be defined. Example: >
+
+ :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
+
+The file "~/vim/bufnetfuncs.vim" should then define functions that start with
+"BufNet". Also see |FuncUndefined|.
+
+
+Using an autoload script ~
+ *autoload* *E746*
+This is introduced in the user manual, section |41.15|.
+
+Using a script in the "autoload" directory is simpler, but requires using
+exactly the right file name. A function that can be autoloaded has a name
+like this: >
+
+ :call filename#funcname()
+
+When such a function is called, and it is not defined yet, Vim will search the
+"autoload" directories in 'runtimepath' for a script file called
+"filename.vim". For example "~/.config/nvim/autoload/filename.vim". That
+file should then define the function like this: >
+
+ function filename#funcname()
+ echo "Done!"
+ endfunction
+
+The file name and the name used before the # in the function must match
+exactly, and the defined function must have the name exactly as it will be
+called.
+
+It is possible to use subdirectories. Every # in the function name works like
+a path separator. Thus when calling a function: >
+
+ :call foo#bar#func()
+
+Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
+
+This also works when reading a variable that has not been set yet: >
+
+ :let l = foo#bar#lvar
+
+However, when the autoload script was already loaded it won't be loaded again
+for an unknown variable.
+
+When assigning a value to such a variable nothing special happens. This can
+be used to pass settings to the autoload script before it's loaded: >
+
+ :let foo#bar#toggle = 1
+ :call foo#bar#func()
+
+Note that when you make a mistake and call a function that is supposed to be
+defined in an autoload script, but the script doesn't actually define the
+function, you will get an error message for the missing function. If you fix
+the autoload script it won't be automatically loaded again. Either restart
+Vim or manually source the script.
+
+Also note that if you have two script files, and one calls a function in the
+other and vice versa, before the used function is defined, it won't work.
+Avoid using the autoload functionality at the toplevel.
+
+Hint: If you distribute a bunch of scripts you can pack them together with the
+|vimball| utility. Also read the user manual |distribute-script|.
+
+
+ vim:tw=78:ts=8:noet:ft=help:norl:
diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt
index 76c2f8454f..ee644be366 100644
--- a/runtime/doc/usr_41.txt
+++ b/runtime/doc/usr_41.txt
@@ -745,6 +745,7 @@ Cursor and mark position: *cursor-functions* *mark-functions*
screencol() get screen column of the cursor
screenrow() get screen row of the cursor
screenpos() screen row and col of a text character
+ virtcol2col() byte index of a text character on screen
getcurpos() get position of the cursor
getpos() get position of cursor, mark, etc.
setpos() set position of cursor, mark, etc.
diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt
index 0011cd9821..b013e00fe8 100644
--- a/runtime/doc/vim_diff.txt
+++ b/runtime/doc/vim_diff.txt
@@ -73,7 +73,7 @@ centralized reference of the differences.
- 'wildmenu' is enabled
- 'wildoptions' defaults to "pum,tagfile"
-- |man.vim| plugin is enabled, so |:Man| is available by default.
+- |man.lua| plugin is enabled, so |:Man| is available by default.
- |matchit| plugin is enabled. To disable it in your config: >
:let loaded_matchit = 1
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt
index ddf4d09e92..6386e4ace1 100644
--- a/runtime/doc/windows.txt
+++ b/runtime/doc/windows.txt
@@ -236,13 +236,13 @@ and 'winminwidth' are relevant.
:vert[ical] {cmd}
Execute {cmd}. If it contains a command that splits a window,
it will be split vertically. For `vertical wincmd =` windows
- will be equialized only vertically.
+ will be equalized only vertically.
Doesn't work for |:execute| and |:normal|.
*:hor* *:horizontal*
:hor[izontal] {cmd}
Execute {cmd}. Currently only makes a difference for
- `horizontal wincmd =`, which will equal windows only
+ `horizontal wincmd =`, which will equalize windows only
horizontally.
:lefta[bove] {cmd} *:lefta* *:leftabove*
diff --git a/runtime/filetype.lua b/runtime/filetype.lua
index 9f5b5fd0dc..c50ba6453d 100644
--- a/runtime/filetype.lua
+++ b/runtime/filetype.lua
@@ -6,7 +6,7 @@ vim.g.did_load_filetypes = 1
vim.api.nvim_create_augroup('filetypedetect', { clear = false })
-vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, {
+vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile', 'StdinReadPost' }, {
group = 'filetypedetect',
callback = function(args)
local ft, on_detect = vim.filetype.match({ filename = args.match, buf = args.buf })
diff --git a/runtime/filetype.vim b/runtime/filetype.vim
index 98d9df8b5c..eb4309ed9a 100644
--- a/runtime/filetype.vim
+++ b/runtime/filetype.vim
@@ -1,7 +1,7 @@
" Vim support file to detect file types
"
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2022 Jul 5
+" Last Change: 2022 Sep 09
" Only run this if enabled
if !exists("do_legacy_filetype")
@@ -721,9 +721,16 @@ au BufNewFile,BufRead *.git/worktrees/*/config.worktree setf gitconfig
au BufNewFile,BufRead .gitmodules,*.git/modules/*/config setf gitconfig
if !empty($XDG_CONFIG_HOME)
au BufNewFile,BufRead $XDG_CONFIG_HOME/git/config setf gitconfig
+ au BufNewFile,BufRead $XDG_CONFIG_HOME/git/attributes setf gitattributes
+ au BufNewFile,BufRead $XDG_CONFIG_HOME/git/ignore setf gitignore
endif
-au BufNewFile,BufRead git-rebase-todo setf gitrebase
-au BufRead,BufNewFile .gitsendemail.msg.?????? setf gitsendemail
+au BufNewFile,BufRead .gitattributes,*.git/info/attributes setf gitattributes
+au BufNewFile,BufRead */.config/git/attributes setf gitattributes
+au BufNewFile,BufRead */etc/gitattributes setf gitattributes
+au BufNewFile,BufRead .gitignore,*.git/info/exclude setf gitignore
+au BufNewFile,BufRead */.config/git/ignore setf gitignore
+au BufNewFile,BufRead git-rebase-todo setf gitrebase
+au BufRead,BufNewFile .gitsendemail.msg.?????? setf gitsendemail
au BufNewFile,BufRead *.git/*
\ if getline(1) =~# '^\x\{40,\}\>\|^ref: ' |
\ setf git |
@@ -868,11 +875,11 @@ au BufNewFile,BufRead *.htt,*.htb setf httest
" i3
au BufNewFile,BufRead */i3/config setf i3config
-au BufNewFile,BufRead */.i3/config setf i3config
+au BufNewFile,BufRead */.i3/config setf i3config
" sway
au BufNewFile,BufRead */sway/config setf swayconfig
-au BufNewFile,BufRead */.sway/config setf swayconfig
+au BufNewFile,BufRead */.sway/config setf swayconfig
" Icon
au BufNewFile,BufRead *.icn setf icon
@@ -941,7 +948,7 @@ au BufNewFile,BufRead *.java,*.jav setf java
au BufNewFile,BufRead *.jj,*.jjt setf javacc
" JavaScript, ECMAScript, ES module script, CommonJS script
-au BufNewFile,BufRead *.js,*.javascript,*.es,*.mjs,*.cjs setf javascript
+au BufNewFile,BufRead *.js,*.jsm,*.javascript,*.es,*.mjs,*.cjs setf javascript
" JavaScript with React
au BufNewFile,BufRead *.jsx setf javascriptreact
@@ -979,6 +986,9 @@ au BufNewFile,BufRead .babelrc,.eslintrc,.prettierrc,.firebaserc setf json
" JSONC
au BufNewFile,BufRead *.jsonc setf jsonc
+" Jsonnet
+au BufNewFile,BufRead *.jsonnet,*.libjsonnet setf jsonnet
+
" Julia
au BufNewFile,BufRead *.jl setf julia
@@ -1317,7 +1327,7 @@ au BufNewFile,BufRead *.or setf openroad
au BufNewFile,BufRead *.[Oo][Pp][Ll] setf opl
" OpenSCAD
-au BufNewFile,BufRead *.scad setf openscad
+au BufNewFile,BufRead *.scad setf openscad
" Oracle config file
au BufNewFile,BufRead *.ora setf ora
@@ -1392,7 +1402,8 @@ au BufNewFile,BufRead *.pod setf pod
" Also Phtml (was used for PHP 2 in the past).
" Also .ctp for Cake template file.
" Also .phpt for php tests.
-au BufNewFile,BufRead *.php,*.php\d,*.phtml,*.ctp,*.phpt setf php
+" Also .theme for Drupal theme files.
+au BufNewFile,BufRead *.php,*.php\d,*.phtml,*.ctp,*.phpt,*.theme setf php
" PHP config
au BufNewFile,BufRead php.ini-* setf dosini
@@ -1823,7 +1834,7 @@ au BufNewFile,BufRead *.score setf slrnsc
au BufNewFile,BufRead *.st setf st
" Smalltalk (and Rexx, TeX, and Visual Basic)
-au BufNewFile,BufRead *.cls call dist#ft#FTcls()
+au BufNewFile,BufRead *.cls call dist#ft#FTcls()
" Smarty templates
au BufNewFile,BufRead *.tpl setf smarty
@@ -1930,8 +1941,8 @@ au BufNewFile,BufRead *.cm setf voscm
au BufNewFile,BufRead *.swift setf swift
au BufNewFile,BufRead *.swift.gyb setf swiftgyb
-" Swift Intermediate Language
-au BufNewFile,BufRead *.sil setf sil
+" Swift Intermediate Language or SILE
+au BufNewFile,BufRead *.sil call dist#ft#FTsil()
" Sysctl
au BufNewFile,BufRead */etc/sysctl.conf,*/etc/sysctl.d/*.conf setf sysctl
@@ -2572,6 +2583,9 @@ au BufNewFile,BufRead *.txt
\| setf text
\| endif
+" Blueprint markup files
+au BufNewFile,BufRead *.blp setf blueprint
+
if !exists('g:did_load_ftdetect')
" Use the filetype detect plugins. They may overrule any of the previously
" detected filetypes.
diff --git a/runtime/ftplugin/gitattributes.vim b/runtime/ftplugin/gitattributes.vim
new file mode 100644
index 0000000000..2025d009d2
--- /dev/null
+++ b/runtime/ftplugin/gitattributes.vim
@@ -0,0 +1,13 @@
+" Vim filetype plugin
+" Language: git attributes
+" Maintainer: ObserverOfTime <chronobserver@disroot.org>
+" Last Change: 2022 Sep 08
+
+if exists('b:did_ftplugin')
+ finish
+endif
+let b:did_ftplugin = 1
+
+setl comments=:# commentstring=#\ %s
+
+let b:undo_ftplugin = 'setl com< cms<'
diff --git a/runtime/ftplugin/gitignore.vim b/runtime/ftplugin/gitignore.vim
new file mode 100644
index 0000000000..3502dd2717
--- /dev/null
+++ b/runtime/ftplugin/gitignore.vim
@@ -0,0 +1,13 @@
+" Vim filetype plugin
+" Language: git ignore
+" Maintainer: ObserverOfTime <chronobserver@disroot.org>
+" Last Change: 2022 Sep 10
+
+if exists('b:did_ftplugin')
+ finish
+endif
+let b:did_ftplugin = 1
+
+setl comments=:# commentstring=#\ %s
+
+let b:undo_ftplugin = 'setl com< cms<'
diff --git a/runtime/ftplugin/jsonnet.vim b/runtime/ftplugin/jsonnet.vim
new file mode 100644
index 0000000000..1e621e1867
--- /dev/null
+++ b/runtime/ftplugin/jsonnet.vim
@@ -0,0 +1,17 @@
+" Vim filetype plugin
+" Language: Jsonnet
+" Maintainer: Cezary Drożak <cezary@drozak.net>
+" URL: https://github.com/google/vim-jsonnet
+" Last Change: 2022-09-08
+
+" Only do this when not done yet for this buffer
+if exists("b:did_ftplugin")
+ finish
+endif
+
+" Don't load another plugin for this buffer
+let b:did_ftplugin = 1
+
+setlocal commentstring=//\ %s
+
+let b:undo_ftplugin = "setlocal commentstring<"
diff --git a/runtime/ftplugin/lua.lua b/runtime/ftplugin/lua.lua
new file mode 100644
index 0000000000..415cf28f9a
--- /dev/null
+++ b/runtime/ftplugin/lua.lua
@@ -0,0 +1,3 @@
+if vim.g.ts_highlight_lua then
+ vim.treesitter.start()
+end
diff --git a/runtime/ftplugin/lua.vim b/runtime/ftplugin/lua.vim
index 2604257594..aaa61f71d9 100644
--- a/runtime/ftplugin/lua.vim
+++ b/runtime/ftplugin/lua.vim
@@ -1,46 +1,46 @@
" Vim filetype plugin file.
-" Language: Lua
+" Language: Lua
" Maintainer: Doug Kearns <dougkearns@gmail.com>
" Previous Maintainer: Max Ischenko <mfi@ukr.net>
-" Last Change: 2021 Nov 15
+" Contributor: Dorai Sitaram <ds26@gte.com>
+" Last Change: 2022 Sep 05
-" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
finish
endif
-
-" Don't load another plugin for this buffer
let b:did_ftplugin = 1
let s:cpo_save = &cpo
set cpo&vim
-" Set 'formatoptions' to break comment lines but not other lines, and insert
-" the comment leader when hitting <CR> or using "o".
+setlocal comments=:--
+setlocal commentstring=--\ %s
setlocal formatoptions-=t formatoptions+=croql
-setlocal comments=:--
-setlocal commentstring=--%s
+let &l:define = '\<function\|\<local\%(\s\+function\)\='
+
setlocal suffixesadd=.lua
-let b:undo_ftplugin = "setlocal fo< com< cms< sua<"
+let b:undo_ftplugin = "setlocal cms< com< def< fo< sua<"
if exists("loaded_matchit") && !exists("b:match_words")
let b:match_ignorecase = 0
let b:match_words =
- \ '\<\%(do\|function\|if\)\>:' .
- \ '\<\%(return\|else\|elseif\)\>:' .
- \ '\<end\>,' .
- \ '\<repeat\>:\<until\>,' .
- \ '\%(--\)\=\[\(=*\)\[:]\1]'
- let b:undo_ftplugin .= " | unlet! b:match_words b:match_ignorecase"
+ \ '\<\%(do\|function\|if\)\>:' ..
+ \ '\<\%(return\|else\|elseif\)\>:' ..
+ \ '\<end\>,' ..
+ \ '\<repeat\>:\<until\>,' ..
+ \ '\%(--\)\=\[\(=*\)\[:]\1]'
+ let b:undo_ftplugin ..= " | unlet! b:match_words b:match_ignorecase"
endif
if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter")
- let b:browsefilter = "Lua Source Files (*.lua)\t*.lua\n" .
- \ "All Files (*.*)\t*.*\n"
- let b:undo_ftplugin .= " | unlet! b:browsefilter"
+ let b:browsefilter = "Lua Source Files (*.lua)\t*.lua\n" ..
+ \ "All Files (*.*)\t*.*\n"
+ let b:undo_ftplugin ..= " | unlet! b:browsefilter"
endif
let &cpo = s:cpo_save
unlet s:cpo_save
+
+" vim: nowrap sw=2 sts=2 ts=8 noet:
diff --git a/runtime/ftplugin/lynx.vim b/runtime/ftplugin/lynx.vim
new file mode 100644
index 0000000000..b76c69f0ae
--- /dev/null
+++ b/runtime/ftplugin/lynx.vim
@@ -0,0 +1,29 @@
+" Vim filetype plugin file
+" Language: Lynx Web Browser Configuration
+" Maintainer: Doug Kearns <dougkearns@gmail.com>
+" Last Change: 2022 Sep 09
+
+if exists("b:did_ftplugin")
+ finish
+endif
+let b:did_ftplugin = 1
+
+let s:cpo_save = &cpo
+set cpo&vim
+
+setlocal comments=:#
+setlocal commentstring=#\ %s
+setlocal formatoptions-=t formatoptions+=croql
+
+let b:undo_ftplugin = "setl cms< com< fo<"
+
+if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter")
+ let b:browsefilter = "Lynx Configuration Files (lynx.cfg .lynxrc)\tlynx.cfg;.lynxrc\n" ..
+ \ "All Files (*.*)\t*.*\n"
+ let b:undo_ftplugin ..= " | unlet! b:browsefilter"
+endif
+
+let &cpo = s:cpo_save
+unlet s:cpo_save
+
+" vim: nowrap sw=2 sts=2 ts=8 noet:
diff --git a/runtime/ftplugin/man.vim b/runtime/ftplugin/man.vim
index d7a08a9941..277ce3c0b3 100644
--- a/runtime/ftplugin/man.vim
+++ b/runtime/ftplugin/man.vim
@@ -17,12 +17,12 @@ setlocal iskeyword=@-@,:,a-z,A-Z,48-57,_,.,-,(,)
setlocal nonumber norelativenumber
setlocal foldcolumn=0 colorcolumn=0 nolist nofoldenable
-setlocal tagfunc=man#goto_tag
+setlocal tagfunc=v:lua.require'man'.goto_tag
if !exists('g:no_plugin_maps') && !exists('g:no_man_maps')
nnoremap <silent> <buffer> j gj
nnoremap <silent> <buffer> k gk
- nnoremap <silent> <buffer> gO :call man#show_toc()<CR>
+ nnoremap <silent> <buffer> gO :lua require'man'.show_toc()<CR>
nnoremap <silent> <buffer> <2-LeftMouse> :Man<CR>
if get(b:, 'pager')
nnoremap <silent> <buffer> <nowait> q :lclose<CR><C-W>q
diff --git a/runtime/ftplugin/sh.vim b/runtime/ftplugin/sh.vim
index 93a46f63e2..b6fdb8f3e2 100644
--- a/runtime/ftplugin/sh.vim
+++ b/runtime/ftplugin/sh.vim
@@ -1,12 +1,12 @@
" Vim filetype plugin file
-" Language: sh
-"
-" This runtime file is looking for a new maintainer.
-"
-" Former maintainer: Dan Sharp
-" Last Changed: 20 Jan 2009
-
-if exists("b:did_ftplugin") | finish | endif
+" Language: sh
+" Maintainer: Doug Kearns <dougkearns@gmail.com>
+" Previous Maintainer: Dan Sharp
+" Last Change: 2022 Sep 07
+
+if exists("b:did_ftplugin")
+ finish
+endif
let b:did_ftplugin = 1
" Make sure the continuation lines below do not cause problems in
@@ -14,28 +14,35 @@ let b:did_ftplugin = 1
let s:save_cpo = &cpo
set cpo-=C
-setlocal commentstring=#%s
+setlocal comments=:#
+setlocal commentstring=#\ %s
+setlocal formatoptions-=t formatoptions+=croql
+
+let b:undo_ftplugin = "setl com< cms< fo<"
" Shell: thanks to Johannes Zellner
-if exists("loaded_matchit")
- let s:sol = '\%(;\s*\|^\s*\)\@<=' " start of line
- let b:match_words =
- \ s:sol.'if\>:' . s:sol.'elif\>:' . s:sol.'else\>:' . s:sol. 'fi\>,' .
- \ s:sol.'\%(for\|while\)\>:' . s:sol. 'done\>,' .
- \ s:sol.'case\>:' . s:sol. 'esac\>'
+if exists("loaded_matchit") && !exists("b:match_words")
+ let b:match_ignorecase = 0
+ let s:sol = '\%(;\s*\|^\s*\)\@<=' " start of line
+ let b:match_words =
+ \ s:sol .. 'if\>:' .. s:sol.'elif\>:' .. s:sol.'else\>:' .. s:sol .. 'fi\>,' ..
+ \ s:sol .. '\%(for\|while\)\>:' .. s:sol .. 'done\>,' ..
+ \ s:sol .. 'case\>:' .. s:sol .. 'esac\>'
+ unlet s:sol
+ let b:undo_ftplugin ..= " | unlet! b:match_ignorecase b:match_words"
endif
" Change the :browse e filter to primarily show shell-related files.
-if has("gui_win32")
- let b:browsefilter="Bourne Shell Scripts (*.sh)\t*.sh\n" .
- \ "Korn Shell Scripts (*.ksh)\t*.ksh\n" .
- \ "Bash Shell Scripts (*.bash)\t*.bash\n" .
- \ "All Files (*.*)\t*.*\n"
+if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter")
+ let b:browsefilter = "Bourne Shell Scripts (*.sh)\t*.sh\n" ..
+ \ "Korn Shell Scripts (*.ksh)\t*.ksh\n" ..
+ \ "Bash Shell Scripts (*.bash)\t*.bash\n" ..
+ \ "All Files (*.*)\t*.*\n"
+ let b:undo_ftplugin ..= " | unlet! b:browsefilter"
endif
-" Undo the stuff we changed.
-let b:undo_ftplugin = "setlocal cms< | unlet! b:browsefilter b:match_words"
-
" Restore the saved compatibility options.
let &cpo = s:save_cpo
unlet s:save_cpo
+
+" vim: nowrap sw=2 sts=2 ts=8 noet:
diff --git a/runtime/ftplugin/vim.vim b/runtime/ftplugin/vim.vim
index 772899cb42..82a4b13f9f 100644
--- a/runtime/ftplugin/vim.vim
+++ b/runtime/ftplugin/vim.vim
@@ -1,7 +1,7 @@
" Vim filetype plugin
" Language: Vim
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2022 Aug 4
+" Last Change: 2022 Sep 09
" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
diff --git a/runtime/ftplugin/zimbu.vim b/runtime/ftplugin/zimbu.vim
index e365ccf07e..cbe2f55572 100644
--- a/runtime/ftplugin/zimbu.vim
+++ b/runtime/ftplugin/zimbu.vim
@@ -1,7 +1,7 @@
" Vim filetype plugin file
" Language: Zimbu
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2021 Nov 12
+" Last Change: 2022 Sep 07
" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
@@ -28,7 +28,7 @@ endif
" Set 'comments' to format dashed lists in comments.
" And to keep Zudocu comment characters.
-setlocal comments=sO:#\ -,mO:#\ \ ,:#=,:#-,:#%,:#
+setlocal comments=sO:#\ -,mO:#\ \ ,exO:#/,s:/*,m:\ ,ex:*/,:#=,:#-,:#%,:#
setlocal errorformat^=%f\ line\ %l\ col\ %c:\ %m,ERROR:\ %m
diff --git a/runtime/ftplugin/zsh.vim b/runtime/ftplugin/zsh.vim
index 34410f1c62..0ca8077305 100644
--- a/runtime/ftplugin/zsh.vim
+++ b/runtime/ftplugin/zsh.vim
@@ -2,7 +2,7 @@
" Language: Zsh shell script
" Maintainer: Christian Brabandt <cb@256bit.org>
" Previous Maintainer: Nikolai Weibull <now@bitwi.se>
-" Latest Revision: 2020-09-01
+" Latest Revision: 2021-04-03
" License: Vim (see :h license)
" Repository: https://github.com/chrisbra/vim-zsh
diff --git a/runtime/indent/json.vim b/runtime/indent/json.vim
index 09c7d7a85a..510f7e8f42 100644
--- a/runtime/indent/json.vim
+++ b/runtime/indent/json.vim
@@ -3,6 +3,7 @@
" Maintainer: Eli Parra <eli@elzr.com> https://github.com/elzr/vim-json
" Last Change: 2020 Aug 30
" https://github.com/jakar/vim-json/commit/20b650e22aa750c4ab6a66aa646bdd95d7cd548a#diff-e81fc111b2052e306d126bd9989f7b7c
+" 2022 Sep 07: b:undo_indent added by Doug Kearns
" Original Author: Rogerz Zhang <rogerz.zhang at gmail.com> http://github.com/rogerz/vim-json
" Acknowledgement: Based off of vim-javascript maintained by Darrick Wiebe
" http://www.vim.org/scripts/script.php?script_id=2765
@@ -22,6 +23,8 @@ setlocal nosmartindent
setlocal indentexpr=GetJSONIndent(v:lnum)
setlocal indentkeys=0{,0},0),0[,0],!^F,o,O,e
+let b:undo_indent = "setl inde< indk< si<"
+
" Only define the function once.
if exists("*GetJSONIndent")
finish
diff --git a/runtime/indent/testdir/runtest.vim b/runtime/indent/testdir/runtest.vim
index 6bbd33cacd..fa4e16e381 100644
--- a/runtime/indent/testdir/runtest.vim
+++ b/runtime/indent/testdir/runtest.vim
@@ -11,6 +11,7 @@ syn on
set nowrapscan
set report=9999
set modeline
+set debug=throw
au! SwapExists * call HandleSwapExists()
func HandleSwapExists()
@@ -84,7 +85,12 @@ for fname in glob('testdir/*.in', 1, 1)
exe start + 1
if pattern == ''
- exe 'normal =' . (end - 1) . 'G'
+ try
+ exe 'normal =' . (end - 1) . 'G'
+ catch
+ call append(indent_at, 'ERROR: ' . v:exception)
+ let failed = 1
+ endtry
else
let lnum = search(pattern)
if lnum <= 0
@@ -99,7 +105,12 @@ for fname in glob('testdir/*.in', 1, 1)
else
exe lnum - 1
endif
- normal ==
+ try
+ normal ==
+ catch
+ call append(indent_at, 'ERROR: ' . v:exception)
+ let failed = 1
+ endtry
endif
endif
endwhile
diff --git a/runtime/indent/testdir/vim.in b/runtime/indent/testdir/vim.in
index 873045bc2c..5eb262f50a 100644
--- a/runtime/indent/testdir/vim.in
+++ b/runtime/indent/testdir/vim.in
@@ -36,6 +36,13 @@ let t = [
\ },
\ ]
+def Func()
+ var d = dd
+ ->extend({
+ })
+ eval 0
+enddef
+
" END_INDENT
" START_INDENT
diff --git a/runtime/indent/testdir/vim.ok b/runtime/indent/testdir/vim.ok
index 8e70abe619..932eebef43 100644
--- a/runtime/indent/testdir/vim.ok
+++ b/runtime/indent/testdir/vim.ok
@@ -36,6 +36,13 @@ let t = [
\ },
\ ]
+def Func()
+ var d = dd
+ ->extend({
+ })
+ eval 0
+enddef
+
" END_INDENT
" START_INDENT
diff --git a/runtime/indent/vim.vim b/runtime/indent/vim.vim
index 8076b2df07..3beb70d255 100644
--- a/runtime/indent/vim.vim
+++ b/runtime/indent/vim.vim
@@ -33,7 +33,9 @@ function GetVimIndent()
endtry
endfunc
-let s:lineContPat = '^\s*\(\\\|"\\ \)'
+" Legacy script line continuation and Vim9 script operators that must mean an
+" expression that continues from the previous line.
+let s:lineContPat = '^\s*\(\\\|"\\ \|->\)'
function GetVimIndentIntern()
" If the current line has line continuation and the previous one too, use
@@ -133,15 +135,15 @@ function GetVimIndentIntern()
endif
endif
- " For a line starting with "}" find the matching "{". If it is at the start
- " of the line align with it, probably end of a block.
+ " For a line starting with "}" find the matching "{". Align with that line,
+ " it is either the matching block start or dictionary start.
" Use the mapped "%" from matchit to find the match, otherwise we may match
" a { inside a comment or string.
if cur_text =~ '^\s*}'
if maparg('%') != ''
exe v:lnum
silent! normal %
- if line('.') < v:lnum && getline('.') =~ '^\s*{'
+ if line('.') < v:lnum
let ind = indent('.')
endif
else
@@ -149,19 +151,33 @@ function GetVimIndentIntern()
endif
endif
- " Below a line starting with "}" find the matching "{". If it is at the
- " end of the line we must be below the end of a dictionary.
- if prev_text =~ '^\s*}'
- if maparg('%') != ''
- exe lnum
- silent! normal %
- if line('.') == lnum || getline('.') !~ '^\s*{'
- let ind = ind - shiftwidth()
+ " Look back for a line to align with
+ while lnum > 1
+ " Below a line starting with "}" find the matching "{".
+ if prev_text =~ '^\s*}'
+ if maparg('%') != ''
+ exe lnum
+ silent! normal %
+ if line('.') < lnum
+ let lnum = line('.')
+ let ind = indent(lnum)
+ let prev_text = getline(lnum)
+ else
+ break
+ endif
+ else
+ " todo: use searchpair() to find a match
+ break
endif
+ elseif prev_text =~ s:lineContPat
+ " looks like a continuation like, go back one line
+ let lnum = lnum - 1
+ let ind = indent(lnum)
+ let prev_text = getline(lnum)
else
- " todo: use searchpair() to find a match
+ break
endif
- endif
+ endwhile
" Below a line starting with "]" we must be below the end of a list.
" Include a "}" and "},} in case a dictionary ends too.
diff --git a/runtime/indent/yaml.vim b/runtime/indent/yaml.vim
index d732c37c05..93fd8ea6f6 100644
--- a/runtime/indent/yaml.vim
+++ b/runtime/indent/yaml.vim
@@ -1,7 +1,7 @@
" Vim indent file
" Language: YAML
" Maintainer: Nikolai Pavlov <zyx.vim@gmail.com>
-" Last Update: Lukas Reineke
+" Last Updates: Lukas Reineke, "lacygoill"
" Last Change: 2022 Jun 17
" Only load this indent file when no other was loaded.
@@ -29,8 +29,8 @@ function s:FindPrevLessIndentedLine(lnum, ...)
let prevlnum = prevnonblank(a:lnum-1)
let curindent = a:0 ? a:1 : indent(a:lnum)
while prevlnum
- \&& indent(prevlnum) >= curindent
- \&& getline(prevlnum) !~# '^\s*#'
+ \ && indent(prevlnum) >= curindent
+ \ && getline(prevlnum) !~# '^\s*#'
let prevlnum = prevnonblank(prevlnum-1)
endwhile
return prevlnum
@@ -54,7 +54,7 @@ let s:c_ns_anchor_name = s:c_ns_anchor_char .. '+'
let s:c_ns_anchor_property = '\v\&' .. s:c_ns_anchor_name
let s:ns_word_char = '\v[[:alnum:]_\-]'
-let s:ns_tag_char = '\v%(%\x\x|' .. s:ns_word_char .. '|[#/;?:@&=+$.~*''()])'
+let s:ns_tag_char = '\v%(\x\x|' .. s:ns_word_char .. '|[#/;?:@&=+$.~*''()])'
let s:c_named_tag_handle = '\v\!' .. s:ns_word_char .. '+\!'
let s:c_secondary_tag_handle = '\v\!\!'
let s:c_primary_tag_handle = '\v\!'
@@ -63,7 +63,7 @@ let s:c_tag_handle = '\v%(' .. s:c_named_tag_handle.
\ '|' .. s:c_primary_tag_handle .. ')'
let s:c_ns_shorthand_tag = '\v' .. s:c_tag_handle .. s:ns_tag_char .. '+'
let s:c_non_specific_tag = '\v\!'
-let s:ns_uri_char = '\v%(%\x\x|' .. s:ns_word_char .. '\v|[#/;?:@&=+$,.!~*''()[\]])'
+let s:ns_uri_char = '\v%(\x\x|' .. s:ns_word_char .. '\v|[#/;?:@&=+$,.!~*''()[\]])'
let s:c_verbatim_tag = '\v\!\<' .. s:ns_uri_char.. '+\>'
let s:c_ns_tag_property = '\v' .. s:c_verbatim_tag.
\ '\v|' .. s:c_ns_shorthand_tag.
diff --git a/runtime/lua/man.lua b/runtime/lua/man.lua
index 5da3d2a92f..82ed0305f7 100644
--- a/runtime/lua/man.lua
+++ b/runtime/lua/man.lua
@@ -1,7 +1,75 @@
require('vim.compat')
+local api, fn = vim.api, vim.fn
+
+local find_arg = '-w'
+local localfile_arg = true -- Always use -l if possible. #6683
local buf_hls = {}
+local M = {}
+
+local function man_error(msg)
+ M.errormsg = 'man.lua: ' .. vim.inspect(msg)
+ error(M.errormsg)
+end
+
+-- Run a system command and timeout after 30 seconds.
+local function man_system(cmd, silent)
+ local stdout_data = {}
+ local stderr_data = {}
+ local stdout = vim.loop.new_pipe(false)
+ local stderr = vim.loop.new_pipe(false)
+
+ local done = false
+ local exit_code
+
+ local handle = vim.loop.spawn(cmd[1], {
+ args = vim.list_slice(cmd, 2),
+ stdio = { nil, stdout, stderr },
+ }, function(code)
+ exit_code = code
+ stdout:close()
+ stderr:close()
+ done = true
+ end)
+
+ if handle then
+ stdout:read_start(function(_, data)
+ stdout_data[#stdout_data + 1] = data
+ end)
+ stderr:read_start(function(_, data)
+ stderr_data[#stderr_data + 1] = data
+ end)
+ else
+ stdout:close()
+ stderr:close()
+ if not silent then
+ man_error(string.format('command error: %s', table.concat(cmd)))
+ end
+ end
+
+ vim.wait(30000, function()
+ return done
+ end)
+
+ if not done then
+ if handle then
+ vim.loop.shutdown(handle)
+ stdout:close()
+ stderr:close()
+ end
+ man_error(string.format('command timed out: %s', table.concat(cmd, ' ')))
+ end
+
+ if exit_code ~= 0 and not silent then
+ man_error(
+ string.format("command error '%s': %s", table.concat(cmd, ' '), table.concat(stderr_data))
+ )
+ end
+
+ return table.concat(stdout_data)
+end
+
local function highlight_line(line, linenr)
local chars = {}
local prev_char = ''
@@ -152,21 +220,540 @@ local function highlight_line(line, linenr)
end
local function highlight_man_page()
- local mod = vim.api.nvim_buf_get_option(0, 'modifiable')
- vim.api.nvim_buf_set_option(0, 'modifiable', true)
+ local mod = vim.bo.modifiable
+ vim.bo.modifiable = true
- local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
+ local lines = api.nvim_buf_get_lines(0, 0, -1, false)
for i, line in ipairs(lines) do
lines[i] = highlight_line(line, i)
end
- vim.api.nvim_buf_set_lines(0, 0, -1, false, lines)
+ api.nvim_buf_set_lines(0, 0, -1, false, lines)
for _, args in ipairs(buf_hls) do
- vim.api.nvim_buf_add_highlight(unpack(args))
+ api.nvim_buf_add_highlight(unpack(args))
end
buf_hls = {}
- vim.api.nvim_buf_set_option(0, 'modifiable', mod)
+ vim.bo.modifiable = mod
+end
+
+-- replace spaces in a man page name with underscores
+-- intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)';
+-- while editing SQL source code, it's nice to visually select 'CREATE TABLE'
+-- and hit 'K', which requires this transformation
+local function spaces_to_underscores(str)
+ local res = str:gsub('%s', '_')
+ return res
+end
+
+local function get_path(sect, name, silent)
+ name = name or ''
+ sect = sect or ''
+ -- Some man implementations (OpenBSD) return all available paths from the
+ -- search command. Previously, this function would simply select the first one.
+ --
+ -- However, some searches will report matches that are incorrect:
+ -- man -w strlen may return string.3 followed by strlen.3, and therefore
+ -- selecting the first would get us the wrong page. Thus, we must find the
+ -- first matching one.
+ --
+ -- There's yet another special case here. Consider the following:
+ -- If you run man -w strlen and string.3 comes up first, this is a problem. We
+ -- should search for a matching named one in the results list.
+ -- However, if you search for man -w clock_gettime, you will *only* get
+ -- clock_getres.2, which is the right page. Searching the resuls for
+ -- clock_gettime will no longer work. In this case, we should just use the
+ -- first one that was found in the correct section.
+ --
+ -- Finally, we can avoid relying on -S or -s here since they are very
+ -- inconsistently supported. Instead, call -w with a section and a name.
+ local cmd
+ if sect == '' then
+ cmd = { 'man', find_arg, name }
+ else
+ cmd = { 'man', find_arg, sect, name }
+ end
+
+ local lines = man_system(cmd, silent)
+ if lines == nil then
+ return nil
+ end
+
+ local results = vim.split(lines, '\n', { trimempty = true })
+
+ if #results == 0 then
+ return
+ end
+
+ -- find any that match the specified name
+ local namematches = vim.tbl_filter(function(v)
+ return fn.fnamemodify(v, ':t'):match(name)
+ end, results) or {}
+ local sectmatches = {}
+
+ if #namematches > 0 and sect ~= '' then
+ sectmatches = vim.tbl_filter(function(v)
+ return fn.fnamemodify(v, ':e') == sect
+ end, namematches)
+ end
+
+ return fn.substitute(sectmatches[1] or namematches[1] or results[1], [[\n\+$]], '', '')
+end
+
+local function matchstr(text, pat_or_re)
+ local re = type(pat_or_re) == 'string' and vim.regex(pat_or_re) or pat_or_re
+
+ local s, e = re:match_str(text)
+
+ if s == nil then
+ return
+ end
+
+ return text:sub(vim.str_utfindex(text, s) + 1, vim.str_utfindex(text, e))
+end
+
+-- attempt to extract the name and sect out of 'name(sect)'
+-- otherwise just return the largest string of valid characters in ref
+local function extract_sect_and_name_ref(ref)
+ ref = ref or ''
+ if ref:sub(1, 1) == '-' then -- try ':Man -pandoc' with this disabled.
+ man_error("manpage name cannot start with '-'")
+ end
+ local ref1 = ref:match('[^()]+%([^()]+%)')
+ if not ref1 then
+ local name = ref:match('[^()]+')
+ if not name then
+ man_error('manpage reference cannot contain only parentheses: ' .. ref)
+ end
+ return '', spaces_to_underscores(name)
+ end
+ local parts = vim.split(ref1, '(', { plain = true })
+ -- see ':Man 3X curses' on why tolower.
+ -- TODO(nhooyr) Not sure if this is portable across OSs
+ -- but I have not seen a single uppercase section.
+ local sect = vim.split(parts[2] or '', ')', { plain = true })[1]:lower()
+ local name = spaces_to_underscores(parts[1])
+ return sect, name
+end
+
+-- verify_exists attempts to find the path to a manpage
+-- based on the passed section and name.
+--
+-- 1. If manpage could not be found with the given sect and name,
+-- then try all the sections in b:man_default_sects.
+-- 2. If it still could not be found, then we try again without a section.
+-- 3. If still not found but $MANSECT is set, then we try again with $MANSECT
+-- unset.
+local function verify_exists(sect, name)
+ if sect and sect ~= '' then
+ local ret = get_path(sect, name, true)
+ if ret then
+ return ret
+ end
+ end
+
+ if vim.b.man_default_sects ~= nil then
+ local sects = vim.split(vim.b.man_default_sects, ',', { plain = true, trimempty = true })
+ for _, sec in ipairs(sects) do
+ local ret = get_path(sec, name, true)
+ if ret then
+ return ret
+ end
+ end
+ end
+
+ -- if none of the above worked, we will try with no section
+ local res_empty_sect = get_path('', name, true)
+ if res_empty_sect then
+ return res_empty_sect
+ end
+
+ -- if that still didn't work, we will check for $MANSECT and try again with it
+ -- unset
+ if vim.env.MANSECT then
+ local mansect = vim.env.MANSECT
+ vim.env.MANSECT = nil
+ local res = get_path('', name, true)
+ vim.env.MANSECT = mansect
+ if res then
+ return res
+ end
+ end
+
+ -- finally, if that didn't work, there is no hope
+ man_error('no manual entry for ' .. name)
+end
+
+local EXT_RE = vim.regex([[\.\%([glx]z\|bz2\|lzma\|Z\)$]])
+
+-- Extracts the name/section from the 'path/name.sect', because sometimes the actual section is
+-- more specific than what we provided to `man` (try `:Man 3 App::CLI`).
+-- Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we
+-- still want the name of the buffer to be 'printf'.
+local function extract_sect_and_name_path(path)
+ local tail = fn.fnamemodify(path, ':t')
+ if EXT_RE:match_str(path) then -- valid extensions
+ tail = fn.fnamemodify(tail, ':r')
+ end
+ local name, sect = tail:match('^(.+)%.([^.]+)$')
+ return sect, name
+end
+
+local function find_man()
+ local win = 1
+ while win <= fn.winnr('$') do
+ local buf = fn.winbufnr(win)
+ if vim.bo[buf].filetype == 'man' then
+ vim.cmd(win .. 'wincmd w')
+ return true
+ end
+ win = win + 1
+ end
+ return false
+end
+
+local function set_options(pager)
+ vim.bo.swapfile = false
+ vim.bo.buftype = 'nofile'
+ vim.bo.bufhidden = 'hide'
+ vim.bo.modified = false
+ vim.bo.readonly = true
+ vim.bo.modifiable = false
+ vim.b.pager = pager
+ vim.bo.filetype = 'man'
+end
+
+local function get_page(path, silent)
+ -- Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065).
+ -- Soft-wrap: ftplugin/man.lua sets wrap/breakindent/….
+ -- Hard-wrap: driven by `man`.
+ local manwidth
+ if (vim.g.man_hardwrap or 1) ~= 1 then
+ manwidth = 999
+ elseif vim.env.MANWIDTH then
+ manwidth = vim.env.MANWIDTH
+ else
+ manwidth = api.nvim_win_get_width(0)
+ end
+ -- Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db).
+ -- http://comments.gmane.org/gmane.editors.vim.devel/29085
+ -- Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces.
+ local cmd = { 'env', 'MANPAGER=cat', 'MANWIDTH=' .. manwidth, 'MAN_KEEP_FORMATTING=1', 'man' }
+ if localfile_arg then
+ cmd[#cmd + 1] = '-l'
+ end
+ cmd[#cmd + 1] = path
+ return man_system(cmd, silent)
+end
+
+local function put_page(page)
+ vim.bo.modified = true
+ vim.bo.readonly = false
+ vim.bo.swapfile = false
+
+ api.nvim_buf_set_lines(0, 0, -1, false, vim.split(page, '\n'))
+
+ while fn.getline(1):match('^%s*$') do
+ api.nvim_buf_set_lines(0, 0, 1, false, {})
+ end
+ -- XXX: nroff justifies text by filling it with whitespace. That interacts
+ -- badly with our use of $MANWIDTH=999. Hack around this by using a fixed
+ -- size for those whitespace regions.
+ vim.cmd([[silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g]])
+ vim.cmd('1') -- Move cursor to first line
+ highlight_man_page()
+ set_options(false)
+end
+
+local function format_candidate(path, psect)
+ if matchstr(path, [[\.\%(pdf\|in\)$]]) then -- invalid extensions
+ return ''
+ end
+ local sect, name = extract_sect_and_name_path(path)
+ if sect == psect then
+ return name
+ elseif sect and name and matchstr(sect, psect .. '.\\+$') then -- invalid extensions
+ -- We include the section if the user provided section is a prefix
+ -- of the actual section.
+ return ('%s(%s)'):format(name, sect)
+ end
+ return ''
end
-return { highlight_man_page = highlight_man_page }
+local function get_paths(sect, name, do_fallback)
+ -- callers must try-catch this, as some `man` implementations don't support `s:find_arg`
+ local ok, ret = pcall(function()
+ local mandirs =
+ table.concat(vim.split(man_system({ 'man', find_arg }), '[:\n]', { trimempty = true }), ',')
+ local paths = fn.globpath(mandirs, 'man?/' .. name .. '*.' .. sect .. '*', false, true)
+ pcall(function()
+ -- Prioritize the result from verify_exists as it obeys b:man_default_sects.
+ local first = verify_exists(sect, name)
+ paths = vim.tbl_filter(function(v)
+ return v ~= first
+ end, paths)
+ paths = { first, unpack(paths) }
+ end)
+ return paths
+ end)
+
+ if not ok then
+ if not do_fallback then
+ error(ret)
+ end
+
+ -- Fallback to a single path, with the page we're trying to find.
+ ok, ret = pcall(verify_exists, sect, name)
+
+ return { ok and ret or nil }
+ end
+ return ret or {}
+end
+
+local function complete(sect, psect, name)
+ local pages = get_paths(sect, name, false)
+ -- We remove duplicates in case the same manpage in different languages was found.
+ return fn.uniq(fn.sort(vim.tbl_map(function(v)
+ return format_candidate(v, psect)
+ end, pages) or {}, 'i'))
+end
+
+-- see extract_sect_and_name_ref on why tolower(sect)
+function M.man_complete(arg_lead, cmd_line, _)
+ local args = vim.split(cmd_line, '%s+', { trimempty = true })
+ local cmd_offset = fn.index(args, 'Man')
+ if cmd_offset > 0 then
+ -- Prune all arguments up to :Man itself. Otherwise modifier commands like
+ -- :tab, :vertical, etc. would lead to a wrong length.
+ args = vim.list_slice(args, cmd_offset + 1)
+ end
+
+ if #args > 3 then
+ return {}
+ end
+
+ if #args == 1 then
+ -- returning full completion is laggy. Require some arg_lead to complete
+ -- return complete('', '', '')
+ return {}
+ end
+
+ if arg_lead:match('^[^()]+%([^()]*$') then
+ -- cursor (|) is at ':Man printf(|' or ':Man 1 printf(|'
+ -- The later is is allowed because of ':Man pri<TAB>'.
+ -- It will offer 'priclass.d(1m)' even though section is specified as 1.
+ local tmp = vim.split(arg_lead, '(', { plain = true })
+ local name = tmp[1]
+ local sect = (tmp[2] or ''):lower()
+ return complete(sect, '', name)
+ end
+
+ if not args[2]:match('^[^()]+$') then
+ -- cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|'
+ -- or ':Man 3() pri |'
+ return {}
+ end
+
+ if #args == 2 then
+ local name, sect
+ if arg_lead == '' then
+ -- cursor (|) is at ':Man 1 |'
+ name = ''
+ sect = args[1]:lower()
+ else
+ -- cursor (|) is at ':Man pri|'
+ if arg_lead:match('/') then
+ -- if the name is a path, complete files
+ -- TODO(nhooyr) why does this complete the last one automatically
+ return fn.glob(arg_lead .. '*', false, true)
+ end
+ name = arg_lead
+ sect = ''
+ end
+ return complete(sect, sect, name)
+ end
+
+ if not arg_lead:match('[^()]+$') then
+ -- cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|'
+ return {}
+ end
+
+ -- cursor (|) is at ':Man 3 pri|'
+ local name = arg_lead
+ local sect = args[2]:lower()
+ return complete(sect, sect, name)
+end
+
+function M.goto_tag(pattern, _, _)
+ local sect, name = extract_sect_and_name_ref(pattern)
+
+ local paths = get_paths(sect, name, true)
+ local structured = {}
+
+ for _, path in ipairs(paths) do
+ sect, name = extract_sect_and_name_path(path)
+ if sect and name then
+ structured[#structured + 1] = {
+ name = name,
+ title = name .. '(' .. sect .. ')',
+ }
+ end
+ end
+
+ if vim.o.cscopetag then
+ -- return only a single entry so we work well with :cstag (#11675)
+ structured = { structured[1] }
+ end
+
+ return vim.tbl_map(function(entry)
+ return {
+ name = entry.name,
+ filename = 'man://' .. entry.title,
+ cmd = '1',
+ }
+ end, structured)
+end
+
+-- Called when Nvim is invoked as $MANPAGER.
+function M.init_pager()
+ if fn.getline(1):match('^%s*$') then
+ api.nvim_buf_set_lines(0, 0, 1, false, {})
+ else
+ vim.cmd('keepjumps 1')
+ end
+ highlight_man_page()
+ -- Guess the ref from the heading (which is usually uppercase, so we cannot
+ -- know the correct casing, cf. `man glDrawArraysInstanced`).
+ local ref = fn.substitute(matchstr(fn.getline(1), [[^[^)]\+)]]) or '', ' ', '_', 'g')
+ local ok, res = pcall(extract_sect_and_name_ref, ref)
+ vim.b.man_sect = ok and res or ''
+
+ if not fn.bufname('%'):match('man://') then -- Avoid duplicate buffers, E95.
+ vim.cmd.file({ 'man://' .. fn.fnameescape(ref):lower(), mods = { silent = true } })
+ end
+
+ set_options(true)
+end
+
+function M.open_page(count, smods, args)
+ if #args > 2 then
+ man_error('too many arguments')
+ end
+
+ local ref
+ if #args == 0 then
+ ref = vim.bo.filetype == 'man' and fn.expand('<cWORD>') or fn.expand('<cword>')
+ if ref == '' then
+ man_error('no identifier under cursor')
+ end
+ elseif #args == 1 then
+ ref = args[1]
+ else
+ -- Combine the name and sect into a manpage reference so that all
+ -- verification/extraction can be kept in a single function.
+ -- If args[2] is a reference as well, that is fine because it is the only
+ -- reference that will match.
+ ref = ('%s(%s)'):format(args[2], args[1])
+ end
+
+ local sect, name = extract_sect_and_name_ref(ref)
+ if count >= 0 then
+ sect = tostring(count)
+ end
+
+ local path = verify_exists(sect, name)
+ sect, name = extract_sect_and_name_path(path)
+
+ local buf = fn.bufnr()
+ local save_tfu = vim.bo[buf].tagfunc
+ vim.bo[buf].tagfunc = "v:lua.require'man'.goto_tag"
+
+ local target = ('%s(%s)'):format(name, sect)
+
+ local ok, ret = pcall(function()
+ if smods.tab == -1 and find_man() then
+ vim.cmd.tag({ target, mods = { silent = true, keepalt = true } })
+ else
+ smods.silent = true
+ smods.keepalt = true
+ vim.cmd.stag({ target, mods = smods })
+ end
+ end)
+
+ vim.bo[buf].tagfunc = save_tfu
+
+ if not ok then
+ error(ret)
+ else
+ set_options(false)
+ end
+
+ vim.b.man_sect = sect
+end
+
+-- Called when a man:// buffer is opened.
+function M.read_page(ref)
+ local sect, name = extract_sect_and_name_ref(ref)
+ local path = verify_exists(sect, name)
+ sect = extract_sect_and_name_path(path)
+ local page = get_page(path)
+ vim.b.man_sect = sect
+ put_page(page)
+end
+
+function M.show_toc()
+ local bufname = fn.bufname('%')
+ local info = fn.getloclist(0, { winid = 1 })
+ if info ~= '' and vim.w[info.winid].qf_toc == bufname then
+ vim.cmd.lopen()
+ return
+ end
+
+ local toc = {}
+ local lnum = 2
+ local last_line = fn.line('$') - 1
+ local section_title_re = vim.regex([[^\%( \{3\}\)\=\S.*$]])
+ local flag_title_re = vim.regex([[^\s\+\%(+\|-\)\S\+]])
+ while lnum and lnum < last_line do
+ local text = fn.getline(lnum)
+ if section_title_re:match_str(text) then
+ -- if text is a section title
+ toc[#toc + 1] = {
+ bufnr = fn.bufnr('%'),
+ lnum = lnum,
+ text = text,
+ }
+ elseif flag_title_re:match_str(text) then
+ -- if text is a flag title. we strip whitespaces and prepend two
+ -- spaces to have a consistent format in the loclist.
+ toc[#toc + 1] = {
+ bufnr = fn.bufnr('%'),
+ lnum = lnum,
+ text = ' ' .. fn.substitute(text, [[^\s*\(.\{-}\)\s*$]], [[\1]], ''),
+ }
+ end
+ lnum = fn.nextnonblank(lnum + 1)
+ end
+
+ fn.setloclist(0, toc, ' ')
+ fn.setloclist(0, {}, 'a', { title = 'Man TOC' })
+ vim.cmd.lopen()
+ vim.w.qf_toc = bufname
+end
+
+local function init()
+ local path = get_path('', 'man', true)
+ local page
+ if path ~= nil then
+ -- Check for -l support.
+ page = get_page(path, true)
+ end
+
+ if page == '' or page == nil then
+ localfile_arg = false
+ end
+end
+
+init()
+
+return M
diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua
index f1652718ee..0f45c916dc 100644
--- a/runtime/lua/vim/_meta.lua
+++ b/runtime/lua/vim/_meta.lua
@@ -198,7 +198,10 @@ end
-- Can be done in a separate PR.
local key_value_options = {
fillchars = true,
+ fcs = true,
listchars = true,
+ lcs = true,
+ winhighlight = true,
winhl = true,
}
diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua
index db92085423..4f7d8cccd5 100644
--- a/runtime/lua/vim/diagnostic.lua
+++ b/runtime/lua/vim/diagnostic.lua
@@ -47,11 +47,11 @@ local bufnr_and_namespace_cacher_mt = {
local diagnostic_cache
do
- local group = vim.api.nvim_create_augroup('DiagnosticBufDelete', {})
+ local group = vim.api.nvim_create_augroup('DiagnosticBufWipeout', {})
diagnostic_cache = setmetatable({}, {
__index = function(t, bufnr)
assert(bufnr > 0, 'Invalid buffer number')
- vim.api.nvim_create_autocmd('BufDelete', {
+ vim.api.nvim_create_autocmd('BufWipeout', {
group = group,
buffer = bufnr,
callback = function()
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua
index fcd697a7c1..e4be1f04a2 100644
--- a/runtime/lua/vim/filetype.lua
+++ b/runtime/lua/vim/filetype.lua
@@ -177,6 +177,7 @@ local extension = {
bbappend = 'bitbake',
bbclass = 'bitbake',
bl = 'blank',
+ blp = 'blueprint',
bsd = 'bsdl',
bsdl = 'bsdl',
bst = 'bst',
@@ -540,6 +541,7 @@ local extension = {
mjs = 'javascript',
javascript = 'javascript',
js = 'javascript',
+ jsm = 'javascript',
cjs = 'javascript',
jsx = 'javascriptreact',
clp = 'jess',
@@ -556,6 +558,8 @@ local extension = {
['json-patch'] = 'json',
json5 = 'json5',
jsonc = 'jsonc',
+ jsonnet = 'jsonnet',
+ libjsonnet = 'jsonnet',
jsp = 'jsp',
jl = 'julia',
kv = 'kivy',
@@ -743,6 +747,7 @@ local extension = {
php = 'php',
phpt = 'php',
phtml = 'php',
+ theme = 'php',
pike = 'pike',
pmod = 'pike',
rcp = 'pilrc',
@@ -902,7 +907,9 @@ local extension = {
sig = function(path, bufnr)
return require('vim.filetype.detect').sig(bufnr)
end,
- sil = 'sil',
+ sil = function(path, bufnr)
+ return require('vim.filetype.detect').sil(bufnr)
+ end,
sim = 'simula',
['s85'] = 'sinda',
sin = 'sinda',
@@ -1378,6 +1385,8 @@ local filename = {
['EDIT_DESCRIPTION'] = 'gitcommit',
['.gitconfig'] = 'gitconfig',
['.gitmodules'] = 'gitconfig',
+ ['.gitattributes'] = 'gitattributes',
+ ['.gitignore'] = 'gitignore',
['gitolite.conf'] = 'gitolite',
['git-rebase-todo'] = 'gitrebase',
gkrellmrc = 'gkrellmrc',
@@ -1820,6 +1829,21 @@ local pattern = {
return 'gitconfig'
end
end,
+ ['.*%.git/info/attributes'] = 'gitattributes',
+ ['.*/etc/gitattributes'] = 'gitattributes',
+ ['.*/%.config/git/attributes'] = 'gitattributes',
+ ['.*/git/attributes'] = function(path, bufnr)
+ if vim.env.XDG_CONFIG_HOME and path:find(vim.env.XDG_CONFIG_HOME .. '/git/attributes') then
+ return 'gitattributes'
+ end
+ end,
+ ['.*%.git/info/exclude'] = 'gitignore',
+ ['.*/%.config/git/ignore'] = 'gitignore',
+ ['.*/git/ignore'] = function(path, bufnr)
+ if vim.env.XDG_CONFIG_HOME and path:find(vim.env.XDG_CONFIG_HOME .. '/git/ignore') then
+ return 'gitignore'
+ end
+ end,
['%.gitsendemail%.msg%.......'] = 'gitsendemail',
['gkrellmrc_.'] = 'gkrellmrc',
['.*/usr/.*/gnupg/options%.skel'] = 'gpg',
diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua
index 2be9dcff88..7fc7f1b7ca 100644
--- a/runtime/lua/vim/filetype/detect.lua
+++ b/runtime/lua/vim/filetype/detect.lua
@@ -1194,6 +1194,19 @@ function M.shell(path, contents, name)
return name
end
+-- Swift Intermediate Language or SILE
+function M.sil(bufnr)
+ for _, line in ipairs(getlines(bufnr, 1, 100)) do
+ if line:find('^%s*[\\%%]') then
+ return 'sile'
+ elseif line:find('^%s*%S') then
+ return 'sil'
+ end
+ end
+ -- No clue, default to "sil"
+ return 'sil'
+end
+
-- SMIL or SNMP MIB file
function M.smi(bufnr)
local line = getlines(bufnr, 1)
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua
index 1dc1a045fd..22933d8143 100644
--- a/runtime/lua/vim/lsp.lua
+++ b/runtime/lua/vim/lsp.lua
@@ -1147,33 +1147,34 @@ function lsp.start_client(config)
local namespace = vim.lsp.diagnostic.get_namespace(client_id)
vim.diagnostic.reset(namespace, bufnr)
- end)
- client_ids[client_id] = nil
- end
- if vim.tbl_isempty(client_ids) then
- vim.schedule(function()
- unset_defaults(bufnr)
+ client_ids[client_id] = nil
+ if vim.tbl_isempty(client_ids) then
+ unset_defaults(bufnr)
+ end
end)
end
end
- local client = active_clients[client_id] and active_clients[client_id]
- or uninitialized_clients[client_id]
- active_clients[client_id] = nil
- uninitialized_clients[client_id] = nil
- -- Client can be absent if executable starts, but initialize fails
- -- init/attach won't have happened
- if client then
- changetracking.reset(client)
- end
- if code ~= 0 or (signal ~= 0 and signal ~= 15) then
- local msg =
- string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal)
- vim.schedule(function()
+ -- Schedule the deletion of the client object so that it exists in the execution of LspDetach
+ -- autocommands
+ vim.schedule(function()
+ local client = active_clients[client_id] and active_clients[client_id]
+ or uninitialized_clients[client_id]
+ active_clients[client_id] = nil
+ uninitialized_clients[client_id] = nil
+
+ -- Client can be absent if executable starts, but initialize fails
+ -- init/attach won't have happened
+ if client then
+ changetracking.reset(client)
+ end
+ if code ~= 0 or (signal ~= 0 and signal ~= 15) then
+ local msg =
+ string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal)
vim.notify(msg, vim.log.levels.WARN)
- end)
- end
+ end
+ end)
end
-- Start the RPC client.
@@ -1644,6 +1645,7 @@ function lsp.buf_attach_client(bufnr, client_id)
if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'openClose') then
client.notify('textDocument/didClose', params)
end
+ client.attached_buffers[bufnr] = nil
end)
util.buf_versions[bufnr] = nil
all_buffer_active_clients[bufnr] = nil
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua
index 6a070928d9..2ce565e1d9 100644
--- a/runtime/lua/vim/lsp/buf.lua
+++ b/runtime/lua/vim/lsp/buf.lua
@@ -150,6 +150,33 @@ local function select_client(method, on_choice)
end
end
+---@private
+---@return table {start={row, col}, end={row, col}} using (1, 0) indexing
+local function range_from_selection()
+ -- TODO: Use `vim.region()` instead https://github.com/neovim/neovim/pull/13896
+
+ -- [bufnum, lnum, col, off]; both row and column 1-indexed
+ local start = vim.fn.getpos('v')
+ local end_ = vim.fn.getpos('.')
+ local start_row = start[2]
+ local start_col = start[3]
+ local end_row = end_[2]
+ local end_col = end_[3]
+
+ -- A user can start visual selection at the end and move backwards
+ -- Normalize the range to start < end
+ if start_row == end_row and end_col < start_col then
+ end_col, start_col = start_col, end_col
+ elseif end_row < start_row then
+ start_row, end_row = end_row, start_row
+ start_col, end_col = end_col, start_col
+ end
+ return {
+ ['start'] = { start_row, start_col - 1 },
+ ['end'] = { end_row, end_col - 1 },
+ }
+end
+
--- Formats a buffer using the attached (and optionally filtered) language
--- server clients.
---
@@ -184,7 +211,12 @@ end
--- Restrict formatting to the client with ID (client.id) matching this field.
--- - name (string|nil):
--- Restrict formatting to the client with name (client.name) matching this field.
-
+---
+--- - range (table|nil) Range to format.
+--- Table must contain `start` and `end` keys with {row, col} tuples using
+--- (1,0) indexing.
+--- Defaults to current selection in visual mode
+--- Defaults to `nil` in other modes, formatting the full buffer
function M.format(options)
options = options or {}
local bufnr = options.bufnr or api.nvim_get_current_buf()
@@ -206,16 +238,32 @@ function M.format(options)
vim.notify('[LSP] Format request failed, no matching language servers.')
end
+ local mode = api.nvim_get_mode().mode
+ local range = options.range
+ if not range and mode == 'v' or mode == 'V' then
+ range = range_from_selection()
+ end
+
+ ---@private
+ local function set_range(client, params)
+ if range then
+ local range_params =
+ util.make_given_range_params(range.start, range['end'], bufnr, client.offset_encoding)
+ params.range = range_params.range
+ end
+ return params
+ end
+
+ local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting'
if options.async then
local do_format
do_format = function(idx, client)
if not client then
return
end
- local params = util.make_formatting_params(options.formatting_options)
- client.request('textDocument/formatting', params, function(...)
- local handler = client.handlers['textDocument/formatting']
- or vim.lsp.handlers['textDocument/formatting']
+ local params = set_range(client, util.make_formatting_params(options.formatting_options))
+ client.request(method, params, function(...)
+ local handler = client.handlers[method] or vim.lsp.handlers[method]
handler(...)
do_format(next(clients, idx))
end, bufnr)
@@ -224,8 +272,8 @@ function M.format(options)
else
local timeout_ms = options.timeout_ms or 1000
for _, client in pairs(clients) do
- local params = util.make_formatting_params(options.formatting_options)
- local result, err = client.request_sync('textDocument/formatting', params, timeout_ms, bufnr)
+ local params = set_range(client, util.make_formatting_params(options.formatting_options))
+ local result, err = client.request_sync(method, params, timeout_ms, bufnr)
if result and result.result then
util.apply_text_edits(result.result, bufnr, client.offset_encoding)
elseif err then
@@ -356,6 +404,7 @@ end
---@param end_pos ({number, number}, optional) mark-indexed position.
---Defaults to the end of the last visual selection.
function M.range_formatting(options, start_pos, end_pos)
+ vim.deprecate('vim.lsp.buf.range_formatting', 'vim.lsp.formatexpr or vim.lsp.format', '0.9.0')
local params = util.make_given_range_params(start_pos, end_pos)
params.options = util.make_formatting_params(options).options
select_client('textDocument/rangeFormatting', function(client)
@@ -885,23 +934,8 @@ function M.code_action(options)
local end_ = assert(options.range['end'], 'range must have a `end` property')
params = util.make_given_range_params(start, end_)
elseif mode == 'v' or mode == 'V' then
- -- [bufnum, lnum, col, off]; both row and column 1-indexed
- local start = vim.fn.getpos('v')
- local end_ = vim.fn.getpos('.')
- local start_row = start[2]
- local start_col = start[3]
- local end_row = end_[2]
- local end_col = end_[3]
-
- -- A user can start visual selection at the end and move backwards
- -- Normalize the range to start < end
- if start_row == end_row and end_col < start_col then
- end_col, start_col = start_col, end_col
- elseif end_row < start_row then
- start_row, end_row = end_row, start_row
- start_col, end_col = end_col, start_col
- end
- params = util.make_given_range_params({ start_row, start_col - 1 }, { end_row, end_col - 1 })
+ local range = range_from_selection()
+ params = util.make_given_range_params(range.start, range['end'])
else
params = util.make_range_params()
end
diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua
index 70f838f34d..7d047f8958 100644
--- a/runtime/lua/vim/lsp/rpc.lua
+++ b/runtime/lua/vim/lsp/rpc.lua
@@ -635,7 +635,8 @@ local function connect(host, port)
end
--- Starts an LSP server process and create an LSP RPC client object to
---- interact with it. Communication with the server is currently limited to stdio.
+--- interact with it. Communication with the spawned process happens via stdio. For
+--- communication via TCP, spawn a process manually and use |vim.lsp.rpc.connect|
---
---@param cmd (string) Command to start the LSP server.
---@param cmd_args (table) List of additional string arguments to pass to {cmd}.
diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua
index e1b4ed4ea9..59cb669609 100644
--- a/runtime/lua/vim/shared.lua
+++ b/runtime/lua/vim/shared.lua
@@ -715,5 +715,30 @@ function vim.is_callable(f)
return type(m.__call) == 'function'
end
+--- Creates a table whose members are automatically created when accessed, if they don't already
+--- exist.
+---
+--- They mimic defaultdict in python.
+---
+--- If @p create is @c nil, this will create a defaulttable whose constructor function is
+--- this function, effectively allowing to create nested tables on the fly:
+---
+--- <pre>
+--- local a = vim.defaulttable()
+--- a.b.c = 1
+--- </pre>
+---
+---@param create function|nil The function called to create a missing value.
+---@return table Empty table with metamethod
+function vim.defaulttable(create)
+ create = create or vim.defaulttable
+ return setmetatable({}, {
+ __index = function(tbl, key)
+ rawset(tbl, key, create())
+ return rawget(tbl, key)
+ end,
+ })
+end
+
return vim
-- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/treesitter.lua b/runtime/lua/vim/treesitter.lua
index 6431162799..d93c485dfe 100644
--- a/runtime/lua/vim/treesitter.lua
+++ b/runtime/lua/vim/treesitter.lua
@@ -3,10 +3,7 @@ local query = require('vim.treesitter.query')
local language = require('vim.treesitter.language')
local LanguageTree = require('vim.treesitter.languagetree')
--- TODO(bfredl): currently we retain parsers for the lifetime of the buffer.
--- Consider use weak references to release parser if all plugins are done with
--- it.
-local parsers = {}
+local parsers = setmetatable({}, { __mode = 'v' })
local M = vim.tbl_extend('error', query, language)
@@ -32,9 +29,11 @@ setmetatable(M, {
---
--- It is not recommended to use this, use vim.treesitter.get_parser() instead.
---
----@param bufnr The buffer the parser will be tied to
----@param lang The language of the parser
----@param opts Options to pass to the created language tree
+---@param bufnr string Buffer the parser will be tied to (0 for current buffer)
+---@param lang string Language of the parser
+---@param opts table|nil Options to pass to the created language tree
+---
+---@returns table Created parser object
function M._create_parser(bufnr, lang, opts)
language.require_language(lang)
if bufnr == 0 then
@@ -79,11 +78,11 @@ end
--- If needed this will create the parser.
--- Unconditionally attach the provided callback
---
----@param bufnr The buffer the parser should be tied to
----@param lang The filetype of this parser
----@param opts Options object to pass to the created language tree
+---@param bufnr number|nil Buffer the parser should be tied to (default: current buffer)
+---@param lang string |nil Filetype of this parser (default: buffer filetype)
+---@param opts table|nil Options to pass to the created language tree
---
----@returns The parser
+---@returns table Parser object
function M.get_parser(bufnr, lang, opts)
opts = opts or {}
@@ -120,8 +119,8 @@ end
--- Determines whether a node is the ancestor of another
---
----@param dest table the possible ancestor
----@param source table the possible descendant node
+---@param dest table Possible ancestor
+---@param source table Possible descendant node
---
---@returns (boolean) True if dest is an ancestor of source
function M.is_ancestor(dest, source)
@@ -145,7 +144,7 @@ end
---
---@param node_or_range table
---
----@returns start_row, start_col, end_row, end_col
+---@returns table start_row, start_col, end_row, end_col
function M.get_node_range(node_or_range)
if type(node_or_range) == 'table' then
return unpack(node_or_range)
@@ -156,9 +155,11 @@ end
---Determines whether (line, col) position is in node range
---
----@param node Node defining the range
----@param line A line (0-based)
----@param col A column (0-based)
+---@param node table Node defining the range
+---@param line number Line (0-based)
+---@param col number Column (0-based)
+---
+---@returns (boolean) True if the position is in node range
function M.is_in_node_range(node, line, col)
local start_line, start_col, end_line, end_col = M.get_node_range(node)
if line >= start_line and line <= end_line then
@@ -177,8 +178,8 @@ function M.is_in_node_range(node, line, col)
end
---Determines if a node contains a range
----@param node table The node
----@param range table The range
+---@param node table
+---@param range table
---
---@returns (boolean) True if the node contains the range
function M.node_contains(node, range)
@@ -190,11 +191,15 @@ function M.node_contains(node, range)
end
---Gets a list of captures for a given cursor position
----@param bufnr number The buffer number
----@param row number The position row
----@param col number The position column
+---@param bufnr number Buffer number (0 for current buffer)
+---@param row number Position row
+---@param col number Position column
---
----@returns (table) A table of captures
+---@param bufnr number Buffer number (0 for current buffer)
+---@param row number Position row
+---@param col number Position column
+---
+---@returns (table) Table of captures
function M.get_captures_at_position(bufnr, row, col)
if bufnr == 0 then
bufnr = a.nvim_get_current_buf()
@@ -241,4 +246,105 @@ function M.get_captures_at_position(bufnr, row, col)
return matches
end
+---Gets a list of captures under the cursor
+---
+---@param winnr number|nil Window handle or 0 for current window (default)
+---
+---@returns (table) Named node under the cursor
+function M.get_captures_at_cursor(winnr)
+ winnr = winnr or 0
+ local bufnr = a.nvim_win_get_buf(winnr)
+ local cursor = a.nvim_win_get_cursor(winnr)
+
+ local data = M.get_captures_at_position(bufnr, cursor[1] - 1, cursor[2])
+
+ local captures = {}
+
+ for _, capture in ipairs(data) do
+ table.insert(captures, capture.capture)
+ end
+
+ return captures
+end
+
+--- Gets the smallest named node at position
+---
+---@param bufnr number Buffer number (0 for current buffer)
+---@param row number Position row
+---@param col number Position column
+---@param opts table Optional keyword arguments:
+--- - ignore_injections boolean Ignore injected languages (default true)
+---
+---@returns (table) Named node under the cursor
+function M.get_node_at_position(bufnr, row, col, opts)
+ if bufnr == 0 then
+ bufnr = a.nvim_get_current_buf()
+ end
+ local ts_range = { row, col, row, col }
+
+ local root_lang_tree = M.get_parser(bufnr)
+ if not root_lang_tree then
+ return
+ end
+
+ return root_lang_tree:named_node_for_range(ts_range, opts)
+end
+
+--- Gets the smallest named node under the cursor
+---
+---@param winnr number|nil Window handle or 0 for current window (default)
+---
+---@returns (string) Named node under the cursor
+function M.get_node_at_cursor(winnr)
+ winnr = winnr or 0
+ local bufnr = a.nvim_win_get_buf(winnr)
+ local cursor = a.nvim_win_get_cursor(winnr)
+
+ return M.get_node_at_position(bufnr, cursor[1] - 1, cursor[2], { ignore_injections = false })
+ :type()
+end
+
+--- Start treesitter highlighting for a buffer
+---
+--- Can be used in an ftplugin or FileType autocommand
+---
+--- Note: By default, disables regex syntax highlighting, which may be required for some plugins.
+--- In this case, add ``vim.bo.syntax = 'on'`` after the call to `start`.
+---
+--- Example:
+---
+--- <pre>
+--- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
+--- callback = function(args)
+--- vim.treesitter.start(args.buf, 'latex')
+--- vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed
+--- end
+--- })
+--- </pre>
+---
+---@param bufnr number|nil Buffer to be highlighted (default: current buffer)
+---@param lang string|nil Language of the parser (default: buffer filetype)
+function M.start(bufnr, lang)
+ bufnr = bufnr or a.nvim_get_current_buf()
+
+ local parser = M.get_parser(bufnr, lang)
+
+ M.highlighter.new(parser)
+
+ vim.b[bufnr].ts_highlight = true
+end
+
+---Stop treesitter highlighting for a buffer
+---
+---@param bufnr number|nil Buffer to stop highlighting (default: current buffer)
+function M.stop(bufnr)
+ bufnr = bufnr or a.nvim_get_current_buf()
+
+ if M.highlighter.active[bufnr] then
+ M.highlighter.active[bufnr]:destroy()
+ end
+
+ vim.bo[bufnr].syntax = 'on'
+end
+
return M
diff --git a/runtime/lua/vim/treesitter/highlighter.lua b/runtime/lua/vim/treesitter/highlighter.lua
index 1f242b0fdd..1e625eddb8 100644
--- a/runtime/lua/vim/treesitter/highlighter.lua
+++ b/runtime/lua/vim/treesitter/highlighter.lua
@@ -86,7 +86,7 @@ function TSHighlighter.new(tree, opts)
end
end
- a.nvim_buf_set_option(self.bufnr, 'syntax', '')
+ vim.bo[self.bufnr].syntax = ''
TSHighlighter.active[self.bufnr] = self
@@ -95,9 +95,13 @@ function TSHighlighter.new(tree, opts)
-- syntax FileType autocmds. Later on we should integrate with the
-- `:syntax` and `set syntax=...` machinery properly.
if vim.g.syntax_on ~= 1 then
- vim.api.nvim_command('runtime! syntax/synload.vim')
+ vim.cmd.runtime({ 'syntax/synload.vim', bang = true })
end
+ a.nvim_buf_call(self.bufnr, function()
+ vim.opt_local.spelloptions:append('noplainbuffer')
+ end)
+
self.tree:parse()
return self
@@ -156,7 +160,7 @@ function TSHighlighter:get_query(lang)
end
---@private
-local function on_line_impl(self, buf, line)
+local function on_line_impl(self, buf, line, spell)
self.tree:for_each_tree(function(tstree, tree)
if not tstree then
return
@@ -193,7 +197,9 @@ local function on_line_impl(self, buf, line)
local start_row, start_col, end_row, end_col = node:range()
local hl = highlighter_query.hl_cache[capture]
- if hl and end_row >= line then
+ local is_spell = highlighter_query:query().captures[capture] == 'spell'
+
+ if hl and end_row >= line and (not spell or is_spell) then
a.nvim_buf_set_extmark(buf, ns, start_row, start_col, {
end_line = end_row,
end_col = end_col,
@@ -201,6 +207,7 @@ local function on_line_impl(self, buf, line)
ephemeral = true,
priority = tonumber(metadata.priority) or 100, -- Low but leaves room below
conceal = metadata.conceal,
+ spell = is_spell,
})
end
if start_row > line then
@@ -217,7 +224,21 @@ function TSHighlighter._on_line(_, _win, buf, line, _)
return
end
- on_line_impl(self, buf, line)
+ on_line_impl(self, buf, line, false)
+end
+
+---@private
+function TSHighlighter._on_spell_nav(_, _, buf, srow, _, erow, _)
+ local self = TSHighlighter.active[buf]
+ if not self then
+ return
+ end
+
+ self:reset_highlight_state()
+
+ for row = srow, erow do
+ on_line_impl(self, buf, row, true)
+ end
end
---@private
@@ -244,6 +265,7 @@ a.nvim_set_decoration_provider(ns, {
on_buf = TSHighlighter._on_buf,
on_win = TSHighlighter._on_win,
on_line = TSHighlighter._on_line,
+ _on_spell_nav = TSHighlighter._on_spell_nav,
})
return TSHighlighter
diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua
index 697e2e7691..2f6227af8e 100644
--- a/runtime/lua/vim/treesitter/query.lua
+++ b/runtime/lua/vim/treesitter/query.lua
@@ -47,6 +47,9 @@ function M.get_query_files(lang, query_name, is_included)
return {}
end
+ local base_query = nil
+ local extensions = {}
+
local base_langs = {}
-- Now get the base languages by looking at the first line of every file
@@ -55,13 +58,26 @@ function M.get_query_files(lang, query_name, is_included)
--
-- {language} ::= {lang} | ({lang})
local MODELINE_FORMAT = '^;+%s*inherits%s*:?%s*([a-z_,()]+)%s*$'
+ local EXTENDS_FORMAT = '^;+%s*extends%s*$'
- for _, file in ipairs(lang_files) do
- local modeline = safe_read(file, '*l')
+ for _, filename in ipairs(lang_files) do
+ local file, err = io.open(filename, 'r')
+ if not file then
+ error(err)
+ end
- if modeline then
- local langlist = modeline:match(MODELINE_FORMAT)
+ local extension = false
+
+ for modeline in
+ function()
+ return file:read('*l')
+ end
+ do
+ if not vim.startswith(modeline, ';') then
+ break
+ end
+ local langlist = modeline:match(MODELINE_FORMAT)
if langlist then
for _, incllang in ipairs(vim.split(langlist, ',', true)) do
local is_optional = incllang:match('%(.*%)')
@@ -74,16 +90,25 @@ function M.get_query_files(lang, query_name, is_included)
table.insert(base_langs, incllang)
end
end
+ elseif modeline:match(EXTENDS_FORMAT) then
+ extension = true
end
end
+
+ if extension then
+ table.insert(extensions, filename)
+ elseif base_query == nil then
+ base_query = filename
+ end
+ io.close(file)
end
- local query_files = {}
+ local query_files = { base_query }
for _, base_lang in ipairs(base_langs) do
local base_files = M.get_query_files(base_lang, query_name, true)
vim.list_extend(query_files, base_files)
end
- vim.list_extend(query_files, lang_files)
+ vim.list_extend(query_files, extensions)
return query_files
end
@@ -140,12 +165,9 @@ function M.get_query(lang, query_name)
end
end
-local query_cache = setmetatable({}, {
- __index = function(tbl, key)
- rawset(tbl, key, {})
- return rawget(tbl, key)
- end,
-})
+local query_cache = vim.defaulttable(function()
+ return setmetatable({}, { __mode = 'v' })
+end)
--- Parse {query} as a string. (If the query is in a file, the caller
--- should read the contents into a string before calling).
diff --git a/runtime/plugin/man.lua b/runtime/plugin/man.lua
new file mode 100644
index 0000000000..4b1528b0cb
--- /dev/null
+++ b/runtime/plugin/man.lua
@@ -0,0 +1,34 @@
+if vim.g.loaded_man ~= nil then
+ return
+end
+vim.g.loaded_man = true
+
+vim.api.nvim_create_user_command('Man', function(params)
+ local man = require('man')
+ if params.bang then
+ man.init_pager()
+ else
+ local ok, err = pcall(man.open_page, params.count, params.smods, params.fargs)
+ if not ok then
+ vim.notify(man.errormsg or err, vim.log.levels.ERROR)
+ end
+ end
+end, {
+ bang = true,
+ bar = true,
+ addr = 'other',
+ nargs = '*',
+ complete = function(...)
+ return require('man').man_complete(...)
+ end,
+})
+
+local augroup = vim.api.nvim_create_augroup('man', {})
+
+vim.api.nvim_create_autocmd('BufReadCmd', {
+ group = augroup,
+ pattern = 'man://*',
+ callback = function(params)
+ require('man').read_page(vim.fn.matchstr(params.match, 'man://\\zs.*'))
+ end,
+})
diff --git a/runtime/plugin/man.vim b/runtime/plugin/man.vim
deleted file mode 100644
index b10677593f..0000000000
--- a/runtime/plugin/man.vim
+++ /dev/null
@@ -1,15 +0,0 @@
-" Maintainer: Anmol Sethi <hi@nhooyr.io>
-
-if exists('g:loaded_man')
- finish
-endif
-let g:loaded_man = 1
-
-command! -bang -bar -addr=other -complete=customlist,man#complete -nargs=* Man
- \ if <bang>0 | call man#init_pager() |
- \ else | call man#open_page(<count>, <q-mods>, <f-args>) | endif
-
-augroup man
- autocmd!
- autocmd BufReadCmd man://* call man#read_page(matchstr(expand('<amatch>'), 'man://\zs.*'))
-augroup END
diff --git a/runtime/queries/c/highlights.scm b/runtime/queries/c/highlights.scm
index 260750a85b..33e6df74ab 100644
--- a/runtime/queries/c/highlights.scm
+++ b/runtime/queries/c/highlights.scm
@@ -101,6 +101,7 @@
[ "(" ")" "[" "]" "{" "}"] @punctuation.bracket
(string_literal) @string
+(string_literal) @spell
(system_lib_string) @string
(null) @constant.builtin
@@ -148,6 +149,7 @@
(comment) @comment
+(comment) @spell
;; Parameters
(parameter_declaration
diff --git a/runtime/queries/c/injections.scm b/runtime/queries/c/injections.scm
new file mode 100644
index 0000000000..7e9e73449d
--- /dev/null
+++ b/runtime/queries/c/injections.scm
@@ -0,0 +1,3 @@
+(preproc_arg) @c
+
+; (comment) @comment
diff --git a/runtime/queries/lua/highlights.scm b/runtime/queries/lua/highlights.scm
new file mode 100644
index 0000000000..054d787932
--- /dev/null
+++ b/runtime/queries/lua/highlights.scm
@@ -0,0 +1,194 @@
+;; Keywords
+
+"return" @keyword.return
+
+[
+ "goto"
+ "in"
+ "local"
+] @keyword
+
+(label_statement) @label
+
+(break_statement) @keyword
+
+(do_statement
+[
+ "do"
+ "end"
+] @keyword)
+
+(while_statement
+[
+ "while"
+ "do"
+ "end"
+] @repeat)
+
+(repeat_statement
+[
+ "repeat"
+ "until"
+] @repeat)
+
+(if_statement
+[
+ "if"
+ "elseif"
+ "else"
+ "then"
+ "end"
+] @conditional)
+
+(elseif_statement
+[
+ "elseif"
+ "then"
+ "end"
+] @conditional)
+
+(else_statement
+[
+ "else"
+ "end"
+] @conditional)
+
+(for_statement
+[
+ "for"
+ "do"
+ "end"
+] @repeat)
+
+(function_declaration
+[
+ "function"
+ "end"
+] @keyword.function)
+
+(function_definition
+[
+ "function"
+ "end"
+] @keyword.function)
+
+;; Operators
+
+[
+ "and"
+ "not"
+ "or"
+] @keyword.operator
+
+[
+ "+"
+ "-"
+ "*"
+ "/"
+ "%"
+ "^"
+ "#"
+ "=="
+ "~="
+ "<="
+ ">="
+ "<"
+ ">"
+ "="
+ "&"
+ "~"
+ "|"
+ "<<"
+ ">>"
+ "//"
+ ".."
+] @operator
+
+;; Punctuations
+
+[
+ ";"
+ ":"
+ ","
+ "."
+] @punctuation.delimiter
+
+;; Brackets
+
+[
+ "("
+ ")"
+ "["
+ "]"
+ "{"
+ "}"
+] @punctuation.bracket
+
+;; Variables
+
+(identifier) @variable
+
+((identifier) @variable.builtin
+ (#eq? @variable.builtin "self"))
+
+;; Constants
+
+((identifier) @constant
+ (#lua-match? @constant "^[A-Z][A-Z_0-9]*$"))
+
+(vararg_expression) @constant
+
+(nil) @constant.builtin
+
+[
+ (false)
+ (true)
+] @boolean
+
+;; Tables
+
+(field name: (identifier) @field)
+
+(dot_index_expression field: (identifier) @field)
+
+(table_constructor
+[
+ "{"
+ "}"
+] @constructor)
+
+;; Functions
+
+(parameters (identifier) @parameter)
+
+(function_call name: (identifier) @function.call)
+(function_declaration name: (identifier) @function)
+
+(function_call name: (dot_index_expression field: (identifier) @function.call))
+(function_declaration name: (dot_index_expression field: (identifier) @function))
+
+(method_index_expression method: (identifier) @method)
+
+(function_call
+ (identifier) @function.builtin
+ (#any-of? @function.builtin
+ ;; built-in functions in Lua 5.1
+ "assert" "collectgarbage" "dofile" "error" "getfenv" "getmetatable" "ipairs"
+ "load" "loadfile" "loadstring" "module" "next" "pairs" "pcall" "print"
+ "rawequal" "rawget" "rawset" "require" "select" "setfenv" "setmetatable"
+ "tonumber" "tostring" "type" "unpack" "xpcall"))
+
+;; Others
+
+(comment) @comment
+(comment) @spell
+
+(hash_bang_line) @comment
+
+(number) @number
+
+(string) @string
+(string) @spell
+
+;; Error
+(ERROR) @error
diff --git a/runtime/queries/lua/injections.scm b/runtime/queries/lua/injections.scm
new file mode 100644
index 0000000000..0e67329139
--- /dev/null
+++ b/runtime/queries/lua/injections.scm
@@ -0,0 +1,22 @@
+((function_call
+ name: [
+ (identifier) @_cdef_identifier
+ (_ _ (identifier) @_cdef_identifier)
+ ]
+ arguments: (arguments (string content: _ @c)))
+ (#eq? @_cdef_identifier "cdef"))
+
+((function_call
+ name: (_) @_vimcmd_identifier
+ arguments: (arguments (string content: _ @vim)))
+ (#any-of? @_vimcmd_identifier "vim.cmd" "vim.api.nvim_command" "vim.api.nvim_exec" "vim.api.nvim_cmd"))
+
+; ((function_call
+; name: (_) @_vimcmd_identifier
+; arguments: (arguments (string content: _ @query) .))
+; (#eq? @_vimcmd_identifier "vim.treesitter.query.set_query"))
+
+; ;; highlight string as query if starts with `;; query`
+; ((string ("string_content") @query) (#lua-match? @query "^%s*;+%s?query"))
+
+; (comment) @comment
diff --git a/runtime/queries/vim/highlights.scm b/runtime/queries/vim/highlights.scm
new file mode 100644
index 0000000000..3d1729b2cd
--- /dev/null
+++ b/runtime/queries/vim/highlights.scm
@@ -0,0 +1,259 @@
+(identifier) @variable
+((identifier) @constant
+ (#lua-match? @constant "^[A-Z][A-Z_0-9]*$"))
+
+;; Keywords
+
+[
+ "if"
+ "else"
+ "elseif"
+ "endif"
+] @conditional
+
+[
+ "try"
+ "catch"
+ "finally"
+ "endtry"
+ "throw"
+] @exception
+
+[
+ "for"
+ "endfor"
+ "in"
+ "while"
+ "endwhile"
+ "break"
+ "continue"
+] @repeat
+
+[
+ "function"
+ "endfunction"
+] @keyword.function
+
+;; Function related
+(function_declaration name: (_) @function)
+(call_expression function: (identifier) @function)
+(parameters (identifier) @parameter)
+(default_parameter (identifier) @parameter)
+
+[ (bang) (spread) ] @punctuation.special
+
+[ (no_option) (inv_option) (default_option) (option_name) ] @variable.builtin
+[
+ (scope)
+ "a:"
+ "$"
+] @namespace
+
+;; Commands and user defined commands
+
+[
+ "let"
+ "unlet"
+ "const"
+ "call"
+ "execute"
+ "normal"
+ "set"
+ "setlocal"
+ "silent"
+ "echo"
+ "echomsg"
+ "autocmd"
+ "augroup"
+ "return"
+ "syntax"
+ "lua"
+ "ruby"
+ "perl"
+ "python"
+ "highlight"
+ "command"
+ "delcommand"
+ "comclear"
+ "colorscheme"
+ "startinsert"
+ "stopinsert"
+ "global"
+ "runtime"
+ "wincmd"
+ "cnext"
+ "cprevious"
+ "cNext"
+ "vertical"
+ "leftabove"
+ "aboveleft"
+ "rightbelow"
+ "belowright"
+ "topleft"
+ "botright"
+ (unknown_command_name)
+ "edit"
+ "enew"
+ "find"
+ "ex"
+ "visual"
+ "view"
+] @keyword
+(map_statement cmd: _ @keyword)
+(command_name) @function.macro
+
+;; Syntax command
+
+(syntax_statement (keyword) @string)
+(syntax_statement [
+ "enable"
+ "on"
+ "off"
+ "reset"
+ "case"
+ "spell"
+ "foldlevel"
+ "iskeyword"
+ "keyword"
+ "match"
+ "cluster"
+ "region"
+] @keyword)
+
+(syntax_argument name: _ @keyword)
+
+[
+ "<buffer>"
+ "<nowait>"
+ "<silent>"
+ "<script>"
+ "<expr>"
+ "<unique>"
+] @constant.builtin
+
+(augroup_name) @namespace
+
+(au_event) @constant
+(normal_statement (commands) @constant)
+
+;; Highlight command
+
+(hl_attribute
+ key: _ @property
+ val: _ @constant)
+
+(hl_group) @type
+
+(highlight_statement [
+ "default"
+ "link"
+ "clear"
+] @keyword)
+
+;; Command command
+
+(command) @string
+
+(command_attribute
+ name: _ @property
+ val: (behavior
+ name: _ @constant
+ val: (identifier)? @function)?)
+
+;; Edit command
+(plus_plus_opt
+ val: _? @constant) @property
+(plus_cmd "+" @property) @property
+
+;; Runtime command
+
+(runtime_statement (where) @keyword.operator)
+
+;; Colorscheme command
+
+(colorscheme_statement (name) @string)
+
+;; Literals
+
+(string_literal) @string @spell
+(integer_literal) @number
+(float_literal) @float
+(comment) @comment @spell
+(pattern) @string.special
+(pattern_multi) @string.regex
+(filename) @string
+(heredoc (body) @string)
+((heredoc (parameter) @keyword))
+((scoped_identifier
+ (scope) @_scope . (identifier) @boolean)
+ (#eq? @_scope "v:")
+ (#any-of? @boolean "true" "false"))
+
+;; Operators
+
+[
+ "||"
+ "&&"
+ "&"
+ "+"
+ "-"
+ "*"
+ "/"
+ "%"
+ ".."
+ "is"
+ "isnot"
+ "=="
+ "!="
+ ">"
+ ">="
+ "<"
+ "<="
+ "=~"
+ "!~"
+ "="
+ "+="
+ "-="
+ "*="
+ "/="
+ "%="
+ ".="
+ "..="
+] @operator
+
+; Some characters have different meanings based on the context
+(unary_operation "!" @operator)
+(binary_operation "." @operator)
+
+;; Punctuation
+
+[
+ "("
+ ")"
+ "{"
+ "}"
+ "["
+ "]"
+] @punctuation.bracket
+
+(field_expression "." @punctuation.delimiter)
+
+[
+ ","
+ ":"
+] @punctuation.delimiter
+
+(ternary_expression ["?" ":"] @conditional)
+
+; Options
+((set_value) @number
+ (#match? @number "^[0-9]+(\.[0-9]+)?$"))
+
+((set_item
+ option: (option_name) @_option
+ value: (set_value) @function)
+ (#any-of? @_option
+ "tagfunc" "tfu"
+ "completefunc" "cfu"
+ "omnifunc" "ofu"
+ "operatorfunc" "opfunc"))
diff --git a/runtime/queries/vim/injections.scm b/runtime/queries/vim/injections.scm
new file mode 100644
index 0000000000..e2dea8fe75
--- /dev/null
+++ b/runtime/queries/vim/injections.scm
@@ -0,0 +1,26 @@
+(lua_statement (script (body) @lua))
+(lua_statement (chunk) @lua)
+; (ruby_statement (script (body) @ruby))
+; (ruby_statement (chunk) @ruby)
+; (python_statement (script (body) @python))
+; (python_statement (chunk) @python)
+;; (perl_statement (script (body) @perl))
+;; (perl_statement (chunk) @perl)
+
+; (autocmd_statement (pattern) @regex)
+
+((set_item
+ option: (option_name) @_option
+ value: (set_value) @vim)
+ (#any-of? @_option
+ "includeexpr" "inex"
+ "printexpr" "pexpr"
+ "formatexpr" "fex"
+ "indentexpr" "inde"
+ "foldtext" "fdt"
+ "foldexpr" "fde"
+ "diffexpr" "dex"
+ "patchexpr" "pex"
+ "charconvert" "ccv"))
+
+; (comment) @comment
diff --git a/runtime/syntax/gdresource.vim b/runtime/syntax/gdresource.vim
index eb500aa6c2..7e1a2513e2 100644
--- a/runtime/syntax/gdresource.vim
+++ b/runtime/syntax/gdresource.vim
@@ -2,12 +2,13 @@
" Language: gdresource
" Maintainer: Maxim Kim <habamax@gmail.com>
" Filenames: *.tscn, *.tres
+" Website: https://github.com/habamax/vim-gdscript
if exists("b:current_syntax")
finish
endif
-let s:keepcpo= &cpo
+let s:keepcpo = &cpo
set cpo&vim
syn match gdResourceNumber "\<0x\%(_\=\x\)\+\>"
diff --git a/runtime/syntax/gdscript.vim b/runtime/syntax/gdscript.vim
index bf6d47c60d..e9295a411d 100644
--- a/runtime/syntax/gdscript.vim
+++ b/runtime/syntax/gdscript.vim
@@ -1,13 +1,14 @@
" Vim syntax file for Godot gdscript
" Language: gdscript
" Maintainer: Maxim Kim <habamax@gmail.com>
+" Website: https://github.com/habamax/vim-gdscript
" Filenames: *.gd
if exists("b:current_syntax")
finish
endif
-let s:keepcpo= &cpo
+let s:keepcpo = &cpo
set cpo&vim
syntax sync maxlines=100
diff --git a/runtime/syntax/gitattributes.vim b/runtime/syntax/gitattributes.vim
new file mode 100644
index 0000000000..b6d997f45d
--- /dev/null
+++ b/runtime/syntax/gitattributes.vim
@@ -0,0 +1,63 @@
+" Vim syntax file
+" Language: git attributes
+" Maintainer: ObserverOfTime <chronobserver@disroot.org>
+" Filenames: .gitattributes, *.git/info/attributes
+" Last Change: 2022 Sep 09
+
+if exists('b:current_syntax')
+ finish
+endif
+
+let s:cpo_save = &cpoptions
+set cpoptions&vim
+
+" Comment
+syn keyword gitattributesTodo contained TODO FIXME XXX
+syn match gitattributesComment /^\s*#.*/ contains=gitattributesTodo
+
+" Pattern
+syn match gitattributesPattern /^\s*#\@!\(".\+"\|\S\+\)/ skipwhite
+ \ nextgroup=gitattributesAttrPrefixed,gitattributesAttrAssigned skipwhite
+ \ contains=gitattributesGlob,gitattributesRange,gitattributesSeparator
+syn match gitattributesGlob /\\\@1<![?*]/ contained
+syn match gitattributesRange /\\\@1<!\[.\{-}\]/ contained
+syn match gitattributesSeparator '/' contained
+
+" Attribute
+syn match gitattributesAttrPrefixed /[!-]\?[A-Za-z0-9_.][-A-Za-z0-9_.]*/
+ \ transparent contained skipwhite
+ \ nextgroup=gitattributesAttrPrefixed,gitattributesAttrAssigned
+ \ contains=gitattributesPrefix,gitattributesName
+syn match gitattributesAttrAssigned /[A-Za-z0-9_.][-A-Za-z0-9_.]*=\S\+/
+ \ transparent contained skipwhite
+ \ nextgroup=gitattributesAttrPrefixed,gitattributesAttrAssigned
+ \ contains=gitattributesName,gitattributesAssign,gitattributesBoolean,gitattributesString
+syn match gitattributesName /[A-Za-z0-9_.][-A-Za-z0-9_.]*/
+ \ contained nextgroup=gitattributesAssign
+syn match gitattributesPrefix /[!-]/ contained
+ \ nextgroup=gitAttributesName
+syn match gitattributesAssign '=' contained
+ \ nextgroup=gitattributesBoolean,gitattributesString
+syn match gitattributesString /=\@1<=\S\+/ contained
+syn keyword gitattributesBoolean true false contained
+
+" Macro
+syn match gitattributesMacro /^\s*\[attr\]\s*\S\+/
+ \ nextgroup=gitattributesAttribute skipwhite
+
+hi def link gitattributesAssign Operator
+hi def link gitattributesBoolean Boolean
+hi def link gitattributesComment Comment
+hi def link gitattributesGlob Special
+hi def link gitattributesMacro Define
+hi def link gitattributesName Identifier
+hi def link gitattributesPrefix SpecialChar
+hi def link gitattributesRange Special
+hi def link gitattributesSeparator Delimiter
+hi def link gitattributesString String
+hi def link gitattributesTodo Todo
+
+let b:current_syntax = 'gitattributes'
+
+let &cpoptions = s:cpo_save
+unlet s:cpo_save
diff --git a/runtime/syntax/gitignore.vim b/runtime/syntax/gitignore.vim
new file mode 100644
index 0000000000..8e6d098acd
--- /dev/null
+++ b/runtime/syntax/gitignore.vim
@@ -0,0 +1,29 @@
+" Vim syntax file
+" Language: git ignore
+" Maintainer: ObserverOfTime <chronobserver@disroot.org>
+" Filenames: .gitignore, *.git/info/exclude
+" Last Change: 2022 Sep 10
+
+if exists('b:current_syntax')
+ finish
+endif
+
+" Comment
+syn keyword gitignoreTodo contained TODO FIXME XXX
+syn match gitignoreComment /^#.*/ contains=gitignoreTodo
+
+" Pattern
+syn match gitignorePattern /^#\@!.*$/ contains=gitignoreNegation,gitignoreGlob,gitignoreRange,gitignoreSeparator
+syn match gitignoreNegation /^!/ contained
+syn match gitignoreGlob /\\\@1<![?*]/ contained
+syn match gitignoreRange /\\\@1<!\[.\{-}\]/ contained
+syn match gitignoreSeparator '/' contained
+
+hi def link gitignoreComment Comment
+hi def link gitignoreGlob Special
+hi def link gitignoreNegation SpecialChar
+hi def link gitignoreRange Special
+hi def link gitignoreSeparator Delimiter
+hi def link gitignoreTodo Todo
+
+let b:current_syntax = 'gitignore'
diff --git a/runtime/syntax/lua.vim b/runtime/syntax/lua.vim
index b398e2e5c6..437a1ff113 100644
--- a/runtime/syntax/lua.vim
+++ b/runtime/syntax/lua.vim
@@ -1,11 +1,11 @@
" Vim syntax file
-" Language: Lua 4.0, Lua 5.0, Lua 5.1 and Lua 5.2
-" Maintainer: Marcus Aurelius Farias <masserahguard-lua 'at' yahoo com>
-" First Author: Carlos Augusto Teixeira Mendes <cmendes 'at' inf puc-rio br>
-" Last Change: 2022 Mar 31
-" Options: lua_version = 4 or 5
-" lua_subversion = 0 (4.0, 5.0) or 1 (5.1) or 2 (5.2)
-" default 5.2
+" Language: Lua 4.0, Lua 5.0, Lua 5.1 and Lua 5.2
+" Maintainer: Marcus Aurelius Farias <masserahguard-lua 'at' yahoo com>
+" First Author: Carlos Augusto Teixeira Mendes <cmendes 'at' inf puc-rio br>
+" Last Change: 2022 Mar 31
+" Options: lua_version = 4 or 5
+" lua_subversion = 0 (4.0, 5.0) or 1 (5.1) or 2 (5.2)
+" default 5.2
" quit when a syntax file was already loaded
if exists("b:current_syntax")
@@ -33,11 +33,11 @@ syn sync minlines=100
syn keyword luaTodo contained TODO FIXME XXX
syn match luaComment "--.*$" contains=luaTodo,@Spell
if lua_version == 5 && lua_subversion == 0
- syn region luaComment matchgroup=luaComment start="--\[\[" end="\]\]" contains=luaTodo,luaInnerComment,@Spell
+ syn region luaComment matchgroup=luaCommentDelimiter start="--\[\[" end="\]\]" contains=luaTodo,luaInnerComment,@Spell
syn region luaInnerComment contained transparent start="\[\[" end="\]\]"
elseif lua_version > 5 || (lua_version == 5 && lua_subversion >= 1)
" Comments in Lua 5.1: --[[ ... ]], [=[ ... ]=], [===[ ... ]===], etc.
- syn region luaComment matchgroup=luaComment start="--\[\z(=*\)\[" end="\]\z1\]" contains=luaTodo,@Spell
+ syn region luaComment matchgroup=luaCommentDelimiter start="--\[\z(=*\)\[" end="\]\z1\]" contains=luaTodo,@Spell
endif
" First line may start with #!
@@ -99,18 +99,18 @@ if lua_version < 5
elseif lua_version == 5
if lua_subversion == 0
syn match luaSpecial contained #\\[\\abfnrtv'"[\]]\|\\[[:digit:]]\{,3}#
- syn region luaString2 matchgroup=luaString start=+\[\[+ end=+\]\]+ contains=luaString2,@Spell
+ syn region luaString2 matchgroup=luaStringDelimiter start=+\[\[+ end=+\]\]+ contains=luaString2,@Spell
else
if lua_subversion == 1
syn match luaSpecial contained #\\[\\abfnrtv'"]\|\\[[:digit:]]\{,3}#
else " Lua 5.2
syn match luaSpecial contained #\\[\\abfnrtvz'"]\|\\x[[:xdigit:]]\{2}\|\\[[:digit:]]\{,3}#
endif
- syn region luaString2 matchgroup=luaString start="\[\z(=*\)\[" end="\]\z1\]" contains=@Spell
+ syn region luaString2 matchgroup=luaStringDelimiter start="\[\z(=*\)\[" end="\]\z1\]" contains=@Spell
endif
endif
-syn region luaString start=+'+ end=+'+ skip=+\\\\\|\\'+ contains=luaSpecial,@Spell
-syn region luaString start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=luaSpecial,@Spell
+syn region luaString matchgroup=luaStringDelimiter start=+'+ end=+'+ skip=+\\\\\|\\'+ contains=luaSpecial,@Spell
+syn region luaString matchgroup=luaStringDelimiter start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=luaSpecial,@Spell
" integer number
syn match luaNumber "\<\d\+\>"
@@ -333,27 +333,29 @@ endif
" Define the default highlighting.
" Only when an item doesn't have highlighting yet
-hi def link luaStatement Statement
-hi def link luaRepeat Repeat
-hi def link luaFor Repeat
-hi def link luaString String
-hi def link luaString2 String
-hi def link luaNumber Number
-hi def link luaOperator Operator
-hi def link luaIn Operator
-hi def link luaConstant Constant
-hi def link luaCond Conditional
-hi def link luaElse Conditional
-hi def link luaFunction Function
-hi def link luaComment Comment
-hi def link luaTodo Todo
-hi def link luaTable Structure
-hi def link luaError Error
-hi def link luaParenError Error
-hi def link luaBraceError Error
-hi def link luaSpecial SpecialChar
-hi def link luaFunc Identifier
-hi def link luaLabel Label
+hi def link luaStatement Statement
+hi def link luaRepeat Repeat
+hi def link luaFor Repeat
+hi def link luaString String
+hi def link luaString2 String
+hi def link luaStringDelimiter luaString
+hi def link luaNumber Number
+hi def link luaOperator Operator
+hi def link luaIn Operator
+hi def link luaConstant Constant
+hi def link luaCond Conditional
+hi def link luaElse Conditional
+hi def link luaFunction Function
+hi def link luaComment Comment
+hi def link luaCommentDelimiter luaComment
+hi def link luaTodo Todo
+hi def link luaTable Structure
+hi def link luaError Error
+hi def link luaParenError Error
+hi def link luaBraceError Error
+hi def link luaSpecial SpecialChar
+hi def link luaFunc Identifier
+hi def link luaLabel Label
let b:current_syntax = "lua"
diff --git a/runtime/syntax/sh.vim b/runtime/syntax/sh.vim
index e44699faa5..822b1a9ed2 100644
--- a/runtime/syntax/sh.vim
+++ b/runtime/syntax/sh.vim
@@ -2,8 +2,8 @@
" Language: shell (sh) Korn shell (ksh) bash (sh)
" Maintainer: Charles E. Campbell <NcampObell@SdrPchip.AorgM-NOSPAM>
" Previous Maintainer: Lennart Schultz <Lennart.Schultz@ecmwf.int>
-" Last Change: Jun 29, 2022
-" Version: 202
+" Last Change: Jul 08, 2022
+" Version: 203
" URL: http://www.drchip.org/astronaut/vim/index.html#SYNTAX_SH
" For options and settings, please use: :help ft-sh-syntax
" This file includes many ideas from Eric Brunet (eric.brunet@ens.fr) and heredoc fixes from Felipe Contreras
@@ -141,7 +141,7 @@ endif
syn cluster shArithParenList contains=shArithmetic,shArithParen,shCaseEsac,shComment,shDeref,shDo,shDerefSimple,shEcho,shEscape,shNumber,shOperator,shPosnParm,shExSingleQuote,shExDoubleQuote,shHereString,shRedir,shSingleQuote,shDoubleQuote,shStatement,shVariable,shAlias,shTest,shCtrlSeq,shSpecial,shParen,bashSpecialVariables,bashStatement,shIf,shFor,shFunctionKey,shFunctionOne,shFunctionTwo
syn cluster shArithList contains=@shArithParenList,shParenError
syn cluster shCaseEsacList contains=shCaseStart,shCaseLabel,shCase,shCaseBar,shCaseIn,shComment,shDeref,shDerefSimple,shCaseCommandSub,shCaseExSingleQuote,shCaseSingleQuote,shCaseDoubleQuote,shCtrlSeq,@shErrorList,shStringSpecial,shCaseRange
-syn cluster shCaseList contains=@shCommandSubList,shCaseEsac,shColon,shCommandSub,shCommandSubBQ,shComment,shDo,shEcho,shExpr,shFor,shHereDoc,shIf,shHereString,shRedir,shSetList,shSource,shStatement,shVariable,shCtrlSeq
+syn cluster shCaseList contains=@shCommandSubList,shCaseEsac,shColon,shCommandSub,shCommandSubBQ,shComment,shDblBrace,shDo,shEcho,shExpr,shFor,shHereDoc,shIf,shHereString,shRedir,shSetList,shSource,shStatement,shVariable,shCtrlSeq
if exists("b:is_kornshell") || exists("b:is_bash")
syn cluster shCaseList add=shForPP
endif
diff --git a/runtime/syntax/syntax.vim b/runtime/syntax/syntax.vim
index 55a2ee6d71..5ec99c7e05 100644
--- a/runtime/syntax/syntax.vim
+++ b/runtime/syntax/syntax.vim
@@ -27,13 +27,13 @@ else
endif
" Set up the connection between FileType and Syntax autocommands.
-" This makes the syntax automatically set when the file type is detected.
+" This makes the syntax automatically set when the file type is detected
+" unless treesitter highlighting is enabled.
" Avoid an error when 'verbose' is set and <amatch> expansion fails.
augroup syntaxset
- au! FileType * 0verbose exe "set syntax=" . expand("<amatch>")
+ au! FileType * if !exists('b:ts_highlight') | 0verbose exe "set syntax=" . expand("<amatch>") | endif
augroup END
-
" Execute the syntax autocommands for the each buffer.
" If the filetype wasn't detected yet, do that now.
" Always do the syntaxset autocommands, for buffers where the 'filetype'
diff --git a/runtime/syntax/vim.vim b/runtime/syntax/vim.vim
index 2b1c58c449..d5e138dbc3 100644
--- a/runtime/syntax/vim.vim
+++ b/runtime/syntax/vim.vim
@@ -53,7 +53,7 @@ syn case ignore
syn keyword vimGroup contained Comment Constant String Character Number Boolean Float Identifier Function Statement Conditional Repeat Label Operator Keyword Exception PreProc Include Define Macro PreCondit Type StorageClass Structure Typedef Special SpecialChar Tag Delimiter SpecialComment Debug Underlined Ignore Error Todo
" Default highlighting groups {{{2
-syn keyword vimHLGroup contained ColorColumn Cursor CursorColumn CursorIM CursorLine CursorLineFold CursorLineNr CursorLineSign DiffAdd DiffChange DiffDelete DiffText Directory EndOfBuffer ErrorMsg FoldColumn Folded IncSearch LineNr MatchParen Menu ModeMsg MoreMsg NonText Normal Pmenu PmenuSbar PmenuSel PmenuThumb Question QuickFixLine Scrollbar Search SignColumn SpecialKey SpellBad SpellCap SpellLocal SpellRare StatusLine StatusLineNC TabLine TabLineFill TabLineSel Title Tooltip VertSplit Visual WarningMsg WildMenu
+syn keyword vimHLGroup contained ColorColumn Cursor CursorColumn CursorIM CursorLine CursorLineFold CursorLineNr CursorLineSign DiffAdd DiffChange DiffDelete DiffText Directory EndOfBuffer ErrorMsg FoldColumn Folded IncSearch LineNr MatchParen Menu MessageWindow ModeMsg MoreMsg NonText Normal Pmenu PmenuSbar PmenuSel PmenuThumb Question QuickFixLine Scrollbar Search SignColumn SpecialKey SpellBad SpellCap SpellLocal SpellRare StatusLine StatusLineNC TabLine TabLineFill TabLineSel Title Tooltip VertSplit Visual WarningMsg WildMenu
syn match vimHLGroup contained "Conceal"
syn keyword vimOnlyHLGroup contained LineNrAbove LineNrBelow StatusLineTerm Terminal VisualNOS
syn keyword nvimHLGroup contained Substitute TermCursor TermCursorNC
diff --git a/runtime/syntax/zsh.vim b/runtime/syntax/zsh.vim
index bab89b916e..69671c59ca 100644
--- a/runtime/syntax/zsh.vim
+++ b/runtime/syntax/zsh.vim
@@ -2,7 +2,7 @@
" Language: Zsh shell script
" Maintainer: Christian Brabandt <cb@256bit.org>
" Previous Maintainer: Nikolai Weibull <now@bitwi.se>
-" Latest Revision: 2020-11-21
+" Latest Revision: 2022-07-26
" License: Vim (see :h license)
" Repository: https://github.com/chrisbra/vim-zsh
@@ -19,9 +19,9 @@ function! s:ContainedGroup()
" vim-pandoc syntax defines the @langname cluster for embedded syntax languages
" However, if no syntax is defined yet, `syn list @zsh` will return
" "No syntax items defined", so make sure the result is actually a valid syn cluster
- for cluster in ['markdownHighlightzsh', 'zsh']
+ for cluster in ['markdownHighlight_zsh', 'zsh']
try
- " markdown syntax defines embedded clusters as @markdownhighlight<lang>,
+ " markdown syntax defines embedded clusters as @markdownhighlight_<lang>,
" pandoc just uses @<lang>, so check both for both clusters
let a=split(execute('syn list @'. cluster), "\n")
if len(a) == 2 && a[0] =~# '^---' && a[1] =~? cluster
@@ -48,17 +48,28 @@ syn match zshPOSIXQuoted '\\u[0-9a-fA-F]\{1,4}'
syn match zshPOSIXQuoted '\\U[1-9a-fA-F]\{1,8}'
syn region zshString matchgroup=zshStringDelimiter start=+"+ end=+"+
- \ contains=zshQuoted,@zshDerefs,@zshSubst fold
+ \ contains=zshQuoted,@zshDerefs,@zshSubstQuoted fold
syn region zshString matchgroup=zshStringDelimiter start=+'+ end=+'+ fold
syn region zshPOSIXString matchgroup=zshStringDelimiter start=+\$'+
\ skip=+\\[\\']+ end=+'+ contains=zshPOSIXQuoted,zshQuoted
syn match zshJobSpec '%\(\d\+\|?\=\w\+\|[%+-]\)'
+syn match zshNumber '[+-]\=\<\d\+\>'
+syn match zshNumber '[+-]\=\<0x\x\+\>'
+syn match zshNumber '[+-]\=\<0\o\+\>'
+syn match zshNumber '[+-]\=\d\+#[-+]\=\w\+\>'
+syn match zshNumber '[+-]\=\d\+\.\d\+\>'
+
syn keyword zshPrecommand noglob nocorrect exec command builtin - time
syn keyword zshDelimiter do done end
-syn keyword zshConditional if then elif else fi case in esac select
+syn keyword zshConditional if then elif else fi esac select
+
+syn keyword zshCase case nextgroup=zshCaseWord skipwhite
+syn match zshCaseWord /\S\+/ nextgroup=zshCaseIn skipwhite contained transparent
+syn keyword zshCaseIn in nextgroup=zshCasePattern skipwhite skipnl contained
+syn match zshCasePattern /\S[^)]*)/ contained
syn keyword zshRepeat while until repeat
@@ -73,9 +84,13 @@ syn match zshFunction '^\s*\k\+\ze\s*()'
syn match zshOperator '||\|&&\|;\|&!\='
-syn match zshRedir '\d\=\(<\|<>\|<<<\|<&\s*[0-9p-]\=\)'
-syn match zshRedir '\d\=\(>\|>>\|>&\s*[0-9p-]\=\|&>\|>>&\|&>>\)[|!]\='
-syn match zshRedir '|&\='
+ " <<<, <, <>, and variants.
+syn match zshRedir '\d\=\(<<<\|<&\s*[0-9p-]\=\|<>\?\)'
+ " >, >>, and variants.
+syn match zshRedir '\d\=\(>&\s*[0-9p-]\=\|&>>\?\|>>\?&\?\)[|!]\='
+ " | and |&, but only if it's not preceeded or
+ " followed by a | to avoid matching ||.
+syn match zshRedir '|\@1<!|&\=|\@!'
syn region zshHereDoc matchgroup=zshRedir
\ start='<\@<!<<\s*\z([^<]\S*\)'
@@ -125,7 +140,7 @@ syn keyword zshCommands alias autoload bg bindkey break bye cap cd
\ enable eval exec exit export false fc fg
\ functions getcap getln getopts hash history
\ jobs kill let limit log logout popd print
- \ printf pushd pushln pwd r read
+ \ printf prompt pushd pushln pwd r read
\ rehash return sched set setcap shift
\ source stat suspend test times trap true
\ ttyctl type ulimit umask unalias unfunction
@@ -139,10 +154,120 @@ syn case ignore
syn match zshOptStart
\ /\v^\s*%(%(un)?setopt|set\s+[-+]o)/
\ nextgroup=zshOption skipwhite
-syn match zshOption nextgroup=zshOption,zshComment skipwhite contained /\v
- \ <%(no_?)?%(
- \ auto_?cd|auto_?pushd|cdable_?vars|cd_?silent|chase_?dots|chase_?links|posix_?cd|pushd_?ignore_?dups|pushd_?minus|pushd_?silent|pushd_?to_?home|always_?last_?prompt|always_?to_?end|auto_?list|auto_?menu|auto_?name_?dirs|auto_?param_?keys|auto_?param_?slash|auto_?remove_?slash|bash_?auto_?list|complete_?aliases|complete_?in_?word|glob_?complete|hash_?list_?all|list_?ambiguous|list_?beep|list_?packed|list_?rows_?first|list_?types|menu_?complete|rec_?exact|bad_?pattern|bare_?glob_?qual|brace_?ccl|case_?glob|case_?match|case_?paths|csh_?null_?glob|equals|extended_?glob|force_?float|glob|glob_?assign|glob_?dots|glob_?star_?short|glob_?subst|hist_?subst_?pattern|ignore_?braces|ignore_?close_?braces|ksh_?glob|magic_?equal_?subst|mark_?dirs|multibyte|nomatch|null_?glob|numeric_?glob_?sort|rc_?expand_?param|rematch_?pcre|sh_?glob|unset|warn_?create_?global|warn_?nested_?var|warnnestedvar|append_?history|bang_?hist|extended_?history|hist_?allow_?clobber|hist_?beep|hist_?expire_?dups_?first|hist_?fcntl_?lock|hist_?find_?no_?dups|hist_?ignore_?all_?dups|hist_?ignore_?dups|hist_?ignore_?space|hist_?lex_?words|hist_?no_?functions|hist_?no_?store|hist_?reduce_?blanks|hist_?save_?by_?copy|hist_?save_?no_?dups|hist_?verify|inc_?append_?history|inc_?append_?history_?time|share_?history|all_?export|global_?export|global_?rcs|rcs|aliases|clobber|clobber_?empty|correct|correct_?all|dvorak|flow_?control|ignore_?eof|interactive_?comments|hash_?cmds|hash_?dirs|hash_?executables_?only|mail_?warning|path_?dirs|path_?script|print_?eight_?bit|print_?exit_?value|rc_?quotes|rm_?star_?silent|rm_?star_?wait|short_?loops|short_?repeat|sun_?keyboard_?hack|auto_?continue|auto_?resume|bg_?nice|check_?jobs|check_?running_?jobs|hup|long_?list_?jobs|monitor|notify|posix_?jobs|prompt_?bang|prompt_?cr|prompt_?sp|prompt_?percent|prompt_?subst|transient_?rprompt|alias_?func_?def|c_?bases|c_?precedences|debug_?before_?cmd|err_?exit|err_?return|eval_?lineno|exec|function_?argzero|local_?loops|local_?options|local_?patterns|local_?traps|multi_?func_?def|multios|octal_?zeroes|pipe_?fail|source_?trace|typeset_?silent|typeset_?to_?unset|verbose|xtrace|append_?create|bash_?rematch|bsd_?echo|continue_?on_?error|csh_?junkie_?history|csh_?junkie_?loops|csh_?junkie_?quotes|csh_?nullcmd|ksh_?arrays|ksh_?autoload|ksh_?option_?print|ksh_?typeset|ksh_?zero_?subscript|posix_?aliases|posix_?argzero|posix_?builtins|posix_?identifiers|posix_?strings|posix_?traps|sh_?file_?expansion|sh_?nullcmd|sh_?option_?letters|sh_?word_?split|traps_?async|interactive|login|privileged|restricted|shin_?stdin|single_?command|beep|combining_?chars|emacs|overstrike|single_?line_?zle|vi|zle|brace_?expand|dot_?glob|hash_?all|hist_?append|hist_?expand|log|mail_?warn|one_?cmd|physical|prompt_?vars|stdin|track_?all|no_?match
- \)>/
+syn keyword zshOption nextgroup=zshOption,zshComment skipwhite contained
+ \ auto_cd no_auto_cd autocd noautocd auto_pushd no_auto_pushd autopushd noautopushd cdable_vars
+ \ no_cdable_vars cdablevars nocdablevars cd_silent no_cd_silent cdsilent nocdsilent chase_dots
+ \ no_chase_dots chasedots nochasedots chase_links no_chase_links chaselinks nochaselinks posix_cd
+ \ posixcd no_posix_cd noposixcd pushd_ignore_dups no_pushd_ignore_dups pushdignoredups
+ \ nopushdignoredups pushd_minus no_pushd_minus pushdminus nopushdminus pushd_silent no_pushd_silent
+ \ pushdsilent nopushdsilent pushd_to_home no_pushd_to_home pushdtohome nopushdtohome
+ \ always_last_prompt no_always_last_prompt alwayslastprompt noalwayslastprompt always_to_end
+ \ no_always_to_end alwaystoend noalwaystoend auto_list no_auto_list autolist noautolist auto_menu
+ \ no_auto_menu automenu noautomenu auto_name_dirs no_auto_name_dirs autonamedirs noautonamedirs
+ \ auto_param_keys no_auto_param_keys autoparamkeys noautoparamkeys auto_param_slash
+ \ no_auto_param_slash autoparamslash noautoparamslash auto_remove_slash no_auto_remove_slash
+ \ autoremoveslash noautoremoveslash bash_auto_list no_bash_auto_list bashautolist nobashautolist
+ \ complete_aliases no_complete_aliases completealiases nocompletealiases complete_in_word
+ \ no_complete_in_word completeinword nocompleteinword glob_complete no_glob_complete globcomplete
+ \ noglobcomplete hash_list_all no_hash_list_all hashlistall nohashlistall list_ambiguous
+ \ no_list_ambiguous listambiguous nolistambiguous list_beep no_list_beep listbeep nolistbeep
+ \ list_packed no_list_packed listpacked nolistpacked list_rows_first no_list_rows_first listrowsfirst
+ \ nolistrowsfirst list_types no_list_types listtypes nolisttypes menu_complete no_menu_complete
+ \ menucomplete nomenucomplete rec_exact no_rec_exact recexact norecexact bad_pattern no_bad_pattern
+ \ badpattern nobadpattern bare_glob_qual no_bare_glob_qual bareglobqual nobareglobqual brace_ccl
+ \ no_brace_ccl braceccl nobraceccl case_glob no_case_glob caseglob nocaseglob case_match
+ \ no_case_match casematch nocasematch case_paths no_case_paths casepaths nocasepaths csh_null_glob
+ \ no_csh_null_glob cshnullglob nocshnullglob equals no_equals noequals extended_glob no_extended_glob
+ \ extendedglob noextendedglob force_float no_force_float forcefloat noforcefloat glob no_glob noglob
+ \ glob_assign no_glob_assign globassign noglobassign glob_dots no_glob_dots globdots noglobdots
+ \ glob_star_short no_glob_star_short globstarshort noglobstarshort glob_subst no_glob_subst globsubst
+ \ noglobsubst hist_subst_pattern no_hist_subst_pattern histsubstpattern nohistsubstpattern
+ \ ignore_braces no_ignore_braces ignorebraces noignorebraces ignore_close_braces
+ \ no_ignore_close_braces ignoreclosebraces noignoreclosebraces ksh_glob no_ksh_glob kshglob nokshglob
+ \ magic_equal_subst no_magic_equal_subst magicequalsubst nomagicequalsubst mark_dirs no_mark_dirs
+ \ markdirs nomarkdirs multibyte no_multibyte nomultibyte nomatch no_nomatch nonomatch null_glob
+ \ no_null_glob nullglob nonullglob numeric_glob_sort no_numeric_glob_sort numericglobsort
+ \ nonumericglobsort rc_expand_param no_rc_expand_param rcexpandparam norcexpandparam rematch_pcre
+ \ no_rematch_pcre rematchpcre norematchpcre sh_glob no_sh_glob shglob noshglob unset no_unset nounset
+ \ warn_create_global no_warn_create_global warncreateglobal nowarncreateglobal warn_nested_var
+ \ no_warn_nested_var warnnestedvar no_warnnestedvar append_history no_append_history appendhistory
+ \ noappendhistory bang_hist no_bang_hist banghist nobanghist extended_history no_extended_history
+ \ extendedhistory noextendedhistory hist_allow_clobber no_hist_allow_clobber histallowclobber
+ \ nohistallowclobber hist_beep no_hist_beep histbeep nohistbeep hist_expire_dups_first
+ \ no_hist_expire_dups_first histexpiredupsfirst nohistexpiredupsfirst hist_fcntl_lock
+ \ no_hist_fcntl_lock histfcntllock nohistfcntllock hist_find_no_dups no_hist_find_no_dups
+ \ histfindnodups nohistfindnodups hist_ignore_all_dups no_hist_ignore_all_dups histignorealldups
+ \ nohistignorealldups hist_ignore_dups no_hist_ignore_dups histignoredups nohistignoredups
+ \ hist_ignore_space no_hist_ignore_space histignorespace nohistignorespace hist_lex_words
+ \ no_hist_lex_words histlexwords nohistlexwords hist_no_functions no_hist_no_functions
+ \ histnofunctions nohistnofunctions hist_no_store no_hist_no_store histnostore nohistnostore
+ \ hist_reduce_blanks no_hist_reduce_blanks histreduceblanks nohistreduceblanks hist_save_by_copy
+ \ no_hist_save_by_copy histsavebycopy nohistsavebycopy hist_save_no_dups no_hist_save_no_dups
+ \ histsavenodups nohistsavenodups hist_verify no_hist_verify histverify nohistverify
+ \ inc_append_history no_inc_append_history incappendhistory noincappendhistory
+ \ inc_append_history_time no_inc_append_history_time incappendhistorytime noincappendhistorytime
+ \ share_history no_share_history sharehistory nosharehistory all_export no_all_export allexport
+ \ noallexport global_export no_global_export globalexport noglobalexport global_rcs no_global_rcs
+ \ globalrcs noglobalrcs rcs no_rcs norcs aliases no_aliases noaliases clobber no_clobber noclobber
+ \ clobber_empty no_clobber_empty clobberempty noclobberempty correct no_correct nocorrect correct_all
+ \ no_correct_all correctall nocorrectall dvorak no_dvorak nodvorak flow_control no_flow_control
+ \ flowcontrol noflowcontrol ignore_eof no_ignore_eof ignoreeof noignoreeof interactive_comments
+ \ no_interactive_comments interactivecomments nointeractivecomments hash_cmds no_hash_cmds hashcmds
+ \ nohashcmds hash_dirs no_hash_dirs hashdirs nohashdirs hash_executables_only
+ \ no_hash_executables_only hashexecutablesonly nohashexecutablesonly mail_warning no_mail_warning
+ \ mailwarning nomailwarning path_dirs no_path_dirs pathdirs nopathdirs path_script no_path_script
+ \ pathscript nopathscript print_eight_bit no_print_eight_bit printeightbit noprinteightbit
+ \ print_exit_value no_print_exit_value printexitvalue noprintexitvalue rc_quotes no_rc_quotes
+ \ rcquotes norcquotes rm_star_silent no_rm_star_silent rmstarsilent normstarsilent rm_star_wait
+ \ no_rm_star_wait rmstarwait normstarwait short_loops no_short_loops shortloops noshortloops
+ \ short_repeat no_short_repeat shortrepeat noshortrepeat sun_keyboard_hack no_sun_keyboard_hack
+ \ sunkeyboardhack nosunkeyboardhack auto_continue no_auto_continue autocontinue noautocontinue
+ \ auto_resume no_auto_resume autoresume noautoresume bg_nice no_bg_nice bgnice nobgnice check_jobs
+ \ no_check_jobs checkjobs nocheckjobs check_running_jobs no_check_running_jobs checkrunningjobs
+ \ nocheckrunningjobs hup no_hup nohup long_list_jobs no_long_list_jobs longlistjobs nolonglistjobs
+ \ monitor no_monitor nomonitor notify no_notify nonotify posix_jobs posixjobs no_posix_jobs
+ \ noposixjobs prompt_bang no_prompt_bang promptbang nopromptbang prompt_cr no_prompt_cr promptcr
+ \ nopromptcr prompt_sp no_prompt_sp promptsp nopromptsp prompt_percent no_prompt_percent
+ \ promptpercent nopromptpercent prompt_subst no_prompt_subst promptsubst nopromptsubst
+ \ transient_rprompt no_transient_rprompt transientrprompt notransientrprompt alias_func_def
+ \ no_alias_func_def aliasfuncdef noaliasfuncdef c_bases no_c_bases cbases nocbases c_precedences
+ \ no_c_precedences cprecedences nocprecedences debug_before_cmd no_debug_before_cmd debugbeforecmd
+ \ nodebugbeforecmd err_exit no_err_exit errexit noerrexit err_return no_err_return errreturn
+ \ noerrreturn eval_lineno no_eval_lineno evallineno noevallineno exec no_exec noexec function_argzero
+ \ no_function_argzero functionargzero nofunctionargzero local_loops no_local_loops localloops
+ \ nolocalloops local_options no_local_options localoptions nolocaloptions local_patterns
+ \ no_local_patterns localpatterns nolocalpatterns local_traps no_local_traps localtraps nolocaltraps
+ \ multi_func_def no_multi_func_def multifuncdef nomultifuncdef multios no_multios nomultios
+ \ octal_zeroes no_octal_zeroes octalzeroes nooctalzeroes pipe_fail no_pipe_fail pipefail nopipefail
+ \ source_trace no_source_trace sourcetrace nosourcetrace typeset_silent no_typeset_silent
+ \ typesetsilent notypesetsilent typeset_to_unset no_typeset_to_unset typesettounset notypesettounset
+ \ verbose no_verbose noverbose xtrace no_xtrace noxtrace append_create no_append_create appendcreate
+ \ noappendcreate bash_rematch no_bash_rematch bashrematch nobashrematch bsd_echo no_bsd_echo bsdecho
+ \ nobsdecho continue_on_error no_continue_on_error continueonerror nocontinueonerror
+ \ csh_junkie_history no_csh_junkie_history cshjunkiehistory nocshjunkiehistory csh_junkie_loops
+ \ no_csh_junkie_loops cshjunkieloops nocshjunkieloops csh_junkie_quotes no_csh_junkie_quotes
+ \ cshjunkiequotes nocshjunkiequotes csh_nullcmd no_csh_nullcmd cshnullcmd nocshnullcmd ksh_arrays
+ \ no_ksh_arrays ksharrays noksharrays ksh_autoload no_ksh_autoload kshautoload nokshautoload
+ \ ksh_option_print no_ksh_option_print kshoptionprint nokshoptionprint ksh_typeset no_ksh_typeset
+ \ kshtypeset nokshtypeset ksh_zero_subscript no_ksh_zero_subscript kshzerosubscript
+ \ nokshzerosubscript posix_aliases no_posix_aliases posixaliases noposixaliases posix_argzero
+ \ no_posix_argzero posixargzero noposixargzero posix_builtins no_posix_builtins posixbuiltins
+ \ noposixbuiltins posix_identifiers no_posix_identifiers posixidentifiers noposixidentifiers
+ \ posix_strings no_posix_strings posixstrings noposixstrings posix_traps no_posix_traps posixtraps
+ \ noposixtraps sh_file_expansion no_sh_file_expansion shfileexpansion noshfileexpansion sh_nullcmd
+ \ no_sh_nullcmd shnullcmd noshnullcmd sh_option_letters no_sh_option_letters shoptionletters
+ \ noshoptionletters sh_word_split no_sh_word_split shwordsplit noshwordsplit traps_async
+ \ no_traps_async trapsasync notrapsasync interactive no_interactive nointeractive login no_login
+ \ nologin privileged no_privileged noprivileged restricted no_restricted norestricted shin_stdin
+ \ no_shin_stdin shinstdin noshinstdin single_command no_single_command singlecommand nosinglecommand
+ \ beep no_beep nobeep combining_chars no_combining_chars combiningchars nocombiningchars emacs
+ \ no_emacs noemacs overstrike no_overstrike nooverstrike single_line_zle no_single_line_zle
+ \ singlelinezle nosinglelinezle vi no_vi novi zle no_zle nozle brace_expand no_brace_expand
+ \ braceexpand nobraceexpand dot_glob no_dot_glob dotglob nodotglob hash_all no_hash_all hashall
+ \ nohashall hist_append no_hist_append histappend nohistappend hist_expand no_hist_expand histexpand
+ \ nohistexpand log no_log nolog mail_warn no_mail_warn mailwarn nomailwarn one_cmd no_one_cmd onecmd
+ \ noonecmd physical no_physical nophysical prompt_vars no_prompt_vars promptvars nopromptvars stdin
+ \ no_stdin nostdin track_all no_track_all trackall notrackall
syn case match
syn keyword zshTypes float integer local typeset declare private readonly
@@ -150,15 +275,12 @@ syn keyword zshTypes float integer local typeset declare private read
" XXX: this may be too much
" syn match zshSwitches '\s\zs--\=[a-zA-Z0-9-]\+'
-syn match zshNumber '[+-]\=\<\d\+\>'
-syn match zshNumber '[+-]\=\<0x\x\+\>'
-syn match zshNumber '[+-]\=\<0\o\+\>'
-syn match zshNumber '[+-]\=\d\+#[-+]\=\w\+\>'
-syn match zshNumber '[+-]\=\d\+\.\d\+\>'
-
" TODO: $[...] is the same as $((...)), so add that as well.
syn cluster zshSubst contains=zshSubst,zshOldSubst,zshMathSubst
+syn cluster zshSubstQuoted contains=zshSubstQuoted,zshOldSubst,zshMathSubst
exe 'syn region zshSubst matchgroup=zshSubstDelim transparent start=/\$(/ skip=/\\)/ end=/)/ contains='.s:contained. ' fold'
+exe 'syn region zshSubstQuoted matchgroup=zshSubstDelim transparent start=/\$(/ skip=/\\)/ end=/)/ contains='.s:contained. ' fold'
+syn region zshSubstQuoted matchgroup=zshSubstDelim start='\${' skip='\\}' end='}' contains=@zshSubst,zshBrackets,zshQuoted fold
syn region zshParentheses transparent start='(' skip='\\)' end=')' fold
syn region zshGlob start='(#' end=')'
syn region zshMathSubst matchgroup=zshSubstDelim transparent
@@ -201,6 +323,8 @@ hi def link zshJobSpec Special
hi def link zshPrecommand Special
hi def link zshDelimiter Keyword
hi def link zshConditional Conditional
+hi def link zshCase zshConditional
+hi def link zshCaseIn zshCase
hi def link zshException Exception
hi def link zshRepeat Repeat
hi def link zshKeyword Keyword
@@ -223,6 +347,7 @@ hi def link zshTypes Type
hi def link zshSwitches Special
hi def link zshNumber Number
hi def link zshSubst PreProc
+hi def link zshSubstQuoted zshSubst
hi def link zshMathSubst zshSubst
hi def link zshOldSubst zshSubst
hi def link zshSubstDelim zshSubst
diff --git a/src/clint.py b/src/clint.py
index 28f6031a57..0556f53372 100755
--- a/src/clint.py
+++ b/src/clint.py
@@ -1941,13 +1941,6 @@ def CheckExpressionAlignment(filename, clean_lines, linenum, error, startpos=0):
error(filename, linenum, 'whitespace/indent', 2,
'End of the inner expression should have '
'the same indent as start')
- else:
- if (pos != depth_line_starts[depth][0] + 4
- and not (depth_line_starts[depth][1] == '{'
- and pos == depth_line_starts[depth][0] + 2)):
- if depth not in ignore_error_levels:
- error(filename, linenum, 'whitespace/indent', 2,
- 'Inner expression indentation should be 4')
else:
if (pos != level_starts[depth][0] + 1
+ (level_starts[depth][2] == '{')):
diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt
index 635833748d..a1b57f927e 100755
--- a/src/nvim/CMakeLists.txt
+++ b/src/nvim/CMakeLists.txt
@@ -443,11 +443,6 @@ endif()
set(NVIM_EXEC_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES} ${LUA_PREFERRED_LIBRARIES})
-# Add IPO flags (for LTO), or error if CMake does not know the flags. #8654
-if(POLICY CMP0069)
- cmake_policy(SET CMP0069 NEW)
-endif()
-
add_executable(nvim ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS}
${NVIM_GENERATED_SOURCES} ${NVIM_SOURCES} ${NVIM_HEADERS}
${EXTERNAL_SOURCES} ${EXTERNAL_HEADERS})
@@ -461,7 +456,7 @@ set_property(TARGET nvim APPEND PROPERTY
INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS})
set_property(TARGET nvim PROPERTY ENABLE_EXPORTS TRUE)
-if(ENABLE_LTO AND (POLICY CMP0069))
+if(ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT IPO_SUPPORTED)
if(IPO_SUPPORTED AND (NOT CMAKE_BUILD_TYPE MATCHES Debug))
diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c
index 16f574f46d..6f8cad3e33 100644
--- a/src/nvim/api/buffer.c
+++ b/src/nvim/api/buffer.c
@@ -570,7 +570,7 @@ void nvim_buf_set_text(uint64_t channel_id, Buffer buffer, Integer start_row, In
char *str_at_end = NULL;
// Another call to ml_get_buf() may free the line, so make a copy.
- str_at_start = xstrdup((char *)ml_get_buf(buf, (linenr_T)start_row, false));
+ str_at_start = xstrdup(ml_get_buf(buf, (linenr_T)start_row, false));
size_t len_at_start = strlen(str_at_start);
if (start_col < 0 || (size_t)start_col > len_at_start) {
api_set_error(err, kErrorTypeValidation, "start_col out of bounds");
@@ -578,7 +578,7 @@ void nvim_buf_set_text(uint64_t channel_id, Buffer buffer, Integer start_row, In
}
// Another call to ml_get_buf() may free the line, so make a copy.
- str_at_end = xstrdup((char *)ml_get_buf(buf, (linenr_T)end_row, false));
+ str_at_end = xstrdup(ml_get_buf(buf, (linenr_T)end_row, false));
size_t len_at_end = strlen(str_at_end);
if (end_col < 0 || (size_t)end_col > len_at_end) {
api_set_error(err, kErrorTypeValidation, "end_col out of bounds");
@@ -608,7 +608,7 @@ void nvim_buf_set_text(uint64_t channel_id, Buffer buffer, Integer start_row, In
for (int64_t i = 1; i < end_row - start_row; i++) {
int64_t lnum = start_row + i;
- const char *bufline = (char *)ml_get_buf(buf, (linenr_T)lnum, false);
+ const char *bufline = ml_get_buf(buf, (linenr_T)lnum, false);
old_byte += (bcount_t)(strlen(bufline)) + 1;
}
old_byte += (bcount_t)end_col + 1;
diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c
index b821e07d60..b3518f1b0f 100644
--- a/src/nvim/api/command.c
+++ b/src/nvim/api/command.c
@@ -69,7 +69,7 @@
/// - keeppatterns: (boolean) |:keeppatterns|.
/// - lockmarks: (boolean) |:lockmarks|.
/// - noswapfile: (boolean) |:noswapfile|.
-/// - tab: (integer) |:tab|.
+/// - tab: (integer) |:tab|. -1 when omitted.
/// - verbose: (integer) |:verbose|. -1 when omitted.
/// - vertical: (boolean) |:vertical|.
/// - split: (string) Split modifier string, is an empty string when there's no split
@@ -239,7 +239,7 @@ Dictionary nvim_parse_cmd(String str, Dictionary opts, Error *err)
PUT(mods, "unsilent", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_UNSILENT));
PUT(mods, "sandbox", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_SANDBOX));
PUT(mods, "noautocmd", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_NOAUTOCMD));
- PUT(mods, "tab", INTEGER_OBJ(cmdinfo.cmdmod.cmod_tab));
+ PUT(mods, "tab", INTEGER_OBJ(cmdinfo.cmdmod.cmod_tab - 1));
PUT(mods, "verbose", INTEGER_OBJ(cmdinfo.cmdmod.cmod_verbose - 1));
PUT(mods, "browse", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_BROWSE));
PUT(mods, "confirm", BOOLEAN_OBJ(cmdinfo.cmdmod.cmod_flags & CMOD_CONFIRM));
@@ -559,15 +559,17 @@ String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Error
}
if (HAS_KEY(mods.tab)) {
- if (mods.tab.type != kObjectTypeInteger || mods.tab.data.integer < 0) {
- VALIDATION_ERROR("'mods.tab' must be a non-negative Integer");
+ if (mods.tab.type != kObjectTypeInteger) {
+ VALIDATION_ERROR("'mods.tab' must be an Integer");
+ } else if ((int)mods.tab.data.integer >= 0) {
+ // Silently ignore negative integers to allow mods.tab to be set to -1.
+ cmdinfo.cmdmod.cmod_tab = (int)mods.tab.data.integer + 1;
}
- cmdinfo.cmdmod.cmod_tab = (int)mods.tab.data.integer + 1;
}
if (HAS_KEY(mods.verbose)) {
if (mods.verbose.type != kObjectTypeInteger) {
- VALIDATION_ERROR("'mods.verbose' must be a Integer");
+ VALIDATION_ERROR("'mods.verbose' must be an Integer");
} else if ((int)mods.verbose.data.integer >= 0) {
// Silently ignore negative integers to allow mods.verbose to be set to -1.
cmdinfo.cmdmod.cmod_verbose = (int)mods.verbose.data.integer + 1;
@@ -589,15 +591,15 @@ String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Error
if (*mods.split.data.string.data == NUL) {
// Empty string, do nothing.
- } else if (STRCMP(mods.split.data.string.data, "aboveleft") == 0
- || STRCMP(mods.split.data.string.data, "leftabove") == 0) {
+ } else if (strcmp(mods.split.data.string.data, "aboveleft") == 0
+ || strcmp(mods.split.data.string.data, "leftabove") == 0) {
cmdinfo.cmdmod.cmod_split |= WSP_ABOVE;
- } else if (STRCMP(mods.split.data.string.data, "belowright") == 0
- || STRCMP(mods.split.data.string.data, "rightbelow") == 0) {
+ } else if (strcmp(mods.split.data.string.data, "belowright") == 0
+ || strcmp(mods.split.data.string.data, "rightbelow") == 0) {
cmdinfo.cmdmod.cmod_split |= WSP_BELOW;
- } else if (STRCMP(mods.split.data.string.data, "topleft") == 0) {
+ } else if (strcmp(mods.split.data.string.data, "topleft") == 0) {
cmdinfo.cmdmod.cmod_split |= WSP_TOP;
- } else if (STRCMP(mods.split.data.string.data, "botright") == 0) {
+ } else if (strcmp(mods.split.data.string.data, "botright") == 0) {
cmdinfo.cmdmod.cmod_split |= WSP_BOT;
} else {
VALIDATION_ERROR("Invalid value for 'mods.split'");
@@ -936,7 +938,7 @@ void nvim_buf_del_user_command(Buffer buffer, String name, Error *err)
for (int i = 0; i < gap->ga_len; i++) {
ucmd_T *cmd = USER_CMD_GA(gap, i);
- if (!STRCMP(name.data, cmd->uc_name)) {
+ if (!strcmp(name.data, cmd->uc_name)) {
free_ucmd(cmd);
gap->ga_len -= 1;
diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c
index 6ff0a2ed21..ae051d8cab 100644
--- a/src/nvim/api/extmark.c
+++ b/src/nvim/api/extmark.c
@@ -473,6 +473,8 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e
/// When a character is supplied it is used as |:syn-cchar|.
/// "hl_group" is used as highlight for the cchar if provided,
/// otherwise it defaults to |hl-Conceal|.
+/// - spell: boolean indicating that spell checking should be
+/// performed within this extmark
/// - ui_watched: boolean that indicates the mark should be drawn
/// by a UI. When set, the UI will receive win_extmark events.
/// Note: the mark is positioned by virt_text attributes. Can be
@@ -719,6 +721,11 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
bool ephemeral = false;
OPTION_TO_BOOL(ephemeral, ephemeral, false);
+ OPTION_TO_BOOL(decor.spell, spell, false);
+ if (decor.spell) {
+ has_decor = true;
+ }
+
OPTION_TO_BOOL(decor.ui_watched, ui_watched, false);
if (decor.ui_watched) {
has_decor = true;
@@ -972,20 +979,21 @@ void nvim_buf_clear_namespace(Buffer buffer, Integer ns_id, Integer line_start,
/// for the moment.
///
/// @param ns_id Namespace id from |nvim_create_namespace()|
-/// @param opts Callbacks invoked during redraw:
+/// @param opts Table of callbacks:
/// - on_start: called first on each screen redraw
/// ["start", tick]
-/// - on_buf: called for each buffer being redrawn (before window
-/// callbacks)
+/// - on_buf: called for each buffer being redrawn (before
+/// window callbacks)
/// ["buf", bufnr, tick]
-/// - on_win: called when starting to redraw a specific window.
+/// - on_win: called when starting to redraw a
+/// specific window.
/// ["win", winid, bufnr, topline, botline_guess]
-/// - on_line: called for each buffer line being redrawn. (The
-/// interaction with fold lines is subject to change)
+/// - on_line: called for each buffer line being redrawn.
+/// (The interaction with fold lines is subject to change)
/// ["win", winid, bufnr, row]
/// - on_end: called at the end of a redraw cycle
/// ["end", tick]
-void nvim_set_decoration_provider(Integer ns_id, DictionaryOf(LuaRef) opts, Error *err)
+void nvim_set_decoration_provider(Integer ns_id, Dict(set_decoration_provider) *opts, Error *err)
FUNC_API_SINCE(7) FUNC_API_LUA_ONLY
{
DecorProvider *p = get_decor_provider((NS)ns_id, true);
@@ -997,37 +1005,32 @@ void nvim_set_decoration_provider(Integer ns_id, DictionaryOf(LuaRef) opts, Erro
struct {
const char *name;
+ Object *source;
LuaRef *dest;
} cbs[] = {
- { "on_start", &p->redraw_start },
- { "on_buf", &p->redraw_buf },
- { "on_win", &p->redraw_win },
- { "on_line", &p->redraw_line },
- { "on_end", &p->redraw_end },
- { "_on_hl_def", &p->hl_def },
- { NULL, NULL },
+ { "on_start", &opts->on_start, &p->redraw_start },
+ { "on_buf", &opts->on_buf, &p->redraw_buf },
+ { "on_win", &opts->on_win, &p->redraw_win },
+ { "on_line", &opts->on_line, &p->redraw_line },
+ { "on_end", &opts->on_end, &p->redraw_end },
+ { "_on_hl_def", &opts->_on_hl_def, &p->hl_def },
+ { "_on_spell_nav", &opts->_on_spell_nav, &p->spell_nav },
+ { NULL, NULL, NULL },
};
- for (size_t i = 0; i < opts.size; i++) {
- String k = opts.items[i].key;
- Object *v = &opts.items[i].value;
- size_t j;
- for (j = 0; cbs[j].name && cbs[j].dest; j++) {
- if (strequal(cbs[j].name, k.data)) {
- if (v->type != kObjectTypeLuaRef) {
- api_set_error(err, kErrorTypeValidation,
- "%s is not a function", cbs[j].name);
- goto error;
- }
- *(cbs[j].dest) = v->data.luaref;
- v->data.luaref = LUA_NOREF;
- break;
- }
+ for (size_t i = 0; cbs[i].source && cbs[i].dest && cbs[i].name; i++) {
+ Object *v = cbs[i].source;
+ if (v->type == kObjectTypeNil) {
+ continue;
}
- if (!cbs[j].name) {
- api_set_error(err, kErrorTypeValidation, "unexpected key: %s", k.data);
+
+ if (v->type != kObjectTypeLuaRef) {
+ api_set_error(err, kErrorTypeValidation,
+ "%s is not a function", cbs[i].name);
goto error;
}
+ *(cbs[i].dest) = v->data.luaref;
+ v->data.luaref = LUA_NOREF;
}
p->active = true;
diff --git a/src/nvim/api/keysets.lua b/src/nvim/api/keysets.lua
index af3dc24f51..ea8949bd2c 100644
--- a/src/nvim/api/keysets.lua
+++ b/src/nvim/api/keysets.lua
@@ -2,6 +2,15 @@ return {
context = {
"types";
};
+ set_decoration_provider = {
+ "on_start";
+ "on_buf";
+ "on_win";
+ "on_line";
+ "on_end";
+ "_on_hl_def";
+ "_on_spell_nav";
+ };
set_extmark = {
"id";
"end_line";
@@ -28,6 +37,7 @@ return {
"line_hl_group";
"cursorline_hl_group";
"conceal";
+ "spell";
"ui_watched";
};
keymap = {
diff --git a/src/nvim/api/private/converter.c b/src/nvim/api/private/converter.c
index 8724ef4432..b6b3c83f3c 100644
--- a/src/nvim/api/private/converter.c
+++ b/src/nvim/api/private/converter.c
@@ -65,8 +65,8 @@ typedef struct {
#define TYPVAL_ENCODE_CONV_FUNC_START(tv, fun) \
do { \
ufunc_T *fp = find_func(fun); \
- if (fp != NULL && fp->uf_cb == nlua_CFunction_func_call) { \
- LuaRef ref = api_new_luaref(((LuaCFunctionState *)fp->uf_cb_state)->lua_callable.func_ref); \
+ if (fp != NULL && (fp->uf_flags & FC_LUAREF)) { \
+ LuaRef ref = api_new_luaref(fp->uf_luaref); \
kvi_push(edata->stack, LUAREF_OBJ(ref)); \
} else { \
TYPVAL_ENCODE_CONV_NIL(tv); \
@@ -351,10 +351,7 @@ bool object_to_vim(Object obj, typval_T *tv, Error *err)
}
case kObjectTypeLuaRef: {
- LuaCFunctionState *state = xmalloc(sizeof(LuaCFunctionState));
- state->lua_callable.func_ref = api_new_luaref(obj.data.luaref);
- char *name =
- (char *)register_cfunc(&nlua_CFunction_func_call, &nlua_CFunction_func_free, state);
+ char *name = (char *)register_luafunc(api_new_luaref(obj.data.luaref));
tv->v_type = VAR_FUNC;
tv->vval.v_string = xstrdup(name);
break;
diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c
index ebcf6cca6d..22d2ffbaf1 100644
--- a/src/nvim/api/private/helpers.c
+++ b/src/nvim/api/private/helpers.c
@@ -466,7 +466,7 @@ bool buf_collect_lines(buf_T *buf, size_t n, int64_t start, bool replace_nl, Arr
return false;
}
- const char *bufstr = (char *)ml_get_buf(buf, (linenr_T)lnum, false);
+ const char *bufstr = ml_get_buf(buf, (linenr_T)lnum, false);
Object str = STRING_OBJ(cstr_to_string(bufstr));
if (replace_nl) {
@@ -499,7 +499,7 @@ String buf_get_text(buf_T *buf, int64_t lnum, int64_t start_col, int64_t end_col
return rv;
}
- const char *bufstr = (char *)ml_get_buf(buf, (linenr_T)lnum, false);
+ const char *bufstr = ml_get_buf(buf, (linenr_T)lnum, false);
size_t line_length = strlen(bufstr);
start_col = start_col < 0 ? (int64_t)line_length + start_col + 1 : start_col;
diff --git a/src/nvim/api/ui.c b/src/nvim/api/ui.c
index 1534e547b0..27fb4b8e16 100644
--- a/src/nvim/api/ui.c
+++ b/src/nvim/api/ui.c
@@ -845,7 +845,7 @@ static void remote_ui_raw_line(UI *ui, Integer grid, Integer row, Integer startc
for (size_t i = 0; i < ncells; i++) {
repeat++;
if (i == ncells - 1 || attrs[i] != attrs[i + 1]
- || STRCMP(chunk[i], chunk[i + 1])) {
+ || strcmp(chunk[i], chunk[i + 1])) {
if (UI_BUF_SIZE - BUF_POS(data) < 2 * (1 + 2 + sizeof(schar_T) + 5 + 5)) {
// close to overflowing the redraw buffer. finish this event,
// flush, and start a new "grid_line" event at the current position.
diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c
index 83d6ba8dc7..95c9919522 100644
--- a/src/nvim/api/vim.c
+++ b/src/nvim/api/vim.c
@@ -336,9 +336,9 @@ Integer nvim_input(String keys)
/// mouse input in a GUI. The deprecated pseudokey form
/// ("<LeftMouse><col,row>") of |nvim_input()| has the same limitation.
///
-/// @param button Mouse button: one of "left", "right", "middle", "wheel".
+/// @param button Mouse button: one of "left", "right", "middle", "wheel", "move".
/// @param action For ordinary buttons, one of "press", "drag", "release".
-/// For the wheel, one of "up", "down", "left", "right".
+/// For the wheel, one of "up", "down", "left", "right". Ignored for "move".
/// @param modifier String of modifiers each represented by a single char.
/// The same specifiers are used as for a key press, except
/// that the "-" separator is optional, so "C-A-", "c-a"
@@ -365,6 +365,8 @@ void nvim_input_mouse(String button, String action, String modifier, Integer gri
code = KE_RIGHTMOUSE;
} else if (strequal(button.data, "wheel")) {
code = KE_MOUSEDOWN;
+ } else if (strequal(button.data, "move")) {
+ code = KE_MOUSEMOVE;
} else {
goto error;
}
@@ -381,7 +383,7 @@ void nvim_input_mouse(String button, String action, String modifier, Integer gri
} else {
goto error;
}
- } else {
+ } else if (code != KE_MOUSEMOVE) {
if (strequal(action.data, "press")) {
// pass
} else if (strequal(action.data, "drag")) {
diff --git a/src/nvim/arglist.c b/src/nvim/arglist.c
index 70b2e71949..02e3a99aab 100644
--- a/src/nvim/arglist.c
+++ b/src/nvim/arglist.c
@@ -79,13 +79,14 @@ void alist_expand(int *fnum_list, int fnum_len)
{
char *save_p_su = p_su;
+ char **old_arg_files = xmalloc(sizeof(*old_arg_files) * GARGCOUNT);
+
// Don't use 'suffixes' here. This should work like the shell did the
// expansion. Also, the vimrc file isn't read yet, thus the user
// can't set the options.
p_su = empty_option;
- char **old_arg_files = xmalloc(sizeof(*old_arg_files) * GARGCOUNT);
for (int i = 0; i < GARGCOUNT; i++) {
- old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
+ old_arg_files[i] = xstrdup(GARGLIST[i].ae_fname);
}
int old_arg_count = GARGCOUNT;
char **new_arg_files;
@@ -308,6 +309,50 @@ static void alist_add_list(int count, char **files, int after, bool will_edit)
}
}
+/// Delete the file names in "alist_ga" from the argument list.
+static void arglist_del_files(garray_T *alist_ga)
+{
+ regmatch_T regmatch;
+
+ // Delete the items: use each item as a regexp and find a match in the
+ // argument list.
+ regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
+ for (int i = 0; i < alist_ga->ga_len && !got_int; i++) {
+ char *p = ((char **)alist_ga->ga_data)[i];
+ p = file_pat_to_reg_pat(p, NULL, NULL, false);
+ if (p == NULL) {
+ break;
+ }
+ regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
+ if (regmatch.regprog == NULL) {
+ xfree(p);
+ break;
+ }
+
+ bool didone = false;
+ for (int match = 0; match < ARGCOUNT; match++) {
+ if (vim_regexec(&regmatch, alist_name(&ARGLIST[match]), (colnr_T)0)) {
+ didone = true;
+ xfree(ARGLIST[match].ae_fname);
+ memmove(ARGLIST + match, ARGLIST + match + 1,
+ (size_t)(ARGCOUNT - match - 1) * sizeof(aentry_T));
+ ALIST(curwin)->al_ga.ga_len--;
+ if (curwin->w_arg_idx > match) {
+ curwin->w_arg_idx--;
+ }
+ match--;
+ }
+ }
+
+ vim_regfree(regmatch.regprog);
+ xfree(p);
+ if (!didone) {
+ semsg(_(e_nomatch2), ((char **)alist_ga->ga_data)[i]);
+ }
+ }
+ ga_clear(alist_ga);
+}
+
/// @param str
/// @param what
/// AL_SET: Redefine the argument list to 'str'.
@@ -324,8 +369,6 @@ static int do_arglist(char *str, int what, int after, bool will_edit)
garray_T new_ga;
int exp_count;
char **exp_files;
- char *p;
- int match;
int arg_escaped = true;
// Set default argument for ":argadd" command.
@@ -341,46 +384,7 @@ static int do_arglist(char *str, int what, int after, bool will_edit)
get_arglist(&new_ga, str, arg_escaped);
if (what == AL_DEL) {
- regmatch_T regmatch;
- bool didone;
-
- // Delete the items: use each item as a regexp and find a match in the
- // argument list.
- regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
- for (int i = 0; i < new_ga.ga_len && !got_int; i++) {
- p = ((char **)new_ga.ga_data)[i];
- p = file_pat_to_reg_pat(p, NULL, NULL, false);
- if (p == NULL) {
- break;
- }
- regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
- if (regmatch.regprog == NULL) {
- xfree(p);
- break;
- }
-
- didone = false;
- for (match = 0; match < ARGCOUNT; match++) {
- if (vim_regexec(&regmatch, alist_name(&ARGLIST[match]), (colnr_T)0)) {
- didone = true;
- xfree(ARGLIST[match].ae_fname);
- memmove(ARGLIST + match, ARGLIST + match + 1,
- (size_t)(ARGCOUNT - match - 1) * sizeof(aentry_T));
- ALIST(curwin)->al_ga.ga_len--;
- if (curwin->w_arg_idx > match) {
- curwin->w_arg_idx--;
- }
- match--;
- }
- }
-
- vim_regfree(regmatch.regprog);
- xfree(p);
- if (!didone) {
- semsg(_(e_nomatch2), ((char **)new_ga.ga_data)[i]);
- }
- }
- ga_clear(&new_ga);
+ arglist_del_files(&new_ga);
} else {
int i = expand_wildcards(new_ga.ga_len, new_ga.ga_data,
&exp_count, &exp_files,
@@ -471,22 +475,27 @@ void ex_args(exarg_T *eap)
ex_next(eap);
} else if (eap->cmdidx == CMD_args) {
// ":args": list arguments.
- if (ARGCOUNT > 0) {
- char **items = xmalloc(sizeof(char *) * (size_t)ARGCOUNT);
- // Overwrite the command, for a short list there is no scrolling
- // required and no wait_return().
- gotocmdline(true);
- for (int i = 0; i < ARGCOUNT; i++) {
- items[i] = alist_name(&ARGLIST[i]);
- }
- list_in_columns(items, ARGCOUNT, curwin->w_arg_idx);
- xfree(items);
+ if (ARGCOUNT <= 0) {
+ return;
}
+
+ char **items = xmalloc(sizeof(char *) * (size_t)ARGCOUNT);
+
+ // Overwrite the command, for a short list there is no scrolling
+ // required and no wait_return().
+ gotocmdline(true);
+
+ for (int i = 0; i < ARGCOUNT; i++) {
+ items[i] = alist_name(&ARGLIST[i]);
+ }
+ list_in_columns(items, ARGCOUNT, curwin->w_arg_idx);
+ xfree(items);
} else if (eap->cmdidx == CMD_arglocal) {
garray_T *gap = &curwin->w_alist->al_ga;
// ":argslocal": make a local copy of the global argument list.
ga_grow(gap, GARGCOUNT);
+
for (int i = 0; i < GARGCOUNT; i++) {
if (GARGLIST[i].ae_fname != NULL) {
AARGLIST(curwin->w_alist)[gap->ga_len].ae_fname = xstrdup(GARGLIST[i].ae_fname);
@@ -624,7 +633,7 @@ void ex_argdedupe(exarg_T *eap FUNC_ATTR_UNUSED)
{
for (int i = 0; i < ARGCOUNT; i++) {
for (int j = i + 1; j < ARGCOUNT; j++) {
- if (FNAMECMP(ARGLIST[i].ae_fname, ARGLIST[j].ae_fname) == 0) {
+ if (path_fnamecmp(ARGLIST[i].ae_fname, ARGLIST[j].ae_fname) == 0) {
xfree(ARGLIST[j].ae_fname);
memmove(ARGLIST + j, ARGLIST + j + 1,
(size_t)(ARGCOUNT - j - 1) * sizeof(aentry_T));
@@ -1126,31 +1135,33 @@ void f_argv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
aentry_T *arglist = NULL;
int argcount = -1;
- if (argvars[0].v_type != VAR_UNKNOWN) {
- if (argvars[1].v_type == VAR_UNKNOWN) {
- arglist = ARGLIST;
- argcount = ARGCOUNT;
- } else if (argvars[1].v_type == VAR_NUMBER
- && tv_get_number(&argvars[1]) == -1) {
- arglist = GARGLIST;
- argcount = GARGCOUNT;
- } else {
- win_T *wp = find_win_by_nr_or_id(&argvars[1]);
- if (wp != NULL) {
- // Use the argument list of the specified window
- arglist = WARGLIST(wp);
- argcount = WARGCOUNT(wp);
- }
- }
- rettv->v_type = VAR_STRING;
- rettv->vval.v_string = NULL;
- int idx = (int)tv_get_number_chk(&argvars[0], NULL);
- if (arglist != NULL && idx >= 0 && idx < argcount) {
- rettv->vval.v_string = xstrdup((const char *)alist_name(&arglist[idx]));
- } else if (idx == -1) {
- get_arglist_as_rettv(arglist, argcount, rettv);
- }
- } else {
+ if (argvars[0].v_type == VAR_UNKNOWN) {
get_arglist_as_rettv(ARGLIST, ARGCOUNT, rettv);
+ return;
+ }
+
+ if (argvars[1].v_type == VAR_UNKNOWN) {
+ arglist = ARGLIST;
+ argcount = ARGCOUNT;
+ } else if (argvars[1].v_type == VAR_NUMBER
+ && tv_get_number(&argvars[1]) == -1) {
+ arglist = GARGLIST;
+ argcount = GARGCOUNT;
+ } else {
+ win_T *wp = find_win_by_nr_or_id(&argvars[1]);
+ if (wp != NULL) {
+ // Use the argument list of the specified window
+ arglist = WARGLIST(wp);
+ argcount = WARGCOUNT(wp);
+ }
+ }
+
+ rettv->v_type = VAR_STRING;
+ rettv->vval.v_string = NULL;
+ int idx = (int)tv_get_number_chk(&argvars[0], NULL);
+ if (arglist != NULL && idx >= 0 && idx < argcount) {
+ rettv->vval.v_string = xstrdup((const char *)alist_name(&arglist[idx]));
+ } else if (idx == -1) {
+ get_arglist_as_rettv(arglist, argcount, rettv);
}
}
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c
index 1c1de214cd..9d37647a4e 100644
--- a/src/nvim/autocmd.c
+++ b/src/nvim/autocmd.c
@@ -2214,7 +2214,7 @@ bool has_autocmd(event_T event, char *sfname, buf_T *buf)
#ifdef BACKSLASH_IN_FILENAME
// Replace all backslashes with forward slashes. This makes the
// autocommand patterns portable between Unix and Windows.
- sfname = vim_strsave(sfname);
+ sfname = xstrdup(sfname);
forward_slash(sfname);
forward_slash(fname);
#endif
@@ -2396,7 +2396,7 @@ bool au_exists(const char *const arg) FUNC_ATTR_WARN_UNUSED_RESULT
}
// if pattern is "<buffer>", special handling is needed which uses curbuf
- // for pattern "<buffer=N>, FNAMECMP() will work fine
+ // for pattern "<buffer=N>, path_fnamecmp() will work fine
if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0) {
buflocal_buf = curbuf;
}
@@ -2404,12 +2404,12 @@ bool au_exists(const char *const arg) FUNC_ATTR_WARN_UNUSED_RESULT
// Check if there is an autocommand with the given pattern.
for (; ap != NULL; ap = ap->next) {
// only use a pattern when it has not been removed and has commands.
- // For buffer-local autocommands, FNAMECMP() works fine.
+ // For buffer-local autocommands, path_fnamecmp() works fine.
if (ap->pat != NULL && ap->cmds != NULL
&& (group == AUGROUP_ALL || ap->group == group)
&& (pattern == NULL
|| (buflocal_buf == NULL
- ? FNAMECMP(ap->pat, pattern) == 0
+ ? path_fnamecmp(ap->pat, pattern) == 0
: ap->buflocal_nr == buflocal_buf->b_fnum))) {
retval = true;
break;
diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c
index 8f23102e2e..1cc68c9cee 100644
--- a/src/nvim/buffer.c
+++ b/src/nvim/buffer.c
@@ -2733,7 +2733,7 @@ void buflist_list(exarg_T *eap)
IObuff[len++] = ' ';
} while (--i > 0 && len < IOSIZE - 18);
if (vim_strchr(eap->arg, 't') && buf->b_last_used) {
- undo_fmt_time(IObuff + len, (size_t)(IOSIZE - len), buf->b_last_used);
+ undo_fmt_time((char_u *)IObuff + len, (size_t)(IOSIZE - len), buf->b_last_used);
} else {
vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len), _("line %" PRId64),
buf == curbuf ? (int64_t)curwin->w_cursor.lnum : (int64_t)buflist_findlnum(buf));
@@ -2965,7 +2965,7 @@ static bool otherfile_buf(buf_T *buf, char *ffname, FileID *file_id_p, bool file
if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL) {
return true;
}
- if (FNAMECMP(ffname, buf->b_ffname) == 0) {
+ if (path_fnamecmp(ffname, buf->b_ffname) == 0) {
return false;
}
{
@@ -3335,7 +3335,7 @@ static bool value_change(char *str, char **last)
FUNC_ATTR_WARN_UNUSED_RESULT
{
if ((str == NULL) != (*last == NULL)
- || (str != NULL && *last != NULL && STRCMP(str, *last) != 0)) {
+ || (str != NULL && *last != NULL && strcmp(str, *last) != 0)) {
xfree(*last);
if (str == NULL) {
*last = NULL;
@@ -4159,7 +4159,7 @@ bool buf_contents_changed(buf_T *buf)
if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count) {
differ = false;
for (linenr_T lnum = 1; lnum <= curbuf->b_ml.ml_line_count; lnum++) {
- if (STRCMP(ml_get_buf(buf, lnum, false), ml_get(lnum)) != 0) {
+ if (strcmp(ml_get_buf(buf, lnum, false), ml_get(lnum)) != 0) {
differ = true;
break;
}
diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h
index c1ac20fd98..3019a1323c 100644
--- a/src/nvim/buffer_defs.h
+++ b/src/nvim/buffer_defs.h
@@ -48,25 +48,23 @@ typedef struct {
#define GETFILE_SUCCESS(x) ((x) <= 0)
#define MODIFIABLE(buf) (buf->b_p_ma)
-/*
- * Flags for w_valid.
- * These are set when something in a window structure becomes invalid, except
- * when the cursor is moved. Call check_cursor_moved() before testing one of
- * the flags.
- * These are reset when that thing has been updated and is valid again.
- *
- * Every function that invalidates one of these must call one of the
- * invalidate_* functions.
- *
- * w_valid is supposed to be used only in screen.c. From other files, use the
- * functions that set or reset the flags.
- *
- * VALID_BOTLINE VALID_BOTLINE_AP
- * on on w_botline valid
- * off on w_botline approximated
- * off off w_botline not valid
- * on off not possible
- */
+// Flags for w_valid.
+// These are set when something in a window structure becomes invalid, except
+// when the cursor is moved. Call check_cursor_moved() before testing one of
+// the flags.
+// These are reset when that thing has been updated and is valid again.
+//
+// Every function that invalidates one of these must call one of the
+// invalidate_* functions.
+//
+// w_valid is supposed to be used only in screen.c. From other files, use the
+// functions that set or reset the flags.
+//
+// VALID_BOTLINE VALID_BOTLINE_AP
+// on on w_botline valid
+// off on w_botline approximated
+// off off w_botline not valid
+// on off not possible
#define VALID_WROW 0x01 // w_wrow (window row) is valid
#define VALID_WCOL 0x02 // w_wcol (window col) is valid
#define VALID_VIRTCOL 0x04 // w_virtcol (file col) is valid
@@ -112,9 +110,7 @@ typedef uint64_t disptick_T; // display tick type
#include "nvim/sign_defs.h"
#include "nvim/terminal.h" // for Terminal
-/*
- * The taggy struct is used to store the information about a :tag command.
- */
+// The taggy struct is used to store the information about a :tag command.
typedef struct taggy {
char *tagname; // tag name
fmark_T fmark; // cursor position BEFORE ":tag"
@@ -126,17 +122,13 @@ typedef struct taggy {
typedef struct buffblock buffblock_T;
typedef struct buffheader buffheader_T;
-/*
- * structure used to store one block of the stuff/redo/recording buffers
- */
+// structure used to store one block of the stuff/redo/recording buffers
struct buffblock {
buffblock_T *b_next; // pointer to next buffblock
char b_str[1]; // contents (actually longer)
};
-/*
- * header used for the stuff buffer and the redo buffer
- */
+// header used for the stuff buffer and the redo buffer
struct buffheader {
buffblock_T bh_first; // first (dummy) block of list
buffblock_T *bh_curr; // buffblock for appending
@@ -149,11 +141,9 @@ typedef struct {
buffheader_T sr_old_redobuff;
} save_redo_T;
-/*
- * Structure that contains all options that are local to a window.
- * Used twice in a window: for the current buffer and for all buffers.
- * Also used in wininfo_T.
- */
+// Structure that contains all options that are local to a window.
+// Used twice in a window: for the current buffer and for all buffers.
+// Also used in wininfo_T.
typedef struct {
int wo_arab;
#define w_p_arab w_onebuf_opt.wo_arab // 'arabic'
@@ -268,16 +258,14 @@ typedef struct {
#define w_p_script_ctx w_onebuf_opt.wo_script_ctx
} winopt_T;
-/*
- * Window info stored with a buffer.
- *
- * Two types of info are kept for a buffer which are associated with a
- * specific window:
- * 1. Each window can have a different line number associated with a buffer.
- * 2. The window-local options for a buffer work in a similar way.
- * The window-info is kept in a list at b_wininfo. It is kept in
- * most-recently-used order.
- */
+// Window info stored with a buffer.
+//
+// Two types of info are kept for a buffer which are associated with a
+// specific window:
+// 1. Each window can have a different line number associated with a buffer.
+// 2. The window-local options for a buffer work in a similar way.
+// The window-info is kept in a list at b_wininfo. It is kept in
+// most-recently-used order.
struct wininfo_S {
wininfo_T *wi_next; // next entry or NULL for last entry
wininfo_T *wi_prev; // previous entry or NULL for first entry
@@ -290,12 +278,10 @@ struct wininfo_S {
int wi_changelistidx; // copy of w_changelistidx
};
-/*
- * Argument list: Array of file names.
- * Used for the global argument list and the argument lists local to a window.
- *
- * TODO: move struct arglist to another header
- */
+// Argument list: Array of file names.
+// Used for the global argument list and the argument lists local to a window.
+//
+// TODO(neovim): move struct arglist to another header
typedef struct arglist {
garray_T al_ga; // growarray with the array of file names
int al_refcount; // number of windows using this arglist
@@ -321,9 +307,7 @@ typedef struct argentry {
#define ARGCOUNT (ALIST(curwin)->al_ga.ga_len)
#define WARGCOUNT(wp) (ALIST(wp)->al_ga.ga_len)
-/*
- * Used for the typeahead buffer: typebuf.
- */
+// Used for the typeahead buffer: typebuf.
typedef struct {
uint8_t *tb_buf; // buffer for typed characters
uint8_t *tb_noremap; // mapping flags for characters in tb_buf[]
@@ -347,9 +331,7 @@ typedef struct {
String save_inputbuf;
} tasave_T;
-/*
- * Structure used for mappings and abbreviations.
- */
+// Structure used for mappings and abbreviations.
typedef struct mapblock mapblock_T;
struct mapblock {
mapblock_T *m_next; // next mapblock in list
@@ -414,9 +396,7 @@ struct stl_item {
typedef struct qf_info_S qf_info_T;
-/*
- * Used for :syntime: timing of executing a syntax pattern.
- */
+// Used for :syntime: timing of executing a syntax pattern.
typedef struct {
proftime_T total; // total time used
proftime_T slowest; // time of slowest call
@@ -424,10 +404,8 @@ typedef struct {
long match; // nr of times matched
} syn_time_T;
-/*
- * These are items normally related to a buffer. But when using ":ownsyntax"
- * a window may have its own instance.
- */
+// These are items normally related to a buffer. But when using ":ownsyntax"
+// a window may have its own instance.
typedef struct {
hashtab_T b_keywtab; // syntax keywords hash table
hashtab_T b_keywtab_ic; // idem, ignore case
@@ -484,6 +462,9 @@ typedef struct {
char *b_p_spf; // 'spellfile'
char *b_p_spl; // 'spelllang'
char *b_p_spo; // 'spelloptions'
+#define SPO_CAMEL 0x1
+#define SPO_NPBUFFER 0x2
+ unsigned b_p_spo_flags; // 'spelloptions' flags
int b_cjk; // all CJK letters as OK
uint8_t b_syn_chartab[32]; // syntax iskeyword option
char *b_syn_isk; // iskeyword option
@@ -514,13 +495,11 @@ EXTERN int curbuf_splice_pending INIT(= 0);
// Maximum number of maphash blocks we will have
#define MAX_MAPHASH 256
-/*
- * buffer: structure that holds information about one file
- *
- * Several windows can share a single Buffer
- * A buffer is unallocated if there is no memfile for it.
- * A buffer is new if the associated file has never been loaded yet.
- */
+// buffer: structure that holds information about one file
+//
+// Several windows can share a single Buffer
+// A buffer is unallocated if there is no memfile for it.
+// A buffer is new if the associated file has never been loaded yet.
struct file_buffer {
handle_T handle; // unique id for the buffer (buffer number)
@@ -570,15 +549,13 @@ struct file_buffer {
varnumber_T b_last_changedtick_pum; // b:changedtick when TextChangedP was
// last triggered.
- bool b_saving; /* Set to true if we are in the middle of
- saving the buffer. */
+ bool b_saving; // Set to true if we are in the middle of
+ // saving the buffer.
- /*
- * Changes to a buffer require updating of the display. To minimize the
- * work, remember changes made and update everything at once.
- */
- bool b_mod_set; /* true when there are changes since the last
- time the display was updated */
+ // Changes to a buffer require updating of the display. To minimize the
+ // work, remember changes made and update everything at once.
+ bool b_mod_set; // true when there are changes since the last
+ // time the display was updated
linenr_T b_mod_top; // topmost lnum that was changed
linenr_T b_mod_bot; // lnum below last changed line, AFTER the
// change
@@ -609,17 +586,13 @@ struct file_buffer {
fmark_T b_last_insert; // where Insert mode was left
fmark_T b_last_change; // position of last change: '. mark
- /*
- * the changelist contains old change positions
- */
+ // the changelist contains old change positions
fmark_T b_changelist[JUMPLISTSIZE];
int b_changelistlen; // number of active entries
bool b_new_change; // set by u_savecommon()
- /*
- * Character table, only used in charset.c for 'iskeyword'
- * bitset with 4*64=256 bits: 1 bit per character 0-255.
- */
+ // Character table, only used in charset.c for 'iskeyword'
+ // bitset with 4*64=256 bits: 1 bit per character 0-255.
uint64_t b_chartab[4];
// Table used for mappings local to a buffer.
@@ -629,18 +602,14 @@ struct file_buffer {
mapblock_T *b_first_abbr;
// User commands local to the buffer.
garray_T b_ucmds;
- /*
- * start and end of an operator, also used for '[ and ']
- */
+ // start and end of an operator, also used for '[ and ']
pos_T b_op_start;
pos_T b_op_start_orig; // used for Insstart_orig
pos_T b_op_end;
bool b_marks_read; // Have we read ShaDa marks yet?
- /*
- * The following only used in undo.c.
- */
+ // The following only used in undo.c.
u_header_T *b_u_oldhead; // pointer to oldest header
u_header_T *b_u_newhead; // pointer to newest header; may not be valid
// if b_u_curhead is not NULL
@@ -673,11 +642,9 @@ struct file_buffer {
#define KEYMAP_LOADED 2 // 'keymap' mappings have been loaded
garray_T b_kmap_ga; // the keymap table
- /*
- * Options local to a buffer.
- * They are here because their value depends on the type of file
- * or contents of the file being edited.
- */
+ // Options local to a buffer.
+ // They are here because their value depends on the type of file
+ // or contents of the file being edited.
bool b_p_initialized; // set when options initialized
LastSet b_p_script_ctx[BV_COUNT]; // SCTXs for buffer-local options
@@ -822,8 +789,8 @@ struct file_buffer {
int b_ind_cpp_extern_c;
int b_ind_pragma;
- linenr_T b_no_eol_lnum; /* non-zero lnum when last line of next binary
- * write should not have an end-of-line */
+ linenr_T b_no_eol_lnum; // non-zero lnum when last line of next binary
+ // write should not have an end-of-line
int b_start_eol; // last line had eol when it was read
int b_start_ffc; // first char of 'ff' when edit started
@@ -834,19 +801,17 @@ struct file_buffer {
ScopeDictDictItem b_bufvar; ///< Variable for "b:" Dictionary.
dict_T *b_vars; ///< b: scope dictionary.
- /* When a buffer is created, it starts without a swap file. b_may_swap is
- * then set to indicate that a swap file may be opened later. It is reset
- * if a swap file could not be opened.
- */
+ // When a buffer is created, it starts without a swap file. b_may_swap is
+ // then set to indicate that a swap file may be opened later. It is reset
+ // if a swap file could not be opened.
bool b_may_swap;
- bool b_did_warn; /* Set to true if user has been warned on first
- change of a read-only file */
-
- /* Two special kinds of buffers:
- * help buffer - used for help files, won't use a swap file.
- * spell buffer - used for spell info, never displayed and doesn't have a
- * file name.
- */
+ bool b_did_warn; // Set to true if user has been warned on first
+ // change of a read-only file
+
+ // Two special kinds of buffers:
+ // help buffer - used for help files, won't use a swap file.
+ // spell buffer - used for spell info, never displayed and doesn't have a
+ // file name.
bool b_help; // true for help file buffer (when set b_p_bt
// is "help")
bool b_spell; // True for a spell file buffer, most fields
@@ -906,25 +871,21 @@ struct file_buffer {
int b_diff_failed; // internal diff failed for this buffer
};
-/*
- * Stuff for diff mode.
- */
+// Stuff for diff mode.
#define DB_COUNT 8 // up to four buffers can be diff'ed
-/*
- * Each diffblock defines where a block of lines starts in each of the buffers
- * and how many lines it occupies in that buffer. When the lines are missing
- * in the buffer the df_count[] is zero. This is all counted in
- * buffer lines.
- * There is always at least one unchanged line in between the diffs.
- * Otherwise it would have been included in the diff above or below it.
- * df_lnum[] + df_count[] is the lnum below the change. When in one buffer
- * lines have been inserted, in the other buffer df_lnum[] is the line below
- * the insertion and df_count[] is zero. When appending lines at the end of
- * the buffer, df_lnum[] is one beyond the end!
- * This is using a linked list, because the number of differences is expected
- * to be reasonable small. The list is sorted on lnum.
- */
+// Each diffblock defines where a block of lines starts in each of the buffers
+// and how many lines it occupies in that buffer. When the lines are missing
+// in the buffer the df_count[] is zero. This is all counted in
+// buffer lines.
+// There is always at least one unchanged line in between the diffs.
+// Otherwise it would have been included in the diff above or below it.
+// df_lnum[] + df_count[] is the lnum below the change. When in one buffer
+// lines have been inserted, in the other buffer df_lnum[] is the line below
+// the insertion and df_count[] is zero. When appending lines at the end of
+// the buffer, df_lnum[] is one beyond the end!
+// This is using a linked list, because the number of differences is expected
+// to be reasonable small. The list is sorted on lnum.
typedef struct diffblock_S diff_T;
struct diffblock_S {
diff_T *df_next;
@@ -964,18 +925,16 @@ struct tabpage_S {
char *tp_prevdir; ///< Previous directory.
};
-/*
- * Structure to cache info for displayed lines in w_lines[].
- * Each logical line has one entry.
- * The entry tells how the logical line is currently displayed in the window.
- * This is updated when displaying the window.
- * When the display is changed (e.g., when clearing the screen) w_lines_valid
- * is changed to exclude invalid entries.
- * When making changes to the buffer, wl_valid is reset to indicate wl_size
- * may not reflect what is actually in the buffer. When wl_valid is false,
- * the entries can only be used to count the number of displayed lines used.
- * wl_lnum and wl_lastlnum are invalid too.
- */
+// Structure to cache info for displayed lines in w_lines[].
+// Each logical line has one entry.
+// The entry tells how the logical line is currently displayed in the window.
+// This is updated when displaying the window.
+// When the display is changed (e.g., when clearing the screen) w_lines_valid
+// is changed to exclude invalid entries.
+// When making changes to the buffer, wl_valid is reset to indicate wl_size
+// may not reflect what is actually in the buffer. When wl_valid is false,
+// the entries can only be used to count the number of displayed lines used.
+// wl_lnum and wl_lastlnum are invalid too.
typedef struct w_line {
linenr_T wl_lnum; // buffer line number for logical line
uint16_t wl_size; // height in screen lines
@@ -984,10 +943,8 @@ typedef struct w_line {
linenr_T wl_lastlnum; // last buffer line number for logical line
} wline_T;
-/*
- * Windows are kept in a tree of frames. Each frame has a column (FR_COL)
- * or row (FR_ROW) layout or is a leaf, which has a window.
- */
+// Windows are kept in a tree of frames. Each frame has a column (FR_COL)
+// or row (FR_ROW) layout or is a leaf, which has a window.
struct frame_S {
char fr_layout; // FR_LEAF, FR_COL or FR_ROW
int fr_width;
@@ -1008,12 +965,10 @@ struct frame_S {
#define FR_ROW 1 // frame with a row of windows
#define FR_COL 2 // frame with a column of windows
-/*
- * Struct used for highlighting 'hlsearch' matches, matches defined by
- * ":match" and matches defined by match functions.
- * For 'hlsearch' there is one pattern for all windows. For ":match" and the
- * match functions there is a different pattern for each window.
- */
+// Struct used for highlighting 'hlsearch' matches, matches defined by
+// ":match" and matches defined by match functions.
+// For 'hlsearch' there is one pattern for all windows. For ":match" and the
+// match functions there is a different pattern for each window.
typedef struct {
regmmatch_T rm; // points to the regexp program; contains last found
// match (may continue in next line)
@@ -1049,10 +1004,8 @@ struct posmatch {
linenr_T botlnum; ///< bottom buffer line
};
-/*
- * matchitem_T provides a linked list for storing match items for ":match" and
- * the match functions.
- */
+// matchitem_T provides a linked list for storing match items for ":match" and
+// the match functions.
typedef struct matchitem matchitem_T;
struct matchitem {
matchitem_T *next;
@@ -1221,12 +1174,10 @@ struct window_S {
int eob;
} w_p_fcs_chars;
- /*
- * "w_topline", "w_leftcol" and "w_skipcol" specify the offsets for
- * displaying the buffer.
- */
- linenr_T w_topline; /* buffer line number of the line at the
- top of the window */
+ // "w_topline", "w_leftcol" and "w_skipcol" specify the offsets for
+ // displaying the buffer.
+ linenr_T w_topline; // buffer line number of the line at the
+ // top of the window
char w_topline_was_set; // flag set to true when topline is set,
// e.g. by winrestview()
int w_topfill; // number of filler lines above w_topline
@@ -1279,26 +1230,20 @@ struct window_S {
int w_height_outer;
int w_width_outer;
- /*
- * === start of cached values ====
- */
- /*
- * Recomputing is minimized by storing the result of computations.
- * Use functions in screen.c to check if they are valid and to update.
- * w_valid is a bitfield of flags, which indicate if specific values are
- * valid or need to be recomputed.
- */
+ // === start of cached values ====
+
+ // Recomputing is minimized by storing the result of computations.
+ // Use functions in screen.c to check if they are valid and to update.
+ // w_valid is a bitfield of flags, which indicate if specific values are
+ // valid or need to be recomputed.
int w_valid;
- pos_T w_valid_cursor; /* last known position of w_cursor, used
- to adjust w_valid */
+ pos_T w_valid_cursor; // last known position of w_cursor, used to adjust w_valid
colnr_T w_valid_leftcol; // last known w_leftcol
bool w_viewport_invalid;
- /*
- * w_cline_height is the number of physical lines taken by the buffer line
- * that the cursor is on. We use this to avoid extra calls to plines_win().
- */
+ // w_cline_height is the number of physical lines taken by the buffer line
+ // that the cursor is on. We use this to avoid extra calls to plines_win().
int w_cline_height; // current size of cursor line
bool w_cline_folded; // cursor line is folded
@@ -1311,11 +1256,9 @@ struct window_S {
// more than one screen line or when
// w_leftcol is non-zero
- /*
- * w_wrow and w_wcol specify the cursor position in the window.
- * This is related to positions in the window, not in the display or
- * buffer, thus w_wrow is relative to w_winrow.
- */
+ // w_wrow and w_wcol specify the cursor position in the window.
+ // This is related to positions in the window, not in the display or
+ // buffer, thus w_wrow is relative to w_winrow.
int w_wrow, w_wcol; // cursor position in window
linenr_T w_botline; // number of the line below the bottom of
@@ -1324,16 +1267,14 @@ struct window_S {
int w_filler_rows; // number of filler rows at the end of the
// window
- /*
- * Info about the lines currently in the window is remembered to avoid
- * recomputing it every time. The allocated size of w_lines[] is Rows.
- * Only the w_lines_valid entries are actually valid.
- * When the display is up-to-date w_lines[0].wl_lnum is equal to w_topline
- * and w_lines[w_lines_valid - 1].wl_lnum is equal to w_botline.
- * Between changing text and updating the display w_lines[] represents
- * what is currently displayed. wl_valid is reset to indicated this.
- * This is used for efficient redrawing.
- */
+ // Info about the lines currently in the window is remembered to avoid
+ // recomputing it every time. The allocated size of w_lines[] is Rows.
+ // Only the w_lines_valid entries are actually valid.
+ // When the display is up-to-date w_lines[0].wl_lnum is equal to w_topline
+ // and w_lines[w_lines_valid - 1].wl_lnum is equal to w_botline.
+ // Between changing text and updating the display w_lines[] represents
+ // what is currently displayed. wl_valid is reset to indicated this.
+ // This is used for efficient redrawing.
int w_lines_valid; // number of valid entries
wline_T *w_lines;
@@ -1346,9 +1287,7 @@ struct window_S {
// column being used
int w_scwidth; // width of 'signcolumn'
- /*
- * === end of cached values ===
- */
+ // === end of cached values ===
int w_redr_type; // type of redraw to be performed on win
int w_upd_rows; // number of window lines to update when
@@ -1406,17 +1345,13 @@ struct window_S {
ScopeDictDictItem w_winvar; ///< Variable for "w:" dictionary.
dict_T *w_vars; ///< Dictionary with w: variables.
- /*
- * The w_prev_pcmark field is used to check whether we really did jump to
- * a new line after setting the w_pcmark. If not, then we revert to
- * using the previous w_pcmark.
- */
+ // The w_prev_pcmark field is used to check whether we really did jump to
+ // a new line after setting the w_pcmark. If not, then we revert to
+ // using the previous w_pcmark.
pos_T w_pcmark; // previous context mark
pos_T w_prev_pcmark; // previous w_pcmark
- /*
- * the jumplist contains old cursor positions
- */
+ // the jumplist contains old cursor positions
xfmark_T w_jumplist[JUMPLISTSIZE];
int w_jumplistlen; // number of active entries
int w_jumplistidx; // current position
@@ -1426,12 +1361,10 @@ struct window_S {
matchitem_T *w_match_head; // head of match list
int w_next_match_id; // next match ID
- /*
- * the tagstack grows from 0 upwards:
- * entry 0: older
- * entry 1: newer
- * entry 2: newest
- */
+ // the tagstack grows from 0 upwards:
+ // entry 0: older
+ // entry 1: newer
+ // entry 2: newest
taggy_T w_tagstack[TAGSTACKSIZE]; // the tag stack
int w_tagstackidx; // idx just below active entry
int w_tagstacklen; // number of tags on stack
@@ -1442,17 +1375,14 @@ struct window_S {
bool w_floating; ///< whether the window is floating
FloatConfig w_float_config;
- /*
- * w_fraction is the fractional row of the cursor within the window, from
- * 0 at the top row to FRACTION_MULT at the last row.
- * w_prev_fraction_row was the actual cursor row when w_fraction was last
- * calculated.
- */
+ // w_fraction is the fractional row of the cursor within the window, from
+ // 0 at the top row to FRACTION_MULT at the last row.
+ // w_prev_fraction_row was the actual cursor row when w_fraction was last
+ // calculated.
int w_fraction;
int w_prev_fraction_row;
- linenr_T w_nrwidth_line_count; /* line count when ml_nrwidth_width
- * was computed. */
+ linenr_T w_nrwidth_line_count; // line count when ml_nrwidth_width was computed.
int w_nrwidth_width; // nr of chars to print line count.
qf_info_T *w_llist; // Location list for this window
@@ -1475,4 +1405,4 @@ struct window_S {
#define CHANGEDTICK(buf) \
(=== Include buffer.h & use buf_(get|set|inc) _changedtick ===)
-#endif // NVIM_BUFFER_DEFS_H
+#endif // NVIM_BUFFER_DEFS_H
diff --git a/src/nvim/change.c b/src/nvim/change.c
index 5bea388f28..6cd971cd74 100644
--- a/src/nvim/change.c
+++ b/src/nvim/change.c
@@ -544,7 +544,7 @@ void save_file_ff(buf_T *buf)
// Only use free/alloc when necessary, they take time.
if (buf->b_start_fenc == NULL
- || STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0) {
+ || strcmp(buf->b_start_fenc, buf->b_p_fenc) != 0) {
xfree(buf->b_start_fenc);
buf->b_start_fenc = xstrdup(buf->b_p_fenc);
}
@@ -582,7 +582,7 @@ bool file_ff_differs(buf_T *buf, bool ignore_empty)
if (buf->b_start_fenc == NULL) {
return *buf->b_p_fenc != NUL;
}
- return STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0;
+ return strcmp(buf->b_start_fenc, buf->b_p_fenc) != 0;
}
/// Insert string "p" at the cursor position. Stops at a NUL byte.
@@ -599,7 +599,7 @@ void ins_bytes_len(char *p, size_t len)
size_t n;
for (size_t i = 0; i < len; i += n) {
// avoid reading past p[len]
- n = (size_t)utfc_ptr2len_len((char_u *)p + i, (int)(len - i));
+ n = (size_t)utfc_ptr2len_len(p + i, (int)(len - i));
ins_char_bytes(p + i, n);
}
}
@@ -774,7 +774,7 @@ int del_char(bool fixpos)
int del_chars(long count, int fixpos)
{
int bytes = 0;
- char *p = (char *)get_cursor_pos_ptr();
+ char *p = get_cursor_pos_ptr();
for (long i = 0; i < count && *p != NUL; i++) {
int l = utfc_ptr2len(p);
bytes += l;
@@ -828,7 +828,7 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine)
col = n;
count = utf_ptr2len(oldp + n);
n += count;
- } while (utf_composinglike((char_u *)oldp + col, (char_u *)oldp + n));
+ } while (utf_composinglike(oldp + col, oldp + n));
fixpos = false;
}
}
@@ -1036,7 +1036,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
colnr_T mincol = curwin->w_cursor.col + 1;
// make a copy of the current line so we can mess with it
- char *saved_line = (char *)vim_strsave(get_cursor_line_ptr());
+ char *saved_line = xstrdup(get_cursor_line_ptr());
if (State & VREPLACE_FLAG) {
// With MODE_VREPLACE we make a copy of the next line, which we will be
@@ -1181,7 +1181,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
if ((pos = findmatch(NULL, '(')) != NULL) {
curwin->w_cursor.lnum = pos->lnum;
newindent = get_indent();
- ptr = (char *)get_cursor_line_ptr();
+ ptr = get_cursor_line_ptr();
}
}
// If last character is '{' do indent, without
@@ -1838,7 +1838,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
// stuff onto the replace stack (via ins_char()).
if (State & VREPLACE_FLAG) {
// Put new line in p_extra
- p_extra = (char *)vim_strsave(get_cursor_line_ptr());
+ p_extra = xstrdup(get_cursor_line_ptr());
// Put back original line
ml_replace(curwin->w_cursor.lnum, next_line, false);
diff --git a/src/nvim/charset.c b/src/nvim/charset.c
index 4604bf7716..693ff90179 100644
--- a/src/nvim/charset.c
+++ b/src/nvim/charset.c
@@ -789,7 +789,7 @@ bool vim_iswordc_buf(const int c, buf_T *const buf)
bool vim_iswordp(const char_u *const p)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
{
- return vim_iswordp_buf(p, curbuf);
+ return vim_iswordp_buf((char *)p, curbuf);
}
/// Just like vim_iswordc_buf() but uses a pointer to the (multi-byte)
@@ -799,13 +799,13 @@ bool vim_iswordp(const char_u *const p)
/// @param buf buffer whose keywords to use
///
/// @return true if "p" points to a keyword character.
-bool vim_iswordp_buf(const char_u *const p, buf_T *const buf)
+bool vim_iswordp_buf(const char *const p, buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
{
- int c = *p;
+ int c = (uint8_t)(*p);
if (MB_BYTE2LEN(c) > 1) {
- c = utf_ptr2char((char *)p);
+ c = utf_ptr2char(p);
}
return vim_iswordc_buf(c, buf);
}
@@ -829,8 +829,8 @@ bool vim_isfilec(int c)
bool vim_isfilec_or_wc(int c)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
- char_u buf[2];
- buf[0] = (char_u)c;
+ char buf[2];
+ buf[0] = (char)c;
buf[1] = NUL;
return vim_isfilec(c) || c == ']' || path_has_wildcard(buf);
}
@@ -905,15 +905,15 @@ bool in_win_border(win_T *wp, colnr_T vcol)
/// @param end
void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *end)
{
- char_u *ptr; // points to current char
- char_u *posptr; // points to char at pos->col
+ char *ptr; // points to current char
+ char *posptr; // points to char at pos->col
int incr;
int head;
long *vts = wp->w_buffer->b_p_vts_array;
int ts = (int)wp->w_buffer->b_p_ts;
colnr_T vcol = 0;
- char_u *line = ptr = ml_get_buf(wp->w_buffer, pos->lnum, false); // start of the line
+ char *line = ptr = ml_get_buf(wp->w_buffer, pos->lnum, false); // start of the line
if (pos->col == MAXCOL) {
// continue until the NUL
@@ -927,11 +927,11 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
}
}
posptr = ptr + pos->col;
- posptr -= utf_head_off((char *)line, (char *)posptr);
+ posptr -= utf_head_off(line, posptr);
}
chartabsize_T cts;
- init_chartabsize_arg(&cts, wp, pos->lnum, 0, (char *)line, (char *)line);
+ init_chartabsize_arg(&cts, wp, pos->lnum, 0, line, line);
// This function is used very often, do some speed optimizations.
// When 'list', 'linebreak', 'showbreak' and 'breakindent' are not set
@@ -944,7 +944,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
&& !cts.cts_has_virt_text) {
for (;;) {
head = 0;
- int c = *ptr;
+ int c = (uint8_t)(*ptr);
// make sure we don't go past the end of the line
if (c == NUL) {
@@ -960,7 +960,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
// For utf-8, if the byte is >= 0x80, need to look at
// further bytes to find the cell width.
if (c >= 0x80) {
- incr = utf_ptr2cells((char *)ptr);
+ incr = utf_ptr2cells(ptr);
} else {
incr = g_chartab[c] & CT_CELL_MASK;
}
@@ -970,7 +970,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
// cells wide.
if ((incr == 2)
&& wp->w_p_wrap
- && (MB_BYTE2LEN(*ptr) > 1)
+ && (MB_BYTE2LEN((uint8_t)(*ptr)) > 1)
&& in_win_border(wp, vcol)) {
incr++;
head = 1;
@@ -999,7 +999,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
break;
}
- if ((posptr != NULL) && ((char_u *)cts.cts_ptr >= posptr)) {
+ if ((posptr != NULL) && (cts.cts_ptr >= posptr)) {
// character at pos->col
break;
}
@@ -1008,7 +1008,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
MB_PTR_ADV(cts.cts_ptr);
}
vcol = cts.cts_vcol;
- ptr = (char_u *)cts.cts_ptr;
+ ptr = cts.cts_ptr;
}
clear_chartabsize_arg(&cts);
@@ -1076,10 +1076,10 @@ void getvvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *e
colnr_T endadd = 0;
// Cannot put the cursor on part of a wide character.
- char_u *ptr = ml_get_buf(wp->w_buffer, pos->lnum, false);
+ char *ptr = ml_get_buf(wp->w_buffer, pos->lnum, false);
if (pos->col < (colnr_T)STRLEN(ptr)) {
- int c = utf_ptr2char((char *)ptr + pos->col);
+ int c = utf_ptr2char(ptr + pos->col);
if ((c != TAB) && vim_isprintc(c)) {
endadd = (colnr_T)(char2cells(c) - 1);
if (coladd > endadd) {
@@ -1182,7 +1182,7 @@ char *skipwhite_len(const char *p, size_t len)
// columns (bytes) at the start of a given line
intptr_t getwhitecols_curline(void)
{
- return getwhitecols((char *)get_cursor_line_ptr());
+ return getwhitecols(get_cursor_line_ptr());
}
intptr_t getwhitecols(const char *p)
@@ -1338,7 +1338,7 @@ char *skip_to_newline(const char *const p)
/// Gets a number from a string and skips over it, signalling overflow.
///
-/// @param[out] pp A pointer to a pointer to char_u.
+/// @param[out] pp A pointer to a pointer to char.
/// It will be advanced past the read number.
/// @param[out] nr Number read from the string.
///
@@ -1355,7 +1355,7 @@ bool try_getdigits(char **pp, intmax_t *nr)
/// Gets a number from a string and skips over it.
///
-/// @param[out] pp Pointer to a pointer to char_u.
+/// @param[out] pp Pointer to a pointer to char.
/// It will be advanced past the read number.
/// @param strict Abort on overflow.
/// @param def Default value, if parsing fails or overflow occurs.
@@ -1463,14 +1463,14 @@ bool vim_isblankline(char *lbuf)
/// @param strict If true, fail if the number has unexpected trailing
/// alphanumeric chars: *len is set to 0 and nothing else is
/// returned.
-void vim_str2nr(const char_u *const start, int *const prep, int *const len, const int what,
+void vim_str2nr(const char *const start, int *const prep, int *const len, const int what,
varnumber_T *const nptr, uvarnumber_T *const unptr, const int maxlen,
const bool strict)
FUNC_ATTR_NONNULL_ARG(1)
{
- const char *ptr = (const char *)start;
+ const char *ptr = start;
#define STRING_ENDED(ptr) \
- (!(maxlen == 0 || (int)((ptr) - (const char *)start) < maxlen))
+ (!(maxlen == 0 || (int)((ptr) - start) < maxlen))
int pre = 0; // default is decimal
const bool negative = (ptr[0] == '-');
uvarnumber_T un = 0;
@@ -1522,7 +1522,7 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, cons
} else if ((what & (STR2NR_HEX | STR2NR_OCT | STR2NR_OOCT | STR2NR_BIN))
&& !STRING_ENDED(ptr + 1) && ptr[0] == '0' && ptr[1] != '8'
&& ptr[1] != '9') {
- pre = (char_u)ptr[1];
+ pre = (uint8_t)ptr[1];
// Detect hexadecimal: 0x or 0X followed by hex digit.
if ((what & STR2NR_HEX)
&& !STRING_ENDED(ptr + 2)
@@ -1610,7 +1610,7 @@ vim_str2nr_hex:
vim_str2nr_proceed:
// Check for an alphanumeric character immediately following, that is
// most likely a typo.
- if (strict && ptr - (const char *)start != maxlen && ASCII_ISALNUM(*ptr)) {
+ if (strict && ptr - start != maxlen && ASCII_ISALNUM(*ptr)) {
return;
}
@@ -1619,7 +1619,7 @@ vim_str2nr_proceed:
}
if (len != NULL) {
- *len = (int)(ptr - (const char *)start);
+ *len = (int)(ptr - start);
}
if (nptr != NULL) {
diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c
index 9d8dd197bd..3e9edea372 100644
--- a/src/nvim/cmdexpand.c
+++ b/src/nvim/cmdexpand.c
@@ -66,8 +66,8 @@ static int compl_selected;
static int sort_func_compare(const void *s1, const void *s2)
{
- char_u *p1 = *(char_u **)s1;
- char_u *p2 = *(char_u **)s2;
+ char *p1 = *(char **)s1;
+ char *p2 = *(char **)s2;
if (*p1 != '<' && *p2 == '<') {
return -1;
@@ -75,7 +75,7 @@ static int sort_func_compare(const void *s1, const void *s2)
if (*p1 == '<' && *p2 != '<') {
return 1;
}
- return STRCMP(p1, p2);
+ return strcmp(p1, p2);
}
static void ExpandEscape(expand_T *xp, char_u *str, int numfiles, char **files, int options)
@@ -177,29 +177,29 @@ int nextwild(expand_T *xp, int type, int options, bool escape)
ui_flush();
}
- i = (int)((char_u *)xp->xp_pattern - ccline->cmdbuff);
+ i = (int)(xp->xp_pattern - ccline->cmdbuff);
assert(ccline->cmdpos >= i);
xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i;
if (type == WILD_NEXT || type == WILD_PREV) {
// Get next/previous match for a previous expanded pattern.
- p2 = ExpandOne(xp, NULL, NULL, 0, type);
+ p2 = (char_u *)ExpandOne(xp, NULL, NULL, 0, type);
} else {
// Translate string into pattern and expand it.
- p1 = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
+ p1 = (char_u *)addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
const int use_options = (options
| WILD_HOME_REPLACE
| WILD_ADD_SLASH
| WILD_SILENT
| (escape ? WILD_ESCAPE : 0)
| (p_wic ? WILD_ICASE : 0));
- p2 = ExpandOne(xp, p1, vim_strnsave(&ccline->cmdbuff[i], xp->xp_pattern_len),
- use_options, type);
+ p2 = (char_u *)ExpandOne(xp, (char *)p1, xstrnsave(&ccline->cmdbuff[i], xp->xp_pattern_len),
+ use_options, type);
xfree(p1);
// xp->xp_pattern might have been modified by ExpandOne (for example,
// in lua completion), so recompute the pattern index and length
- i = (int)((char_u *)xp->xp_pattern - ccline->cmdbuff);
+ i = (int)(xp->xp_pattern - ccline->cmdbuff);
xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i;
// Longest match: make sure it is not shorter, happens with :help.
@@ -220,7 +220,7 @@ int nextwild(expand_T *xp, int type, int options, bool escape)
difflen = (int)STRLEN(p2) - (int)(xp->xp_pattern_len);
if (ccline->cmdlen + difflen + 4 > ccline->cmdbufflen) {
realloc_cmdbuff(ccline->cmdlen + difflen + 4);
- xp->xp_pattern = (char *)ccline->cmdbuff + i;
+ xp->xp_pattern = ccline->cmdbuff + i;
}
assert(ccline->cmdpos <= ccline->cmdlen);
memmove(&ccline->cmdbuff[ccline->cmdpos + difflen],
@@ -278,7 +278,7 @@ void cmdline_pum_cleanup(CmdlineInfo *cclp)
/// Get the next or prev cmdline completion match. The index of the match is set
/// in "p_findex"
-static char_u *get_next_or_prev_match(int mode, expand_T *xp, int *p_findex, char_u *orig_save)
+static char *get_next_or_prev_match(int mode, expand_T *xp, int *p_findex, char *orig_save)
{
if (xp->xp_numfiles <= 0) {
return NULL;
@@ -318,17 +318,17 @@ static char_u *get_next_or_prev_match(int mode, expand_T *xp, int *p_findex, cha
}
*p_findex = findex;
- return vim_strsave(findex == -1 ? orig_save : (char_u *)xp->xp_files[findex]);
+ return xstrdup(findex == -1 ? orig_save : xp->xp_files[findex]);
}
/// Start the command-line expansion and get the matches.
-static char_u *ExpandOne_start(int mode, expand_T *xp, char_u *str, int options)
+static char *ExpandOne_start(int mode, expand_T *xp, char *str, int options)
{
int non_suf_match; // number without matching suffix
- char_u *ss = NULL;
+ char *ss = NULL;
// Do the expansion.
- if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files, options) == FAIL) {
+ if (ExpandFromContext(xp, (char_u *)str, &xp->xp_numfiles, &xp->xp_files, options) == FAIL) {
#ifdef FNAME_ILLEGAL
// Illegal file name has been silently skipped. But when there
// are wildcards, the real problem is that there was no match,
@@ -343,7 +343,7 @@ static char_u *ExpandOne_start(int mode, expand_T *xp, char_u *str, int options)
}
} else {
// Escape the matches for use on the command line.
- ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
+ ExpandEscape(xp, (char_u *)str, xp->xp_numfiles, xp->xp_files, options);
// Check for matching suffixes in file names.
if (mode != WILD_ALL && mode != WILD_ALL_KEEP
@@ -361,7 +361,7 @@ static char_u *ExpandOne_start(int mode, expand_T *xp, char_u *str, int options)
// expand_wildcards, only need to check the first two.
non_suf_match = 0;
for (int i = 0; i < 2; i++) {
- if (match_suffix((char_u *)xp->xp_files[i])) {
+ if (match_suffix(xp->xp_files[i])) {
non_suf_match++;
}
}
@@ -378,7 +378,7 @@ static char_u *ExpandOne_start(int mode, expand_T *xp, char_u *str, int options)
}
}
if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE)) {
- ss = vim_strsave((char_u *)xp->xp_files[0]);
+ ss = xstrdup(xp->xp_files[0]);
}
}
}
@@ -458,11 +458,11 @@ static char *find_longest_match(expand_T *xp, int options)
/// The variables xp->xp_context and xp->xp_backslash must have been set!
///
/// @param orig allocated copy of original of expanded string
-char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode)
+char *ExpandOne(expand_T *xp, char *str, char *orig, int options, int mode)
{
- char_u *ss = NULL;
+ char *ss = NULL;
static int findex;
- static char_u *orig_save = NULL; // kept value of orig
+ static char *orig_save = NULL; // kept value of orig
int orig_saved = false;
int i;
@@ -472,10 +472,11 @@ char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode
}
if (mode == WILD_CANCEL) {
- ss = vim_strsave(orig_save ? orig_save : (char_u *)"");
+ ss = xstrdup(orig_save ? orig_save : "");
} else if (mode == WILD_APPLY) {
- ss = vim_strsave(findex == -1 ? (orig_save ? orig_save : (char_u *)"")
- : (char_u *)xp->xp_files[findex]);
+ ss = xstrdup(findex == -1
+ ? (orig_save ? orig_save : "")
+ : xp->xp_files[findex]);
}
// free old names
@@ -500,7 +501,7 @@ char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode
// Find longest common part
if (mode == WILD_LONGEST && xp->xp_numfiles > 0) {
- ss = (char_u *)find_longest_match(xp, options);
+ ss = find_longest_match(xp, options);
findex = -1; // next p_wc gets first one
}
@@ -573,7 +574,7 @@ int showmatches(expand_T *xp, int wildmenu)
if (xp->xp_numfiles == -1) {
set_expand_context(xp);
- i = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos,
+ i = expand_cmdline(xp, (char_u *)ccline->cmdbuff, ccline->cmdpos,
&num_files, &files_found);
showtail = expand_showtail(xp);
if (i != EXPAND_OK) {
@@ -602,7 +603,7 @@ int showmatches(expand_T *xp, int wildmenu)
.pum_kind = NULL,
};
}
- char_u *endpos = (char_u *)(showtail ? sm_gettail(xp->xp_pattern, true) : xp->xp_pattern);
+ char *endpos = (showtail ? sm_gettail(xp->xp_pattern, true) : xp->xp_pattern);
if (ui_has(kUICmdline)) {
compl_startcol = (int)(endpos - ccline->cmdbuff);
} else {
@@ -803,13 +804,13 @@ static bool expand_showtail(expand_T *xp)
/// the name into allocated memory and prepend "^".
///
/// @param context EXPAND_FILES etc.
-char_u *addstar(char_u *fname, size_t len, int context)
+char *addstar(char *fname, size_t len, int context)
FUNC_ATTR_NONNULL_RET
{
- char_u *retval;
+ char *retval;
size_t i, j;
size_t new_len;
- char_u *tail;
+ char *tail;
int ends_in_star;
if (context != EXPAND_FILES
@@ -831,7 +832,7 @@ char_u *addstar(char_u *fname, size_t len, int context)
|| context == EXPAND_PACKADD
|| ((context == EXPAND_TAGS_LISTFILES || context == EXPAND_TAGS)
&& fname[0] == '/')) {
- retval = vim_strnsave(fname, len);
+ retval = xstrnsave(fname, len);
} else {
new_len = len + 2; // +2 for '^' at start, NUL at end
for (i = 0; i < len; i++) {
@@ -901,7 +902,7 @@ char_u *addstar(char_u *fname, size_t len, int context)
// $ could be anywhere in the tail.
// ` could be anywhere in the file name.
// When the name ends in '$' don't add a star, remove the '$'.
- tail = (char_u *)path_tail((char *)retval);
+ tail = path_tail(retval);
ends_in_star = (len > 0 && retval[len - 1] == '*');
#ifndef BACKSLASH_IN_FILENAME
for (ssize_t k = (ssize_t)len - 2; k >= 0; k--) {
@@ -913,8 +914,8 @@ char_u *addstar(char_u *fname, size_t len, int context)
#endif
if ((*retval != '~' || tail != retval)
&& !ends_in_star
- && vim_strchr((char *)tail, '$') == NULL
- && vim_strchr((char *)retval, '`') == NULL) {
+ && vim_strchr(tail, '$') == NULL
+ && vim_strchr(retval, '`') == NULL) {
retval[len++] = '*';
} else if (len > 0 && retval[len - 1] == '$') {
len--;
@@ -976,7 +977,7 @@ void set_expand_context(expand_T *xp)
xp->xp_context = EXPAND_NOTHING;
return;
}
- set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true);
+ set_cmd_context(xp, (char_u *)ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true);
}
/// Sets the index of a built-in or user defined command "cmd" in eap->cmdidx.
@@ -1147,7 +1148,7 @@ static void set_context_for_wildcard_arg(exarg_T *eap, const char *arg, bool use
// A full match ~user<Tab> will be replaced by user's home
// directory i.e. something like ~user<Tab> -> /home/user/
if (*p == NUL && p > (const char *)xp->xp_pattern + 1
- && match_user((char_u *)xp->xp_pattern + 1) >= 1) {
+ && match_user(xp->xp_pattern + 1) >= 1) {
xp->xp_context = EXPAND_USER;
xp->xp_pattern++;
}
@@ -1851,7 +1852,7 @@ void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline
set_context_for_expression(xp, (char *)str, CMD_SIZE);
} else if (use_ccline && ccline->input_fn) {
xp->xp_context = ccline->xp_context;
- xp->xp_pattern = (char *)ccline->cmdbuff;
+ xp->xp_pattern = ccline->cmdbuff;
xp->xp_arg = (char *)ccline->xp_arg;
} else {
while (nextcomm != NULL) {
@@ -1898,7 +1899,7 @@ int expand_cmdline(expand_T *xp, char_u *str, int col, int *matchcount, char ***
// add star to file name, or convert to regexp if not exp. files.
assert((str + col) - (char_u *)xp->xp_pattern >= 0);
xp->xp_pattern_len = (size_t)((str + col) - (char_u *)xp->xp_pattern);
- file_str = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
+ file_str = (char_u *)addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
if (p_wic) {
options += WILD_ICASE;
@@ -1915,7 +1916,7 @@ int expand_cmdline(expand_T *xp, char_u *str, int col, int *matchcount, char ***
}
/// Expand file or directory names.
-static int expand_files_and_dirs(expand_T *xp, char_u *pat, char ***file, int *num_file, int flags,
+static int expand_files_and_dirs(expand_T *xp, char *pat, char ***file, int *num_file, int flags,
int options)
{
bool free_pat = false;
@@ -1923,7 +1924,7 @@ static int expand_files_and_dirs(expand_T *xp, char_u *pat, char ***file, int *n
// for ":set path=" and ":set tags=" halve backslashes for escaped space
if (xp->xp_backslash != XP_BS_NONE) {
free_pat = true;
- pat = vim_strsave(pat);
+ pat = xstrdup(pat);
for (int i = 0; pat[i]; i++) {
if (pat[i] == '\\') {
if (xp->xp_backslash == XP_BS_THREE
@@ -2124,7 +2125,7 @@ static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char ***f
if (xp->xp_context == EXPAND_FILES
|| xp->xp_context == EXPAND_DIRECTORIES
|| xp->xp_context == EXPAND_FILES_IN_PATH) {
- return expand_files_and_dirs(xp, pat, file, num_file, flags, options);
+ return expand_files_and_dirs(xp, (char *)pat, file, num_file, flags, options);
}
*file = NULL;
@@ -2142,7 +2143,7 @@ static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char ***f
if (xp->xp_context == EXPAND_SHELLCMD) {
*file = NULL;
- expand_shellcmd(pat, num_file, file, flags);
+ expand_shellcmd((char *)pat, num_file, file, flags);
return OK;
}
if (xp->xp_context == EXPAND_OLD_SETTING) {
@@ -2238,18 +2239,18 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha
{
int i;
size_t count = 0;
- char_u *str;
+ char *str;
// count the number of matching names
for (i = 0;; i++) {
- str = (char_u *)(*func)(xp, i);
+ str = (*func)(xp, i);
if (str == NULL) { // end of list
break;
}
if (*str == NUL) { // skip empty strings
continue;
}
- if (vim_regexec(regmatch, (char *)str, (colnr_T)0)) {
+ if (vim_regexec(regmatch, str, (colnr_T)0)) {
count++;
}
}
@@ -2263,20 +2264,20 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha
// copy the matching names into allocated memory
count = 0;
for (i = 0;; i++) {
- str = (char_u *)(*func)(xp, i);
+ str = (*func)(xp, i);
if (str == NULL) { // End of list.
break;
}
if (*str == NUL) { // Skip empty strings.
continue;
}
- if (vim_regexec(regmatch, (char *)str, (colnr_T)0)) {
+ if (vim_regexec(regmatch, str, (colnr_T)0)) {
if (escaped) {
- str = vim_strsave_escaped(str, (char_u *)" \t\\.");
+ str = (char *)vim_strsave_escaped((char_u *)str, (char_u *)" \t\\.");
} else {
- str = vim_strsave(str);
+ str = xstrdup(str);
}
- (*file)[count++] = (char *)str;
+ (*file)[count++] = str;
if (func == get_menu_names) {
// Test for separator added by get_menu_names().
str += STRLEN(str) - 1;
@@ -2293,8 +2294,7 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha
|| xp->xp_context == EXPAND_FUNCTIONS
|| xp->xp_context == EXPAND_USER_FUNC) {
// <SNR> functions should be sorted to the end.
- qsort((void *)(*file), (size_t)(*num_file), sizeof(char_u *),
- sort_func_compare);
+ qsort((void *)(*file), (size_t)(*num_file), sizeof(char *), sort_func_compare);
} else {
sort_strings(*file, *num_file);
}
@@ -2313,22 +2313,22 @@ static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, cha
/// *file will either be set to NULL or point to
/// allocated memory.
/// @param flagsarg is a combination of EW_* flags.
-static void expand_shellcmd(char_u *filepat, int *num_file, char ***file, int flagsarg)
+static void expand_shellcmd(char *filepat, int *num_file, char ***file, int flagsarg)
FUNC_ATTR_NONNULL_ALL
{
- char_u *pat;
+ char *pat;
int i;
- char_u *path = NULL;
+ char *path = NULL;
garray_T ga;
char *buf = xmalloc(MAXPATHL);
size_t l;
- char_u *s, *e;
+ char *s, *e;
int flags = flagsarg;
int ret;
bool did_curdir = false;
// for ":set path=" and ":set tags=" halve backslashes for escaped space
- pat = vim_strsave(filepat);
+ pat = xstrdup(filepat);
for (i = 0; pat[i]; i++) {
if (pat[i] == '\\' && pat[i + 1] == ' ') {
STRMOVE(pat + i, pat + i + 1);
@@ -2340,14 +2340,14 @@ static void expand_shellcmd(char_u *filepat, int *num_file, char ***file, int fl
bool mustfree = false; // Track memory allocation for *path.
if (pat[0] == '.' && (vim_ispathsep(pat[1])
|| (pat[1] == '.' && vim_ispathsep(pat[2])))) {
- path = (char_u *)".";
+ path = ".";
} else {
// For an absolute name we don't use $PATH.
- if (!path_is_absolute(pat)) {
- path = (char_u *)vim_getenv("PATH");
+ if (!path_is_absolute((char_u *)pat)) {
+ path = vim_getenv("PATH");
}
if (path == NULL) {
- path = (char_u *)"";
+ path = "";
} else {
mustfree = true;
}
@@ -2360,7 +2360,7 @@ static void expand_shellcmd(char_u *filepat, int *num_file, char ***file, int fl
hashtab_T found_ht;
hash_init(&found_ht);
for (s = path;; s = e) {
- e = (char_u *)vim_strchr((char *)s, ENV_SEPCHAR);
+ e = vim_strchr(s, ENV_SEPCHAR);
if (e == NULL) {
e = s + STRLEN(s);
}
@@ -2438,9 +2438,9 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T
FUNC_ATTR_NONNULL_ALL
{
CmdlineInfo *const ccline = get_cmdline_info();
- char_u keep = 0;
+ char keep = 0;
typval_T args[4];
- char_u *pat = NULL;
+ char *pat = NULL;
const sctx_T save_current_sctx = current_sctx;
if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL) {
@@ -2454,12 +2454,12 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T
ccline->cmdbuff[ccline->cmdlen] = 0;
}
- pat = vim_strnsave((char_u *)xp->xp_pattern, xp->xp_pattern_len);
+ pat = xstrnsave(xp->xp_pattern, xp->xp_pattern_len);
args[0].v_type = VAR_STRING;
args[1].v_type = VAR_STRING;
args[2].v_type = VAR_NUMBER;
args[3].v_type = VAR_UNKNOWN;
- args[0].vval.v_string = (char *)pat;
+ args[0].vval.v_string = pat;
args[1].vval.v_string = xp->xp_line;
args[2].vval.v_number = xp->xp_col;
@@ -2479,30 +2479,29 @@ static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T
/// Expand names with a function defined by the user.
static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file)
{
- char_u *e;
+ char *e;
garray_T ga;
- char_u *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file,
- file);
+ char *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file,
+ file);
if (retstr == NULL) {
return FAIL;
}
ga_init(&ga, (int)sizeof(char *), 3);
- for (char_u *s = retstr; *s != NUL; s = e) {
- e = (char_u *)vim_strchr((char *)s, '\n');
+ for (char *s = retstr; *s != NUL; s = e) {
+ e = vim_strchr(s, '\n');
if (e == NULL) {
e = s + STRLEN(s);
}
- const char_u keep = *e;
+ const char keep = *e;
*e = NUL;
- const bool skip = xp->xp_pattern[0]
- && vim_regexec(regmatch, (char *)s, (colnr_T)0) == 0;
+ const bool skip = xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0;
*e = keep;
if (!skip) {
- GA_APPEND(char_u *, &ga, vim_strnsave(s, (size_t)(e - s)));
+ GA_APPEND(char *, &ga, xstrnsave(s, (size_t)(e - s)));
}
if (*e != NUL) {
@@ -2663,7 +2662,7 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp)
// cursor
int found = false;
- int j = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff);
+ int j = (int)(xp->xp_pattern - cclp->cmdbuff);
int i = 0;
while (--j > 0) {
// check for start of menu name
@@ -2718,9 +2717,9 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp)
int found = false;
int j = cclp->cmdpos;
- int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff);
+ int i = (int)(xp->xp_pattern - cclp->cmdbuff);
while (--j > i) {
- j -= utf_head_off((char *)cclp->cmdbuff, (char *)cclp->cmdbuff + j);
+ j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j);
if (vim_ispathsep(cclp->cmdbuff[j])) {
found = true;
break;
@@ -2739,9 +2738,9 @@ int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp)
int found = false;
int j = cclp->cmdpos - 1;
- int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff);
+ int i = (int)(xp->xp_pattern - cclp->cmdbuff);
while (--j > i) {
- j -= utf_head_off((char *)cclp->cmdbuff, (char *)cclp->cmdbuff + j);
+ j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j);
if (vim_ispathsep(cclp->cmdbuff[j])
#ifdef BACKSLASH_IN_FILENAME
&& vim_strchr((const char_u *)" *?[{`$%#", cclp->cmdbuff[j + 1])
@@ -2895,8 +2894,8 @@ void f_getcompletion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
theend:
- pat = addstar((char_u *)xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
- ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP);
+ pat = (char_u *)addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
+ ExpandOne(&xpc, (char *)pat, NULL, options, WILD_ALL_KEEP);
tv_list_alloc_ret(rettv, xpc.xp_numfiles);
for (int i = 0; i < xpc.xp_numfiles; i++) {
diff --git a/src/nvim/cmdhist.c b/src/nvim/cmdhist.c
index 2057b0db9e..3747c91c4f 100644
--- a/src/nvim/cmdhist.c
+++ b/src/nvim/cmdhist.c
@@ -186,7 +186,7 @@ static inline void clear_hist_entry(histentry_T *hisptr)
/// If 'move_to_front' is true, matching entry is moved to end of history.
///
/// @param move_to_front Move the entry to the front if it exists
-static int in_history(int type, char_u *str, int move_to_front, int sep)
+static int in_history(int type, char *str, int move_to_front, int sep)
{
int last_i = -1;
@@ -201,8 +201,8 @@ static int in_history(int type, char_u *str, int move_to_front, int sep)
// For search history, check that the separator character matches as
// well.
- char_u *p = history[type][i].hisstr;
- if (STRCMP(str, p) == 0
+ char *p = history[type][i].hisstr;
+ if (strcmp(str, p) == 0
&& (type != HIST_SEARCH || sep == p[STRLEN(p) + 1])) {
if (!move_to_front) {
return true;
@@ -276,7 +276,7 @@ static int last_maptick = -1; // last seen maptick
/// @param histype may be one of the HIST_ values.
/// @param in_map consider maptick when inside a mapping
/// @param sep separator character used (search hist)
-void add_to_history(int histype, char_u *new_entry, int in_map, int sep)
+void add_to_history(int histype, char *new_entry, int in_map, int sep)
{
histentry_T *hisptr;
@@ -313,10 +313,10 @@ void add_to_history(int histype, char_u *new_entry, int in_map, int sep)
// Store the separator after the NUL of the string.
size_t len = STRLEN(new_entry);
- hisptr->hisstr = vim_strnsave(new_entry, len + 2);
+ hisptr->hisstr = xstrnsave(new_entry, len + 2);
hisptr->timestamp = os_time();
hisptr->additional_elements = NULL;
- hisptr->hisstr[len + 1] = (char_u)sep;
+ hisptr->hisstr[len + 1] = (char)sep;
hisptr->hisnum = ++hisnum[histype];
if (histype == HIST_SEARCH && in_map) {
@@ -382,13 +382,13 @@ static int calc_hist_idx(int histype, int num)
/// Get a history entry by its index.
///
/// @param histype may be one of the HIST_ values.
-static char_u *get_history_entry(int histype, int idx)
+static char *get_history_entry(int histype, int idx)
{
idx = calc_hist_idx(histype, idx);
if (idx >= 0) {
return history[histype][idx].hisstr;
} else {
- return (char_u *)"";
+ return "";
}
}
@@ -438,7 +438,7 @@ static int del_history_entry(int histype, char_u *str)
if (hisptr->hisstr == NULL) {
break;
}
- if (vim_regexec(&regmatch, (char *)hisptr->hisstr, (colnr_T)0)) {
+ if (vim_regexec(&regmatch, hisptr->hisstr, (colnr_T)0)) {
found = true;
hist_free_entry(hisptr);
} else {
@@ -509,7 +509,7 @@ void f_histadd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
str = tv_get_string_buf(&argvars[1], buf);
if (*str != NUL) {
init_history();
- add_to_history(histype, (char_u *)str, false, NUL);
+ add_to_history(histype, (char *)str, false, NUL);
rettv->vval.v_number = true;
return;
}
@@ -556,7 +556,7 @@ void f_histget(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
idx = (int)tv_get_number_chk(&argvars[1], NULL);
}
// -1 on type error
- rettv->vval.v_string = (char *)vim_strsave(get_history_entry(type, idx));
+ rettv->vval.v_string = xstrdup(get_history_entry(type, idx));
}
rettv->v_type = VAR_STRING;
}
@@ -643,8 +643,8 @@ void ex_history(exarg_T *eap)
msg_putchar('\n');
snprintf((char *)IObuff, IOSIZE, "%c%6d ", i == idx ? '>' : ' ',
hist[i].hisnum);
- if (vim_strsize((char *)hist[i].hisstr) > Columns - 10) {
- trunc_string((char *)hist[i].hisstr, (char *)IObuff + STRLEN(IObuff),
+ if (vim_strsize(hist[i].hisstr) > Columns - 10) {
+ trunc_string(hist[i].hisstr, (char *)IObuff + STRLEN(IObuff),
Columns - 10, IOSIZE - (int)STRLEN(IObuff));
} else {
STRCAT(IObuff, hist[i].hisstr);
diff --git a/src/nvim/cmdhist.h b/src/nvim/cmdhist.h
index 797b79a5f0..8b7bb7ac24 100644
--- a/src/nvim/cmdhist.h
+++ b/src/nvim/cmdhist.h
@@ -22,7 +22,7 @@ typedef enum {
/// History entry definition
typedef struct hist_entry {
int hisnum; ///< Entry identifier number.
- char_u *hisstr; ///< Actual entry, separator char after the NUL.
+ char *hisstr; ///< Actual entry, separator char after the NUL.
Timestamp timestamp; ///< Time when entry was added.
list_T *additional_elements; ///< Additional entries from ShaDa file.
} histentry_T;
diff --git a/src/nvim/cursor.c b/src/nvim/cursor.c
index 54e5ffff37..cd651fcf4c 100644
--- a/src/nvim/cursor.c
+++ b/src/nvim/cursor.c
@@ -101,7 +101,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
|| (VIsual_active && *p_sel != 'o')
|| ((get_ve_flags() & VE_ONEMORE) && wcol < MAXCOL);
- char_u *line = ml_get_buf(curbuf, pos->lnum, false);
+ char_u *line = (char_u *)ml_get_buf(curbuf, pos->lnum, false);
if (wcol >= MAXCOL) {
idx = (int)STRLEN(line) - 1 + one_more;
@@ -308,7 +308,7 @@ void check_pos(buf_T *buf, pos_T *pos)
}
if (pos->col > 0) {
- char_u *line = ml_get_buf(buf, pos->lnum, false);
+ char_u *line = (char_u *)ml_get_buf(buf, pos->lnum, false);
colnr_T len = (colnr_T)STRLEN(line);
if (pos->col > len) {
pos->col = len;
@@ -481,7 +481,7 @@ bool leftcol_changed(void)
int gchar_cursor(void)
{
- return utf_ptr2char((char *)get_cursor_pos_ptr());
+ return utf_ptr2char(get_cursor_pos_ptr());
}
/// Write a character at the current cursor position.
@@ -489,18 +489,17 @@ int gchar_cursor(void)
void pchar_cursor(char_u c)
{
*(ml_get_buf(curbuf, curwin->w_cursor.lnum, true)
- + curwin->w_cursor.col) = c;
+ + curwin->w_cursor.col) = (char)c;
}
/// @return pointer to cursor line.
-char_u *get_cursor_line_ptr(void)
+char *get_cursor_line_ptr(void)
{
return ml_get_buf(curbuf, curwin->w_cursor.lnum, false);
}
/// @return pointer to cursor position.
-char_u *get_cursor_pos_ptr(void)
+char *get_cursor_pos_ptr(void)
{
- return ml_get_buf(curbuf, curwin->w_cursor.lnum, false) +
- curwin->w_cursor.col;
+ return ml_get_buf(curbuf, curwin->w_cursor.lnum, false) + curwin->w_cursor.col;
}
diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c
index b720628e33..e91491e665 100644
--- a/src/nvim/debugger.c
+++ b/src/nvim/debugger.c
@@ -646,7 +646,7 @@ void ex_breakdel(exarg_T *eap)
for (int i = 0; i < gap->ga_len; i++) {
bpi = &DEBUGGY(gap, i);
if (bp->dbg_type == bpi->dbg_type
- && STRCMP(bp->dbg_name, bpi->dbg_name) == 0
+ && strcmp(bp->dbg_name, bpi->dbg_name) == 0
&& (bp->dbg_lnum == bpi->dbg_lnum
|| (bp->dbg_lnum == 0
&& (best_lnum == 0
diff --git a/src/nvim/decoration.c b/src/nvim/decoration.c
index 8955048f45..778f9293fb 100644
--- a/src/nvim/decoration.c
+++ b/src/nvim/decoration.c
@@ -69,7 +69,7 @@ void bufhl_add_hl_pos_offset(buf_T *buf, int src_id, int hl_id, lpos_T pos_start
void decor_redraw(buf_T *buf, int row1, int row2, Decoration *decor)
{
if (row2 >= row1) {
- if (!decor || decor->hl_id || decor_has_sign(decor) || decor->conceal) {
+ if (!decor || decor->hl_id || decor_has_sign(decor) || decor->conceal || decor->spell) {
redraw_buf_range_later(buf, row1 + 1, row2 + 1);
}
}
@@ -116,6 +116,11 @@ void decor_free(Decoration *decor)
}
}
+void decor_state_free(DecorState *state)
+{
+ xfree(state->active.items);
+}
+
void clear_virttext(VirtText *text)
{
for (size_t i = 0; i < kv_size(*text); i++) {
@@ -306,6 +311,7 @@ next_mark:
bool conceal = 0;
int conceal_char = 0;
int conceal_attr = 0;
+ bool spell = false;
for (size_t i = 0; i < kv_size(state->active); i++) {
DecorRange item = kv_A(state->active, i);
@@ -339,6 +345,9 @@ next_mark:
conceal_attr = item.attr_id;
}
}
+ if (active && item.decor.spell) {
+ spell = true;
+ }
if ((item.start_row == state->row && item.start_col <= col)
&& decor_virt_pos(item.decor)
&& item.decor.virt_text_pos == kVTOverlay && item.win_col == -1) {
@@ -355,6 +364,7 @@ next_mark:
state->conceal = conceal;
state->conceal_char = conceal_char;
state->conceal_attr = conceal_attr;
+ state->spell = spell;
return attr;
}
diff --git a/src/nvim/decoration.h b/src/nvim/decoration.h
index 8f28442d41..bdbfd72a81 100644
--- a/src/nvim/decoration.h
+++ b/src/nvim/decoration.h
@@ -46,6 +46,7 @@ struct Decoration {
bool hl_eol;
bool virt_lines_above;
bool conceal;
+ bool spell;
// TODO(bfredl): style, etc
DecorPriority priority;
int col; // fixed col value, like win_col
@@ -61,8 +62,8 @@ struct Decoration {
bool ui_watched; // watched for win_extmark
};
#define DECORATION_INIT { KV_INITIAL_VALUE, KV_INITIAL_VALUE, 0, kVTEndOfLine, \
- kHlModeUnknown, false, false, false, false, DECOR_PRIORITY_BASE, \
- 0, 0, NULL, 0, 0, 0, 0, 0, false }
+ kHlModeUnknown, false, false, false, false, false, \
+ DECOR_PRIORITY_BASE, 0, 0, NULL, 0, 0, 0, 0, 0, false }
typedef struct {
int start_row;
@@ -90,6 +91,8 @@ typedef struct {
bool conceal;
int conceal_char;
int conceal_attr;
+
+ bool spell;
} DecorState;
EXTERN DecorState decor_state INIT(= { 0 });
diff --git a/src/nvim/decoration_provider.c b/src/nvim/decoration_provider.c
index 14c1238fa4..a11a4d2b04 100644
--- a/src/nvim/decoration_provider.c
+++ b/src/nvim/decoration_provider.c
@@ -7,6 +7,7 @@
#include "nvim/decoration.h"
#include "nvim/decoration_provider.h"
#include "nvim/highlight.h"
+#include "nvim/lib/kvec.h"
#include "nvim/lua/executor.h"
static kvec_t(DecorProvider) decor_providers = KV_INITIAL_VALUE;
@@ -14,7 +15,7 @@ static kvec_t(DecorProvider) decor_providers = KV_INITIAL_VALUE;
#define DECORATION_PROVIDER_INIT(ns_id) (DecorProvider) \
{ ns_id, false, LUA_NOREF, LUA_NOREF, \
LUA_NOREF, LUA_NOREF, LUA_NOREF, \
- LUA_NOREF, -1, false }
+ LUA_NOREF, -1, false, false }
static bool decor_provider_invoke(NS ns_id, const char *name, LuaRef ref, Array args,
bool default_true, char **perr)
@@ -47,11 +48,33 @@ static bool decor_provider_invoke(NS ns_id, const char *name, LuaRef ref, Array
return false;
}
+void decor_providers_invoke_spell(win_T *wp, int start_row, int start_col, int end_row, int end_col,
+ char **err)
+{
+ for (size_t i = 0; i < kv_size(decor_providers); i++) {
+ DecorProvider *p = &kv_A(decor_providers, i);
+ if (!p->active) {
+ continue;
+ }
+
+ if (p->spell_nav != LUA_NOREF) {
+ MAXSIZE_TEMP_ARRAY(args, 6);
+ ADD_C(args, INTEGER_OBJ(wp->handle));
+ ADD_C(args, INTEGER_OBJ(wp->w_buffer->handle));
+ ADD_C(args, INTEGER_OBJ(start_row));
+ ADD_C(args, INTEGER_OBJ(start_col));
+ ADD_C(args, INTEGER_OBJ(end_row));
+ ADD_C(args, INTEGER_OBJ(end_col));
+ decor_provider_invoke(p->ns_id, "spell", p->spell_nav, args, true, err);
+ }
+ }
+}
+
/// For each provider invoke the 'start' callback
///
/// @param[out] providers Decoration providers
/// @param[out] err Provider err
-void decor_providers_start(DecorProviders *providers, int type, char **err)
+void decor_providers_start(DecorProviders *providers, char **err)
{
kvi_init(*providers);
@@ -65,7 +88,6 @@ void decor_providers_start(DecorProviders *providers, int type, char **err)
if (p->redraw_start != LUA_NOREF) {
MAXSIZE_TEMP_ARRAY(args, 2);
ADD_C(args, INTEGER_OBJ((int)display_tick));
- ADD_C(args, INTEGER_OBJ(type));
active = decor_provider_invoke(p->ns_id, "start", p->redraw_start, args, true, err);
} else {
active = true;
@@ -116,8 +138,8 @@ void decor_providers_invoke_win(win_T *wp, DecorProviders *providers,
/// @param row Row to invoke line callback for
/// @param[out] has_decor Set when at least one provider invokes a line callback
/// @param[out] err Provider error
-void providers_invoke_line(win_T *wp, DecorProviders *providers, int row, bool *has_decor,
- char **err)
+void decor_providers_invoke_line(win_T *wp, DecorProviders *providers, int row, bool *has_decor,
+ char **err)
{
for (size_t k = 0; k < kv_size(*providers); k++) {
DecorProvider *p = kv_A(*providers, k);
@@ -215,6 +237,7 @@ void decor_provider_clear(DecorProvider *p)
NLUA_CLEAR_REF(p->redraw_win);
NLUA_CLEAR_REF(p->redraw_line);
NLUA_CLEAR_REF(p->redraw_end);
+ NLUA_CLEAR_REF(p->spell_nav);
p->active = false;
}
diff --git a/src/nvim/decoration_provider.h b/src/nvim/decoration_provider.h
index dd1ed6c581..852b1583b9 100644
--- a/src/nvim/decoration_provider.h
+++ b/src/nvim/decoration_provider.h
@@ -12,6 +12,7 @@ typedef struct {
LuaRef redraw_line;
LuaRef redraw_end;
LuaRef hl_def;
+ LuaRef spell_nav;
int hl_valid;
bool hl_cached;
} DecorProvider;
diff --git a/src/nvim/diff.c b/src/nvim/diff.c
index a3046bb7d7..c5092dc866 100644
--- a/src/nvim/diff.c
+++ b/src/nvim/diff.c
@@ -573,9 +573,9 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp)
if (dir == BACKWARD) {
off_org = dp->df_count[i_org] - 1;
}
- char *line_org = (char *)vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org],
- dp->df_lnum[i_org] + off_org,
- false));
+ char *line_org = xstrdup(ml_get_buf(tp->tp_diffbuf[i_org],
+ dp->df_lnum[i_org] + off_org,
+ false));
int i_new;
for (i_new = i_org + 1; i_new < DB_COUNT; i_new++) {
@@ -592,9 +592,9 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp)
break;
}
- if (diff_cmp((char_u *)line_org, ml_get_buf(tp->tp_diffbuf[i_new],
- dp->df_lnum[i_new] + off_new,
- false)) != 0) {
+ if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new],
+ dp->df_lnum[i_new] + off_new,
+ false)) != 0) {
break;
}
}
@@ -750,7 +750,7 @@ static int diff_write_buffer(buf_T *buf, diffin_T *din)
len = 0;
for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
- for (char_u *s = ml_get_buf(buf, lnum, false); *s != NUL;) {
+ for (char_u *s = (char_u *)ml_get_buf(buf, lnum, false); *s != NUL;) {
if (diff_flags & DIFF_ICASE) {
int c;
char cbuf[MB_MAXBYTES + 1];
@@ -824,9 +824,9 @@ static void diff_try_update(diffio_T *dio, int idx_orig, exarg_T *eap)
ga_init(&dio->dio_diff.dout_ga, sizeof(char *), 1000);
} else {
// We need three temp file names.
- dio->dio_orig.din_fname = vim_tempname();
- dio->dio_new.din_fname = vim_tempname();
- dio->dio_diff.dout_fname = vim_tempname();
+ dio->dio_orig.din_fname = (char_u *)vim_tempname();
+ dio->dio_new.din_fname = (char_u *)vim_tempname();
+ dio->dio_diff.dout_fname = (char_u *)vim_tempname();
if (dio->dio_orig.din_fname == NULL
|| dio->dio_new.din_fname == NULL
|| dio->dio_diff.dout_fname == NULL) {
@@ -1178,9 +1178,9 @@ void ex_diffpatch(exarg_T *eap)
// We need two temp file names.
// Name of original temp file.
- char_u *tmp_orig = vim_tempname();
+ char_u *tmp_orig = (char_u *)vim_tempname();
// Name of patched temp file.
- char_u *tmp_new = vim_tempname();
+ char_u *tmp_new = (char_u *)vim_tempname();
if ((tmp_orig == NULL) || (tmp_new == NULL)) {
goto theend;
@@ -1920,11 +1920,11 @@ static bool diff_equal_entry(diff_T *dp, int idx1, int idx2)
}
for (int i = 0; i < dp->df_count[idx1]; i++) {
- char *line = (char *)vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1],
- dp->df_lnum[idx1] + i, false));
+ char *line = xstrdup(ml_get_buf(curtab->tp_diffbuf[idx1],
+ dp->df_lnum[idx1] + i, false));
- int cmp = diff_cmp((char_u *)line, ml_get_buf(curtab->tp_diffbuf[idx2],
- dp->df_lnum[idx2] + i, false));
+ int cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2],
+ dp->df_lnum[idx2] + i, false));
xfree(line);
if (cmp != 0) {
@@ -1968,23 +1968,23 @@ static bool diff_equal_char(const char_u *const p1, const char_u *const p2, int
/// @param s2 The second string
///
/// @return on-zero if the two strings are different.
-static int diff_cmp(char_u *s1, char_u *s2)
+static int diff_cmp(char *s1, char *s2)
{
if ((diff_flags & DIFF_IBLANK)
- && (*(char_u *)skipwhite((char *)s1) == NUL || *skipwhite((char *)s2) == NUL)) {
+ && (*(char_u *)skipwhite(s1) == NUL || *skipwhite(s2) == NUL)) {
return 0;
}
if ((diff_flags & (DIFF_ICASE | ALL_WHITE_DIFF)) == 0) {
- return STRCMP(s1, s2);
+ return strcmp(s1, s2);
}
if ((diff_flags & DIFF_ICASE) && !(diff_flags & ALL_WHITE_DIFF)) {
return mb_stricmp((const char *)s1, (const char *)s2);
}
- char *p1 = (char *)s1;
- char *p2 = (char *)s2;
+ char *p1 = s1;
+ char *p2 = s2;
// Ignore white space changes and possibly ignore case.
while (*p1 != NUL && *p2 != NUL) {
@@ -2290,7 +2290,7 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp)
int l;
// Make a copy of the line, the next ml_get() will invalidate it.
- char *line_org = (char *)vim_strsave(ml_get_buf(wp->w_buffer, lnum, false));
+ char *line_org = xstrdup(ml_get_buf(wp->w_buffer, lnum, false));
int idx = diff_buf_idx(wp->w_buffer);
if (idx == DB_COUNT) {
@@ -2322,8 +2322,7 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp)
continue;
}
added = false;
- line_new = (char *)ml_get_buf(curtab->tp_diffbuf[i],
- dp->df_lnum[i] + off, false);
+ line_new = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off, false);
// Search for start of difference
si_org = si_new = 0;
@@ -2718,7 +2717,7 @@ void ex_diffgetput(exarg_T *eap)
if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) {
break;
}
- p = (char *)vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, false));
+ p = xstrdup(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, false));
ml_append(lnum + i - 1, p, 0, false);
xfree(p);
added++;
diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c
index e4528f9038..8e31d3feab 100644
--- a/src/nvim/digraph.c
+++ b/src/nvim/digraph.c
@@ -1932,9 +1932,9 @@ void f_digraph_get(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
int code = digraph_get(digraphs[0], digraphs[1], false);
- char_u buf[NUMBUFLEN];
- buf[utf_char2bytes(code, (char *)buf)] = NUL;
- rettv->vval.v_string = (char *)vim_strsave(buf);
+ char buf[NUMBUFLEN];
+ buf[utf_char2bytes(code, buf)] = NUL;
+ rettv->vval.v_string = xstrdup(buf);
}
/// "digraph_getlist()" function
@@ -2010,8 +2010,8 @@ void f_digraph_setlist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
/// structure used for b_kmap_ga.ga_data
typedef struct {
- char_u *from;
- char_u *to;
+ char *from;
+ char *to;
} kmap_T;
#define KMAP_MAXLEN 20 // maximum length of "from" or "to"
@@ -2064,10 +2064,10 @@ char *keymap_init(void)
/// @param eap
void ex_loadkeymap(exarg_T *eap)
{
- char_u *s;
+ char *s;
#define KMAP_LLEN 200 // max length of "to" and "from" together
- char_u buf[KMAP_LLEN + 11];
+ char buf[KMAP_LLEN + 11];
char *save_cpo = p_cpo;
if (!getline_equal(eap->getline, eap->cookie, getsourceline)) {
@@ -2092,15 +2092,15 @@ void ex_loadkeymap(exarg_T *eap)
break;
}
- char_u *p = (char_u *)skipwhite(line);
+ char *p = skipwhite(line);
if ((*p != '"') && (*p != NUL)) {
kmap_T *kp = GA_APPEND_VIA_PTR(kmap_T, &curbuf->b_kmap_ga);
- s = (char_u *)skiptowhite((char *)p);
- kp->from = vim_strnsave(p, (size_t)(s - p));
- p = (char_u *)skipwhite((char *)s);
- s = (char_u *)skiptowhite((char *)p);
- kp->to = vim_strnsave(p, (size_t)(s - p));
+ s = skiptowhite(p);
+ kp->from = xstrnsave(p, (size_t)(s - p));
+ p = skipwhite(s);
+ s = skiptowhite(p);
+ kp->to = xstrnsave(p, (size_t)(s - p));
if ((STRLEN(kp->from) + STRLEN(kp->to) >= KMAP_LLEN)
|| (*kp->from == NUL)
@@ -2118,10 +2118,10 @@ void ex_loadkeymap(exarg_T *eap)
// setup ":lmap" to map the keys
for (int i = 0; i < curbuf->b_kmap_ga.ga_len; i++) {
- vim_snprintf((char *)buf, sizeof(buf), "<buffer> %s %s",
+ vim_snprintf(buf, sizeof(buf), "<buffer> %s %s",
((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].from,
((kmap_T *)curbuf->b_kmap_ga.ga_data)[i].to);
- (void)do_map(MAPTYPE_MAP, buf, MODE_LANGMAP, false);
+ (void)do_map(MAPTYPE_MAP, (char_u *)buf, MODE_LANGMAP, false);
}
p_cpo = save_cpo;
diff --git a/src/nvim/drawline.c b/src/nvim/drawline.c
index 85a0bf2f5f..9de8b9996a 100644
--- a/src/nvim/drawline.c
+++ b/src/nvim/drawline.c
@@ -11,9 +11,11 @@
#include "nvim/arabic.h"
#include "nvim/buffer.h"
+#include "nvim/buffer_defs.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/cursor_shape.h"
+#include "nvim/decoration.h"
#include "nvim/diff.h"
#include "nvim/drawline.h"
#include "nvim/fold.h"
@@ -654,7 +656,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
has_decor = decor_redraw_line(buf, lnum - 1, &decor_state);
- providers_invoke_line(wp, providers, lnum - 1, &has_decor, provider_err);
+ decor_providers_invoke_line(wp, providers, lnum - 1, &has_decor, provider_err);
if (*provider_err) {
provider_err_virt_text(lnum, *provider_err);
@@ -687,7 +689,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
// Trick: skip a few chars for C/shell/Vim comments
nextline[SPWORDLEN] = NUL;
if (lnum < wp->w_buffer->b_ml.ml_line_count) {
- line = ml_get_buf(wp->w_buffer, lnum + 1, false);
+ line = (char_u *)ml_get_buf(wp->w_buffer, lnum + 1, false);
spell_cat_line(nextline + SPWORDLEN, line, SPWORDLEN);
}
@@ -864,7 +866,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
line_attr_lowprio_save = line_attr_lowprio;
}
- line = end_fill ? (char_u *)"" : ml_get_buf(wp->w_buffer, lnum, false);
+ line = end_fill ? (char_u *)"" : (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
ptr = line;
if (has_spell && !number_only) {
@@ -1004,7 +1006,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
len = spell_move_to(wp, FORWARD, true, true, &spell_hlf);
// spell_move_to() may call ml_get() and make "line" invalid
- line = ml_get_buf(wp->w_buffer, lnum, false);
+ line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
ptr = line + linecol;
if (len == 0 || (int)wp->w_cursor.col > ptr - line) {
@@ -1222,7 +1224,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
c_extra = ' ';
c_final = NUL;
n_extra =
- get_breakindent_win(wp, ml_get_buf(wp->w_buffer, lnum, false));
+ get_breakindent_win(wp, (char_u *)ml_get_buf(wp->w_buffer, lnum, false));
if (row == startrow) {
n_extra -= win_col_off2(wp);
if (n_extra < 0) {
@@ -1646,7 +1648,8 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
ptr++;
if (extra_check) {
- bool can_spell = true;
+ bool no_plain_buffer = (wp->w_s->b_p_spo_flags & SPO_NPBUFFER) != 0;
+ bool can_spell = !no_plain_buffer;
// Get syntax attribute, unless still at the start of the line
// (double-wide char that doesn't fit).
@@ -1673,7 +1676,7 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
// Need to get the line again, a multi-line regexp may
// have made it invalid.
- line = ml_get_buf(wp->w_buffer, lnum, false);
+ line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
ptr = line + v;
if (!attr_pri) {
@@ -1698,6 +1701,29 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
char_attr = 0;
}
+ if (has_decor && v > 0) {
+ bool selected = (area_active || (area_highlighting && noinvcur
+ && (colnr_T)vcol == wp->w_virtcol));
+ int extmark_attr = decor_redraw_col(wp->w_buffer, (colnr_T)v - 1, off,
+ selected, &decor_state);
+ if (extmark_attr != 0) {
+ if (!attr_pri) {
+ char_attr = hl_combine_attr(char_attr, extmark_attr);
+ } else {
+ char_attr = hl_combine_attr(extmark_attr, char_attr);
+ }
+ }
+
+ decor_conceal = decor_state.conceal;
+ if (decor_conceal && decor_state.conceal_char) {
+ decor_conceal = 2; // really??
+ }
+
+ if (decor_state.spell) {
+ can_spell = true;
+ }
+ }
+
// Check spelling (unless at the end of the line).
// Only do this when there is no syntax highlighting, the
// @Spell cluster is not used or the current syntax item
@@ -1706,9 +1732,9 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
if (has_spell && v >= word_end && v > cur_checked_col) {
spell_attr = 0;
if (!attr_pri) {
- char_attr = syntax_attr;
+ char_attr = hl_combine_attr(char_attr, syntax_attr);
}
- if (c != 0 && (!has_syntax || can_spell)) {
+ if (c != 0 && ((!has_syntax && !no_plain_buffer) || can_spell)) {
char_u *prev_ptr;
char_u *p;
int len;
@@ -1781,25 +1807,6 @@ int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
char_attr = hl_combine_attr(term_attrs[vcol], char_attr);
}
- if (has_decor && v > 0) {
- bool selected = (area_active || (area_highlighting && noinvcur
- && (colnr_T)vcol == wp->w_virtcol));
- int extmark_attr = decor_redraw_col(wp->w_buffer, (colnr_T)v - 1, off,
- selected, &decor_state);
- if (extmark_attr != 0) {
- if (!attr_pri) {
- char_attr = hl_combine_attr(char_attr, extmark_attr);
- } else {
- char_attr = hl_combine_attr(extmark_attr, char_attr);
- }
- }
-
- decor_conceal = decor_state.conceal;
- if (decor_conceal && decor_state.conceal_char) {
- decor_conceal = 2; // really??
- }
- }
-
// Found last space before word: check for line break.
if (wp->w_p_lbr && c0 == c && vim_isbreak(c)
&& !vim_isbreak((int)(*ptr))) {
diff --git a/src/nvim/drawscreen.c b/src/nvim/drawscreen.c
index 29ff261461..5b83821927 100644
--- a/src/nvim/drawscreen.c
+++ b/src/nvim/drawscreen.c
@@ -539,7 +539,7 @@ int update_screen(int type)
ui_comp_set_screen_valid(true);
DecorProviders providers;
- decor_providers_start(&providers, type, &provider_err);
+ decor_providers_start(&providers, &provider_err);
// "start" callback could have changed highlights for global elements
if (win_check_ns_hl(NULL)) {
diff --git a/src/nvim/edit.c b/src/nvim/edit.c
index 9144d055f7..1a8030d511 100644
--- a/src/nvim/edit.c
+++ b/src/nvim/edit.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * edit.c: functions for Insert mode
- */
+// edit.c: functions for Insert mode
#include <assert.h>
#include <inttypes.h>
@@ -190,7 +188,7 @@ static void insert_enter(InsertState *s)
}
}
- Insstart_textlen = (colnr_T)linetabsize(get_cursor_line_ptr());
+ Insstart_textlen = (colnr_T)linetabsize((char_u *)get_cursor_line_ptr());
Insstart_blank_vcol = MAXCOL;
if (!did_ai) {
@@ -274,7 +272,7 @@ static void insert_enter(InsertState *s)
update_curswant();
if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
|| curwin->w_curswant > curwin->w_virtcol)
- && *(s->ptr = get_cursor_line_ptr() + curwin->w_cursor.col) != NUL) {
+ && *(s->ptr = (char_u *)get_cursor_line_ptr() + curwin->w_cursor.col) != NUL) {
if (s->ptr[1] == NUL) {
curwin->w_cursor.col++;
} else {
@@ -1359,9 +1357,7 @@ void ins_redraw(bool ready)
emsg_on_display = false; // may remove error message now
}
-/*
- * Handle a CTRL-V or CTRL-Q typed in Insert mode.
- */
+// Handle a CTRL-V or CTRL-Q typed in Insert mode.
static void ins_ctrl_v(void)
{
int c;
@@ -1391,10 +1387,8 @@ static void ins_ctrl_v(void)
revins_legal++;
}
-/*
- * Put a character directly onto the screen. It's not stored in a buffer.
- * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
- */
+// Put a character directly onto the screen. It's not stored in a buffer.
+// Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
static int pc_status;
#define PC_STATUS_UNSET 0 // pc_bytes was not set
#define PC_STATUS_RIGHT 1 // right half of double-wide char
@@ -1445,21 +1439,21 @@ void edit_putchar(int c, bool highlight)
}
}
-/// Return the effective prompt for the specified buffer.
-char_u *buf_prompt_text(const buf_T *const buf)
+/// @return the effective prompt for the specified buffer.
+char *buf_prompt_text(const buf_T *const buf)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
{
if (buf->b_prompt_text == NULL) {
- return (char_u *)"% ";
+ return "% ";
}
- return (char_u *)buf->b_prompt_text;
+ return buf->b_prompt_text;
}
// Return the effective prompt for the current buffer.
char_u *prompt_text(void)
FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
{
- return buf_prompt_text(curbuf);
+ return (char_u *)buf_prompt_text(curbuf);
}
// Prepare for prompt mode: Make sure the last line has the prompt text.
@@ -1470,7 +1464,7 @@ static void init_prompt(int cmdchar_todo)
char_u *text;
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
- text = get_cursor_line_ptr();
+ text = (char_u *)get_cursor_line_ptr();
if (STRNCMP(text, prompt, STRLEN(prompt)) != 0) {
// prompt is missing, insert it or append a line with it
if (*text == NUL) {
@@ -1511,9 +1505,7 @@ bool prompt_curpos_editable(void)
&& curwin->w_cursor.col >= (int)STRLEN(prompt_text());
}
-/*
- * Undo the previous edit_putchar().
- */
+// Undo the previous edit_putchar().
void edit_unputchar(void)
{
if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled) {
@@ -1528,10 +1520,8 @@ void edit_unputchar(void)
}
}
-/*
- * Called when p_dollar is set: display a '$' at the end of the changed text
- * Only works when cursor is in the line that changes.
- */
+// Called when p_dollar is set: display a '$' at the end of the changed text
+// Only works when cursor is in the line that changes.
void display_dollar(colnr_T col)
{
colnr_T save_col;
@@ -1544,7 +1534,7 @@ void display_dollar(colnr_T col)
curwin->w_cursor.col = col;
// If on the last byte of a multi-byte move to the first byte.
- char_u *p = get_cursor_line_ptr();
+ char_u *p = (char_u *)get_cursor_line_ptr();
curwin->w_cursor.col -= utf_head_off((char *)p, (char *)p + col);
curs_columns(curwin, false); // Recompute w_wrow and w_wcol
if (curwin->w_wcol < curwin->w_grid.cols) {
@@ -1554,10 +1544,8 @@ void display_dollar(colnr_T col)
curwin->w_cursor.col = save_col;
}
-/*
- * Call this function before moving the cursor from the normal insert position
- * in insert mode.
- */
+// Call this function before moving the cursor from the normal insert position
+// in insert mode.
void undisplay_dollar(void)
{
if (dollar_vcol >= 0) {
@@ -1586,11 +1574,11 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
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 *new_line, *orig_line = NULL; // init for GCC
// MODE_VREPLACE state needs to know what the line was like before changing
if (State & VREPLACE_FLAG) {
- orig_line = vim_strsave(get_cursor_line_ptr()); // Deal with NULL below
+ orig_line = xstrdup(get_cursor_line_ptr()); // Deal with NULL below
orig_col = curwin->w_cursor.col;
}
@@ -1600,11 +1588,9 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
vc = getvcol_nolist(&curwin->w_cursor);
vcol = vc;
- /*
- * For Replace mode we need to fix the replace stack later, which is only
- * possible when the cursor is in the indent. Remember the number of
- * characters before the cursor if it's possible.
- */
+ // For Replace mode we need to fix the replace stack later, which is only
+ // possible when the cursor is in the indent. Remember the number of
+ // characters before the cursor if it's possible.
start_col = curwin->w_cursor.col;
// determine offset from first non-blank
@@ -1614,10 +1600,8 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
insstart_less = curwin->w_cursor.col;
- /*
- * If the cursor is in the indent, compute how many screen columns the
- * cursor is to the left of the first non-blank.
- */
+ // If the cursor is in the indent, compute how many screen columns the
+ // cursor is to the left of the first non-blank.
if (new_cursor_col < 0) {
vcol = get_indent() - vcol;
}
@@ -1626,9 +1610,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
start_col = -1;
}
- /*
- * Set the new indent. The cursor will be put on the first non-blank.
- */
+ // Set the new indent. The cursor will be put on the first non-blank.
if (type == INDENT_SET) {
(void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
} else {
@@ -1643,20 +1625,16 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
}
insstart_less -= curwin->w_cursor.col;
- /*
- * Try to put cursor on same character.
- * If the cursor is at or after the first non-blank in the line,
- * compute the cursor column relative to the column of the first
- * non-blank character.
- * If we are not in insert mode, leave the cursor on the first non-blank.
- * If the cursor is before the first non-blank, position it relative
- * to the first non-blank, counted in screen columns.
- */
+ // Try to put cursor on same character.
+ // If the cursor is at or after the first non-blank in the line,
+ // compute the cursor column relative to the column of the first
+ // non-blank character.
+ // If we are not in insert mode, leave the cursor on the first non-blank.
+ // If the cursor is before the first non-blank, position it relative
+ // to the first non-blank, counted in screen columns.
if (new_cursor_col >= 0) {
- /*
- * When changing the indent while the cursor is touching it, reset
- * Insstart_col to 0.
- */
+ // When changing the indent while the cursor is touching it, reset
+ // Insstart_col to 0.
if (new_cursor_col == 0) {
insstart_less = MAXCOL;
}
@@ -1670,7 +1648,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
// Advance the cursor until we reach the right screen column.
last_vcol = 0;
- ptr = get_cursor_line_ptr();
+ ptr = (char_u *)get_cursor_line_ptr();
chartabsize_T cts;
init_chartabsize_arg(&cts, curwin, 0, 0, (char *)ptr, (char *)ptr);
while (cts.cts_vcol <= (int)curwin->w_virtcol) {
@@ -1687,10 +1665,8 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
new_cursor_col = (int)(cts.cts_ptr - cts.cts_line);
clear_chartabsize_arg(&cts);
- /*
- * May need to insert spaces to be able to position the cursor on
- * the right screen column.
- */
+ // May need to insert spaces to be able to position the cursor on
+ // the right screen column.
if (vcol != (int)curwin->w_virtcol) {
curwin->w_cursor.col = (colnr_T)new_cursor_col;
size_t i = (size_t)(curwin->w_virtcol - vcol);
@@ -1701,10 +1677,8 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
xfree(ptr);
}
- /*
- * When changing the indent while the cursor is in it, reset
- * Insstart_col to 0.
- */
+ // When changing the indent while the cursor is in it, reset
+ // Insstart_col to 0.
insstart_less = MAXCOL;
}
@@ -1718,9 +1692,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
curwin->w_set_curswant = true;
changed_cline_bef_curs();
- /*
- * May have to adjust the start of the insert.
- */
+ // May have to adjust the start of the insert.
if (State & MODE_INSERT) {
if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) {
if ((int)Insstart.col <= insstart_less) {
@@ -1761,14 +1733,14 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
// then put it back again the way we wanted it.
if (State & VREPLACE_FLAG) {
// Save new line
- new_line = vim_strsave(get_cursor_line_ptr());
+ new_line = xstrdup(get_cursor_line_ptr());
// We only put back the new line up to the cursor
new_line[curwin->w_cursor.col] = NUL;
int new_col = curwin->w_cursor.col;
// Put back original line
- ml_replace(curwin->w_cursor.lnum, (char *)orig_line, false);
+ ml_replace(curwin->w_cursor.lnum, orig_line, false);
curwin->w_cursor.col = orig_col;
curbuf_splice_pending++;
@@ -1777,7 +1749,7 @@ void change_indent(int type, int amount, int round, int replaced, int call_chang
backspace_until_column(0);
// Insert new stuff into line again
- ins_bytes((char *)new_line);
+ ins_bytes(new_line);
xfree(new_line);
@@ -1841,7 +1813,7 @@ static bool del_char_after_col(int limit_col)
// composing character.
mb_adjust_cursor();
while (curwin->w_cursor.col < (colnr_T)limit_col) {
- int l = utf_ptr2len((char *)get_cursor_pos_ptr());
+ int l = utf_ptr2len(get_cursor_pos_ptr());
if (l == 0) { // end of line
break;
@@ -1998,15 +1970,13 @@ static void insert_special(int c, int allow_modmask, int ctrlv)
}
}
-/*
- * Special characters in this context are those that need processing other
- * than the simple insertion that can be performed here. This includes ESC
- * which terminates the insert, and CR/NL which need special processing to
- * open up a new line. This routine tries to optimize insertions performed by
- * the "redo", "undo" or "put" commands, so it needs to know when it should
- * stop and defer processing to the "normal" mechanism.
- * '0' and '^' are special, because they can be followed by CTRL-D.
- */
+// Special characters in this context are those that need processing other
+// than the simple insertion that can be performed here. This includes ESC
+// which terminates the insert, and CR/NL which need special processing to
+// open up a new line. This routine tries to optimize insertions performed by
+// the "redo", "undo" or "put" commands, so it needs to know when it should
+// stop and defer processing to the "normal" mechanism.
+// '0' and '^' are special, because they can be followed by CTRL-D.
#define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
///
@@ -2082,7 +2052,7 @@ void insertchar(int c, int flags, int second_indent)
// Need to remove existing (middle) comment leader and insert end
// comment leader. First, check what comment leader we can find.
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
int i = get_leader_len((char *)line, &p, false, true);
if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) { // Just checking
// Skip middle-comment string
@@ -2207,9 +2177,7 @@ void insertchar(int c, int flags, int second_indent)
}
}
-/*
- * Put a character in the redo buffer, for when just after a CTRL-V.
- */
+// Put a character in the redo buffer, for when just after a CTRL-V.
static void redo_literal(int c)
{
char buf[10];
@@ -2259,10 +2227,8 @@ static void start_arrow_common(pos_T *end_insert_pos, bool end_change)
check_spell_redraw();
}
-/*
- * If we skipped highlighting word at cursor, do it now.
- * It may be skipped again, thus reset spell_redraw_lnum first.
- */
+// If we skipped highlighting word at cursor, do it now.
+// It may be skipped again, thus reset spell_redraw_lnum first.
static void check_spell_redraw(void)
{
if (spell_redraw_lnum != 0) {
@@ -2273,11 +2239,9 @@ static void check_spell_redraw(void)
}
}
-/*
- * stop_arrow() is called before a change is made in insert mode.
- * If an arrow key has been used, start a new insertion.
- * Returns FAIL if undo is impossible, shouldn't insert then.
- */
+// stop_arrow() is called before a change is made in insert mode.
+// If an arrow key has been used, start a new insertion.
+// Returns FAIL if undo is impossible, shouldn't insert then.
int stop_arrow(void)
{
if (arrow_used) {
@@ -2287,7 +2251,7 @@ int stop_arrow(void)
// right, except when nothing was inserted yet.
update_Insstart_orig = false;
}
- Insstart_textlen = (colnr_T)linetabsize(get_cursor_line_ptr());
+ Insstart_textlen = (colnr_T)linetabsize((char_u *)get_cursor_line_ptr());
if (u_save_cursor() == OK) {
arrow_used = false;
@@ -2327,11 +2291,9 @@ static void stop_insert(pos_T *end_insert_pos, int esc, int nomove)
stop_redo_ins();
replace_flush(); // abandon replace stack
- /*
- * Save the inserted text for later redo with ^@ and CTRL-A.
- * Don't do it when "restart_edit" was set and nothing was inserted,
- * otherwise CTRL-O w and then <Left> will clear "last_insert".
- */
+ // Save the inserted text for later redo with ^@ and CTRL-A.
+ // Don't do it when "restart_edit" was set and nothing was inserted,
+ // otherwise CTRL-O w and then <Left> will clear "last_insert".
ptr = get_inserted();
if (did_restart_edit == 0 || (ptr != NULL
&& (int)STRLEN(ptr) > new_insert_skip)) {
@@ -2368,8 +2330,8 @@ static void stop_insert(pos_T *end_insert_pos, int esc, int nomove)
if (gchar_cursor() != NUL) {
inc_cursor();
}
- /* If the cursor is still at the same character, also keep
- * the "coladd". */
+ // 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) {
@@ -2438,10 +2400,8 @@ static void stop_insert(pos_T *end_insert_pos, int esc, int nomove)
}
}
-/*
- * Set the last inserted text to a single character.
- * Used for the replace command.
- */
+// Set the last inserted text to a single character.
+// Used for the replace command.
void set_last_insert(int c)
{
char_u *s;
@@ -2466,13 +2426,11 @@ void free_last_insert(void)
}
#endif
-/*
- * move cursor to start of line
- * if flags & BL_WHITE move to first non-white
- * if flags & BL_SOL move to first non-white if startofline is set,
- * otherwise keep "curswant" column
- * if flags & BL_FIX don't leave the cursor on a NUL.
- */
+// move cursor to start of line
+// if flags & BL_WHITE move to first non-white
+// if flags & BL_SOL move to first non-white if startofline is set,
+// otherwise keep "curswant" column
+// if flags & BL_FIX don't leave the cursor on a NUL.
void beginline(int flags)
{
if ((flags & BL_SOL) && !p_sol) {
@@ -2484,7 +2442,7 @@ void beginline(int flags)
if (flags & (BL_WHITE | BL_SOL)) {
char_u *ptr;
- for (ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr)
+ for (ptr = (char_u *)get_cursor_line_ptr(); ascii_iswhite(*ptr)
&& !((flags & BL_FIX) && ptr[1] == NUL); ptr++) {
curwin->w_cursor.col++;
}
@@ -2493,13 +2451,11 @@ void beginline(int flags)
}
}
-/*
- * oneright oneleft cursor_down cursor_up
- *
- * Move one char {right,left,down,up}.
- * Doesn't move onto the NUL past the end of the line, unless it is allowed.
- * Return OK when successful, FAIL when we hit a line of file boundary.
- */
+// oneright oneleft cursor_down cursor_up
+//
+// Move one char {right,left,down,up}.
+// Doesn't move onto the NUL past the end of the line, unless it is allowed.
+// Return OK when successful, FAIL when we hit a line of file boundary.
int oneright(void)
{
@@ -2510,7 +2466,7 @@ int oneright(void)
pos_T prevpos = curwin->w_cursor;
// Adjust for multi-wide char (excluding TAB)
- ptr = (char *)get_cursor_pos_ptr();
+ ptr = get_cursor_pos_ptr();
coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(utf_ptr2char(ptr))) ?
ptr2cells(ptr) : 1));
curwin->w_set_curswant = true;
@@ -2519,7 +2475,7 @@ int oneright(void)
|| prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
}
- ptr = (char *)get_cursor_pos_ptr();
+ ptr = get_cursor_pos_ptr();
if (*ptr == NUL) {
return FAIL; // already at the very end
}
@@ -2562,7 +2518,7 @@ int oneleft(void)
if (curwin->w_cursor.coladd == 1) {
// Adjust for multi-wide char (not a TAB)
- char *ptr = (char *)get_cursor_pos_ptr();
+ char *ptr = get_cursor_pos_ptr();
if (*ptr != TAB && vim_isprintc(utf_ptr2char(ptr)) && ptr2cells(ptr) > 1) {
curwin->w_cursor.coladd = 0;
}
@@ -2600,9 +2556,8 @@ int cursor_up(long n, int upd_topline)
if (n >= lnum) {
lnum = 1;
} else if (hasAnyFolding(curwin)) {
- /*
- * Count each sequence of folded lines as one logical line.
- */
+ // Count each sequence of folded lines as one logical line.
+
// go to the start of the current fold
(void)hasFolding(lnum, &lnum, NULL);
@@ -2761,25 +2716,23 @@ char_u *get_last_insert(void)
return last_insert + last_insert_skip;
}
-/*
- * Get last inserted string, and remove trailing <Esc>.
- * Returns pointer to allocated memory (must be freed) or NULL.
- */
+// Get last inserted string, and remove trailing <Esc>.
+// Returns pointer to allocated memory (must be freed) or NULL.
char_u *get_last_insert_save(void)
{
- char_u *s;
+ char *s;
int len;
if (last_insert == NULL) {
return NULL;
}
- s = vim_strsave(last_insert + last_insert_skip);
+ s = xstrdup((char *)last_insert + last_insert_skip);
len = (int)STRLEN(s);
if (len > 0 && s[len - 1] == ESC) { // remove trailing ESC
s[len - 1] = NUL;
}
- return s;
+ return (char_u *)s;
}
/// Check the word in front of the cursor for an abbreviation.
@@ -2799,24 +2752,22 @@ static bool echeck_abbr(int c)
return false;
}
- return check_abbr(c, get_cursor_line_ptr(), curwin->w_cursor.col,
+ return check_abbr(c, (char_u *)get_cursor_line_ptr(), curwin->w_cursor.col,
curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
}
-/*
- * replace-stack functions
- *
- * When replacing characters, the replaced characters are remembered for each
- * new character. This is used to re-insert the old text when backspacing.
- *
- * There is a NUL headed list of characters for each character that is
- * currently in the file after the insertion point. When BS is used, one NUL
- * headed list is put back for the deleted character.
- *
- * For a newline, there are two NUL headed lists. One contains the characters
- * that the NL replaced. The extra one stores the characters after the cursor
- * that were deleted (always white space).
- */
+// replace-stack functions
+//
+// When replacing characters, the replaced characters are remembered for each
+// new character. This is used to re-insert the old text when backspacing.
+//
+// There is a NUL headed list of characters for each character that is
+// currently in the file after the insertion point. When BS is used, one NUL
+// headed list is put back for the deleted character.
+//
+// For a newline, there are two NUL headed lists. One contains the characters
+// that the NL replaced. The extra one stores the characters after the cursor
+// that were deleted (always white space).
static char_u *replace_stack = NULL;
static ssize_t replace_stack_nr = 0; // next entry in replace stack
@@ -2901,10 +2852,8 @@ static void replace_pop_ins(void)
State = oldState;
}
-/*
- * Insert bytes popped from the replace stack. "cc" is the first byte. If it
- * indicates a multi-byte char, pop the other bytes too.
- */
+// Insert bytes popped from the replace stack. "cc" is the first byte. If it
+// indicates a multi-byte char, pop the other bytes too.
static void mb_replace_pop_ins(int cc)
{
int n;
@@ -2951,10 +2900,8 @@ static void mb_replace_pop_ins(int cc)
}
}
-/*
- * make the replace stack empty
- * (called when exiting replace mode)
- */
+// make the replace stack empty
+// (called when exiting replace mode)
static void replace_flush(void)
{
XFREE_CLEAR(replace_stack);
@@ -2962,15 +2909,13 @@ static void replace_flush(void)
replace_stack_nr = 0;
}
-/*
- * Handle doing a BS for one character.
- * cc < 0: replace stack empty, just move cursor
- * cc == 0: character was inserted, delete it
- * cc > 0: character was replaced, put cc (first byte of original char) back
- * and check for more characters to be put back
- * When "limit_col" is >= 0, don't delete before this column. Matters when
- * using composing characters, use del_char_after_col() instead of del_char().
- */
+// Handle doing a BS for one character.
+// cc < 0: replace stack empty, just move cursor
+// cc == 0: character was inserted, delete it
+// cc > 0: character was replaced, put cc (first byte of original char) back
+// and check for more characters to be put back
+// When "limit_col" is >= 0, don't delete before this column. Matters when
+// using composing characters, use del_char_after_col() instead of del_char().
static void replace_do_bs(int limit_col)
{
int cc;
@@ -2989,7 +2934,7 @@ static void replace_do_bs(int limit_col)
// Get the number of screen cells used by the character we are
// going to delete.
getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
- orig_vcols = win_chartabsize(curwin, (char *)get_cursor_pos_ptr(), start_vcol);
+ orig_vcols = win_chartabsize(curwin, get_cursor_pos_ptr(), start_vcol);
}
(void)del_char_after_col(limit_col);
if (l_State & VREPLACE_FLAG) {
@@ -3000,7 +2945,7 @@ static void replace_do_bs(int limit_col)
if (l_State & VREPLACE_FLAG) {
// Get the number of screen cells used by the inserted characters
- p = get_cursor_pos_ptr();
+ p = (char_u *)get_cursor_pos_ptr();
ins_len = (int)STRLEN(p) - orig_len;
vcol = start_vcol;
for (i = 0; i < ins_len; i++) {
@@ -3033,12 +2978,10 @@ bool cindent_on(void)
return !p_paste && (curbuf->b_p_cin || *curbuf->b_p_inde != NUL);
}
-/*
- * Re-indent the current line, based on the current contents of it and the
- * surrounding lines. Fixing the cursor position seems really easy -- I'm very
- * confused what all the part that handles Control-T is doing that I'm not.
- * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
- */
+// Re-indent the current line, based on the current contents of it and the
+// surrounding lines. Fixing the cursor position seems really easy -- I'm very
+// confused what all the part that handles Control-T is doing that I'm not.
+// "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
void fixthisline(IndentGetter get_the_indent)
{
int amount = get_the_indent();
@@ -3096,10 +3039,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
look = (char_u *)curbuf->b_p_cink; // 'indentexpr' empty: use 'cinkeys'
}
while (*look) {
- /*
- * Find out if we want to try a match with this key, depending on
- * 'when' and a '*' or '!' before the key.
- */
+ // Find out if we want to try a match with this key, depending on
+ // 'when' and a '*' or '!' before the key.
switch (when) {
case '*':
try_match = (*look == '*'); break;
@@ -3148,7 +3089,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
// cursor.
} else if (*look == 'e') {
if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4) {
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
if ((char_u *)skipwhite((char *)p) == p + curwin->w_cursor.col - 4
&& STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0) {
return true;
@@ -3161,12 +3102,12 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
// class::method for C++).
} else if (*look == ':') {
if (try_match && keytyped == ':') {
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
if (cin_iscase(p, false) || cin_isscopedecl(p) || cin_islabel()) {
return true;
}
// Need to get the line again after cin_islabel().
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
if (curwin->w_cursor.col > 2
&& p[curwin->w_cursor.col - 1] == ':'
&& p[curwin->w_cursor.col - 2] == ':') {
@@ -3174,7 +3115,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
const bool i = cin_iscase(p, false)
|| cin_isscopedecl(p)
|| cin_islabel();
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
p[curwin->w_cursor.col - 1] = ':';
if (i) {
return true;
@@ -3224,9 +3165,9 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
if (keytyped == KEY_COMPLETE) {
char_u *n, *s;
- /* Just completed a word, check if it starts with "look".
- * search back for the start of a word. */
- line = get_cursor_line_ptr();
+ // Just completed a word, check if it starts with "look".
+ // search back for the start of a word.
+ line = (char_u *)get_cursor_line_ptr();
for (s = line + curwin->w_cursor.col; s > line; s = n) {
n = mb_prevptr(line, s);
if (!vim_iswordp(n)) {
@@ -3245,7 +3186,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
if (keytyped == (int)p[-1]
|| (icase && keytyped < 256
&& TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1]))) {
- line = get_cursor_pos_ptr();
+ line = (char_u *)get_cursor_pos_ptr();
assert(p >= look && (uintmax_t)(p - look) <= SIZE_MAX);
if ((curwin->w_cursor.col == (colnr_T)(p - look)
|| !vim_iswordc(line[-(p - look) - 1]))
@@ -3257,8 +3198,8 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
}
}
if (match && try_match_word && !try_match) {
- /* "0=word": Check if there are only blanks before the
- * word. */
+ // "0=word": Check if there are only blanks before the
+ // word.
if (getwhitecols_curline() !=
(int)(curwin->w_cursor.col - (p - look))) {
match = false;
@@ -3286,9 +3227,7 @@ bool in_cinkeys(int keytyped, int when, bool line_is_empty)
return false;
}
-/*
- * Map Hebrew keyboard when in hkmap mode.
- */
+// Map Hebrew keyboard when in hkmap mode.
int hkmap(int c)
FUNC_ATTR_PURE
{
@@ -3390,9 +3329,7 @@ static void ins_reg(void)
int literally = 0;
int vis_active = VIsual_active;
- /*
- * If we are going to wait for a character, show a '"'.
- */
+ // If we are going to wait for a character, show a '"'.
pc_status = PC_STATUS_UNSET;
if (redrawing() && !char_avail()) {
// may need to redraw when no more chars available now
@@ -3474,9 +3411,7 @@ static void ins_reg(void)
}
}
-/*
- * CTRL-G commands in Insert mode.
- */
+// CTRL-G commands in Insert mode.
static void ins_ctrl_g(void)
{
int c;
@@ -3530,9 +3465,7 @@ static void ins_ctrl_g(void)
}
}
-/*
- * CTRL-^ in Insert mode.
- */
+// CTRL-^ in Insert mode.
static void ins_ctrl_hat(void)
{
if (map_to_exists_mode("", MODE_LANGMAP, false)) {
@@ -3576,10 +3509,8 @@ static bool ins_esc(long *count, int cmdchar, bool nomove)
AppendToRedobuff(ESC_STR);
}
- /*
- * Repeating insert may take a long time. Check for
- * interrupt now and then.
- */
+ // Repeating insert may take a long time. Check for
+ // interrupt now and then.
if (*count > 0) {
line_breakcheck();
if (got_int) {
@@ -3622,10 +3553,8 @@ static bool ins_esc(long *count, int cmdchar, bool nomove)
RESET_FMARK(&curbuf->b_last_insert, curwin->w_cursor, curbuf->b_fnum, view);
}
- /*
- * The cursor should end up on the last inserted character.
- * Don't do it for CTRL-O, unless past the end of the line.
- */
+ // The cursor should end up on the last inserted character.
+ // Don't do it for CTRL-O, unless past the end of the line.
if (!nomove
&& (curwin->w_cursor.col != 0 || curwin->w_cursor.coladd > 0)
&& (restart_edit == NUL || (gchar_cursor() == NUL && !VIsual_active))
@@ -3663,10 +3592,8 @@ static bool ins_esc(long *count, int cmdchar, bool nomove)
return true;
}
-/*
- * Toggle language: hkmap and revins_on.
- * Move to end of reverse inserted text.
- */
+// Toggle language: hkmap and revins_on.
+// Move to end of reverse inserted text.
static void ins_ctrl_(void)
{
if (revins_on && revins_chars && revins_scol >= 0) {
@@ -3733,9 +3660,7 @@ static bool ins_start_select(int c)
return false;
}
-/*
- * <Insert> key in Insert mode: toggle insert/replace mode.
- */
+// <Insert> key in Insert mode: toggle insert/replace mode.
static void ins_insert(int replaceState)
{
set_vim_var_string(VV_INSERTMODE, ((State & REPLACE_FLAG) ? "i" :
@@ -3753,9 +3678,7 @@ static void ins_insert(int replaceState)
ui_cursor_shape(); // may show different cursor shape
}
-/*
- * Pressed CTRL-O in Insert mode.
- */
+// Pressed CTRL-O in Insert mode.
static void ins_ctrl_o(void)
{
if (State & VREPLACE_FLAG) {
@@ -3772,13 +3695,11 @@ static void ins_ctrl_o(void)
}
}
-/*
- * If the cursor is on an indent, ^T/^D insert/delete one
- * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
- * Always round the indent to 'shiftwidth', this is compatible
- * with vi. But vi only supports ^T and ^D after an
- * autoindent, we support it everywhere.
- */
+// If the cursor is on an indent, ^T/^D insert/delete one
+// shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
+// Always round the indent to 'shiftwidth', this is compatible
+// with vi. But vi only supports ^T and ^D after an
+// autoindent, we support it everywhere.
static void ins_shift(int c, int lastc)
{
if (stop_arrow() == FAIL) {
@@ -3786,9 +3707,7 @@ static void ins_shift(int c, int lastc)
}
AppendCharToRedobuff(c);
- /*
- * 0^D and ^^D: remove all indent.
- */
+ // 0^D and ^^D: remove all indent.
if (c == Ctrl_D && (lastc == '0' || lastc == '^')
&& curwin->w_cursor.col > 0) {
curwin->w_cursor.col--;
@@ -3805,7 +3724,7 @@ static void ins_shift(int c, int lastc)
change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, true, 0, true);
}
- if (did_ai && *skipwhite((char *)get_cursor_line_ptr()) != NUL) {
+ if (did_ai && *skipwhite(get_cursor_line_ptr()) != NUL) {
did_ai = false;
}
did_si = false;
@@ -3844,9 +3763,7 @@ static void ins_del(void)
AppendCharToRedobuff(K_DEL);
}
-/*
- * Delete one character for ins_bs().
- */
+// Delete one character for ins_bs().
static void ins_bs_one(colnr_T *vcolp)
{
dec_cursor();
@@ -3941,11 +3858,9 @@ static bool ins_bs(int c, int mode, int *inserted_space_p)
Insstart.lnum--;
Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));
}
- /*
- * In replace mode:
- * cc < 0: NL was inserted, delete it
- * cc >= 0: NL was replaced, put original characters back
- */
+ // In replace mode:
+ // cc < 0: NL was inserted, delete it
+ // cc >= 0: NL was replaced, put original characters back
cc = -1;
if (State & REPLACE_FLAG) {
cc = replace_pop(); // returns -1 if NL was inserted
@@ -3965,7 +3880,7 @@ 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 = (char_u *)ml_get_buf(curbuf, curwin->w_cursor.lnum, true);
int len;
len = (int)STRLEN(ptr);
@@ -4025,9 +3940,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p)
curwin->w_cursor.col = save_col;
}
- /*
- * Handle deleting one 'shiftwidth' or 'softtabstop'.
- */
+ // Handle deleting one 'shiftwidth' or 'softtabstop'.
if (mode == BACKSPACE_CHAR
&& ((p_sta && in_indent)
|| ((get_sts_value() != 0
@@ -4061,7 +3974,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p)
// delete characters until we are at or before want_vcol
while (vcol > want_vcol && curwin->w_cursor.col > 0
- && (cc = *(get_cursor_pos_ptr() - 1), ascii_iswhite(cc))) {
+ && (cc = (uint8_t)(*(get_cursor_pos_ptr() - 1)), ascii_iswhite(cc))) {
ins_bs_one(&vcol);
}
@@ -4093,7 +4006,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p)
// Delete up to starting point, start of line or previous word.
int prev_cclass = 0;
- int cclass = mb_get_class(get_cursor_pos_ptr());
+ int cclass = mb_get_class((char_u *)get_cursor_pos_ptr());
do {
if (!revins_on) { // put cursor on char to be deleted
dec_cursor();
@@ -4101,7 +4014,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p)
cc = gchar_cursor();
// look multi-byte character class
prev_cclass = cclass;
- cclass = mb_get_class(get_cursor_pos_ptr());
+ cclass = mb_get_class((char_u *)get_cursor_pos_ptr());
if (mode == BACKSPACE_WORD && !ascii_isspace(cc)) { // start of word?
mode = BACKSPACE_WORD_NOT_SPACE;
temp = vim_iswordc(cc);
@@ -4120,7 +4033,7 @@ static bool ins_bs(int c, int mode, int *inserted_space_p)
} else {
const int l_p_deco = p_deco;
if (l_p_deco) {
- (void)utfc_ptr2char((char *)get_cursor_pos_ptr(), cpc);
+ (void)utfc_ptr2char(get_cursor_pos_ptr(), cpc);
}
(void)del_char(false);
// If there are combining characters and 'delcombine' is set
@@ -4373,7 +4286,7 @@ static void ins_right(void)
if (virtual_active()) {
oneright();
} else {
- curwin->w_cursor.col += utfc_ptr2len((char *)get_cursor_pos_ptr());
+ curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr());
}
revins_legal++;
@@ -4589,14 +4502,12 @@ static bool ins_tab(void)
}
}
- /*
- * When 'expandtab' not set: Replace spaces by TABs where possible.
- */
+ // When 'expandtab' not set: Replace spaces by TABs where possible.
if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_array) > 0
|| get_sts_value() > 0
|| (p_sta && ind))) {
char_u *ptr;
- char_u *saved_line = NULL; // init for GCC
+ char *saved_line = NULL; // init for GCC
pos_T pos;
pos_T fpos;
pos_T *cursor;
@@ -4609,10 +4520,10 @@ static bool ins_tab(void)
if (State & VREPLACE_FLAG) {
pos = curwin->w_cursor;
cursor = &pos;
- saved_line = vim_strsave(get_cursor_line_ptr());
- ptr = saved_line + pos.col;
+ saved_line = xstrdup(get_cursor_line_ptr());
+ ptr = (char_u *)saved_line + pos.col;
} else {
- ptr = get_cursor_pos_ptr();
+ ptr = (char_u *)get_cursor_pos_ptr();
cursor = &curwin->w_cursor;
}
@@ -4716,7 +4627,7 @@ static bool ins_tab(void)
// Insert each char in saved_line from changed_col to
// ptr-cursor
- ins_bytes_len((char *)saved_line + change_col, (size_t)(cursor->col - change_col));
+ ins_bytes_len(saved_line + change_col, (size_t)(cursor->col - change_col));
}
}
@@ -4742,11 +4653,9 @@ bool ins_eol(int c)
}
undisplay_dollar();
- /*
- * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
- * character under the cursor. Only push a NUL on the replace stack,
- * nothing to put back when the NL is deleted.
- */
+ // Strange Vi behaviour: In Replace mode, typing a NL will not delete the
+ // character under the cursor. Only push a NUL on the replace stack,
+ // nothing to put back when the NL is deleted.
if ((State & REPLACE_FLAG)
&& !(State & VREPLACE_FLAG)) {
replace_push(NUL);
@@ -4780,11 +4689,9 @@ bool ins_eol(int c)
return i;
}
-/*
- * Handle digraph in insert mode.
- * Returns character still to be inserted, or NUL when nothing remaining to be
- * done.
- */
+// Handle digraph in insert mode.
+// Returns character still to be inserted, or NUL when nothing remaining to be
+// done.
static int ins_digraph(void)
{
int c;
@@ -4853,10 +4760,8 @@ static int ins_digraph(void)
return NUL;
}
-/*
- * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
- * Returns the char to be inserted, or NUL if none found.
- */
+// Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
+// Returns the char to be inserted, or NUL if none found.
int ins_copychar(linenr_T lnum)
{
int c;
@@ -4894,9 +4799,7 @@ int ins_copychar(linenr_T lnum)
return c;
}
-/*
- * CTRL-Y or CTRL-E typed in Insert mode.
- */
+// CTRL-Y or CTRL-E typed in Insert mode.
static int ins_ctrl_ey(int tc)
{
int c = tc;
@@ -4933,10 +4836,8 @@ static int ins_ctrl_ey(int tc)
return c;
}
-/*
- * Try to do some very smart auto-indenting.
- * Used when inserting a "normal" character.
- */
+// Try to do some very smart auto-indenting.
+// Used when inserting a "normal" character.
static void ins_try_si(int c)
{
pos_T *pos, old_pos;
@@ -4944,20 +4845,16 @@ static void ins_try_si(int c)
int i;
bool temp;
- /*
- * do some very smart indenting when entering '{' or '}'
- */
+ // do some very smart indenting when entering '{' or '}'
if (((did_si || can_si_back) && c == '{') || (can_si && c == '}' && inindent(0))) {
// for '}' set indent equal to indent of line containing matching '{'
if (c == '}' && (pos = findmatch(NULL, '{')) != NULL) {
old_pos = curwin->w_cursor;
- /*
- * If the matching '{' has a ')' immediately before it (ignoring
- * white-space), then line up with the start of the line
- * containing the matching '(' if there is one. This handles the
- * case where an "if (..\n..) {" statement continues over multiple
- * lines -- webb
- */
+ // If the matching '{' has a ')' immediately before it (ignoring
+ // white-space), then line up with the start of the line
+ // containing the matching '(' if there is one. This handles the
+ // case where an "if (..\n..) {" statement continues over multiple
+ // lines -- webb
ptr = (char_u *)ml_get(pos->lnum);
i = pos->col;
if (i > 0) { // skip blanks before '{'
@@ -5001,9 +4898,7 @@ static void ins_try_si(int c)
}
}
- /*
- * set indent of '#' always to 0
- */
+ // set indent of '#' always to 0
if (curwin->w_cursor.col > 0 && can_si && c == '#' && inindent(0)) {
// remember current indent for next line
old_indent = get_indent();
@@ -5016,10 +4911,8 @@ static void ins_try_si(int c)
}
}
-/*
- * Get the value that w_virtcol would have when 'list' is off.
- * Unless 'cpo' contains the 'L' flag.
- */
+// Get the value that w_virtcol would have when 'list' is off.
+// Unless 'cpo' contains the 'L' flag.
colnr_T get_nolist_virtcol(void)
{
// check validity of cursor in current buffer
@@ -5034,12 +4927,10 @@ colnr_T get_nolist_virtcol(void)
return curwin->w_virtcol;
}
-/*
- * Handle the InsertCharPre autocommand.
- * "c" is the character that was typed.
- * Return a pointer to allocated memory with the replacement string.
- * Return NULL to continue inserting "c".
- */
+// Handle the InsertCharPre autocommand.
+// "c" is the character that was typed.
+// Return a pointer to allocated memory with the replacement string.
+// Return NULL to continue inserting "c".
static char_u *do_insert_char_pre(int c)
{
char buf[MB_MAXBYTES + 1];
@@ -5055,13 +4946,13 @@ static char_u *do_insert_char_pre(int c)
textlock++;
set_vim_var_string(VV_CHAR, buf, -1);
- char_u *res = NULL;
+ char *res = NULL;
if (ins_apply_autocmds(EVENT_INSERTCHARPRE)) {
// Get the value of v:char. It may be empty or more than one
// character. Only use it when changed, otherwise continue with the
// original character to avoid breaking autoindent.
- if (STRCMP(buf, get_vim_var_str(VV_CHAR)) != 0) {
- res = vim_strsave((char_u *)get_vim_var_str(VV_CHAR));
+ if (strcmp(buf, get_vim_var_str(VV_CHAR)) != 0) {
+ res = xstrdup(get_vim_var_str(VV_CHAR));
}
}
@@ -5071,7 +4962,7 @@ static char_u *do_insert_char_pre(int c)
// Restore the State, it may have been changed.
State = save_State;
- return res;
+ return (char_u *)res;
}
bool get_can_cindent(void)
diff --git a/src/nvim/eval.c b/src/nvim/eval.c
index 8927e52349..ead01fcbad 100644
--- a/src/nvim/eval.c
+++ b/src/nvim/eval.c
@@ -2995,9 +2995,11 @@ static int eval7(char **arg, typval_T *rettv, int evaluate, int want_string)
*arg = bp;
} else {
// decimal, hex or octal number
- vim_str2nr((char_u *)(*arg), NULL, &len, STR2NR_ALL, &n, NULL, 0, true);
+ vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0, true);
if (len == 0) {
- semsg(_(e_invexpr2), *arg);
+ if (evaluate) {
+ semsg(_(e_invexpr2), *arg);
+ }
ret = FAIL;
break;
}
@@ -3909,7 +3911,7 @@ char *partial_name(partial_T *pt)
FUNC_ATTR_PURE
{
if (pt->pt_name != NULL) {
- return (char *)pt->pt_name;
+ return pt->pt_name;
}
return (char *)pt->pt_func->uf_name;
}
@@ -3924,7 +3926,7 @@ static void partial_free(partial_T *pt)
xfree(pt->pt_argv);
tv_dict_unref(pt->pt_dict);
if (pt->pt_name != NULL) {
- func_unref(pt->pt_name);
+ func_unref((char_u *)pt->pt_name);
xfree(pt->pt_name);
} else {
func_ptr_unref(pt->pt_func);
@@ -3996,13 +3998,11 @@ failret:
bool func_equal(typval_T *tv1, typval_T *tv2, bool ic)
{
// empty and NULL function name considered the same
- char_u *s1 =
- (char_u *)(tv1->v_type == VAR_FUNC ? tv1->vval.v_string : partial_name(tv1->vval.v_partial));
+ char *s1 = tv1->v_type == VAR_FUNC ? tv1->vval.v_string : partial_name(tv1->vval.v_partial);
if (s1 != NULL && *s1 == NUL) {
s1 = NULL;
}
- char_u *s2 =
- (char_u *)(tv2->v_type == VAR_FUNC ? tv2->vval.v_string : partial_name(tv2->vval.v_partial));
+ char *s2 = tv2->v_type == VAR_FUNC ? tv2->vval.v_string : partial_name(tv2->vval.v_partial);
if (s2 != NULL && *s2 == NUL) {
s2 = NULL;
}
@@ -4010,7 +4010,7 @@ bool func_equal(typval_T *tv1, typval_T *tv2, bool ic)
if (s1 != s2) {
return false;
}
- } else if (STRCMP(s1, s2) != 0) {
+ } else if (strcmp(s1, s2) != 0) {
return false;
}
@@ -4478,7 +4478,7 @@ bool set_ref_in_item(typval_T *tv, int copyID, ht_stack_T **ht_stack, list_stack
// A partial does not have a copyID, because it cannot contain itself.
if (pt != NULL) {
- abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);
+ abort = set_ref_in_func((char_u *)pt->pt_name, pt->pt_func, copyID);
if (pt->pt_dict != NULL) {
typval_T dtv;
@@ -4582,21 +4582,20 @@ static int dict_get_tv(char **arg, typval_T *rettv, int evaluate, bool literal)
{
typval_T tv;
char *key = NULL;
- char *start = skipwhite(*arg + 1);
+ char *curly_expr = skipwhite(*arg + 1);
char buf[NUMBUFLEN];
- // First check if it's not a curly-braces thing: {expr}.
+ // First check if it's not a curly-braces expression: {expr}.
// Must do this without evaluating, otherwise a function may be called
// twice. Unfortunately this means we need to call eval1() twice for the
// first item.
- // But {} is an empty Dictionary.
- if (*start != '}') {
- if (eval1(&start, &tv, false) == FAIL) { // recursive!
- return FAIL;
- }
- if (*skipwhite(start) == '}') {
- return NOTDONE;
- }
+ // "{}" is an empty Dictionary.
+ // "#{abc}" is never a curly-braces expression.
+ if (*curly_expr != '}'
+ && !literal
+ && eval1(&curly_expr, &tv, false) == OK
+ && *skipwhite(curly_expr) == '}') {
+ return NOTDONE;
}
dict_T *d = NULL;
@@ -4846,7 +4845,7 @@ void filter_map(typval_T *argvars, typval_T *rettv, int map)
break;
}
- vimvars[VV_KEY].vv_str = (char *)vim_strsave(di->di_key);
+ vimvars[VV_KEY].vv_str = xstrdup((char *)di->di_key);
int r = filter_map_one(&di->di_tv, expr, map, &rem);
tv_clear(&vimvars[VV_KEY].vv_tv);
if (r == FAIL || did_emsg) {
@@ -5113,7 +5112,7 @@ void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref)
func_ptr_ref(pt->pt_func);
xfree(name);
} else {
- pt->pt_name = (char_u *)name;
+ pt->pt_name = name;
func_ref((char_u *)name);
}
@@ -6208,7 +6207,7 @@ char *save_tv_as_string(typval_T *tv, ptrdiff_t *const len, bool endnl)
buf_T *buf = buflist_findnr((int)tv->vval.v_number);
if (buf) {
for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
- for (char *p = (char *)ml_get_buf(buf, lnum, false); *p != NUL; p++) {
+ for (char *p = ml_get_buf(buf, lnum, false); *p != NUL; p++) {
*len += 1;
}
*len += 1;
@@ -6226,7 +6225,7 @@ char *save_tv_as_string(typval_T *tv, ptrdiff_t *const len, bool endnl)
char *ret = xmalloc((size_t)(*len) + 1);
char *end = ret;
for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
- for (char *p = (char *)ml_get_buf(buf, lnum, false); *p != NUL; p++) {
+ for (char *p = ml_get_buf(buf, lnum, false); *p != NUL; p++) {
*end++ = (*p == '\n') ? NUL : *p;
}
*end++ = '\n';
@@ -6275,7 +6274,7 @@ int buf_byteidx_to_charidx(buf_T *buf, linenr_T lnum, int byteidx)
lnum = buf->b_ml.ml_line_count;
}
- char *str = (char *)ml_get_buf(buf, lnum, false);
+ char *str = ml_get_buf(buf, lnum, false);
if (*str == NUL) {
return 0;
@@ -6313,7 +6312,7 @@ int buf_charidx_to_byteidx(buf_T *buf, linenr_T lnum, int charidx)
lnum = buf->b_ml.ml_line_count;
}
- char *str = (char *)ml_get_buf(buf, lnum, false);
+ char *str = ml_get_buf(buf, lnum, false);
// Convert the character offset to a byte offset
char *t = str;
@@ -6373,7 +6372,7 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret
listitem_T *li = tv_list_find(l, 1L);
if (li != NULL && TV_LIST_ITEM_TV(li)->v_type == VAR_STRING
&& TV_LIST_ITEM_TV(li)->vval.v_string != NULL
- && STRCMP(TV_LIST_ITEM_TV(li)->vval.v_string, "$") == 0) {
+ && strcmp(TV_LIST_ITEM_TV(li)->vval.v_string, "$") == 0) {
pos.col = len + 1;
}
@@ -6450,7 +6449,7 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret
} else {
pos.lnum = curwin->w_cursor.lnum;
if (charcol) {
- pos.col = (colnr_T)mb_charlen(get_cursor_line_ptr());
+ pos.col = (colnr_T)mb_charlen((char_u *)get_cursor_line_ptr());
} else {
pos.col = (colnr_T)STRLEN(get_cursor_line_ptr());
}
@@ -7821,7 +7820,7 @@ bool script_autoload(const char *const name, const size_t name_len, const bool r
// "autoload/", it's always the same.
int i = 0;
for (; i < ga_loaded.ga_len; i++) {
- if (STRCMP(((char **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0) {
+ if (strcmp(((char **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0) {
break;
}
}
@@ -8118,7 +8117,7 @@ repeat:
// Do not call shorten_fname() here since it removes the prefix
// even though the path does not have a prefix.
- if (FNAMENCMP(p, dirname, namelen) == 0) {
+ if (path_fnamencmp(p, dirname, namelen) == 0) {
p += namelen;
if (vim_ispathsep(*p)) {
while (*p && vim_ispathsep(*p)) {
@@ -8330,7 +8329,7 @@ char *do_string_sub(char *str, char *pat, char *sub, typval_T *expr, char *flags
while (vim_regexec_nl(&regmatch, (char_u *)str, (colnr_T)(tail - str))) {
// Skip empty match except for first match.
if (regmatch.startp[0] == regmatch.endp[0]) {
- if ((char_u *)zero_width == regmatch.startp[0]) {
+ if (zero_width == regmatch.startp[0]) {
// avoid getting stuck on a match with an empty string
int i = utfc_ptr2len(tail);
memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
@@ -8338,7 +8337,7 @@ char *do_string_sub(char *str, char *pat, char *sub, typval_T *expr, char *flags
tail += i;
continue;
}
- zero_width = (char *)regmatch.startp[0];
+ zero_width = regmatch.startp[0];
}
// Get some space for a temporary buffer to do the substitution
@@ -8351,14 +8350,14 @@ char *do_string_sub(char *str, char *pat, char *sub, typval_T *expr, char *flags
(regmatch.endp[0] - regmatch.startp[0])));
// copy the text up to where the match is
- int i = (int)(regmatch.startp[0] - (char_u *)tail);
+ int i = (int)(regmatch.startp[0] - tail);
memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
// add the substituted text
(void)vim_regsub(&regmatch, (char_u *)sub, expr,
(char_u *)ga.ga_data + ga.ga_len + i, sublen,
REGSUB_COPY | REGSUB_MAGIC);
ga.ga_len += i + sublen - 1;
- tail = (char *)regmatch.endp[0];
+ tail = regmatch.endp[0];
if (*tail == NUL) {
break;
}
diff --git a/src/nvim/eval.h b/src/nvim/eval.h
index b0cb5fd8c1..afebdf5acb 100644
--- a/src/nvim/eval.h
+++ b/src/nvim/eval.h
@@ -11,33 +11,31 @@
#define COPYID_INC 2
#define COPYID_MASK (~0x1)
-/*
- * Structure returned by get_lval() and used by set_var_lval().
- * For a plain name:
- * "name" points to the variable name.
- * "exp_name" is NULL.
- * "tv" is NULL
- * For a magic braces name:
- * "name" points to the expanded variable name.
- * "exp_name" is non-NULL, to be freed later.
- * "tv" is NULL
- * For an index in a list:
- * "name" points to the (expanded) variable name.
- * "exp_name" NULL or non-NULL, to be freed later.
- * "tv" points to the (first) list item value
- * "li" points to the (first) list item
- * "range", "n1", "n2" and "empty2" indicate what items are used.
- * For an existing Dict item:
- * "name" points to the (expanded) variable name.
- * "exp_name" NULL or non-NULL, to be freed later.
- * "tv" points to the dict item value
- * "newkey" is NULL
- * For a non-existing Dict item:
- * "name" points to the (expanded) variable name.
- * "exp_name" NULL or non-NULL, to be freed later.
- * "tv" points to the Dictionary typval_T
- * "newkey" is the key for the new item.
- */
+// Structure returned by get_lval() and used by set_var_lval().
+// For a plain name:
+// "name" points to the variable name.
+// "exp_name" is NULL.
+// "tv" is NULL
+// For a magic braces name:
+// "name" points to the expanded variable name.
+// "exp_name" is non-NULL, to be freed later.
+// "tv" is NULL
+// For an index in a list:
+// "name" points to the (expanded) variable name.
+// "exp_name" NULL or non-NULL, to be freed later.
+// "tv" points to the (first) list item value
+// "li" points to the (first) list item
+// "range", "n1", "n2" and "empty2" indicate what items are used.
+// For an existing Dict item:
+// "name" points to the (expanded) variable name.
+// "exp_name" NULL or non-NULL, to be freed later.
+// "tv" points to the dict item value
+// "newkey" is NULL
+// For a non-existing Dict item:
+// "name" points to the (expanded) variable name.
+// "exp_name" NULL or non-NULL, to be freed later.
+// "tv" points to the Dictionary typval_T
+// "newkey" is the key for the new item.
typedef struct lval_S {
const char *ll_name; ///< Start of variable name (can be NULL).
size_t ll_name_len; ///< Length of the .ll_name.
diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua
index 3e89489459..5c500af899 100644
--- a/src/nvim/eval.lua
+++ b/src/nvim/eval.lua
@@ -425,6 +425,7 @@ return {
uniq={args={1, 3}, base=1},
values={args=1, base=1},
virtcol={args=1, base=1},
+ virtcol2col={args=3, base=1},
visualmode={args={0, 1}},
wait={args={2,3}},
wildmenumode={},
diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c
index 7b975ce775..d585509df4 100644
--- a/src/nvim/eval/decode.c
+++ b/src/nvim/eval/decode.c
@@ -430,7 +430,7 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len,
const char ubuf[] = { t[1], t[2], t[3], t[4] };
t += 4;
uvarnumber_T ch;
- vim_str2nr((char_u *)ubuf, NULL, NULL,
+ vim_str2nr(ubuf, NULL, NULL,
STR2NR_HEX | STR2NR_FORCE, NULL, &ch, 4, true);
if (ch == 0) {
hasnul = true;
@@ -600,7 +600,7 @@ parse_json_number_check:
// Convert integer
varnumber_T nr;
int num_len;
- vim_str2nr((char_u *)s, NULL, &num_len, 0, &nr, NULL, (int)(p - s), true);
+ vim_str2nr(s, NULL, &num_len, 0, &nr, NULL, (int)(p - s), true);
if ((int)exp_num_len != num_len) {
semsg(_("E685: internal error: while converting number \"%.*s\" "
"to integer vim_str2nr consumed %i bytes in place of %zu"),
diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c
index 5a5293780d..4a139c85d1 100644
--- a/src/nvim/eval/funcs.c
+++ b/src/nvim/eval/funcs.c
@@ -423,7 +423,7 @@ static buf_T *find_buffer(typval_T *avar)
FOR_ALL_BUFFERS(bp) {
if (bp->b_fname != NULL
&& (path_with_url(bp->b_fname) || bt_nofilename(bp))
- && STRCMP(bp->b_fname, avar->vval.v_string) == 0) {
+ && strcmp(bp->b_fname, avar->vval.v_string) == 0) {
buf = bp;
break;
}
@@ -849,7 +849,7 @@ static void get_col(typval_T *argvars, typval_T *rettv, bool charcol)
// col(".") when the cursor is on the NUL at the end of the line
// because of "coladd" can be seen as an extra column.
if (virtual_active() && fp == &curwin->w_cursor) {
- char *p = (char *)get_cursor_pos_ptr();
+ char *p = get_cursor_pos_ptr();
if (curwin->w_cursor.coladd >=
(colnr_T)win_chartabsize(curwin, p,
curwin->w_virtcol - curwin->w_cursor.coladd)) {
@@ -930,12 +930,12 @@ static void f_chdir(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
// Return the current directory
- char_u *cwd = xmalloc(MAXPATHL);
- if (os_dirname(cwd, MAXPATHL) != FAIL) {
+ char *cwd = xmalloc(MAXPATHL);
+ if (os_dirname((char_u *)cwd, MAXPATHL) != FAIL) {
#ifdef BACKSLASH_IN_FILENAME
slash_adjust(cwd);
#endif
- rettv->vval.v_string = (char *)vim_strsave(cwd);
+ rettv->vval.v_string = xstrdup(cwd);
}
xfree(cwd);
@@ -1772,7 +1772,7 @@ static void f_eventhandler(typval_T *argvars, typval_T *rettv, EvalFuncData fptr
/// "executable()" function
static void f_executable(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
- if (tv_check_for_string(&argvars[0]) == FAIL) {
+ if (tv_check_for_string_arg(argvars, 0) == FAIL) {
return;
}
@@ -1901,7 +1901,7 @@ static void f_win_execute(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
/// "exepath()" function
static void f_exepath(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
- if (tv_check_for_nonempty_string(&argvars[0]) == FAIL) {
+ if (tv_check_for_nonempty_string_arg(argvars, 0) == FAIL) {
return;
}
@@ -2016,10 +2016,9 @@ static void f_expand(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
options += WILD_ICASE;
}
if (rettv->v_type == VAR_STRING) {
- rettv->vval.v_string = (char *)ExpandOne(&xpc, (char_u *)s, NULL, options,
- WILD_ALL);
+ rettv->vval.v_string = ExpandOne(&xpc, (char *)s, NULL, options, WILD_ALL);
} else {
- ExpandOne(&xpc, (char_u *)s, NULL, options, WILD_ALL_KEEP);
+ ExpandOne(&xpc, (char *)s, NULL, options, WILD_ALL_KEEP);
tv_list_alloc_ret(rettv, xpc.xp_numfiles);
for (int i = 0; i < xpc.xp_numfiles; i++) {
tv_list_append_string(rettv->vval.v_list,
@@ -2437,7 +2436,7 @@ static void f_get(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
pt = argvars[0].vval.v_partial;
} else {
CLEAR_FIELD(fref_pt);
- fref_pt.pt_name = (char_u *)argvars[0].vval.v_string;
+ fref_pt.pt_name = argvars[0].vval.v_string;
pt = &fref_pt;
}
@@ -2579,9 +2578,8 @@ static void get_buffer_lines(buf_T *buf, linenr_T start, linenr_T end, int retli
}
} else {
rettv->v_type = VAR_STRING;
- rettv->vval.v_string =
- (char *)((start >= 1 && start <= buf->b_ml.ml_line_count)
- ? vim_strsave(ml_get_buf(buf, start, false)) : NULL);
+ rettv->vval.v_string = ((start >= 1 && start <= buf->b_ml.ml_line_count)
+ ? xstrdup(ml_get_buf(buf, start, false)) : NULL);
}
}
@@ -2919,7 +2917,7 @@ static void f_getftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
/// "getftype({fname})" function
static void f_getftype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
- char_u *type = NULL;
+ char *type = NULL;
char *t;
const char *fname = tv_get_string(&argvars[0]);
@@ -2945,9 +2943,9 @@ static void f_getftype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
} else {
t = "other";
}
- type = vim_strsave((char_u *)t);
+ type = xstrdup(t);
}
- rettv->vval.v_string = (char *)type;
+ rettv->vval.v_string = type;
}
/// "getjumplist()" function
@@ -3441,11 +3439,11 @@ static void f_glob(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
options += WILD_ICASE;
}
if (rettv->v_type == VAR_STRING) {
- rettv->vval.v_string = (char *)ExpandOne(&xpc, (char_u *)
- tv_get_string(&argvars[0]), NULL, options,
- WILD_ALL);
+ rettv->vval.v_string = ExpandOne(&xpc, (char *)
+ tv_get_string(&argvars[0]), NULL, options,
+ WILD_ALL);
} else {
- ExpandOne(&xpc, (char_u *)tv_get_string(&argvars[0]), NULL, options,
+ ExpandOne(&xpc, (char *)tv_get_string(&argvars[0]), NULL, options,
WILD_ALL_KEEP);
tv_list_alloc_ret(rettv, xpc.xp_numfiles);
for (int i = 0; i < xpc.xp_numfiles; i++) {
@@ -4986,9 +4984,9 @@ static void find_some_match(typval_T *const argvars, typval_T *const rettv,
li = TV_LIST_ITEM_NEXT(l, li);
idx++;
} else {
- startcol = (colnr_T)(regmatch.startp[0]
- + utfc_ptr2len((char *)regmatch.startp[0]) - str);
- if (startcol > (colnr_T)len || str + startcol <= regmatch.startp[0]) {
+ startcol = (colnr_T)((char_u *)regmatch.startp[0]
+ + utfc_ptr2len(regmatch.startp[0]) - str);
+ if (startcol > (colnr_T)len || str + startcol <= (char_u *)regmatch.startp[0]) {
match = false;
break;
}
@@ -5007,8 +5005,8 @@ static void find_some_match(typval_T *const argvars, typval_T *const rettv,
const size_t rd = (size_t)(regmatch.endp[0] - regmatch.startp[0]);
TV_LIST_ITEM_TV(li1)->vval.v_string = xmemdupz((const char *)regmatch.startp[0], rd);
- TV_LIST_ITEM_TV(li3)->vval.v_number = (varnumber_T)(regmatch.startp[0] - expr);
- TV_LIST_ITEM_TV(li4)->vval.v_number = (varnumber_T)(regmatch.endp[0] - expr);
+ TV_LIST_ITEM_TV(li3)->vval.v_number = (varnumber_T)((char_u *)regmatch.startp[0] - expr);
+ TV_LIST_ITEM_TV(li4)->vval.v_number = (varnumber_T)(regmatch.endp[0] - (char *)expr);
if (l != NULL) {
TV_LIST_ITEM_TV(li2)->vval.v_number = (varnumber_T)idx;
}
@@ -5043,10 +5041,10 @@ static void find_some_match(typval_T *const argvars, typval_T *const rettv,
} else {
if (type == kSomeMatch) {
rettv->vval.v_number =
- (varnumber_T)(regmatch.startp[0] - str);
+ (varnumber_T)((char_u *)regmatch.startp[0] - str);
} else {
rettv->vval.v_number =
- (varnumber_T)(regmatch.endp[0] - str);
+ (varnumber_T)(regmatch.endp[0] - (char *)str);
}
rettv->vval.v_number += (varnumber_T)(str - expr);
}
@@ -5443,11 +5441,11 @@ static void f_pathshorten(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
rettv->v_type = VAR_STRING;
- const char_u *p = (char_u *)tv_get_string_chk(&argvars[0]);
+ const char *p = tv_get_string_chk(&argvars[0]);
if (p == NULL) {
rettv->vval.v_string = NULL;
} else {
- rettv->vval.v_string = (char *)vim_strsave(p);
+ rettv->vval.v_string = xstrdup(p);
shorten_dir_len((char_u *)rettv->vval.v_string, trim_len);
}
}
@@ -5565,7 +5563,7 @@ static void f_prompt_getprompt(typval_T *argvars, typval_T *rettv, EvalFuncData
return;
}
- rettv->vval.v_string = (char *)vim_strsave(buf_prompt_text(buf));
+ rettv->vval.v_string = xstrdup(buf_prompt_text(buf));
}
/// "prompt_setprompt({buffer}, {text})" function
@@ -5869,9 +5867,9 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
bool binary = false;
bool blob = false;
FILE *fd;
- char_u buf[(IOSIZE/256) * 256]; // rounded to avoid odd + 1
+ char buf[(IOSIZE/256) * 256]; // rounded to avoid odd + 1
int io_size = sizeof(buf);
- char_u *prev = NULL; // previously read bytes, if any
+ char *prev = NULL; // previously read bytes, if any
long prevlen = 0; // length of data in prev
long prevsize = 0; // size of prev buffer
long maxline = MAXLNUM;
@@ -5922,13 +5920,13 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
// - an incomplete line gets written
// - a "binary" file gets an empty line at the end if it ends in a
// newline.
- char_u *p; // Position in buf.
- char_u *start; // Start of current line.
+ char *p; // Position in buf.
+ char *start; // Start of current line.
for (p = buf, start = buf;
p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
p++) {
if (*p == '\n' || readlen <= 0) {
- char_u *s = NULL;
+ char *s = NULL;
size_t len = (size_t)(p - start);
// Finished a line. Remove CRs before NL.
@@ -5945,7 +5943,7 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
if (prevlen == 0) {
assert(len < INT_MAX);
- s = vim_strnsave(start, len);
+ s = xstrnsave(start, len);
} else {
// Change "prev" buffer to be the right size. This way
// the bytes are only copied once, and very long lines are
@@ -5960,7 +5958,7 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
tv_list_append_owned_tv(l, (typval_T) {
.v_type = VAR_STRING,
.v_lock = VAR_UNLOCKED,
- .vval.v_string = (char *)s,
+ .vval.v_string = s,
});
start = p + 1; // Step over newline.
@@ -5980,18 +5978,18 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
*p = '\n';
// Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
// when finding the BF and check the previous two bytes.
- } else if (*p == 0xbf && !binary) {
+ } else if ((uint8_t)(*p) == 0xbf && !binary) {
// Find the two bytes before the 0xbf. If p is at buf, or buf + 1,
// these may be in the "prev" string.
- char_u back1 = p >= buf + 1 ? p[-1]
+ char back1 = p >= buf + 1 ? p[-1]
: prevlen >= 1 ? prev[prevlen - 1] : NUL;
- char_u back2 = p >= buf + 2 ? p[-2]
+ char back2 = p >= buf + 2 ? p[-2]
: p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
: prevlen >=
- 2 ? prev[prevlen - 2] : NUL;
+ 2 ? prev[prevlen - 2] : NUL;
- if (back2 == 0xef && back1 == 0xbb) {
- char_u *dest = p - 2;
+ if ((uint8_t)back2 == 0xef && (uint8_t)back1 == 0xbb) {
+ char *dest = p - 2;
// Usually a BOM is at the beginning of a file, and so at
// the beginning of a line; then we can just step over it.
@@ -6227,8 +6225,8 @@ static void f_rename(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
rettv->vval.v_number = -1;
} else {
char buf[NUMBUFLEN];
- rettv->vval.v_number = vim_rename((const char_u *)tv_get_string(&argvars[0]),
- (const char_u *)tv_get_string_buf(&argvars[1], buf));
+ rettv->vval.v_number = vim_rename(tv_get_string(&argvars[0]),
+ tv_get_string_buf(&argvars[1], buf));
}
}
@@ -7059,32 +7057,6 @@ static void f_screencol(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
rettv->vval.v_number = ui_current_col() + 1;
}
-/// "screenpos({winid}, {lnum}, {col})" function
-static void f_screenpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
-{
- tv_dict_alloc_ret(rettv);
- dict_T *dict = rettv->vval.v_dict;
-
- win_T *wp = find_win_by_nr_or_id(&argvars[0]);
- if (wp == NULL) {
- return;
- }
-
- pos_T pos = {
- .lnum = (linenr_T)tv_get_number(&argvars[1]),
- .col = (colnr_T)tv_get_number(&argvars[2]) - 1,
- .coladd = 0
- };
- int row = 0;
- int scol = 0, ccol = 0, ecol = 0;
- textpos2screenpos(wp, &pos, &row, &scol, &ccol, &ecol, false);
-
- tv_dict_add_nr(dict, S_LEN("row"), row);
- tv_dict_add_nr(dict, S_LEN("col"), scol);
- tv_dict_add_nr(dict, S_LEN("curscol"), ccol);
- tv_dict_add_nr(dict, S_LEN("endcol"), ecol);
-}
-
/// "screenrow()" function
static void f_screenrow(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
@@ -7107,7 +7079,7 @@ static void f_screenstring(typval_T *argvars, typval_T *rettv, EvalFuncData fptr
return;
}
- rettv->vval.v_string = (char *)vim_strsave(grid->chars[grid->line_offset[row] + (size_t)col]);
+ rettv->vval.v_string = xstrdup((char *)grid->chars[grid->line_offset[row] + (size_t)col]);
}
/// "search()" function
@@ -8052,7 +8024,7 @@ static void f_spellbadword(typval_T *argvars, typval_T *rettv, EvalFuncData fptr
// Find the start and length of the badly spelled word.
len = spell_move_to(curwin, FORWARD, true, true, &attr);
if (len != 0) {
- word = (char *)get_cursor_pos_ptr();
+ word = get_cursor_pos_ptr();
curwin->w_set_curswant = true;
}
} else if (*curbuf->b_s.b_p_spl != NUL) {
@@ -8195,11 +8167,11 @@ static void f_split(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
break;
}
// Advance to just after the match.
- if (regmatch.endp[0] > (char_u *)str) {
+ if (regmatch.endp[0] > str) {
col = 0;
} else {
// Don't get stuck at the same match.
- col = utfc_ptr2len((char *)regmatch.endp[0]);
+ col = utfc_ptr2len(regmatch.endp[0]);
}
str = (const char *)regmatch.endp[0];
}
@@ -8304,7 +8276,7 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
break;
}
varnumber_T n;
- vim_str2nr(p, NULL, NULL, what, &n, NULL, 0, false);
+ vim_str2nr((char *)p, NULL, NULL, what, &n, NULL, 0, false);
// Text after the number is silently ignored.
if (isneg) {
rettv->vval.v_number = -n;
@@ -8740,7 +8712,7 @@ static void f_swapname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
|| buf->b_ml.ml_mfp->mf_fname == NULL) {
rettv->vval.v_string = NULL;
} else {
- rettv->vval.v_string = (char *)vim_strsave(buf->b_ml.ml_mfp->mf_fname);
+ rettv->vval.v_string = xstrdup(buf->b_ml.ml_mfp->mf_fname);
}
}
@@ -9101,7 +9073,7 @@ static void f_taglist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
static void f_tempname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
rettv->v_type = VAR_STRING;
- rettv->vval.v_string = (char *)vim_tempname();
+ rettv->vval.v_string = vim_tempname();
}
/// "termopen(cmd[, cwd])" function
@@ -9416,10 +9388,10 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
char buf1[NUMBUFLEN];
char buf2[NUMBUFLEN];
- const char_u *head = (const char_u *)tv_get_string_buf_chk(&argvars[0], buf1);
- const char_u *mask = NULL;
- const char_u *prev;
- const char_u *p;
+ const char *head = tv_get_string_buf_chk(&argvars[0], buf1);
+ const char *mask = NULL;
+ const char *prev;
+ const char *p;
int dir = 0;
rettv->v_type = VAR_STRING;
@@ -9434,7 +9406,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
if (argvars[1].v_type == VAR_STRING) {
- mask = (const char_u *)tv_get_string_buf_chk(&argvars[1], buf2);
+ mask = tv_get_string_buf_chk(&argvars[1], buf2);
if (argvars[2].v_type != VAR_UNKNOWN) {
bool error = false;
// leading or trailing characters to trim
@@ -9472,7 +9444,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
}
- const char_u *tail = head + STRLEN(head);
+ const char *tail = head + STRLEN(head);
if (dir == 0 || dir == 2) {
// Trim trailing characters
for (; tail > head; tail = prev) {
@@ -9495,7 +9467,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
}
}
}
- rettv->vval.v_string = (char *)vim_strnsave(head, (size_t)(tail - head));
+ rettv->vval.v_string = xstrnsave(head, (size_t)(tail - head));
}
/// "type(expr)" function
@@ -9595,12 +9567,12 @@ static void f_virtcol(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
/// "visualmode()" function
static void f_visualmode(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
- char_u str[2];
+ char str[2];
rettv->v_type = VAR_STRING;
- str[0] = (char_u)curbuf->b_visual_mode_eval;
+ str[0] = (char)curbuf->b_visual_mode_eval;
str[1] = NUL;
- rettv->vval.v_string = (char *)vim_strsave(str);
+ rettv->vval.v_string = xstrdup(str);
// A non-zero number or non-empty string argument: reset mode.
if (non_zero_arg(&argvars[0])) {
diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c
index d5b2b1f2ae..2089415ffa 100644
--- a/src/nvim/eval/typval.c
+++ b/src/nvim/eval/typval.c
@@ -40,6 +40,13 @@
# include "eval/typval.c.generated.h"
#endif
+static char e_string_required_for_argument_nr[]
+ = N_("E1174: String required for argument %d");
+static char e_non_empty_string_required_for_argument_nr[]
+ = N_("E1142: Non-empty string required for argument %d");
+static char e_number_required_for_argument_nr[]
+ = N_("E1210: Number required for argument %d");
+
bool tv_in_free_unref_items = false;
// TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead
@@ -1016,7 +1023,7 @@ static int item_compare(const void *s1, const void *s2, bool keep_zero)
if (sortinfo->item_compare_lc) {
res = strcoll(p1, p2);
} else {
- res = sortinfo->item_compare_ic ? STRICMP(p1, p2): STRCMP(p1, p2);
+ res = sortinfo->item_compare_ic ? STRICMP(p1, p2): strcmp(p1, p2);
}
} else {
double n1, n2;
@@ -1568,7 +1575,7 @@ bool tv_callback_equal(const Callback *cb1, const Callback *cb2)
}
switch (cb1->type) {
case kCallbackFuncref:
- return STRCMP(cb1->data.funcref, cb2->data.funcref) == 0;
+ return strcmp(cb1->data.funcref, cb2->data.funcref) == 0;
case kCallbackPartial:
// FIXME: this is inconsistent with tv_equal but is needed for precision
// maybe change dictwatcheradd to return a watcher id instead?
@@ -2777,7 +2784,7 @@ static void tv_dict_list(typval_T *const tv, typval_T *const rettv, const DictLi
switch (what) {
case kDictListKeys:
tv_item.v_type = VAR_STRING;
- tv_item.vval.v_string = (char *)vim_strsave(di->di_key);
+ tv_item.vval.v_string = xstrdup((char *)di->di_key);
break;
case kDictListValues:
tv_copy(&di->di_tv, &tv_item);
@@ -3717,8 +3724,7 @@ varnumber_T tv_get_number_chk(const typval_T *const tv, bool *const ret_error)
case VAR_STRING: {
varnumber_T n = 0;
if (tv->vval.v_string != NULL) {
- vim_str2nr((char_u *)tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0,
- false);
+ vim_str2nr(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0, false);
}
return n;
}
@@ -3801,26 +3807,37 @@ float_T tv_get_float(const typval_T *const tv)
return 0;
}
-// Give an error and return FAIL unless "tv" is a string.
-int tv_check_for_string(const typval_T *const tv)
+/// Give an error and return FAIL unless "args[idx]" is a string.
+int tv_check_for_string_arg(const typval_T *const args, const int idx)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
{
- if (tv->v_type != VAR_STRING) {
- emsg(_(e_stringreq));
+ if (args[idx].v_type != VAR_STRING) {
+ semsg(_(e_string_required_for_argument_nr), idx + 1);
return FAIL;
}
return OK;
}
-// Give an error and return FAIL unless "tv" is a non-empty string.
-int tv_check_for_nonempty_string(const typval_T *const tv)
+/// Give an error and return FAIL unless "args[idx]" is a non-empty string.
+int tv_check_for_nonempty_string_arg(const typval_T *const args, const int idx)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
{
- if (tv_check_for_string(tv) == FAIL) {
+ if (tv_check_for_string_arg(args, idx) == FAIL) {
+ return FAIL;
+ }
+ if (args[idx].vval.v_string == NULL || *args[idx].vval.v_string == NUL) {
+ semsg(_(e_non_empty_string_required_for_argument_nr), idx + 1);
return FAIL;
}
- if (tv->vval.v_string == NULL || *tv->vval.v_string == NUL) {
- emsg(_(e_non_empty_string_required));
+ return OK;
+}
+
+/// Give an error and return FAIL unless "args[idx]" is a number.
+int tv_check_for_number_arg(const typval_T *const args, const int idx)
+ FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
+{
+ if (args[idx].v_type != VAR_NUMBER) {
+ semsg(_(e_number_required_for_argument_nr), idx + 1);
return FAIL;
}
return OK;
diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h
index 8177d01f90..6373ead1a3 100644
--- a/src/nvim/eval/typval.h
+++ b/src/nvim/eval/typval.h
@@ -286,12 +286,6 @@ typedef struct {
/// Number of fixed variables used for arguments
#define FIXVAR_CNT 12
-/// Callback interface for C function reference>
-/// Used for managing functions that were registered with |register_cfunc|
-typedef int (*cfunc_T)(int argcount, typval_T *argvars, typval_T *rettv, void *state); // NOLINT
-/// Callback to clear cfunc_T and any associated state.
-typedef void (*cfunc_free_T)(void *state);
-
// Structure to hold info for a function that is currently being executed.
typedef struct funccall_S funccall_T;
@@ -330,10 +324,7 @@ struct ufunc {
garray_T uf_lines; ///< function lines
int uf_profiling; ///< true when func is being profiled
int uf_prof_initialized;
- // Managing cfuncs
- cfunc_T uf_cb; ///< C function extension callback
- cfunc_free_T uf_cb_free; ///< C function extension free callback
- void *uf_cb_state; ///< State of C function extension.
+ LuaRef uf_luaref; ///< lua callback, used if (uf_flags & FC_LUAREF)
// Profiling the function as a whole.
int uf_tm_count; ///< nr of calls
proftime_T uf_tm_total; ///< time spent in function + children
@@ -360,15 +351,14 @@ struct ufunc {
};
struct partial_S {
- int pt_refcount; ///< Reference count.
- char_u *pt_name; ///< Function name; when NULL use pt_func->name.
- ufunc_T *pt_func; ///< Function pointer; when NULL lookup function with
- ///< pt_name.
- bool pt_auto; ///< When true the partial was created by using dict.member
- ///< in handle_subscript().
- int pt_argc; ///< Number of arguments.
+ int pt_refcount; ///< Reference count.
+ char *pt_name; ///< Function name; when NULL use pt_func->name.
+ ufunc_T *pt_func; ///< Function pointer; when NULL lookup function with pt_name.
+ bool pt_auto; ///< When true the partial was created by using dict.member
+ ///< in handle_subscript().
+ int pt_argc; ///< Number of arguments.
typval_T *pt_argv; ///< Arguments in allocated array.
- dict_T *pt_dict; ///< Dict for "self".
+ dict_T *pt_dict; ///< Dict for "self".
};
/// Structure used for explicit stack while garbage collecting hash tables
diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c
index bcaca0ca13..70c9e02d5c 100644
--- a/src/nvim/eval/userfunc.c
+++ b/src/nvim/eval/userfunc.c
@@ -28,20 +28,6 @@
#include "nvim/ui.h"
#include "nvim/vim.h"
-// flags used in uf_flags
-#define FC_ABORT 0x01 // abort function on error
-#define FC_RANGE 0x02 // function accepts range
-#define FC_DICT 0x04 // Dict function, uses "self"
-#define FC_CLOSURE 0x08 // closure, uses outer scope variables
-#define FC_DELETED 0x10 // :delfunction used while uf_refcount > 0
-#define FC_REMOVED 0x20 // function redefined while uf_refcount > 0
-#define FC_SANDBOX 0x40 // function defined in the sandbox
-#define FC_DEAD 0x80 // function kept only for reference to dfunc
-#define FC_EXPORT 0x100 // "export def Func()"
-#define FC_NOARGS 0x200 // no a: variables in lambda
-#define FC_VIM9 0x400 // defined in vim9 script file
-#define FC_CFUNC 0x800 // C function extension
-
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "eval/userfunc.c.generated.h"
#endif
@@ -125,7 +111,7 @@ static int get_function_args(char **argp, char_u endchar, garray_T *newargs, int
// Check for duplicate argument name.
for (i = 0; i < newargs->ga_len; i++) {
- if (STRCMP(((char **)(newargs->ga_data))[i], arg) == 0) {
+ if (strcmp(((char **)(newargs->ga_data))[i], arg) == 0) {
semsg(_("E853: Duplicate argument name: %s"), arg);
xfree(arg);
goto err_ret;
@@ -142,18 +128,18 @@ static int get_function_args(char **argp, char_u endchar, garray_T *newargs, int
any_default = true;
p = skipwhite(p) + 1;
p = skipwhite(p);
- char_u *expr = (char_u *)p;
+ char *expr = p;
if (eval1(&p, &rettv, false) != FAIL) {
ga_grow(default_args, 1);
// trim trailing whitespace
- while (p > (char *)expr && ascii_iswhite(p[-1])) {
+ while (p > expr && ascii_iswhite(p[-1])) {
p--;
}
c = (char_u)(*p);
*p = NUL;
- expr = vim_strsave(expr);
- ((char **)(default_args->ga_data))[default_args->ga_len] = (char *)expr;
+ expr = xstrdup(expr);
+ ((char **)(default_args->ga_data))[default_args->ga_len] = expr;
default_args->ga_len++;
*p = (char)c;
} else {
@@ -525,22 +511,22 @@ static inline bool eval_fname_sid(const char *const name)
///
/// @return transformed name: either `fname_buf` or a pointer to an allocated
/// memory.
-static char_u *fname_trans_sid(const char_u *const name, char_u *const fname_buf,
- char_u **const tofree, int *const error)
+static char *fname_trans_sid(const char *const name, char *const fname_buf, char **const tofree,
+ int *const error)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
- char_u *fname;
- const int llen = eval_fname_script((const char *)name);
+ char *fname;
+ const int llen = eval_fname_script(name);
if (llen > 0) {
- fname_buf[0] = K_SPECIAL;
- fname_buf[1] = KS_EXTRA;
+ fname_buf[0] = (char)K_SPECIAL;
+ fname_buf[1] = (char)KS_EXTRA;
fname_buf[2] = KE_SNR;
int i = 3;
- if (eval_fname_sid((const char *)name)) { // "<SID>" or "s:"
+ if (eval_fname_sid(name)) { // "<SID>" or "s:"
if (current_sctx.sc_sid <= 0) {
*error = ERROR_SCRIPT;
} else {
- snprintf((char *)fname_buf + i, (size_t)(FLEN_FIXED + 1 - i), "%" PRId64 "_",
+ snprintf(fname_buf + i, (size_t)(FLEN_FIXED + 1 - i), "%" PRId64 "_",
(int64_t)current_sctx.sc_sid);
i = (int)STRLEN(fname_buf);
}
@@ -555,7 +541,7 @@ static char_u *fname_trans_sid(const char_u *const name, char_u *const fname_buf
STRCPY(fname + i, name + llen);
}
} else {
- fname = (char_u *)name;
+ fname = (char *)name;
}
return fname;
@@ -758,9 +744,9 @@ static void func_clear_items(ufunc_T *fp)
ga_clear_strings(&(fp->uf_lines));
XFREE_CLEAR(fp->uf_name_exp);
- if (fp->uf_cb_free != NULL) {
- fp->uf_cb_free(fp->uf_cb_state);
- fp->uf_cb_free = NULL;
+ if (fp->uf_flags & FC_LUAREF) {
+ api_free_luaref(fp->uf_luaref);
+ fp->uf_luaref = LUA_NOREF;
}
XFREE_CLEAR(fp->uf_tml_count);
@@ -1437,10 +1423,10 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t
int ret = FAIL;
int error = ERROR_NONE;
ufunc_T *fp = NULL;
- char_u fname_buf[FLEN_FIXED + 1];
- char_u *tofree = NULL;
- char_u *fname = NULL;
- char_u *name = NULL;
+ char fname_buf[FLEN_FIXED + 1];
+ char *tofree = NULL;
+ char *fname = NULL;
+ char *name = NULL;
int argcount = argcount_in;
typval_T *argvars = argvars_in;
dict_T *selfdict = funcexe->selfdict;
@@ -1463,8 +1449,8 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t
if (fp == NULL) {
// Make a copy of the name, if it comes from a funcref variable it could
// be changed or deleted in the called function.
- name = vim_strnsave((char_u *)funcname, (size_t)len);
- fname = fname_trans_sid(name, fname_buf, &tofree, &error);
+ name = xstrnsave(funcname, (size_t)len);
+ fname = fname_trans_sid(name, (char *)fname_buf, &tofree, &error);
}
if (funcexe->doesrange != NULL) {
@@ -1495,7 +1481,7 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t
}
if (error == ERROR_NONE && funcexe->evaluate) {
- char_u *rfname = fname;
+ char *rfname = fname;
// Ignore "g:" before a function name.
if (fp == NULL && fname[0] == 'g' && fname[1] == ':') {
@@ -1519,28 +1505,27 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t
} else if (fp != NULL || !builtin_function((const char *)rfname, -1)) {
// User defined function.
if (fp == NULL) {
- fp = find_func(rfname);
+ fp = find_func((char_u *)rfname);
}
// Trigger FuncUndefined event, may load the function.
if (fp == NULL
- && apply_autocmds(EVENT_FUNCUNDEFINED, (char *)rfname, (char *)rfname, true, NULL)
+ && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, true, NULL)
&& !aborting()) {
// executed an autocommand, search for the function again
- fp = find_func(rfname);
+ fp = find_func((char_u *)rfname);
}
// Try loading a package.
if (fp == NULL && script_autoload((const char *)rfname, STRLEN(rfname),
true) && !aborting()) {
// Loaded a package, search for the function again.
- fp = find_func(rfname);
+ fp = find_func((char_u *)rfname);
}
if (fp != NULL && (fp->uf_flags & FC_DELETED)) {
error = ERROR_DELETED;
- } else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) {
- cfunc_T cb = fp->uf_cb;
- error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state);
+ } else if (fp != NULL && (fp->uf_flags & FC_LUAREF)) {
+ error = typval_exec_lua_callable(fp->uf_luaref, argcount, argvars, rettv);
} else if (fp != NULL) {
if (funcexe->argv_func != NULL) {
// postponed filling in the arguments, do it now
@@ -1570,22 +1555,20 @@ int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, t
} else if (funcexe->basetv != NULL) {
// expr->method(): Find the method name in the table, call its
// implementation with the base as one of the arguments.
- error = call_internal_method(fname, argcount, argvars, rettv,
+ error = call_internal_method((char_u *)fname, argcount, argvars, rettv,
funcexe->basetv);
} else {
// Find the function name in the table, call its implementation.
- error = call_internal_func(fname, argcount, argvars, rettv);
- }
- /*
- * The function call (or "FuncUndefined" autocommand sequence) might
- * have been aborted by an error, an interrupt, or an explicitly thrown
- * exception that has not been caught so far. This situation can be
- * tested for by calling aborting(). For an error in an internal
- * function or for the "E132" error in call_user_func(), however, the
- * throw point at which the "force_abort" flag (temporarily reset by
- * emsg()) is normally updated has not been reached yet. We need to
- * update that flag first to make aborting() reliable.
- */
+ error = call_internal_func((char_u *)fname, argcount, argvars, rettv);
+ }
+ // The function call (or "FuncUndefined" autocommand sequence) might
+ // have been aborted by an error, an interrupt, or an explicitly thrown
+ // exception that has not been caught so far. This situation can be
+ // tested for by calling aborting(). For an error in an internal
+ // function or for the "E132" error in call_user_func(), however, the
+ // throw point at which the "force_abort" flag (temporarily reset by
+ // emsg()) is normally updated has not been reached yet. We need to
+ // update that flag first to make aborting() reliable.
update_force_abort();
}
if (error == ERROR_NONE) {
@@ -1596,7 +1579,7 @@ theend:
// Report an error unless the argument evaluation or function call has been
// cancelled due to an aborting error, an interrupt, or an exception.
if (!aborting()) {
- user_func_error(error, (name != NULL) ? name : (char_u *)funcname);
+ user_func_error(error, (name != NULL) ? (char_u *)name : (char_u *)funcname);
}
// clear the copies made from the partial
@@ -1682,7 +1665,7 @@ static void list_func_head(ufunc_T *fp, int indent, bool force)
char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, partial_T **partial)
FUNC_ATTR_NONNULL_ARG(1)
{
- char_u *name = NULL;
+ char *name = NULL;
const char_u *start;
const char_u *end;
int lead;
@@ -1720,11 +1703,9 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa
goto theend;
}
if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) {
- /*
- * Report an invalid expression in braces, unless the expression
- * evaluation has been cancelled due to an aborting error, an
- * interrupt, or an exception.
- */
+ // Report an invalid expression in braces, unless the expression
+ // evaluation has been cancelled due to an aborting error, an
+ // interrupt, or an exception.
if (!aborting()) {
if (end != NULL) {
semsg(_(e_invarg2), start);
@@ -1743,7 +1724,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa
fdp->fd_di = lv.ll_di;
}
if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) {
- name = vim_strsave((char_u *)lv.ll_tv->vval.v_string);
+ name = xstrdup(lv.ll_tv->vval.v_string);
*pp = (char *)end;
} else if (lv.ll_tv->v_type == VAR_PARTIAL
&& lv.ll_tv->vval.v_partial != NULL) {
@@ -1757,7 +1738,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa
memcpy(name, end + 1, (size_t)len);
*pp = (char *)end + 1 + len;
} else {
- name = vim_strsave((char_u *)partial_name(lv.ll_tv->vval.v_partial));
+ name = xstrdup(partial_name(lv.ll_tv->vval.v_partial));
*pp = (char *)end;
}
if (partial != NULL) {
@@ -1785,28 +1766,28 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa
// Check if the name is a Funcref. If so, use the value.
if (lv.ll_exp_name != NULL) {
len = (int)strlen(lv.ll_exp_name);
- name = deref_func_name(lv.ll_exp_name, &len, partial,
- flags & TFN_NO_AUTOLOAD);
+ name = (char *)deref_func_name(lv.ll_exp_name, &len, partial,
+ flags & TFN_NO_AUTOLOAD);
if ((const char *)name == lv.ll_exp_name) {
name = NULL;
}
} else if (!(flags & TFN_NO_DEREF)) {
len = (int)(end - (char_u *)(*pp));
- name = deref_func_name((const char *)(*pp), &len, partial,
- flags & TFN_NO_AUTOLOAD);
- if (name == (char_u *)(*pp)) {
+ name = (char *)deref_func_name((const char *)(*pp), &len, partial,
+ flags & TFN_NO_AUTOLOAD);
+ if (name == *pp) {
name = NULL;
}
}
if (name != NULL) {
- name = vim_strsave(name);
+ name = xstrdup(name);
*pp = (char *)end;
if (STRNCMP(name, "<SNR>", 5) == 0) {
// Change "<SNR>" to the byte sequence.
- name[0] = K_SPECIAL;
- name[1] = KS_EXTRA;
+ name[0] = (char)K_SPECIAL;
+ name[1] = (char)KS_EXTRA;
name[2] = KE_SNR;
- memmove(name + 3, name + 5, strlen((char *)name + 5) + 1);
+ memmove(name + 3, name + 5, strlen(name + 5) + 1);
}
goto theend;
}
@@ -1869,8 +1850,8 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa
name = xmalloc((size_t)len + (size_t)lead + 1);
if (!skip && lead > 0) {
- name[0] = K_SPECIAL;
- name[1] = KS_EXTRA;
+ name[0] = (char)K_SPECIAL;
+ name[1] = (char)KS_EXTRA;
name[2] = KE_SNR;
if (sid_buf_len > 0) { // If it's "<SID>"
memcpy(name + 3, sid_buf, sid_buf_len);
@@ -1882,7 +1863,7 @@ char_u *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, pa
theend:
clear_lval(&lv);
- return name;
+ return (char_u *)name;
}
#define MAX_FUNC_NESTING 50
@@ -1890,15 +1871,15 @@ theend:
/// ":function"
void ex_function(exarg_T *eap)
{
- char_u *theline;
- char_u *line_to_free = NULL;
- char_u c;
+ char *theline;
+ char *line_to_free = NULL;
+ char c;
int saved_did_emsg;
bool saved_wait_return = need_wait_return;
- char_u *name = NULL;
- char_u *p;
- char_u *arg;
- char_u *line_arg = NULL;
+ char *name = NULL;
+ char *p;
+ char *arg;
+ char *line_arg = NULL;
garray_T newargs;
garray_T default_args;
garray_T newlines;
@@ -1918,14 +1899,12 @@ void ex_function(exarg_T *eap)
linenr_T sourcing_lnum_off;
linenr_T sourcing_lnum_top;
bool is_heredoc = false;
- char_u *skip_until = NULL;
- char_u *heredoc_trimmed = NULL;
+ char *skip_until = NULL;
+ char *heredoc_trimmed = NULL;
bool show_block = false;
bool do_concat = true;
- /*
- * ":function" without argument: list functions.
- */
+ // ":function" without argument: list functions.
if (ends_excmd(*eap->arg)) {
if (!eap->skip) {
todo = (int)func_hashtab.ht_used;
@@ -1946,11 +1925,9 @@ void ex_function(exarg_T *eap)
return;
}
- /*
- * ":function /pat": list functions matching pattern.
- */
+ // ":function /pat": list functions matching pattern.
if (*eap->arg == '/') {
- p = (char_u *)skip_regexp(eap->arg + 1, '/', true, NULL);
+ p = skip_regexp(eap->arg + 1, '/', true, NULL);
if (!eap->skip) {
regmatch_T regmatch;
@@ -1978,7 +1955,7 @@ void ex_function(exarg_T *eap)
if (*p == '/') {
p++;
}
- eap->nextcmd = check_nextcmd((char *)p);
+ eap->nextcmd = check_nextcmd(p);
return;
}
@@ -1996,15 +1973,13 @@ void ex_function(exarg_T *eap)
// "fudi.fd_di" set, "fudi.fd_newkey" == NULL
// s:func script-local function name
// g:func global function name, same as "func"
- p = (char_u *)eap->arg;
- name = trans_function_name((char **)&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL);
- paren = (vim_strchr((char *)p, '(') != NULL);
+ p = eap->arg;
+ name = (char *)trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL);
+ paren = (vim_strchr(p, '(') != NULL);
if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) {
- /*
- * Return on an invalid expression in braces, unless the expression
- * evaluation has been cancelled due to an aborting error, an
- * interrupt, or an exception.
- */
+ // Return on an invalid expression in braces, unless the expression
+ // evaluation has been cancelled due to an aborting error, an
+ // interrupt, or an exception.
if (!aborting()) {
if (fudi.fd_newkey != NULL) {
semsg(_(e_dictkey), fudi.fd_newkey);
@@ -2028,16 +2003,16 @@ void ex_function(exarg_T *eap)
// - exclude line numbers from function body
//
if (!paren) {
- if (!ends_excmd(*skipwhite((char *)p))) {
+ if (!ends_excmd(*skipwhite(p))) {
semsg(_(e_trailing_arg), p);
goto ret_free;
}
- eap->nextcmd = check_nextcmd((char *)p);
+ eap->nextcmd = check_nextcmd(p);
if (eap->nextcmd != NULL) {
*p = NUL;
}
if (!eap->skip && !got_int) {
- fp = find_func(name);
+ fp = find_func((char_u *)name);
if (fp != NULL) {
list_func_head(fp, !eap->forceit, eap->forceit);
for (int j = 0; j < fp->uf_lines.ga_len && !got_int; j++) {
@@ -2063,27 +2038,25 @@ void ex_function(exarg_T *eap)
msg_puts(eap->forceit ? "endfunction" : " endfunction");
}
} else {
- emsg_funcname(N_("E123: Undefined function: %s"), name);
+ emsg_funcname(N_("E123: Undefined function: %s"), (char_u *)name);
}
}
goto ret_free;
}
- /*
- * ":function name(arg1, arg2)" Define function.
- */
- p = (char_u *)skipwhite((char *)p);
+ // ":function name(arg1, arg2)" Define function.
+ p = skipwhite(p);
if (*p != '(') {
if (!eap->skip) {
semsg(_("E124: Missing '(': %s"), eap->arg);
goto ret_free;
}
// attempt to continue by skipping some text
- if (vim_strchr((char *)p, '(') != NULL) {
- p = (char_u *)vim_strchr((char *)p, '(');
+ if (vim_strchr(p, '(') != NULL) {
+ p = vim_strchr(p, '(');
}
}
- p = (char_u *)skipwhite((char *)p + 1);
+ p = skipwhite(p + 1);
ga_init(&newargs, (int)sizeof(char_u *), 3);
ga_init(&newlines, (int)sizeof(char_u *), 3);
@@ -2094,15 +2067,15 @@ void ex_function(exarg_T *eap)
if (name != NULL) {
arg = name;
} else {
- arg = fudi.fd_newkey;
+ arg = (char *)fudi.fd_newkey;
}
if (arg != NULL && (fudi.fd_di == NULL || !tv_is_func(fudi.fd_di->di_tv))) {
- int j = (*arg == K_SPECIAL) ? 3 : 0;
+ int j = ((uint8_t)(*arg) == K_SPECIAL) ? 3 : 0;
while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j]) : eval_isnamec(arg[j]))) {
j++;
}
if (arg[j] != NUL) {
- emsg_funcname((char *)e_invarg2, arg);
+ emsg_funcname((char *)e_invarg2, (char_u *)arg);
}
}
// Disallow using the g: dict.
@@ -2111,7 +2084,7 @@ void ex_function(exarg_T *eap)
}
}
- if (get_function_args((char **)&p, ')', &newargs, &varargs,
+ if (get_function_args(&p, ')', &newargs, &varargs,
&default_args, eap->skip) == FAIL) {
goto errret_2;
}
@@ -2123,7 +2096,7 @@ void ex_function(exarg_T *eap)
// find extra arguments "range", "dict", "abort" and "closure"
for (;;) {
- p = (char_u *)skipwhite((char *)p);
+ p = skipwhite(p);
if (STRNCMP(p, "range", 5) == 0) {
flags |= FC_RANGE;
p += 5;
@@ -2137,9 +2110,8 @@ void ex_function(exarg_T *eap)
flags |= FC_CLOSURE;
p += 7;
if (current_funccal == NULL) {
- emsg_funcname(N_
- ("E932: Closure function should not be at top level: %s"),
- name == NULL ? (char_u *)"" : name);
+ emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
+ name == NULL ? (char_u *)"" : (char_u *)name);
goto erret;
}
} else {
@@ -2155,9 +2127,7 @@ void ex_function(exarg_T *eap)
semsg(_(e_trailing_arg), p);
}
- /*
- * Read the body of the function, until ":endfunction" is found.
- */
+ // Read the body of the function, until ":endfunction" is found.
if (KeyTyped) {
// Check if the function already exists, don't let the user type the
// whole function before telling him it doesn't work! For a script we
@@ -2165,8 +2135,8 @@ void ex_function(exarg_T *eap)
if (!eap->skip && !eap->forceit) {
if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) {
emsg(_(e_funcdict));
- } else if (name != NULL && find_func(name) != NULL) {
- emsg_funcname(e_funcexts, name);
+ } else if (name != NULL && find_func((char_u *)name) != NULL) {
+ emsg_funcname(e_funcexts, (char_u *)name);
}
}
@@ -2195,7 +2165,7 @@ void ex_function(exarg_T *eap)
if (line_arg != NULL) {
// Use eap->arg, split up in parts by line breaks.
theline = line_arg;
- p = (char_u *)vim_strchr((char *)theline, '\n');
+ p = vim_strchr(theline, '\n');
if (p == NULL) {
line_arg += STRLEN(line_arg);
} else {
@@ -2205,9 +2175,9 @@ void ex_function(exarg_T *eap)
} else {
xfree(line_to_free);
if (eap->getline == NULL) {
- theline = getcmdline(':', 0L, indent, do_concat);
+ theline = (char *)getcmdline(':', 0L, indent, do_concat);
} else {
- theline = (char_u *)eap->getline(':', eap->cookie, indent, do_concat);
+ theline = eap->getline(':', eap->cookie, indent, do_concat);
}
line_to_free = theline;
}
@@ -2237,18 +2207,18 @@ void ex_function(exarg_T *eap)
// * ":python <<EOF" and "EOF"
// * ":let {var-name} =<< [trim] {marker}" and "{marker}"
if (heredoc_trimmed == NULL
- || (is_heredoc && (char_u *)skipwhite((char *)theline) == theline)
+ || (is_heredoc && skipwhite(theline) == theline)
|| STRNCMP(theline, heredoc_trimmed,
STRLEN(heredoc_trimmed)) == 0) {
if (heredoc_trimmed == NULL) {
p = theline;
} else if (is_heredoc) {
- p = (char_u *)skipwhite((char *)theline) == theline
+ p = skipwhite(theline) == theline
? theline : theline + STRLEN(heredoc_trimmed);
} else {
p = theline + STRLEN(heredoc_trimmed);
}
- if (STRCMP(p, skip_until) == 0) {
+ if (strcmp(p, skip_until) == 0) {
XFREE_CLEAR(skip_until);
XFREE_CLEAR(heredoc_trimmed);
do_concat = true;
@@ -2260,27 +2230,26 @@ void ex_function(exarg_T *eap)
for (p = theline; ascii_iswhite(*p) || *p == ':'; p++) {}
// Check for "endfunction".
- if (checkforcmd((char **)&p, "endfunction", 4) && nesting-- == 0) {
+ if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0) {
if (*p == '!') {
p++;
}
- char_u *nextcmd = NULL;
+ char *nextcmd = NULL;
if (*p == '|') {
nextcmd = p + 1;
- } else if (line_arg != NULL && *skipwhite((char *)line_arg) != NUL) {
+ } else if (line_arg != NULL && *skipwhite(line_arg) != NUL) {
nextcmd = line_arg;
} else if (*p != NUL && *p != '"' && p_verbose > 0) {
- give_warning2(_("W22: Text found after :endfunction: %s"),
- (char *)p, true);
+ give_warning2(_("W22: Text found after :endfunction: %s"), p, true);
}
if (nextcmd != NULL) {
// Another command follows. If the line came from "eap" we
// can simply point into it, otherwise we need to change
// "eap->cmdlinep".
- eap->nextcmd = (char *)nextcmd;
+ eap->nextcmd = nextcmd;
if (line_to_free != NULL) {
xfree(*eap->cmdlinep);
- *eap->cmdlinep = (char *)line_to_free;
+ *eap->cmdlinep = line_to_free;
line_to_free = NULL;
}
}
@@ -2299,13 +2268,13 @@ void ex_function(exarg_T *eap)
}
// Check for defining a function inside this function.
- if (checkforcmd((char **)&p, "function", 2)) {
+ if (checkforcmd(&p, "function", 2)) {
if (*p == '!') {
- p = (char_u *)skipwhite((char *)p + 1);
+ p = skipwhite(p + 1);
}
p += eval_fname_script((const char *)p);
- xfree(trans_function_name((char **)&p, true, 0, NULL, NULL));
- if (*skipwhite((char *)p) == '(') {
+ xfree(trans_function_name(&p, true, 0, NULL, NULL));
+ if (*skipwhite(p) == '(') {
if (nesting == MAX_FUNC_NESTING - 1) {
emsg(_("E1058: function nesting too deep"));
} else {
@@ -2316,7 +2285,7 @@ void ex_function(exarg_T *eap)
}
// Check for ":append", ":change", ":insert".
- p = (char_u *)skip_range((char *)p, NULL);
+ p = skip_range(p, NULL);
if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
|| (p[0] == 'c'
&& (!ASCII_ISALPHA(p[1])
@@ -2328,11 +2297,11 @@ void ex_function(exarg_T *eap)
&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
&& (!ASCII_ISALPHA(p[2])
|| (p[2] == 's')))))) {
- skip_until = vim_strsave((char_u *)".");
+ skip_until = xstrdup(".");
}
// heredoc: Check for ":python <<EOF", ":lua <<EOF", etc.
- arg = (char_u *)skipwhite(skiptowhite((char *)p));
+ arg = skipwhite(skiptowhite(p));
if (arg[0] == '<' && arg[1] == '<'
&& ((p[0] == 'p' && p[1] == 'y'
&& (!ASCII_ISALNUM(p[2]) || p[2] == 't'
@@ -2349,22 +2318,22 @@ void ex_function(exarg_T *eap)
|| (p[0] == 'm' && p[1] == 'z'
&& (!ASCII_ISALPHA(p[2]) || p[2] == 's')))) {
// ":python <<" continues until a dot, like ":append"
- p = (char_u *)skipwhite((char *)arg + 2);
+ p = skipwhite(arg + 2);
if (*p == NUL) {
- skip_until = vim_strsave((char_u *)".");
+ skip_until = xstrdup(".");
} else {
- skip_until = vim_strsave(p);
+ skip_until = xstrdup(p);
}
}
// Check for ":let v =<< [trim] EOF"
// and ":let [a, b] =<< [trim] EOF"
- arg = (char_u *)skipwhite(skiptowhite((char *)p));
+ arg = skipwhite(skiptowhite(p));
if (*arg == '[') {
- arg = (char_u *)vim_strchr((char *)arg, ']');
+ arg = vim_strchr(arg, ']');
}
if (arg != NULL) {
- arg = (char_u *)skipwhite(skiptowhite((char *)arg));
+ arg = skipwhite(skiptowhite(arg));
if (arg[0] == '='
&& arg[1] == '<'
&& arg[2] == '<'
@@ -2372,14 +2341,13 @@ void ex_function(exarg_T *eap)
&& p[1] == 'e'
&& (!ASCII_ISALNUM(p[2])
|| (p[2] == 't' && !ASCII_ISALNUM(p[3]))))) {
- p = (char_u *)skipwhite((char *)arg + 3);
+ p = skipwhite(arg + 3);
if (STRNCMP(p, "trim", 4) == 0) {
// Ignore leading white space.
- p = (char_u *)skipwhite((char *)p + 4);
- heredoc_trimmed =
- vim_strnsave(theline, (size_t)((char_u *)skipwhite((char *)theline) - theline));
+ p = skipwhite(p + 4);
+ heredoc_trimmed = xstrnsave(theline, (size_t)(skipwhite(theline) - theline));
}
- skip_until = vim_strnsave(p, (size_t)((char_u *)skiptowhite((char *)p) - p));
+ skip_until = xstrnsave(p, (size_t)(skiptowhite(p) - p));
do_concat = false;
is_heredoc = true;
}
@@ -2392,8 +2360,8 @@ void ex_function(exarg_T *eap)
// Copy the line to newly allocated memory. get_one_sourceline()
// allocates 250 bytes per line, this saves 80% on average. The cost
// is an extra alloc/free.
- p = vim_strsave(theline);
- ((char **)(newlines.ga_data))[newlines.ga_len++] = (char *)p;
+ p = xstrdup(theline);
+ ((char **)(newlines.ga_data))[newlines.ga_len++] = p;
// Add NULL lines for continuation lines, so that the line count is
// equal to the index in the growarray.
@@ -2413,30 +2381,28 @@ void ex_function(exarg_T *eap)
goto erret;
}
- /*
- * If there are no errors, add the function
- */
+ // If there are no errors, add the function
if (fudi.fd_dict == NULL) {
v = find_var((const char *)name, STRLEN(name), &ht, false);
if (v != NULL && v->di_tv.v_type == VAR_FUNC) {
emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
- name);
+ (char_u *)name);
goto erret;
}
- fp = find_func(name);
+ fp = find_func((char_u *)name);
if (fp != NULL) {
// Function can be replaced with "function!" and when sourcing the
// same script again, but only once.
if (!eap->forceit
&& (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid
|| fp->uf_script_ctx.sc_seq == current_sctx.sc_seq)) {
- emsg_funcname(e_funcexts, name);
+ emsg_funcname(e_funcexts, (char_u *)name);
goto erret;
}
if (fp->uf_calls > 0) {
emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
- name);
+ (char_u *)name);
goto erret;
}
if (fp->uf_refcount > 1) {
@@ -2480,12 +2446,12 @@ void ex_function(exarg_T *eap)
// Give the function a sequential number. Can only be used with a
// Funcref!
xfree(name);
- sprintf(numbuf, "%d", ++func_nr);
- name = vim_strsave((char_u *)numbuf);
+ sprintf(numbuf, "%d", ++func_nr); // NOLINT(runtime/printf)
+ name = xstrdup(numbuf);
}
if (fp == NULL) {
- if (fudi.fd_dict == NULL && vim_strchr((char *)name, AUTOLOAD_CHAR) != NULL) {
+ if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) {
int slen, plen;
char_u *scriptname;
@@ -2493,10 +2459,10 @@ void ex_function(exarg_T *eap)
int j = FAIL;
if (SOURCING_NAME != NULL) {
scriptname = (char_u *)autoload_name((const char *)name, STRLEN(name));
- p = (char_u *)vim_strchr((char *)scriptname, '/');
+ p = vim_strchr((char *)scriptname, '/');
plen = (int)STRLEN(p);
slen = (int)STRLEN(SOURCING_NAME);
- if (slen > plen && FNAMECMP(p, SOURCING_NAME + slen - plen) == 0) {
+ if (slen > plen && path_fnamecmp(p, SOURCING_NAME + slen - plen) == 0) {
j = OK;
}
xfree(scriptname);
@@ -2524,16 +2490,16 @@ void ex_function(exarg_T *eap)
tv_clear(&fudi.fd_di->di_tv);
}
fudi.fd_di->di_tv.v_type = VAR_FUNC;
- fudi.fd_di->di_tv.vval.v_string = (char *)vim_strsave(name);
+ fudi.fd_di->di_tv.vval.v_string = xstrdup(name);
// behave like "dict" was used
flags |= FC_DICT;
}
// insert the new function in the function list
- set_ufunc_name(fp, name);
+ set_ufunc_name(fp, (char_u *)name);
if (overwrite) {
- hi = hash_find(&func_hashtab, (char *)name);
+ hi = hash_find(&func_hashtab, name);
hi->hi_key = UF2HIKEY(fp);
} else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) {
xfree(fp);
@@ -2666,7 +2632,7 @@ char *get_user_func_name(expand_T *xp, int idx)
return (char *)fp->uf_name; // Prevent overflow.
}
- cat_func_name(IObuff, fp);
+ cat_func_name((char_u *)IObuff, fp);
if (xp->xp_context != EXPAND_USER_FUNC) {
STRCAT(IObuff, "(");
if (!fp->uf_varargs && GA_EMPTY(&fp->uf_args)) {
@@ -3123,7 +3089,7 @@ char *get_return_cmd(void *rettv)
STRCPY(IObuff + IOSIZE - 4, "...");
}
xfree(tofree);
- return (char *)vim_strsave(IObuff);
+ return xstrdup((char *)IObuff);
}
/// Get next function line.
@@ -3211,9 +3177,9 @@ void make_partial(dict_T *const selfdict, typval_T *const rettv)
} else {
fname = rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING
? (char_u *)rettv->vval.v_string
- : rettv->vval.v_partial->pt_name;
+ : (char_u *)rettv->vval.v_partial->pt_name;
// Translate "s:func" to the stored function name.
- fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
+ fname = (char_u *)fname_trans_sid((char *)fname, (char *)fname_buf, (char **)&tofree, &error);
fp = find_func(fname);
xfree(tofree);
}
@@ -3227,7 +3193,7 @@ void make_partial(dict_T *const selfdict, typval_T *const rettv)
pt->pt_auto = true;
if (rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING) {
// Just a function: Take over the function name and use selfdict.
- pt->pt_name = (char_u *)rettv->vval.v_string;
+ pt->pt_name = rettv->vval.v_string;
} else {
partial_T *ret_pt = rettv->vval.v_partial;
int i;
@@ -3236,8 +3202,8 @@ void make_partial(dict_T *const selfdict, typval_T *const rettv)
// args. Can't take over name or args, the partial might
// be referenced elsewhere.
if (ret_pt->pt_name != NULL) {
- pt->pt_name = vim_strsave(ret_pt->pt_name);
- func_ref(pt->pt_name);
+ pt->pt_name = xstrdup(ret_pt->pt_name);
+ func_ref((char_u *)pt->pt_name);
} else {
pt->pt_func = ret_pt->pt_func;
func_ptr_ref(pt->pt_func);
@@ -3559,7 +3525,7 @@ bool set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
}
if (fp_in == NULL) {
- fname = fname_trans_sid(name, fname_buf, &tofree, &error);
+ fname = (char_u *)fname_trans_sid((char *)name, (char *)fname_buf, (char **)&tofree, &error);
fp = find_func(fname);
}
if (fp != NULL) {
@@ -3571,20 +3537,18 @@ bool set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
return abort;
}
-/// Registers a C extension user function.
-char_u *register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state)
+/// Registers a luaref as a lambda.
+char_u *register_luafunc(LuaRef ref)
{
char_u *name = get_lambda_name();
ufunc_T *fp = xcalloc(1, offsetof(ufunc_T, uf_name) + STRLEN(name) + 1);
fp->uf_refcount = 1;
fp->uf_varargs = true;
- fp->uf_flags = FC_CFUNC;
+ fp->uf_flags = FC_LUAREF;
fp->uf_calls = 0;
fp->uf_script_ctx = current_sctx;
- fp->uf_cb = cb;
- fp->uf_cb_free = cb_free;
- fp->uf_cb_state = state;
+ fp->uf_luaref = ref;
STRCPY(fp->uf_name, name);
hash_add(&func_hashtab, UF2HIKEY(fp));
diff --git a/src/nvim/eval/userfunc.h b/src/nvim/eval/userfunc.h
index 4b7007aae9..9811f2afb3 100644
--- a/src/nvim/eval/userfunc.h
+++ b/src/nvim/eval/userfunc.h
@@ -9,6 +9,20 @@
#define HIKEY2UF(p) ((ufunc_T *)(p - offsetof(ufunc_T, uf_name)))
#define HI2UF(hi) HIKEY2UF((hi)->hi_key)
+// flags used in uf_flags
+#define FC_ABORT 0x01 // abort function on error
+#define FC_RANGE 0x02 // function accepts range
+#define FC_DICT 0x04 // Dict function, uses "self"
+#define FC_CLOSURE 0x08 // closure, uses outer scope variables
+#define FC_DELETED 0x10 // :delfunction used while uf_refcount > 0
+#define FC_REMOVED 0x20 // function redefined while uf_refcount > 0
+#define FC_SANDBOX 0x40 // function defined in the sandbox
+#define FC_DEAD 0x80 // function kept only for reference to dfunc
+#define FC_EXPORT 0x100 // "export def Func()"
+#define FC_NOARGS 0x200 // no a: variables in lambda
+#define FC_VIM9 0x400 // defined in vim9 script file
+#define FC_LUAREF 0x800 // luaref callback
+
///< Structure used by trans_function_name()
typedef struct {
dict_T *fd_dict; ///< Dictionary used.
diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c
index ba58254bdd..004a239fda 100644
--- a/src/nvim/eval/vars.c
+++ b/src/nvim/eval/vars.c
@@ -113,7 +113,7 @@ static list_T *heredoc_get(exarg_T *eap, char *cmd)
&& STRNCMP(theline, *eap->cmdlinep, marker_indent_len) == 0) {
mi = marker_indent_len;
}
- if (STRCMP(marker, theline + mi) == 0) {
+ if (strcmp(marker, theline + mi) == 0) {
xfree(theline);
break;
}
diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c
index db79187b7d..96bef4902c 100644
--- a/src/nvim/ex_cmds.c
+++ b/src/nvim/ex_cmds.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * ex_cmds.c: some functions for command line commands
- */
+// ex_cmds.c: some functions for command line commands
#include <assert.h>
#include <float.h>
@@ -120,7 +118,7 @@ void do_ascii(const exarg_T *const eap)
{
char *dig;
int cc[MAX_MCO];
- int c = utfc_ptr2char((char *)get_cursor_pos_ptr(), cc);
+ int c = utfc_ptr2char(get_cursor_pos_ptr(), cc);
if (c == NUL) {
msg("NUL");
return;
@@ -249,11 +247,9 @@ void ex_align(exarg_T *eap)
indent = width;
}
} else {
- /*
- * if 'textwidth' set, use it
- * else if 'wrapmargin' set, use it
- * if invalid value, use 80
- */
+ // if 'textwidth' set, use it
+ // else if 'wrapmargin' set, use it
+ // if invalid value, use 80
if (width <= 0) {
width = (int)curbuf->b_p_tw;
}
@@ -287,18 +283,14 @@ void ex_align(exarg_T *eap)
} else {
new_indent = width - len; // right align
- /*
- * Make sure that embedded TABs don't make the text go too far
- * to the right.
- */
+ // Make sure that embedded TABs don't make the text go too far
+ // to the right.
if (has_tab) {
while (new_indent > 0) {
(void)set_indent(new_indent, 0);
if (linelen(NULL) <= width) {
- /*
- * Now try to move the line as much as possible to
- * the right. Stop when it moves too far.
- */
+ // Now try to move the line as much as possible to
+ // the right. Stop when it moves too far.
do {
(void)set_indent(++new_indent, 0);
} while (linelen(NULL) <= width);
@@ -330,7 +322,7 @@ static int linelen(int *has_tab)
// Get the line. If it's empty bail out early (could be the empty string
// for an unloaded buffer).
- line = (char *)get_cursor_line_ptr();
+ line = get_cursor_line_ptr();
if (*line == NUL) {
return 0;
}
@@ -387,7 +379,7 @@ static int string_compare(const void *s1, const void *s2) FUNC_ATTR_NONNULL_ALL
if (sort_lc) {
return strcoll((char *)s1, (char *)s2);
}
- return sort_ic ? STRICMP(s1, s2) : STRCMP(s1, s2);
+ return sort_ic ? STRICMP(s1, s2) : strcmp(s1, s2);
}
static int sort_compare(const void *s1, const void *s2)
@@ -567,10 +559,10 @@ void ex_sort(exarg_T *eap)
end_col = len;
if (regmatch.regprog != NULL && vim_regexec(&regmatch, s, 0)) {
if (sort_rx) {
- start_col = (colnr_T)(regmatch.startp[0] - (char_u *)s);
- end_col = (colnr_T)(regmatch.endp[0] - (char_u *)s);
+ start_col = (colnr_T)(regmatch.startp[0] - s);
+ end_col = (colnr_T)(regmatch.endp[0] - s);
} else {
- start_col = (colnr_T)(regmatch.endp[0] - (char_u *)s);
+ start_col = (colnr_T)(regmatch.endp[0] - s);
}
} else if (regmatch.regprog != NULL) {
end_col = 0;
@@ -601,7 +593,7 @@ void ex_sort(exarg_T *eap)
nrs[lnum - eap->line1].st_u.num.value = 0;
} else {
nrs[lnum - eap->line1].st_u.num.is_number = true;
- vim_str2nr((char_u *)s, NULL, NULL, sort_what,
+ vim_str2nr(s, NULL, NULL, sort_what,
&nrs[lnum - eap->line1].st_u.num.value, NULL, 0, false);
}
} else {
@@ -933,10 +925,8 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
num_lines = line2 - line1 + 1;
- /*
- * First we copy the old text to its new location -- webb
- * Also copy the flag that ":global" command uses.
- */
+ // First we copy the old text to its new location -- webb
+ // Also copy the flag that ":global" command uses.
if (u_save(dest, dest + 1) == FAIL) {
return FAIL;
}
@@ -949,21 +939,19 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
}
}
- /*
- * Now we must be careful adjusting our marks so that we don't overlap our
- * mark_adjust() calls.
- *
- * We adjust the marks within the old text so that they refer to the
- * last lines of the file (temporarily), because we know no other marks
- * will be set there since these line numbers did not exist until we added
- * our new lines.
- *
- * Then we adjust the marks on lines between the old and new text positions
- * (either forwards or backwards).
- *
- * And Finally we adjust the marks we put at the end of the file back to
- * their final destination at the new text position -- webb
- */
+ // Now we must be careful adjusting our marks so that we don't overlap our
+ // mark_adjust() calls.
+ //
+ // We adjust the marks within the old text so that they refer to the
+ // last lines of the file (temporarily), because we know no other marks
+ // will be set there since these line numbers did not exist until we added
+ // our new lines.
+ //
+ // Then we adjust the marks on lines between the old and new text positions
+ // (either forwards or backwards).
+ //
+ // And Finally we adjust the marks we put at the end of the file back to
+ // their final destination at the new text position -- webb
last_line = curbuf->b_ml.ml_line_count;
mark_adjust_nofold(line1, line2, last_line - line2, 0L, kExtmarkNOOP);
@@ -1011,9 +999,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
// send update regarding the new lines that were added
buf_updates_send_changes(curbuf, dest + 1, num_lines, 0);
- /*
- * Now we delete the original text -- webb
- */
+ // Now we delete the original text -- webb
if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL) {
return FAIL;
}
@@ -1030,9 +1016,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
dest + line_off, 0, dest_byte + byte_off,
kExtmarkUndo);
- /*
- * Leave the cursor on the last of the moved lines.
- */
+ // Leave the cursor on the last of the moved lines.
if (dest >= line1) {
curwin->w_cursor.lnum = dest;
} else {
@@ -1069,24 +1053,22 @@ void ex_copy(linenr_T line1, linenr_T line2, linenr_T n)
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
}
- /*
- * there are three situations:
- * 1. destination is above line1
- * 2. destination is between line1 and line2
- * 3. destination is below line2
- *
- * n = destination (when starting)
- * curwin->w_cursor.lnum = destination (while copying)
- * line1 = start of source (while copying)
- * line2 = end of source (while copying)
- */
+ // there are three situations:
+ // 1. destination is above line1
+ // 2. destination is between line1 and line2
+ // 3. destination is below line2
+ //
+ // n = destination (when starting)
+ // curwin->w_cursor.lnum = destination (while copying)
+ // line1 = start of source (while copying)
+ // line2 = end of source (while copying)
if (u_save(n, n + 1) == FAIL) {
return;
}
curwin->w_cursor.lnum = n;
while (line1 <= line2) {
- // need to use vim_strsave() because the line will be unlocked within
+ // need to use xstrdup() because the line will be unlocked within
// ml_append()
p = xstrdup(ml_get(line1));
ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, false);
@@ -1155,10 +1137,8 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out
msg_scroll = scroll_save;
}
- /*
- * Try to find an embedded bang, like in :!<cmd> ! [args]
- * (:!! is indicated by the 'forceit' variable)
- */
+ // Try to find an embedded bang, like in :!<cmd> ! [args]
+ // (:!! is indicated by the 'forceit' variable)
bool ins_prevcmd = forceit;
trailarg = arg;
do {
@@ -1187,10 +1167,8 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out
xfree(newcmd);
newcmd = t;
- /*
- * Scan the rest of the argument for '!', which is replaced by the
- * previous command. "\!" is replaced by "!" (this is vi compatible).
- */
+ // Scan the rest of the argument for '!', which is replaced by the
+ // previous command. "\!" is replaced by "!" (this is vi compatible).
trailarg = NULL;
while (*p) {
if (*p == '!') {
@@ -1221,9 +1199,7 @@ void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out
AppendToRedobuff("\n");
bangredo = false;
}
- /*
- * Add quotes around the command, for shells that need them.
- */
+ // Add quotes around the command, for shells that need them.
if (*p_shq != NUL) {
newcmd = xmalloc(STRLEN(prevcmd) + 2 * STRLEN(p_shq) + 1);
STRCPY(newcmd, p_shq);
@@ -1298,18 +1274,16 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b
changed_line_abv_curs();
invalidate_botline();
- /*
- * When using temp files:
- * 1. * Form temp file names
- * 2. * Write the lines to a temp file
- * 3. Run the filter command on the temp file
- * 4. * Read the output of the command into the buffer
- * 5. * Delete the original lines to be filtered
- * 6. * Remove the temp files
- *
- * When writing the input with a pipe or when catching the output with a
- * pipe only need to do 3.
- */
+ // When using temp files:
+ // 1. * Form temp file names
+ // 2. * Write the lines to a temp file
+ // 3. Run the filter command on the temp file
+ // 4. * Read the output of the command into the buffer
+ // 5. * Delete the original lines to be filtered
+ // 6. * Remove the temp files
+ //
+ // When writing the input with a pipe or when catching the output with a
+ // pipe only need to do 3.
if (do_out) {
shell_flags |= kShellOptDoOut;
@@ -1331,16 +1305,14 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b
curbuf->b_op_start.lnum = line1;
curbuf->b_op_end.lnum = line2;
curwin->w_cursor.lnum = line2;
- } else if ((do_in && (itmp = (char *)vim_tempname()) == NULL)
- || (do_out && (otmp = (char *)vim_tempname()) == NULL)) {
+ } else if ((do_in && (itmp = vim_tempname()) == NULL)
+ || (do_out && (otmp = vim_tempname()) == NULL)) {
emsg(_(e_notmp));
goto filterend;
}
- /*
- * The writing and reading of temp files will not be shown.
- * Vi also doesn't do this and the messages are not very informative.
- */
+ // The writing and reading of temp files will not be shown.
+ // Vi also doesn't do this and the messages are not very informative.
no_wait_return++; // don't call wait_return() while busy
if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap,
false, false, false, true) == FAIL) {
@@ -1428,10 +1400,8 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b
}
}
- /*
- * Put cursor on first filtered line for ":range!cmd".
- * Adjust '[ and '] (set by buf_write()).
- */
+ // Put cursor on first filtered line for ":range!cmd".
+ // Adjust '[ and '] (set by buf_write()).
curwin->w_cursor.lnum = line1;
del_lines(linecount, true);
curbuf->b_op_start.lnum -= linecount; // adjust '[
@@ -1440,9 +1410,7 @@ static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, b
// for next write
foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum);
} else {
- /*
- * Put cursor on last new line for ":r !cmd".
- */
+ // Put cursor on last new line for ":r !cmd".
linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1;
curwin->w_cursor.lnum = curbuf->b_op_end.lnum;
}
@@ -1504,10 +1472,8 @@ void do_shell(char *cmd, int flags)
return;
}
- /*
- * For autocommands we want to get the output on the current screen, to
- * avoid having to type return below.
- */
+ // For autocommands we want to get the output on the current screen, to
+ // avoid having to type return below.
msg_putchar('\r'); // put cursor at start of line
msg_putchar('\n'); // may shift screen one line up
@@ -1569,12 +1535,12 @@ char *make_filter_cmd(char *cmd, char *itmp, char *otmp)
{
bool is_fish_shell =
#if defined(UNIX)
- STRNCMP(invocation_path_tail(p_sh, NULL), "fish", 4) == 0;
+ STRNCMP(invocation_path_tail((char_u *)p_sh, NULL), "fish", 4) == 0;
#else
false;
#endif
- bool is_pwsh = STRNCMP(invocation_path_tail(p_sh, NULL), "pwsh", 4) == 0
- || STRNCMP(invocation_path_tail(p_sh, NULL), "powershell", 10) == 0;
+ bool is_pwsh = STRNCMP(invocation_path_tail((char_u *)p_sh, NULL), "pwsh", 4) == 0
+ || STRNCMP(invocation_path_tail((char_u *)p_sh, NULL), "powershell", 10) == 0;
size_t len = STRLEN(cmd) + 1; // At least enough space for cmd + NULL.
@@ -1740,13 +1706,11 @@ int rename_buffer(char *new_fname)
if (aborting()) { // autocmds may abort script processing
return FAIL;
}
- /*
- * The name of the current buffer will be changed.
- * A new (unlisted) buffer entry needs to be made to hold the old file
- * name, which will become the alternate file name.
- * But don't set the alternate file name if the buffer didn't have a
- * name.
- */
+ // The name of the current buffer will be changed.
+ // A new (unlisted) buffer entry needs to be made to hold the old file
+ // name, which will become the alternate file name.
+ // But don't set the alternate file name if the buffer didn't have a
+ // name.
fname = curbuf->b_ffname;
sfname = curbuf->b_sfname;
xfname = curbuf->b_fname;
@@ -1860,9 +1824,7 @@ int do_write(exarg_T *eap)
other = otherfile(ffname);
}
- /*
- * If we have a new file, put its name in the list of alternate file names.
- */
+ // If we have a new file, put its name in the list of alternate file names.
if (other) {
if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL
|| eap->cmdidx == CMD_saveas) {
@@ -2113,13 +2075,11 @@ void do_wqall(exarg_T *eap)
} else if (!bufIsChanged(buf) || bt_dontwrite(buf)) {
continue;
}
- /*
- * Check if there is a reason the buffer cannot be written:
- * 1. if the 'write' option is set
- * 2. if there is no file name (even after browsing)
- * 3. if the 'readonly' is set (even after a dialog)
- * 4. if overwriting is allowed (even after a dialog)
- */
+ // Check if there is a reason the buffer cannot be written:
+ // 1. if the 'write' option is set
+ // 2. if there is no file name (even after browsing)
+ // 3. if the 'readonly' is set (even after a dialog)
+ // 4. if overwriting is allowed (even after a dialog)
if (not_writing()) {
error++;
break;
@@ -2405,10 +2365,8 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
goto theend;
}
- /*
- * End Visual mode before switching to another buffer, so the text can be
- * copied into the GUI selection buffer.
- */
+ // End Visual mode before switching to another buffer, so the text can be
+ // copied into the GUI selection buffer.
reset_VIsual();
if ((command != NULL || newlnum > (linenr_T)0)
@@ -2426,10 +2384,8 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
xfree(p);
}
- /*
- * If we are starting to edit another file, open a (new) buffer.
- * Otherwise we re-use the current buffer.
- */
+ // If we are starting to edit another file, open a (new) buffer.
+ // Otherwise we re-use the current buffer.
if (other_file) {
const int prev_alt_fnum = curwin->w_alt_fnum;
@@ -2507,12 +2463,10 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
solcol = pos->col;
}
- /*
- * Make the (new) buffer the one used by the current window.
- * If the old buffer becomes unused, free it if ECMD_HIDE is false.
- * If the current buffer was empty and has no file name, curbuf
- * is returned by buflist_new(), nothing to do here.
- */
+ // Make the (new) buffer the one used by the current window.
+ // If the old buffer becomes unused, free it if ECMD_HIDE is false.
+ // If the current buffer was empty and has no file name, curbuf
+ // is returned by buflist_new(), nothing to do here.
if (buf != curbuf) {
const int save_cmdwin_type = cmdwin_type;
@@ -2663,13 +2617,11 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
// highlighting to work in the other file.
did_filetype = false;
- /*
- * other_file oldbuf
- * false false re-edit same file, buffer is re-used
- * false true re-edit same file, nothing changes
- * true false start editing new file, new buffer
- * true true start editing in existing buffer (nothing to do)
- */
+ // other_file oldbuf
+ // false false re-edit same file, buffer is re-used
+ // false true re-edit same file, nothing changes
+ // true false start editing new file, new buffer
+ // true true start editing in existing buffer (nothing to do)
if (!other_file && !oldbuf) { // re-use the buffer
set_last_cursor(curwin); // may set b_last_cursor
if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL) {
@@ -2728,9 +2680,7 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
curbuf->b_op_end.lnum = 0;
}
- /*
- * If we get here we are sure to start editing
- */
+ // If we get here we are sure to start editing
// Assume success now
retval = OK;
@@ -2741,17 +2691,13 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
curbuf->b_flags &= ~BF_NOTEDITED;
}
- /*
- * Check if we are editing the w_arg_idx file in the argument list.
- */
+ // Check if we are editing the w_arg_idx file in the argument list.
check_arg_idx(curwin);
if (!auto_buf) {
- /*
- * Set cursor and init window before reading the file and executing
- * autocommands. This allows for the autocommands to position the
- * cursor.
- */
+ // Set cursor and init window before reading the file and executing
+ // autocommands. This allows for the autocommands to position the
+ // cursor.
curwin_init();
// It's possible that all lines in the buffer changed. Need to update
@@ -2765,19 +2711,15 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
// Change directories when the 'acd' option is set.
do_autochdir();
- /*
- * Careful: open_buffer() and apply_autocmds() may change the current
- * buffer and window.
- */
+ // Careful: open_buffer() and apply_autocmds() may change the current
+ // buffer and window.
orig_pos = curwin->w_cursor;
topline = curwin->w_topline;
if (!oldbuf) { // need to read the file
swap_exists_action = SEA_DIALOG;
curbuf->b_flags |= BF_CHECK_RO; // set/reset 'ro' flag
- /*
- * Open the buffer and read the file.
- */
+ // Open the buffer and read the file.
if (flags & ECMD_NOWINENTER) {
readfile_flags |= READ_NOWINENTER;
}
@@ -2808,7 +2750,7 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
// keep it. Also when it moves within a line. But not when it moves
// to the first non-blank.
if (!equalpos(curwin->w_cursor, orig_pos)) {
- const char *text = (char *)get_cursor_line_ptr();
+ const char *text = get_cursor_line_ptr();
if (curwin->w_cursor.lnum != orig_pos.lnum
|| curwin->w_cursor.col != (int)(skipwhite(text) - text)) {
@@ -2868,10 +2810,8 @@ int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum
// Check if cursors in other windows on the same buffer are still valid
check_lnums(false);
- /*
- * Did not read the file, need to show some info about the file.
- * Do this after setting the cursor.
- */
+ // Did not read the file, need to show some info about the file.
+ // Do this after setting the cursor.
if (oldbuf
&& !auto_buf) {
int msg_scroll_save = msg_scroll;
@@ -3318,7 +3258,7 @@ static bool sub_joining_lines(exarg_T *eap, char *pat, char *sub, char *cmd, boo
// TODO(vim): find a generic solution to make line-joining operations more
// efficient, avoid allocating a string that grows in size.
if (pat != NULL
- && STRCMP(pat, "\\n") == 0
+ && strcmp(pat, "\\n") == 0
&& *sub == NUL
&& (*cmd == NUL || (cmd[1] == NUL
&& (*cmd == 'g'
@@ -3351,10 +3291,10 @@ static bool sub_joining_lines(exarg_T *eap, char *pat, char *sub, char *cmd, boo
if (save) {
if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) {
- save_re_pat(RE_SUBST, (char_u *)pat, p_magic);
+ save_re_pat(RE_SUBST, pat, p_magic);
}
// put pattern in history
- add_to_history(HIST_SEARCH, (char_u *)pat, true, NUL);
+ add_to_history(HIST_SEARCH, pat, true, NUL);
}
return true;
@@ -3559,10 +3499,8 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
}
}
- /*
- * Small incompatibility: vi sees '\n' as end of the command, but in
- * Vim we want to use '\n' to find/substitute a NUL.
- */
+ // Small incompatibility: vi sees '\n' as end of the command, but in
+ // Vim we want to use '\n' to find/substitute a NUL.
sub = cmd; // remember the start of the substitution
while (cmd[0]) {
@@ -3620,9 +3558,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
}
}
- /*
- * check for trailing command or garbage
- */
+ // check for trailing command or garbage
cmd = skipwhite(cmd);
if (*cmd && *cmd != '"') { // if not end-of-line or comment
eap->nextcmd = check_nextcmd(cmd);
@@ -3672,7 +3608,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
sub = xstrdup(sub);
sub_copy = sub;
} else {
- char *newsub = (char *)regtilde((char_u *)sub, p_magic, cmdpreview);
+ char *newsub = regtilde(sub, p_magic, cmdpreview);
if (newsub != sub) {
// newsub was allocated, free it later.
sub_copy = newsub;
@@ -3711,50 +3647,48 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
bool skip_match = false;
linenr_T sub_firstlnum; // nr of first sub line
- /*
- * The new text is build up step by step, to avoid too much
- * copying. There are these pieces:
- * sub_firstline The old text, unmodified.
- * copycol Column in the old text where we started
- * looking for a match; from here old text still
- * needs to be copied to the new text.
- * matchcol Column number of the old text where to look
- * for the next match. It's just after the
- * previous match or one further.
- * prev_matchcol Column just after the previous match (if any).
- * Mostly equal to matchcol, except for the first
- * match and after skipping an empty match.
- * regmatch.*pos Where the pattern matched in the old text.
- * new_start The new text, all that has been produced so
- * far.
- * new_end The new text, where to append new text.
- *
- * lnum The line number where we found the start of
- * the match. Can be below the line we searched
- * when there is a \n before a \zs in the
- * pattern.
- * sub_firstlnum The line number in the buffer where to look
- * for a match. Can be different from "lnum"
- * when the pattern or substitute string contains
- * line breaks.
- *
- * Special situations:
- * - When the substitute string contains a line break, the part up
- * to the line break is inserted in the text, but the copy of
- * the original line is kept. "sub_firstlnum" is adjusted for
- * the inserted lines.
- * - When the matched pattern contains a line break, the old line
- * is taken from the line at the end of the pattern. The lines
- * in the match are deleted later, "sub_firstlnum" is adjusted
- * accordingly.
- *
- * The new text is built up in new_start[]. It has some extra
- * room to avoid using xmalloc()/free() too often.
- *
- * Make a copy of the old line, so it won't be taken away when
- * updating the screen or handling a multi-line match. The "old_"
- * pointers point into this copy.
- */
+ // The new text is build up step by step, to avoid too much
+ // copying. There are these pieces:
+ // sub_firstline The old text, unmodified.
+ // copycol Column in the old text where we started
+ // looking for a match; from here old text still
+ // needs to be copied to the new text.
+ // matchcol Column number of the old text where to look
+ // for the next match. It's just after the
+ // previous match or one further.
+ // prev_matchcol Column just after the previous match (if any).
+ // Mostly equal to matchcol, except for the first
+ // match and after skipping an empty match.
+ // regmatch.*pos Where the pattern matched in the old text.
+ // new_start The new text, all that has been produced so
+ // far.
+ // new_end The new text, where to append new text.
+ //
+ // lnum The line number where we found the start of
+ // the match. Can be below the line we searched
+ // when there is a \n before a \zs in the
+ // pattern.
+ // sub_firstlnum The line number in the buffer where to look
+ // for a match. Can be different from "lnum"
+ // when the pattern or substitute string contains
+ // line breaks.
+ //
+ // Special situations:
+ // - When the substitute string contains a line break, the part up
+ // to the line break is inserted in the text, but the copy of
+ // the original line is kept. "sub_firstlnum" is adjusted for
+ // the inserted lines.
+ // - When the matched pattern contains a line break, the old line
+ // is taken from the line at the end of the pattern. The lines
+ // in the match are deleted later, "sub_firstlnum" is adjusted
+ // accordingly.
+ //
+ // The new text is built up in new_start[]. It has some extra
+ // room to avoid using xmalloc()/free() too often.
+ //
+ // Make a copy of the old line, so it won't be taken away when
+ // updating the screen or handling a multi-line match. The "old_"
+ // pointers point into this copy.
sub_firstlnum = lnum;
copycol = 0;
matchcol = 0;
@@ -3765,14 +3699,12 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
got_match = true;
}
- /*
- * Loop until nothing more to replace in this line.
- * 1. Handle match with empty string.
- * 2. If subflags.do_ask is set, ask for confirmation.
- * 3. substitute the string.
- * 4. if subflags.do_all is set, find next match
- * 5. break if there isn't another match in this line
- */
+ // Loop until nothing more to replace in this line.
+ // 1. Handle match with empty string.
+ // 2. If subflags.do_ask is set, ask for confirmation.
+ // 3. substitute the string.
+ // 4. if subflags.do_all is set, find next match
+ // 5. break if there isn't another match in this line
for (;;) {
SubResult current_match = {
.start = { 0, 0 },
@@ -3811,11 +3743,9 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
curwin->w_cursor.lnum = lnum;
do_again = false;
- /*
- * 1. Match empty string does not count, except for first
- * match. This reproduces the strange vi behaviour.
- * This also catches endless loops.
- */
+ // 1. Match empty string does not count, except for first
+ // match. This reproduces the strange vi behaviour.
+ // This also catches endless loops.
if (matchcol == prev_matchcol
&& regmatch.endpos[0].lnum == 0
&& matchcol == regmatch.endpos[0].col) {
@@ -3880,9 +3810,7 @@ static int do_sub(exarg_T *eap, proftime_T timeout, long cmdpreview_ns, handle_T
no_u_sync++;
}
- /*
- * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
- */
+ // Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
while (subflags.do_ask) {
if (exmode_active) {
char *prompt;
@@ -4266,15 +4194,13 @@ skip:
&& !re_multiline(regmatch.regprog)));
nmatch = -1;
- /*
- * Replace the line in the buffer when needed. This is
- * skipped when there are more matches.
- * The check for nmatch_tl is needed for when multi-line
- * matching must replace the lines before trying to do another
- * match, otherwise "\@<=" won't work.
- * When the match starts below where we start searching also
- * need to replace the line first (using \zs after \n).
- */
+ // Replace the line in the buffer when needed. This is
+ // skipped when there are more matches.
+ // The check for nmatch_tl is needed for when multi-line
+ // matching must replace the lines before trying to do another
+ // match, otherwise "\@<=" won't work.
+ // When the match starts below where we start searching also
+ // need to replace the line first (using \zs after \n).
if (lastone
|| nmatch_tl > 0
|| (nmatch = vim_regexec_multi(&regmatch, curwin,
@@ -4282,13 +4208,11 @@ skip:
matchcol, NULL, NULL)) == 0
|| regmatch.startpos[0].lnum > 0) {
if (new_start != NULL) {
- /*
- * Copy the rest of the line, that didn't match.
- * "matchcol" has to be adjusted, we use the end of
- * the line as reference, because the substitute may
- * have changed the number of characters. Same for
- * "prev_matchcol".
- */
+ // Copy the rest of the line, that didn't match.
+ // "matchcol" has to be adjusted, we use the end of
+ // the line as reference, because the substitute may
+ // have changed the number of characters. Same for
+ // "prev_matchcol".
STRCAT(new_start, sub_firstline + copycol);
matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
prev_matchcol = (colnr_T)STRLEN(sub_firstline)
@@ -4300,12 +4224,10 @@ skip:
ml_replace(lnum, new_start, true);
if (nmatch_tl > 0) {
- /*
- * Matched lines have now been substituted and are
- * useless, delete them. The part after the match
- * has been appended to new_start, we don't need
- * it in the buffer.
- */
+ // Matched lines have now been substituted and are
+ // useless, delete them. The part after the match
+ // has been appended to new_start, we don't need
+ // it in the buffer.
lnum++;
if (u_savedel(lnum, nmatch_tl) != OK) {
break;
@@ -4348,9 +4270,7 @@ skip:
sub_firstlnum, matchcol, NULL, NULL);
}
- /*
- * 5. break if there isn't another match in this line
- */
+ // 5. break if there isn't another match in this line
if (nmatch <= 0) {
// If the match found didn't start where we were
// searching, do the next search in the line where we
@@ -4513,12 +4433,10 @@ skip:
/// @return true if a message was given.
bool do_sub_msg(bool count_only)
{
- /*
- * Only report substitutions when:
- * - more than 'report' substitutions
- * - command was typed by user, or number of changed lines > 'report'
- * - giving messages is not disabled by 'lazyredraw'
- */
+ // Only report substitutions when:
+ // - more than 'report' substitutions
+ // - command was typed by user, or number of changed lines > 'report'
+ // - giving messages is not disabled by 'lazyredraw'
if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
|| count_only)
&& messaging()) {
@@ -4609,11 +4527,9 @@ void ex_global(exarg_T *eap)
cmd = eap->arg;
which_pat = RE_LAST; // default: use last used regexp
- /*
- * undocumented vi feature:
- * "\/" and "\?": use previous search pattern.
- * "\&": use previous substitute pattern.
- */
+ // undocumented vi feature:
+ // "\/" and "\?": use previous search pattern.
+ // "\&": use previous substitute pattern.
if (*cmd == '\\') {
cmd++;
if (vim_strchr("/?&", *cmd) == NULL) {
@@ -4752,9 +4668,7 @@ void free_old_sub(void)
/// @return true when it was created.
bool prepare_tagpreview(bool undo_sync)
{
- /*
- * If there is already a preview window open, use that one.
- */
+ // If there is already a preview window open, use that one.
if (!curwin->w_p_pvw) {
bool found_win = false;
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
@@ -4765,9 +4679,7 @@ bool prepare_tagpreview(bool undo_sync)
}
}
if (!found_win) {
- /*
- * There is no preview window open yet. Create one.
- */
+ // There is no preview window open yet. Create one.
if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0)
== FAIL) {
return false;
@@ -4870,7 +4782,7 @@ static int show_sub(exarg_T *eap, pos_T old_cusr, PreviewLines *preview_lines, i
if (next_linenr == orig_buf->b_ml.ml_line_count + 1) {
line = "";
} else {
- line = (char *)ml_get_buf(orig_buf, next_linenr, false);
+ line = ml_get_buf(orig_buf, next_linenr, false);
line_size = strlen(line) + (size_t)col_width + 1;
// Reallocate if line not long enough
diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c
index ea21dc8ae7..5defabc05a 100644
--- a/src/nvim/ex_docmd.c
+++ b/src/nvim/ex_docmd.c
@@ -642,7 +642,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags)
// Check for the next breakpoint at or after the ":while"
// or ":for".
- if (breakpoint != NULL) {
+ if (breakpoint != NULL && lines_ga.ga_len > current_line) {
*breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), fname,
((wcmd_T *)lines_ga.ga_data)[current_line].lnum - 1);
*dbg_tick = debug_tick;
@@ -785,7 +785,7 @@ int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags)
vim_snprintf((char *)IObuff, IOSIZE,
_("E605: Exception not caught: %s"),
current_exception->value);
- p = (char *)vim_strsave(IObuff);
+ p = xstrdup((char *)IObuff);
break;
case ET_ERROR:
messages = current_exception->messages;
@@ -1300,7 +1300,7 @@ static void parse_register(exarg_T *eap)
// for '=' register: accept the rest of the line as an expression
if (eap->arg[-1] == '=' && eap->arg[0] != NUL) {
if (!eap->skip) {
- set_expr_line(vim_strsave((char_u *)eap->arg));
+ set_expr_line(xstrdup(eap->arg));
}
eap->arg += STRLEN(eap->arg);
}
@@ -2836,12 +2836,12 @@ static void append_command(char *cmd)
}
STRCAT(IObuff, ": ");
d = (char *)IObuff + STRLEN(IObuff);
- while (*s != NUL && (char_u *)d - IObuff + 5 < IOSIZE) {
+ while (*s != NUL && d - IObuff + 5 < IOSIZE) {
if ((char_u)s[0] == 0xc2 && (char_u)s[1] == 0xa0) {
s += 2;
STRCPY(d, "<a0>");
d += 4;
- } else if ((char_u *)d - IObuff + utfc_ptr2len(s) + 1 >= IOSIZE) {
+ } else if (d - IObuff + utfc_ptr2len(s) + 1 >= IOSIZE) {
break;
} else {
mb_copy_char((const char **)&s, &d);
@@ -3657,7 +3657,7 @@ char *replace_makeprg(exarg_T *eap, char *arg, char **cmdlinep)
// Don't do it when ":vimgrep" is used for ":grep".
if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake || isgrep)
&& !grep_internal(eap->cmdidx)) {
- const char *program = isgrep ? (*curbuf->b_p_gp == NUL ? (char *)p_gp : curbuf->b_p_gp)
+ const char *program = isgrep ? (*curbuf->b_p_gp == NUL ? p_gp : curbuf->b_p_gp)
: (*curbuf->b_p_mp == NUL ? (char *)p_mp : curbuf->b_p_mp);
arg = skipwhite(arg);
@@ -3694,7 +3694,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp)
// Decide to expand wildcards *before* replacing '%', '#', etc. If
// the file name contains a wildcard it should not cause expanding.
// (it will be expanded anyway if there is a wildcard before replacing).
- int has_wildcards = path_has_wildcard((char_u *)p);
+ int has_wildcards = path_has_wildcard(p);
while (*p != NUL) {
// Skip over `=expr`, wildcards in it are not expanded.
if (p[0] == '`' && p[1] == '=') {
@@ -3799,7 +3799,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp)
if (vim_strchr(eap->arg, '$') != NULL
|| vim_strchr(eap->arg, '~') != NULL) {
expand_env_esc((char_u *)eap->arg, (char_u *)NameBuff, MAXPATHL, true, true, NULL);
- has_wildcards = path_has_wildcard((char_u *)NameBuff);
+ has_wildcards = path_has_wildcard(NameBuff);
p = (char *)NameBuff;
} else {
p = NULL;
@@ -3829,7 +3829,7 @@ int expand_filename(exarg_T *eap, char **cmdlinep, char **errormsgp)
if (p_wic) {
options += WILD_ICASE;
}
- p = (char *)ExpandOne(&xpc, (char_u *)eap->arg, NULL, options, WILD_EXPAND_FREE);
+ p = ExpandOne(&xpc, eap->arg, NULL, options, WILD_EXPAND_FREE);
if (p == NULL) {
return FAIL;
}
@@ -4114,9 +4114,9 @@ static int get_tabpage_arg(exarg_T *eap)
tab_number = (int)getdigits(&p, false, tab_number);
if (relative == 0) {
- if (STRCMP(p, "$") == 0) {
+ if (strcmp(p, "$") == 0) {
tab_number = LAST_TAB_NR;
- } else if (STRCMP(p, "#") == 0) {
+ } else if (strcmp(p, "#") == 0) {
if (valid_tabpage(lastused_tabpage)) {
tab_number = tabpage_index(lastused_tabpage);
} else {
@@ -5274,7 +5274,7 @@ static void ex_swapname(exarg_T *eap)
if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL) {
msg(_("No swap file"));
} else {
- msg((char *)curbuf->b_ml.ml_mfp->mf_fname);
+ msg(curbuf->b_ml.ml_mfp->mf_fname);
}
}
@@ -5480,7 +5480,7 @@ bool changedir_func(char *new_dir, CdScope scope)
char *pdir = NULL;
// ":cd -": Change to previous directory
- if (STRCMP(new_dir, "-") == 0) {
+ if (strcmp(new_dir, "-") == 0) {
pdir = get_prevdir(scope);
if (pdir == NULL) {
emsg(_("E186: No previous directory"));
@@ -5544,27 +5544,26 @@ void ex_cd(exarg_T *eap)
// for non-UNIX ":cd" means: print current directory unless 'cdhome' is set
if (*new_dir == NUL && !p_cdh) {
ex_pwd(NULL);
- } else
+ return;
+ }
#endif
- {
- CdScope scope = kCdScopeGlobal;
- switch (eap->cmdidx) {
- case CMD_tcd:
- case CMD_tchdir:
- scope = kCdScopeTabpage;
- break;
- case CMD_lcd:
- case CMD_lchdir:
- scope = kCdScopeWindow;
- break;
- default:
- break;
- }
- if (changedir_func(new_dir, scope)) {
- // Echo the new current directory if the command was typed.
- if (KeyTyped || p_verbose >= 5) {
- ex_pwd(eap);
- }
+ CdScope scope = kCdScopeGlobal;
+ switch (eap->cmdidx) {
+ case CMD_tcd:
+ case CMD_tchdir:
+ scope = kCdScopeTabpage;
+ break;
+ case CMD_lcd:
+ case CMD_lchdir:
+ scope = kCdScopeWindow;
+ break;
+ default:
+ break;
+ }
+ if (changedir_func(new_dir, scope)) {
+ // Echo the new current directory if the command was typed.
+ if (KeyTyped || p_verbose >= 5) {
+ ex_pwd(eap);
}
}
}
@@ -6564,7 +6563,7 @@ static void ex_tag_cmd(exarg_T *eap, char *name)
cmd = DT_LTAG;
}
- do_tag((char_u *)eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
+ do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
eap->forceit, true);
}
@@ -6713,7 +6712,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum
valid = 0; // Must have ":p:h" to be valid
} else {
result = curbuf->b_fname;
- tilde_file = STRCMP(result, "~") == 0;
+ tilde_file = strcmp(result, "~") == 0;
}
break;
@@ -6767,7 +6766,7 @@ char_u *eval_vars(char_u *src, char_u *srcstart, size_t *usedlen, linenr_T *lnum
valid = 0; // Must have ":p:h" to be valid
} else {
result = buf->b_fname;
- tilde_file = STRCMP(result, "~") == 0;
+ tilde_file = strcmp(result, "~") == 0;
}
}
break;
@@ -6987,12 +6986,12 @@ void dialog_msg(char *buff, char *format, char *fname)
/// ":behave {mswin,xterm}"
static void ex_behave(exarg_T *eap)
{
- if (STRCMP(eap->arg, "mswin") == 0) {
+ if (strcmp(eap->arg, "mswin") == 0) {
set_option_value_give_err("selection", 0L, "exclusive", 0);
set_option_value_give_err("selectmode", 0L, "mouse,key", 0);
set_option_value_give_err("mousemodel", 0L, "popup", 0);
set_option_value_give_err("keymodel", 0L, "startsel,stopsel", 0);
- } else if (STRCMP(eap->arg, "xterm") == 0) {
+ } else if (strcmp(eap->arg, "xterm") == 0) {
set_option_value_give_err("selection", 0L, "inclusive", 0);
set_option_value_give_err("selectmode", 0L, "", 0);
set_option_value_give_err("mousemodel", 0L, "extend", 0);
@@ -7042,7 +7041,7 @@ static void ex_filetype(exarg_T *eap)
}
break;
}
- if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0) {
+ if (strcmp(arg, "on") == 0 || strcmp(arg, "detect") == 0) {
if (*arg == 'o' || !filetype_detect) {
source_runtime(FILETYPE_FILE, DIP_ALL);
filetype_detect = kTrue;
@@ -7059,7 +7058,7 @@ static void ex_filetype(exarg_T *eap)
(void)do_doautocmd("filetypedetect BufRead", true, NULL);
do_modelines(0);
}
- } else if (STRCMP(arg, "off") == 0) {
+ } else if (strcmp(arg, "off") == 0) {
if (plugin || indent) {
if (plugin) {
source_runtime(FTPLUGOF_FILE, DIP_ALL);
diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c
index 6dddafcfcb..f40149d07a 100644
--- a/src/nvim/ex_eval.c
+++ b/src/nvim/ex_eval.c
@@ -79,15 +79,13 @@ static void discard_pending_return(typval_T *p)
tv_free(p);
}
-/*
- * When several errors appear in a row, setting "force_abort" is delayed until
- * the failing command returned. "cause_abort" is set to true meanwhile, in
- * order to indicate that situation. This is useful when "force_abort" was set
- * during execution of a function call from an expression: the aborting of the
- * expression evaluation is done without producing any error messages, but all
- * error messages on parsing errors during the expression evaluation are given
- * (even if a try conditional is active).
- */
+// When several errors appear in a row, setting "force_abort" is delayed until
+// the failing command returned. "cause_abort" is set to true meanwhile, in
+// order to indicate that situation. This is useful when "force_abort" was set
+// during execution of a function call from an expression: the aborting of the
+// expression evaluation is done without producing any error messages, but all
+// error messages on parsing errors during the expression evaluation are given
+// (even if a try conditional is active).
static int cause_abort = false;
/// @return true when immediately aborting on error, or when an interrupt
@@ -153,69 +151,57 @@ bool cause_errthrow(const char *mesg, bool severe, bool *ignore)
msglist_T *elem;
msglist_T **plist;
- /*
- * Do nothing when displaying the interrupt message or reporting an
- * uncaught exception (which has already been discarded then) at the top
- * level. Also when no exception can be thrown. The message will be
- * displayed by emsg().
- */
+ // Do nothing when displaying the interrupt message or reporting an
+ // uncaught exception (which has already been discarded then) at the top
+ // level. Also when no exception can be thrown. The message will be
+ // displayed by emsg().
if (suppress_errthrow) {
return false;
}
- /*
- * If emsg() has not been called previously, temporarily reset
- * "force_abort" until the throw point for error messages has been
- * reached. This ensures that aborting() returns the same value for all
- * errors that appear in the same command. This means particularly that
- * for parsing errors during expression evaluation emsg() will be called
- * multiply, even when the expression is evaluated from a finally clause
- * that was activated due to an aborting error, interrupt, or exception.
- */
+ // If emsg() has not been called previously, temporarily reset
+ // "force_abort" until the throw point for error messages has been
+ // reached. This ensures that aborting() returns the same value for all
+ // errors that appear in the same command. This means particularly that
+ // for parsing errors during expression evaluation emsg() will be called
+ // multiply, even when the expression is evaluated from a finally clause
+ // that was activated due to an aborting error, interrupt, or exception.
if (!did_emsg) {
cause_abort = force_abort;
force_abort = false;
}
- /*
- * If no try conditional is active and no exception is being thrown and
- * there has not been an error in a try conditional or a throw so far, do
- * nothing (for compatibility of non-EH scripts). The message will then
- * be displayed by emsg(). When ":silent!" was used and we are not
- * currently throwing an exception, do nothing. The message text will
- * then be stored to v:errmsg by emsg() without displaying it.
- */
+ // If no try conditional is active and no exception is being thrown and
+ // there has not been an error in a try conditional or a throw so far, do
+ // nothing (for compatibility of non-EH scripts). The message will then
+ // be displayed by emsg(). When ":silent!" was used and we are not
+ // currently throwing an exception, do nothing. The message text will
+ // then be stored to v:errmsg by emsg() without displaying it.
if (((trylevel == 0 && !cause_abort) || emsg_silent) && !did_throw) {
return false;
}
- /*
- * Ignore an interrupt message when inside a try conditional or when an
- * exception is being thrown or when an error in a try conditional or
- * throw has been detected previously. This is important in order that an
- * interrupt exception is catchable by the innermost try conditional and
- * not replaced by an interrupt message error exception.
- */
+ // Ignore an interrupt message when inside a try conditional or when an
+ // exception is being thrown or when an error in a try conditional or
+ // throw has been detected previously. This is important in order that an
+ // interrupt exception is catchable by the innermost try conditional and
+ // not replaced by an interrupt message error exception.
if (mesg == _(e_interr)) {
*ignore = true;
return true;
}
- /*
- * Ensure that all commands in nested function calls and sourced files
- * are aborted immediately.
- */
+ // Ensure that all commands in nested function calls and sourced files
+ // are aborted immediately.
cause_abort = true;
- /*
- * When an exception is being thrown, some commands (like conditionals) are
- * not skipped. Errors in those commands may affect what of the subsequent
- * commands are regarded part of catch and finally clauses. Catching the
- * exception would then cause execution of commands not intended by the
- * user, who wouldn't even get aware of the problem. Therefore, discard the
- * exception currently being thrown to prevent it from being caught. Just
- * execute finally clauses and terminate.
- */
+ // When an exception is being thrown, some commands (like conditionals) are
+ // not skipped. Errors in those commands may affect what of the subsequent
+ // commands are regarded part of catch and finally clauses. Catching the
+ // exception would then cause execution of commands not intended by the
+ // user, who wouldn't even get aware of the problem. Therefore, discard the
+ // exception currently being thrown to prevent it from being caught. Just
+ // execute finally clauses and terminate.
if (did_throw) {
// When discarding an interrupt exception, reset got_int to prevent the
// same interrupt being converted to an exception again and discarding
@@ -228,25 +214,21 @@ bool cause_errthrow(const char *mesg, bool severe, bool *ignore)
#ifdef THROW_TEST
if (!THROW_ON_ERROR) {
- /*
- * Print error message immediately without searching for a matching
- * catch clause; just finally clauses are executed before the script
- * is terminated.
- */
+ // Print error message immediately without searching for a matching
+ // catch clause; just finally clauses are executed before the script
+ // is terminated.
return false;
} else // NOLINT(readability/braces)
#endif
{
- /*
- * Prepare the throw of an error exception, so that everything will
- * be aborted (except for executing finally clauses), until the error
- * exception is caught; if still uncaught at the top level, the error
- * message will be displayed and the script processing terminated
- * then. - This function has no access to the conditional stack.
- * Thus, the actual throw is made after the failing command has
- * returned. - Throw only the first of several errors in a row, except
- * a severe error is following.
- */
+ // Prepare the throw of an error exception, so that everything will
+ // be aborted (except for executing finally clauses), until the error
+ // exception is caught; if still uncaught at the top level, the error
+ // message will be displayed and the script processing terminated
+ // then. - This function has no access to the conditional stack.
+ // Thus, the actual throw is made after the failing command has
+ // returned. - Throw only the first of several errors in a row, except
+ // a severe error is following.
if (msg_list != NULL) {
plist = msg_list;
while (*plist != NULL) {
@@ -312,10 +294,8 @@ void free_global_msglist(void)
/// has returned (see do_one_cmd()).
void do_errthrow(cstack_T *cstack, char *cmdname)
{
- /*
- * Ensure that all commands in nested function calls and sourced files
- * are aborted immediately.
- */
+ // Ensure that all commands in nested function calls and sourced files
+ // are aborted immediately.
if (cause_abort) {
cause_abort = false;
force_abort = true;
@@ -455,11 +435,9 @@ static int throw_exception(void *value, except_type_T type, char *cmdname)
except_T *excp;
int should_free;
- /*
- * Disallow faking Interrupt or error exceptions as user exceptions. They
- * would be treated differently from real interrupt or error exceptions
- * when no active try block is found, see do_cmdline().
- */
+ // Disallow faking Interrupt or error exceptions as user exceptions. They
+ // would be treated differently from real interrupt or error exceptions
+ // when no active try block is found, see do_cmdline().
if (type == ET_USER) {
if (STRNCMP((char_u *)value, "Vim", 3) == 0
&& (((char_u *)value)[3] == NUL || ((char_u *)value)[3] == ':'
@@ -551,7 +529,7 @@ static void discard_exception(except_T *excp, bool was_finished)
if (p_verbose >= 13 || debug_break_level > 0) {
int save_msg_silent = msg_silent;
- saved_IObuff = (char *)vim_strsave(IObuff);
+ saved_IObuff = xstrdup((char *)IObuff);
if (debug_break_level > 0) {
msg_silent = false; // display messages
} else {
@@ -678,9 +656,7 @@ static void finish_exception(except_T *excp)
discard_exception(excp, true);
}
-/*
- * Flags specifying the message displayed by report_pending.
- */
+// Flags specifying the message displayed by report_pending.
#define RP_MAKE 0
#define RP_RESUME 1
#define RP_DISCARD 2
@@ -958,11 +934,9 @@ void ex_while(exarg_T *eap)
if (cstack->cs_idx == CSTACK_LEN - 1) {
eap->errmsg = _("E585: :while/:for nesting too deep");
} else {
- /*
- * The loop flag is set when we have jumped back from the matching
- * ":endwhile" or ":endfor". When not set, need to initialise this
- * cstack entry.
- */
+ // The loop flag is set when we have jumped back from the matching
+ // ":endwhile" or ":endfor". When not set, need to initialise this
+ // cstack entry.
if ((cstack->cs_lflags & CSL_HAD_LOOP) == 0) {
cstack->cs_idx++;
cstack->cs_looplevel++;
@@ -973,16 +947,12 @@ void ex_while(exarg_T *eap)
skip = CHECK_SKIP;
if (eap->cmdidx == CMD_while) {
- /*
- * ":while bool-expr"
- */
+ // ":while bool-expr"
result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip);
} else {
void *fi;
- /*
- * ":for var in list-expr"
- */
+ // ":for var in list-expr"
if ((cstack->cs_lflags & CSL_HAD_LOOP) != 0) {
// Jumping here from a ":continue" or ":endfor": use the
// previously evaluated list.
@@ -1007,11 +977,9 @@ void ex_while(exarg_T *eap)
}
}
- /*
- * If this cstack entry was just initialised and is active, set the
- * loop flag, so do_cmdline() will set the line number in cs_line[].
- * If executing the command a second time, clear the loop flag.
- */
+ // If this cstack entry was just initialised and is active, set the
+ // loop flag, so do_cmdline() will set the line number in cs_line[].
+ // If executing the command a second time, clear the loop flag.
if (!skip && !error && result) {
cstack->cs_flags[cstack->cs_idx] |= (CSF_ACTIVE | CSF_TRUE);
cstack->cs_lflags ^= CSL_HAD_LOOP;
@@ -1046,10 +1014,8 @@ void ex_continue(exarg_T *eap)
if (cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR)) {
rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel);
- /*
- * Set CSL_HAD_CONT, so do_cmdline() will jump back to the
- * matching ":while".
- */
+ // Set CSL_HAD_CONT, so do_cmdline() will jump back to the
+ // matching ":while".
cstack->cs_lflags |= CSL_HAD_CONT; // let do_cmdline() handle it
} else {
// If a try conditional not in its finally clause is reached first,
@@ -1147,10 +1113,8 @@ void ex_endwhile(exarg_T *eap)
(void)do_intthrow(cstack);
}
- /*
- * Set loop flag, so do_cmdline() will jump back to the matching
- * ":while" or ":for".
- */
+ // Set loop flag, so do_cmdline() will jump back to the matching
+ // ":while" or ":for".
cstack->cs_lflags |= CSL_HAD_ENDLOOP;
}
}
@@ -1211,19 +1175,17 @@ void do_throw(cstack_T *cstack)
#endif
idx = cleanup_conditionals(cstack, 0, inactivate_try);
if (idx >= 0) {
- /*
- * If this try conditional is active and we are before its first
- * ":catch", set THROWN so that the ":catch" commands will check
- * whether the exception matches. When the exception came from any of
- * the catch clauses, it will be made pending at the ":finally" (if
- * present) and rethrown at the ":endtry". This will also happen if
- * the try conditional is inactive. This is the case when we are
- * throwing an exception due to an error or interrupt on the way from
- * a preceding ":continue", ":break", ":return", ":finish", error or
- * interrupt (not converted to an exception) to the finally clause or
- * from a preceding throw of a user or error or interrupt exception to
- * the matching catch clause or the finally clause.
- */
+ // If this try conditional is active and we are before its first
+ // ":catch", set THROWN so that the ":catch" commands will check
+ // whether the exception matches. When the exception came from any of
+ // the catch clauses, it will be made pending at the ":finally" (if
+ // present) and rethrown at the ":endtry". This will also happen if
+ // the try conditional is inactive. This is the case when we are
+ // throwing an exception due to an error or interrupt on the way from
+ // a preceding ":continue", ":break", ":return", ":finish", error or
+ // interrupt (not converted to an exception) to the finally clause or
+ // from a preceding throw of a user or error or interrupt exception to
+ // the matching catch clause or the finally clause.
if (!(cstack->cs_flags[idx] & CSF_CAUGHT)) {
if (cstack->cs_flags[idx] & CSF_ACTIVE) {
cstack->cs_flags[idx] |= CSF_THROWN;
@@ -1263,22 +1225,20 @@ void ex_try(exarg_T *eap)
// that the finally clause needs to be executed.
cstack->cs_flags[cstack->cs_idx] |= CSF_ACTIVE | CSF_TRUE;
- /*
- * ":silent!", even when used in a try conditional, disables
- * displaying of error messages and conversion of errors to
- * exceptions. When the silent commands again open a try
- * conditional, save "emsg_silent" and reset it so that errors are
- * again converted to exceptions. The value is restored when that
- * try conditional is left. If it is left normally, the commands
- * following the ":endtry" are again silent. If it is left by
- * a ":continue", ":break", ":return", or ":finish", the commands
- * executed next are again silent. If it is left due to an
- * aborting error, an interrupt, or an exception, restoring
- * "emsg_silent" does not matter since we are already in the
- * aborting state and/or the exception has already been thrown.
- * The effect is then just freeing the memory that was allocated
- * to save the value.
- */
+ // ":silent!", even when used in a try conditional, disables
+ // displaying of error messages and conversion of errors to
+ // exceptions. When the silent commands again open a try
+ // conditional, save "emsg_silent" and reset it so that errors are
+ // again converted to exceptions. The value is restored when that
+ // try conditional is left. If it is left normally, the commands
+ // following the ":endtry" are again silent. If it is left by
+ // a ":continue", ":break", ":return", or ":finish", the commands
+ // executed next are again silent. If it is left due to an
+ // aborting error, an interrupt, or an exception, restoring
+ // "emsg_silent" does not matter since we are already in the
+ // aborting state and/or the exception has already been thrown.
+ // The effect is then just freeing the memory that was allocated
+ // to save the value.
if (emsg_silent) {
eslist_T *elem = xmalloc(sizeof(*elem));
elem->saved_emsg_silent = emsg_silent;
@@ -1342,20 +1302,16 @@ void ex_catch(exarg_T *eap)
}
if (!give_up) {
- /*
- * Don't do something when no exception has been thrown or when the
- * corresponding try block never got active (because of an inactive
- * surrounding conditional or after an error or interrupt or throw).
- */
+ // Don't do something when no exception has been thrown or when the
+ // corresponding try block never got active (because of an inactive
+ // surrounding conditional or after an error or interrupt or throw).
if (!did_throw || !(cstack->cs_flags[idx] & CSF_TRUE)) {
skip = true;
}
- /*
- * Check for a match only if an exception is thrown but not caught by
- * a previous ":catch". An exception that has replaced a discarded
- * exception is not checked (THROWN is not set then).
- */
+ // Check for a match only if an exception is thrown but not caught by
+ // a previous ":catch". An exception that has replaced a discarded
+ // exception is not checked (THROWN is not set then).
if (!skip && (cstack->cs_flags[idx] & CSF_THROWN)
&& !(cstack->cs_flags[idx] & CSF_CAUGHT)) {
if (end != NULL && *end != NUL && !ends_excmd(*skipwhite(end + 1))) {
@@ -1422,16 +1378,14 @@ void ex_catch(exarg_T *eap)
internal_error("ex_catch()");
}
} else {
- /*
- * If there is a preceding catch clause and it caught the exception,
- * finish the exception now. This happens also after errors except
- * when this ":catch" was after the ":finally" or not within
- * a ":try". Make the try conditional inactive so that the
- * following catch clauses are skipped. On an error or interrupt
- * after the preceding try block or catch clause was left by
- * a ":continue", ":break", ":return", or ":finish", discard the
- * pending action.
- */
+ // If there is a preceding catch clause and it caught the exception,
+ // finish the exception now. This happens also after errors except
+ // when this ":catch" was after the ":finally" or not within
+ // a ":try". Make the try conditional inactive so that the
+ // following catch clauses are skipped. On an error or interrupt
+ // after the preceding try block or catch clause was left by
+ // a ":continue", ":break", ":return", or ":finish", discard the
+ // pending action.
cleanup_conditionals(cstack, CSF_TRY, true);
}
}
@@ -1495,14 +1449,12 @@ void ex_finally(exarg_T *eap)
(void)do_intthrow(cstack);
}
- /*
- * If there is a preceding catch clause and it caught the exception,
- * finish the exception now. This happens also after errors except
- * when this is a multiple ":finally" or one not within a ":try".
- * After an error or interrupt, this also discards a pending
- * ":continue", ":break", ":finish", or ":return" from the preceding
- * try block or catch clause.
- */
+ // If there is a preceding catch clause and it caught the exception,
+ // finish the exception now. This happens also after errors except
+ // when this is a multiple ":finally" or one not within a ":try".
+ // After an error or interrupt, this also discards a pending
+ // ":continue", ":break", ":finish", or ":return" from the preceding
+ // try block or catch clause.
cleanup_conditionals(cstack, CSF_TRY, false);
// Make did_emsg, got_int, did_throw pending. If set, they overrule
@@ -1606,12 +1558,10 @@ void ex_endtry(exarg_T *eap)
} else {
idx = cstack->cs_idx;
- /*
- * If we stopped with the exception currently being thrown at this
- * try conditional since we didn't know that it doesn't have
- * a finally clause, we need to rethrow it after closing the try
- * conditional.
- */
+ // If we stopped with the exception currently being thrown at this
+ // try conditional since we didn't know that it doesn't have
+ // a finally clause, we need to rethrow it after closing the try
+ // conditional.
if (did_throw
&& (cstack->cs_flags[idx] & CSF_TRUE)
&& !(cstack->cs_flags[idx] & CSF_FINALLY)) {
@@ -1645,12 +1595,10 @@ void ex_endtry(exarg_T *eap)
}
}
- /*
- * If a ":return" is pending, we need to resume it after closing the
- * try conditional; remember the return value. If there was a finally
- * clause making an exception pending, we need to rethrow it. Make it
- * the exception currently being thrown.
- */
+ // If a ":return" is pending, we need to resume it after closing the
+ // try conditional; remember the return value. If there was a finally
+ // clause making an exception pending, we need to rethrow it. Make it
+ // the exception currently being thrown.
if (!skip) {
pending = cstack->cs_pending[idx];
cstack->cs_pending[idx] = CSTP_NONE;
@@ -1661,16 +1609,14 @@ void ex_endtry(exarg_T *eap)
}
}
- /*
- * Discard anything pending on an error, interrupt, or throw in the
- * finally clause. If there was no ":finally", discard a pending
- * ":continue", ":break", ":return", or ":finish" if an error or
- * interrupt occurred afterwards, but before the ":endtry" was reached.
- * If an exception was caught by the last of the catch clauses and there
- * was no finally clause, finish the exception now. This happens also
- * after errors except when this ":endtry" is not within a ":try".
- * Restore "emsg_silent" if it has been reset by this try conditional.
- */
+ // Discard anything pending on an error, interrupt, or throw in the
+ // finally clause. If there was no ":finally", discard a pending
+ // ":continue", ":break", ":return", or ":finish" if an error or
+ // interrupt occurred afterwards, but before the ":endtry" was reached.
+ // If an exception was caught by the last of the catch clauses and there
+ // was no finally clause, finish the exception now. This happens also
+ // after errors except when this ":endtry" is not within a ":try".
+ // Restore "emsg_silent" if it has been reset by this try conditional.
(void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, true);
if (cstack->cs_idx >= 0 && (cstack->cs_flags[cstack->cs_idx] & CSF_TRY)) {
@@ -1733,18 +1679,16 @@ void ex_endtry(exarg_T *eap)
}
}
-/*
- * enter_cleanup() and leave_cleanup()
- *
- * Functions to be called before/after invoking a sequence of autocommands for
- * cleanup for a failed command. (Failure means here that a call to emsg()
- * has been made, an interrupt occurred, or there is an uncaught exception
- * from a previous autocommand execution of the same command.)
- *
- * Call enter_cleanup() with a pointer to a cleanup_T and pass the same
- * pointer to leave_cleanup(). The cleanup_T structure stores the pending
- * error/interrupt/exception state.
- */
+// enter_cleanup() and leave_cleanup()
+//
+// Functions to be called before/after invoking a sequence of autocommands for
+// cleanup for a failed command. (Failure means here that a call to emsg()
+// has been made, an interrupt occurred, or there is an uncaught exception
+// from a previous autocommand execution of the same command.)
+//
+// Call enter_cleanup() with a pointer to a cleanup_T and pass the same
+// pointer to leave_cleanup(). The cleanup_T structure stores the pending
+// error/interrupt/exception state.
/// This function works a bit like ex_finally() except that there was not
/// actually an extra try block around the part that failed and an error or
@@ -1829,18 +1773,14 @@ void leave_cleanup(cleanup_T *csp)
if (msg_list != NULL) {
free_global_msglist();
}
- }
- /*
- * If there was no new error, interrupt, or throw between the calls
- * to enter_cleanup() and leave_cleanup(), restore the pending
- * error/interrupt/exception state.
- */
- else {
- /*
- * If there was an exception being thrown when enter_cleanup() was
- * called, we need to rethrow it. Make it the exception currently
- * being thrown.
- */
+ } else {
+ // If there was no new error, interrupt, or throw between the calls
+ // to enter_cleanup() and leave_cleanup(), restore the pending
+ // error/interrupt/exception state.
+
+ // If there was an exception being thrown when enter_cleanup() was
+ // called, we need to rethrow it. Make it the exception currently
+ // being thrown.
if (pending & CSTP_THROW) {
current_exception = csp->exception;
} else if (pending & CSTP_ERROR) {
@@ -1893,12 +1833,10 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive)
for (idx = cstack->cs_idx; idx >= 0; idx--) {
if (cstack->cs_flags[idx] & CSF_TRY) {
- /*
- * Discard anything pending in a finally clause and continue the
- * search. There may also be a pending ":continue", ":break",
- * ":return", or ":finish" before the finally clause. We must not
- * discard it, unless an error or interrupt occurred afterwards.
- */
+ // Discard anything pending in a finally clause and continue the
+ // search. There may also be a pending ":continue", ":break",
+ // ":return", or ":finish" before the finally clause. We must not
+ // discard it, unless an error or interrupt occurred afterwards.
if (did_emsg || got_int || (cstack->cs_flags[idx] & CSF_FINALLY)) {
switch (cstack->cs_pending[idx]) {
case CSTP_NONE:
@@ -1934,11 +1872,9 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive)
}
}
- /*
- * Stop at a try conditional not in its finally clause. If this try
- * conditional is in an active catch clause, finish the caught
- * exception.
- */
+ // Stop at a try conditional not in its finally clause. If this try
+ // conditional is in an active catch clause, finish the caught
+ // exception.
if (!(cstack->cs_flags[idx] & CSF_FINALLY)) {
if ((cstack->cs_flags[idx] & CSF_ACTIVE)
&& (cstack->cs_flags[idx] & CSF_CAUGHT) && !(cstack->cs_flags[idx] & CSF_FINISHED)) {
@@ -1973,11 +1909,9 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive)
break;
}
- /*
- * When leaving a try conditional that reset "emsg_silent" on its
- * entry after saving the original value, restore that value here and
- * free the memory used to store it.
- */
+ // When leaving a try conditional that reset "emsg_silent" on its
+ // entry after saving the original value, restore that value here and
+ // free the memory used to store it.
if ((cstack->cs_flags[idx] & CSF_TRY)
&& (cstack->cs_flags[idx] & CSF_SILENT)) {
eslist_T *elem;
diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c
index 9d1cebd43e..2b7797ddc8 100644
--- a/src/nvim/ex_getln.c
+++ b/src/nvim/ex_getln.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * ex_getln.c: Functions for entering and editing an Ex command line.
- */
+// ex_getln.c: Functions for entering and editing an Ex command line.
#include <assert.h>
#include <inttypes.h>
@@ -107,7 +105,7 @@ typedef struct command_line_state {
int c;
int gotesc; // true when <ESC> just typed
int do_abbr; // when true check for abbr.
- char_u *lookfor; // string to match
+ char *lookfor; // string to match
int hiscnt; // current history line in use
int save_hiscnt; // history line before attempting
// to jump to next match
@@ -118,7 +116,7 @@ typedef struct command_line_state {
int res;
int save_msg_scroll;
int save_State; // remember State when called
- char_u *save_p_icm;
+ char *save_p_icm;
int some_key_typed; // one of the keys was typed
// mouse drag and release events are ignored, unless they are
// preceded with a mouse down event
@@ -255,7 +253,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s
exarg_T ea = {
.line1 = 1,
.line2 = 1,
- .cmd = (char *)ccline.cmdbuff,
+ .cmd = ccline.cmdbuff,
.addr_type = ADDR_LINES,
};
@@ -336,7 +334,7 @@ static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_s
}
// found a non-empty pattern or //
- *skiplen = (int)((char_u *)p - ccline.cmdbuff);
+ *skiplen = (int)(p - ccline.cmdbuff);
*patlen = (int)(end - p);
// parse the address range
@@ -409,7 +407,7 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat
int found; // do_search() result
// Use the previous pattern for ":s//".
- next_char = ccline.cmdbuff[skiplen + patlen];
+ next_char = (char_u)ccline.cmdbuff[skiplen + patlen];
use_last_pat = patlen == 0 && skiplen > 0
&& ccline.cmdbuff[skiplen - 1] == next_char;
@@ -436,9 +434,9 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat
.sa_tm = &tm,
};
found = do_search(NULL, firstc == ':' ? '/' : firstc, search_delim,
- ccline.cmdbuff + skiplen, count,
+ (char_u *)ccline.cmdbuff + skiplen, count,
search_flags, &sia);
- ccline.cmdbuff[skiplen + patlen] = next_char;
+ ccline.cmdbuff[skiplen + patlen] = (char)next_char;
emsg_off--;
if (curwin->w_cursor.lnum < search_first_line
|| curwin->w_cursor.lnum > search_last_line) {
@@ -487,13 +485,13 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat
// Disable 'hlsearch' highlighting if the pattern matches
// everything. Avoids a flash when typing "foo\|".
if (!use_last_pat) {
- next_char = ccline.cmdbuff[skiplen + patlen];
+ next_char = (char_u)ccline.cmdbuff[skiplen + patlen];
ccline.cmdbuff[skiplen + patlen] = NUL;
- if (empty_pattern((char *)ccline.cmdbuff) && !no_hlsearch) {
+ if (empty_pattern(ccline.cmdbuff) && !no_hlsearch) {
redraw_all_later(UPD_SOME_VALID);
set_no_hlsearch(true);
}
- ccline.cmdbuff[skiplen + patlen] = next_char;
+ ccline.cmdbuff[skiplen + patlen] = (char)next_char;
}
validate_cursor();
@@ -548,7 +546,7 @@ static int may_add_char_to_search(int firstc, int *c, incsearch_state_T *s)
// command line has no uppercase characters, convert
// the character to lowercase
if (p_ic && p_scs
- && !pat_has_uppercase(ccline.cmdbuff + skiplen)) {
+ && !pat_has_uppercase((char_u *)ccline.cmdbuff + skiplen)) {
*c = mb_tolower(*c);
}
if (*c == search_delim
@@ -634,7 +632,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init
.ignore_drag_release = true,
};
CommandLineState *s = &state;
- s->save_p_icm = vim_strsave((char_u *)p_icm);
+ s->save_p_icm = xstrdup(p_icm);
init_incsearch_state(&s->is_state);
CmdlineInfo save_ccline;
bool did_save_ccline = false;
@@ -724,7 +722,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init
if (ccline.input_fn) {
s->xpc.xp_context = ccline.xp_context;
- s->xpc.xp_pattern = (char *)ccline.cmdbuff;
+ s->xpc.xp_pattern = ccline.cmdbuff;
s->xpc.xp_arg = (char *)ccline.xp_arg;
}
@@ -854,7 +852,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init
s->histype == HIST_SEARCH ? s->firstc : NUL);
if (s->firstc == ':') {
xfree(new_last_cmdline);
- new_last_cmdline = (char *)vim_strsave(ccline.cmdbuff);
+ new_last_cmdline = xstrdup(ccline.cmdbuff);
}
}
@@ -881,7 +879,7 @@ static uint8_t *command_line_enter(int firstc, long count, int indent, bool init
need_wait_return = false;
}
- set_string_option_direct("icm", -1, (char *)s->save_p_icm, OPT_FREE, SID_NONE);
+ set_string_option_direct("icm", -1, s->save_p_icm, OPT_FREE, SID_NONE);
State = s->save_State;
if (cmdpreview != save_cmdpreview) {
cmdpreview = save_cmdpreview; // restore preview state
@@ -897,7 +895,7 @@ theend:
xfree(ccline.last_colors.cmdbuff);
kv_destroy(ccline.last_colors.colors);
- char_u *p = ccline.cmdbuff;
+ char_u *p = (char_u *)ccline.cmdbuff;
if (ui_has(kUICmdline)) {
ui_call_cmdline_hide(ccline.level);
@@ -1089,7 +1087,7 @@ static int command_line_execute(VimState *state, int key)
s->c = get_expr_register();
if (s->c == '=') {
textlock++;
- p = get_expr_line();
+ p = (char_u *)get_expr_line();
textlock--;
if (p != NULL) {
@@ -1339,7 +1337,7 @@ static int may_do_command_line_next_incsearch(int firstc, long count, incsearch_
skiplen = 0;
patlen = (int)STRLEN(pat);
} else {
- pat = ccline.cmdbuff + skiplen;
+ pat = (char_u *)ccline.cmdbuff + skiplen;
}
if (next_match) {
@@ -1483,24 +1481,24 @@ static int command_line_handle_key(CommandLineState *s)
}
if (s->c == K_DEL) {
- ccline.cmdpos += mb_off_next(ccline.cmdbuff,
- ccline.cmdbuff + ccline.cmdpos);
+ ccline.cmdpos += mb_off_next((char_u *)ccline.cmdbuff,
+ (char_u *)ccline.cmdbuff + ccline.cmdpos);
}
if (ccline.cmdpos > 0) {
char_u *p;
int j = ccline.cmdpos;
- p = mb_prevptr(ccline.cmdbuff, ccline.cmdbuff + j);
+ p = mb_prevptr((char_u *)ccline.cmdbuff, (char_u *)ccline.cmdbuff + j);
if (s->c == Ctrl_W) {
- while (p > ccline.cmdbuff && ascii_isspace(*p)) {
- p = mb_prevptr(ccline.cmdbuff, p);
+ while (p > (char_u *)ccline.cmdbuff && ascii_isspace(*p)) {
+ p = mb_prevptr((char_u *)ccline.cmdbuff, p);
}
int i = mb_get_class(p);
- while (p > ccline.cmdbuff && mb_get_class(p) == i) {
- p = mb_prevptr(ccline.cmdbuff, p);
+ while (p > (char_u *)ccline.cmdbuff && mb_get_class(p) == i) {
+ p = mb_prevptr((char_u *)ccline.cmdbuff, p);
}
if (mb_get_class(p) != i) {
@@ -1508,7 +1506,7 @@ static int command_line_handle_key(CommandLineState *s)
}
}
- ccline.cmdpos = (int)(p - ccline.cmdbuff);
+ ccline.cmdpos = (int)(p - (char_u *)ccline.cmdbuff);
ccline.cmdlen -= j - ccline.cmdpos;
int i = ccline.cmdpos;
@@ -1688,7 +1686,7 @@ static int command_line_handle_key(CommandLineState *s)
}
ccline.cmdspos += cells;
- ccline.cmdpos += utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos);
+ ccline.cmdpos += utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos);
} while ((s->c == K_S_RIGHT || s->c == K_C_RIGHT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos] != ' ');
@@ -1704,8 +1702,8 @@ static int command_line_handle_key(CommandLineState *s)
do {
ccline.cmdpos--;
// Move to first byte of possibly multibyte char.
- ccline.cmdpos -= utf_head_off((char *)ccline.cmdbuff,
- (char *)ccline.cmdbuff + ccline.cmdpos);
+ ccline.cmdpos -= utf_head_off(ccline.cmdbuff,
+ ccline.cmdbuff + ccline.cmdpos);
ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
} while (ccline.cmdpos > 0
&& (s->c == K_S_LEFT || s->c == K_C_LEFT
@@ -1761,7 +1759,7 @@ static int command_line_handle_key(CommandLineState *s)
// Count ">" for double-wide char that doesn't fit.
correct_screencol(ccline.cmdpos, cells, &ccline.cmdspos);
- ccline.cmdpos += utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos) - 1;
+ ccline.cmdpos += utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos) - 1;
ccline.cmdspos += cells;
}
return command_line_not_changed(s);
@@ -1855,7 +1853,7 @@ static int command_line_handle_key(CommandLineState *s)
// save current command string so it can be restored later
if (s->lookfor == NULL) {
- s->lookfor = vim_strsave(ccline.cmdbuff);
+ s->lookfor = xstrdup(ccline.cmdbuff);
s->lookfor[ccline.cmdpos] = NUL;
}
@@ -1872,13 +1870,13 @@ static int command_line_handle_key(CommandLineState *s)
XFREE_CLEAR(ccline.cmdbuff);
s->xpc.xp_context = EXPAND_NOTHING;
if (s->hiscnt == get_hislen()) {
- p = s->lookfor; // back to the old one
+ p = (char_u *)s->lookfor; // back to the old one
} else {
- p = get_histentry(s->histype)[s->hiscnt].hisstr;
+ p = (char_u *)get_histentry(s->histype)[s->hiscnt].hisstr;
}
if (s->histype == HIST_SEARCH
- && p != s->lookfor
+ && p != (char_u *)s->lookfor
&& (old_firstc = p[STRLEN(p) + 1]) != s->firstc) {
// Correct for the separator character used when
// adding the history entry vs the one used now.
@@ -1892,7 +1890,7 @@ static int command_line_handle_key(CommandLineState *s)
if (p[j] == old_firstc
&& (j == 0 || p[j - 1] != '\\')) {
if (i > 0) {
- ccline.cmdbuff[len] = (char_u)s->firstc;
+ ccline.cmdbuff[len] = (char)s->firstc;
}
} else {
// Escape new sep, unless it is already
@@ -1906,7 +1904,7 @@ static int command_line_handle_key(CommandLineState *s)
}
if (i > 0) {
- ccline.cmdbuff[len] = p[j];
+ ccline.cmdbuff[len] = (char)p[j];
}
}
len++;
@@ -2007,7 +2005,7 @@ static int command_line_handle_key(CommandLineState *s)
} else {
int j = utf_char2bytes(s->c, (char *)IObuff);
IObuff[j] = NUL; // exclude composing chars
- put_on_cmdline(IObuff, j, true);
+ put_on_cmdline((char_u *)IObuff, j, true);
}
return command_line_changed(s);
}
@@ -2281,7 +2279,7 @@ static bool cmdpreview_may_show(CommandLineState *s)
CmdParseInfo cmdinfo;
// Copy the command line so we can modify it.
int cmdpreview_type = 0;
- char *cmdline = xstrdup((char *)ccline.cmdbuff);
+ char *cmdline = xstrdup(ccline.cmdbuff);
char *errormsg = NULL;
emsg_off++; // Block errors when parsing the command line, and don't update v:errmsg
if (!parse_cmdline(cmdline, &ea, &cmdinfo, &errormsg)) {
@@ -2603,10 +2601,8 @@ bool text_locked(void)
return textlock != 0;
}
-/*
- * Give an error message for a command that isn't allowed while the cmdline
- * window is open or editing the cmdline in another way.
- */
+// Give an error message for a command that isn't allowed while the cmdline
+// window is open or editing the cmdline in another way.
void text_locked_msg(void)
{
emsg(_(get_text_locked_msg()));
@@ -2659,7 +2655,7 @@ static int cmdline_charsize(int idx)
if (cmdline_star > 0) { // showing '*', always 1 position
return 1;
}
- return ptr2cells((char *)ccline.cmdbuff + idx);
+ return ptr2cells(ccline.cmdbuff + idx);
}
/// Compute the offset of the cursor on the command line for the prompt and
@@ -2685,7 +2681,7 @@ int cmd_screencol(int bytepos)
}
for (int i = 0; i < ccline.cmdlen && i < bytepos;
- i += utfc_ptr2len((char *)ccline.cmdbuff + i)) {
+ i += utfc_ptr2len(ccline.cmdbuff + i)) {
int c = cmdline_charsize(i);
// Count ">" for double-wide multi-byte char that doesn't fit.
correct_screencol(i, c, &col);
@@ -2704,8 +2700,8 @@ int cmd_screencol(int bytepos)
/// character that doesn't fit, so that a ">" must be displayed.
static void correct_screencol(int idx, int cells, int *col)
{
- if (utfc_ptr2len((char *)ccline.cmdbuff + idx) > 1
- && utf_ptr2cells((char *)ccline.cmdbuff + idx) > 1
+ if (utfc_ptr2len(ccline.cmdbuff + idx) > 1
+ && utf_ptr2cells(ccline.cmdbuff + idx) > 1
&& (*col) % Columns + cells > Columns) {
(*col)++;
}
@@ -2738,15 +2734,11 @@ bool cmdline_at_end(void)
return (ccline.cmdpos >= ccline.cmdlen);
}
-/*
- * Allocate a new command line buffer.
- * Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen.
- */
+// Allocate a new command line buffer.
+// Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen.
static void alloc_cmdbuff(int len)
{
- /*
- * give some extra space to avoid having to allocate all the time
- */
+ // give some extra space to avoid having to allocate all the time
if (len < 80) {
len = 100;
} else {
@@ -2764,7 +2756,7 @@ void realloc_cmdbuff(int len)
return; // no need to resize
}
- char_u *p = ccline.cmdbuff;
+ char_u *p = (char_u *)ccline.cmdbuff;
alloc_cmdbuff(len); // will get some more
// There isn't always a NUL after the command, but it may need to be
// there, thus copy up to the NUL and add a NUL.
@@ -2781,7 +2773,7 @@ void realloc_cmdbuff(int len)
// If xp_pattern points inside the old cmdbuff it needs to be adjusted
// to point into the newly allocated memory.
if (i >= 0 && i <= ccline.cmdlen) {
- ccline.xpc->xp_pattern = (char *)ccline.cmdbuff + i;
+ ccline.xpc->xp_pattern = ccline.cmdbuff + i;
}
}
}
@@ -2889,7 +2881,7 @@ static bool color_cmdline(CmdlineInfo *colored_ccline)
// Check whether result of the previous call is still valid.
if (ccline_colors->prompt_id == colored_ccline->prompt_id
&& ccline_colors->cmdbuff != NULL
- && STRCMP(ccline_colors->cmdbuff, colored_ccline->cmdbuff) == 0) {
+ && strcmp(ccline_colors->cmdbuff, colored_ccline->cmdbuff) == 0) {
return ret;
}
@@ -2904,7 +2896,7 @@ static bool color_cmdline(CmdlineInfo *colored_ccline)
bool arg_allocated = false;
typval_T arg = {
.v_type = VAR_STRING,
- .vval.v_string = (char *)colored_ccline->cmdbuff,
+ .vval.v_string = colored_ccline->cmdbuff,
};
typval_T tv = { .v_type = VAR_UNKNOWN };
@@ -3088,10 +3080,8 @@ color_cmdline_error:
#undef PRINT_ERRMSG
}
-/*
- * Draw part of the cmdline at the current cursor position. But draw stars
- * when cmdline_star is true.
- */
+// Draw part of the cmdline at the current cursor position. But draw stars
+// when cmdline_star is true.
static void draw_cmdline(int start, int len)
{
if (!color_cmdline(&ccline)) {
@@ -3107,16 +3097,16 @@ static void draw_cmdline(int start, int len)
if (cmdline_star > 0) {
for (int i = 0; i < len; i++) {
msg_putchar('*');
- i += utfc_ptr2len((char *)ccline.cmdbuff + start + i) - 1;
+ i += utfc_ptr2len(ccline.cmdbuff + start + i) - 1;
}
} else if (p_arshape && !p_tbidi && len > 0) {
bool do_arabicshape = false;
int mb_l;
for (int i = start; i < start + len; i += mb_l) {
- char_u *p = ccline.cmdbuff + i;
+ char_u *p = (char_u *)ccline.cmdbuff + i;
int u8cc[MAX_MCO];
int u8c = utfc_ptr2char_len(p, u8cc, start + len - i);
- mb_l = utfc_ptr2len_len(p, start + len - i);
+ mb_l = utfc_ptr2len_len((char *)p, start + len - i);
if (ARABIC_CHAR(u8c)) {
do_arabicshape = true;
break;
@@ -3140,7 +3130,7 @@ static void draw_cmdline(int start, int len)
}
int newlen = 0;
- if (utf_iscomposing(utf_ptr2char((char *)ccline.cmdbuff + start))) {
+ if (utf_iscomposing(utf_ptr2char(ccline.cmdbuff + start))) {
// Prepend a space to draw the leading composing char on.
arshape_buf[0] = ' ';
newlen = 1;
@@ -3149,10 +3139,10 @@ static void draw_cmdline(int start, int len)
int prev_c = 0;
int prev_c1 = 0;
for (int i = start; i < start + len; i += mb_l) {
- char_u *p = ccline.cmdbuff + i;
+ char_u *p = (char_u *)ccline.cmdbuff + i;
int u8cc[MAX_MCO];
int u8c = utfc_ptr2char_len(p, u8cc, start + len - i);
- mb_l = utfc_ptr2len_len(p, start + len - i);
+ mb_l = utfc_ptr2len_len((char *)p, start + len - i);
if (ARABIC_CHAR(u8c)) {
int pc;
int pc1 = 0;
@@ -3208,12 +3198,12 @@ draw_cmdline_no_arabicshape:
continue;
}
const int chunk_start = MAX(chunk.start, start);
- msg_outtrans_len_attr((char *)ccline.cmdbuff + chunk_start,
+ msg_outtrans_len_attr(ccline.cmdbuff + chunk_start,
chunk.end - chunk_start,
chunk.attr);
}
} else {
- msg_outtrans_len((char *)ccline.cmdbuff + start, len);
+ msg_outtrans_len(ccline.cmdbuff + start, len);
}
}
}
@@ -3225,7 +3215,7 @@ static void ui_ext_cmdline_show(CmdlineInfo *line)
if (cmdline_star) {
content = arena_array(&arena, 1);
size_t len = 0;
- for (char_u *p = ccline.cmdbuff; *p; MB_PTR_ADV(p)) {
+ for (char_u *p = (char_u *)ccline.cmdbuff; *p; MB_PTR_ADV(p)) {
len++;
}
char *buf = arena_alloc(&arena, len, false);
@@ -3342,11 +3332,9 @@ void cmdline_ui_flush(void)
}
}
-/*
- * Put a character on the command line. Shifts the following text to the
- * right when "shift" is true. Used for CTRL-V, CTRL-K, etc.
- * "c" must be printable (fit in one display cell)!
- */
+// Put a character on the command line. Shifts the following text to the
+// right when "shift" is true. Used for CTRL-V, CTRL-K, etc.
+// "c" must be printable (fit in one display cell)!
void putcmdline(char c, int shift)
{
if (cmd_silent) {
@@ -3380,7 +3368,7 @@ void unputcmdline(void)
if (ccline.cmdlen == ccline.cmdpos && !ui_has(kUICmdline)) {
msg_putchar(' ');
} else {
- draw_cmdline(ccline.cmdpos, utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos));
+ draw_cmdline(ccline.cmdpos, utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos));
}
msg_no_more = false;
cursorcmd();
@@ -3388,14 +3376,12 @@ void unputcmdline(void)
ui_cursor_shape();
}
-/*
- * Put the given string, of the given length, onto the command line.
- * If len is -1, then STRLEN() is used to calculate the length.
- * If 'redraw' is true then the new part of the command line, and the remaining
- * part will be redrawn, otherwise it will not. If this function is called
- * twice in a row, then 'redraw' should be false and redrawcmd() should be
- * called afterwards.
- */
+// Put the given string, of the given length, onto the command line.
+// If len is -1, then STRLEN() is used to calculate the length.
+// If 'redraw' is true then the new part of the command line, and the remaining
+// part will be redrawn, otherwise it will not. If this function is called
+// twice in a row, then 'redraw' should be false and redrawcmd() should be
+// called afterwards.
void put_on_cmdline(char_u *str, int len, int redraw)
{
int i;
@@ -3422,7 +3408,7 @@ void put_on_cmdline(char_u *str, int len, int redraw)
// Count nr of bytes in cmdline that are overwritten by these
// characters.
for (i = ccline.cmdpos; i < ccline.cmdlen && m > 0;
- i += utfc_ptr2len((char *)ccline.cmdbuff + i)) {
+ i += utfc_ptr2len(ccline.cmdbuff + i)) {
m--;
}
if (i < ccline.cmdlen) {
@@ -3440,17 +3426,17 @@ void put_on_cmdline(char_u *str, int len, int redraw)
// When the inserted text starts with a composing character,
// backup to the character before it. There could be two of them.
i = 0;
- c = utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos);
+ c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
while (ccline.cmdpos > 0 && utf_iscomposing(c)) {
- i = utf_head_off((char *)ccline.cmdbuff, (char *)ccline.cmdbuff + ccline.cmdpos - 1) + 1;
+ i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos - 1) + 1;
ccline.cmdpos -= i;
len += i;
- c = utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos);
+ c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
}
if (i == 0 && ccline.cmdpos > 0 && arabic_maycombine(c)) {
// Check the previous character for Arabic combining pair.
- i = utf_head_off((char *)ccline.cmdbuff, (char *)ccline.cmdbuff + ccline.cmdpos - 1) + 1;
- if (arabic_combine(utf_ptr2char((char *)ccline.cmdbuff + ccline.cmdpos - i), c)) {
+ i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos - 1) + 1;
+ if (arabic_combine(utf_ptr2char(ccline.cmdbuff + ccline.cmdpos - i), c)) {
ccline.cmdpos -= i;
len += i;
} else {
@@ -3459,7 +3445,7 @@ void put_on_cmdline(char_u *str, int len, int redraw)
}
if (i != 0) {
// Also backup the cursor position.
- i = ptr2cells((char *)ccline.cmdbuff + ccline.cmdpos);
+ i = ptr2cells(ccline.cmdbuff + ccline.cmdpos);
ccline.cmdspos -= i;
msg_col -= i;
if (msg_col < 0) {
@@ -3498,7 +3484,7 @@ void put_on_cmdline(char_u *str, int len, int redraw)
if (ccline.cmdspos + c < m) {
ccline.cmdspos += c;
}
- c = utfc_ptr2len((char *)ccline.cmdbuff + ccline.cmdpos) - 1;
+ c = utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos) - 1;
if (c > len - i - 1) {
c = len - i - 1;
}
@@ -3580,14 +3566,14 @@ static bool cmdline_paste(int regname, bool literally, bool remcr)
int len;
// Locate start of last word in the cmd buffer.
- for (w = ccline.cmdbuff + ccline.cmdpos; w > ccline.cmdbuff;) {
- len = utf_head_off((char *)ccline.cmdbuff, (char *)w - 1) + 1;
+ for (w = (char_u *)ccline.cmdbuff + ccline.cmdpos; w > (char_u *)ccline.cmdbuff;) {
+ len = utf_head_off(ccline.cmdbuff, (char *)w - 1) + 1;
if (!vim_iswordc(utf_ptr2char((char *)w - len))) {
break;
}
w -= len;
}
- len = (int)((ccline.cmdbuff + ccline.cmdpos) - w);
+ len = (int)(((char_u *)ccline.cmdbuff + ccline.cmdpos) - w);
if (p_ic ? STRNICMP(w, arg, len) == 0 : STRNCMP(w, arg, len) == 0) {
p += len;
}
@@ -3603,12 +3589,10 @@ static bool cmdline_paste(int regname, bool literally, bool remcr)
return cmdline_paste_reg(regname, literally, remcr);
}
-/*
- * Put a string on the command line.
- * When "literally" is true, insert literally.
- * When "literally" is false, insert as typed, but don't leave the command
- * line.
- */
+// Put a string on the command line.
+// When "literally" is true, insert literally.
+// When "literally" is false, insert as typed, but don't leave the command
+// line.
void cmdline_paste_str(char_u *s, int literally)
{
int c, cv;
@@ -3675,9 +3659,7 @@ static void redrawcmdprompt(void)
}
}
-/*
- * Redraw what is currently on the command line.
- */
+// Redraw what is currently on the command line.
void redrawcmd(void)
{
if (cmd_silent) {
@@ -3714,10 +3696,8 @@ void redrawcmd(void)
putcmdline(ccline.special_char, ccline.special_shift);
}
- /*
- * An emsg() before may have set msg_scroll. This is used in normal mode,
- * in cmdline mode we can reset them now.
- */
+ // An emsg() before may have set msg_scroll. This is used in normal mode,
+ // in cmdline mode we can reset them now.
msg_scroll = false; // next message overwrites cmdline
// Typing ':' at the more prompt may set skip_redraw. We don't want this
@@ -3794,12 +3774,10 @@ void gotocmdline(bool clr)
cmd_cursor_goto(cmdline_row, 0);
}
-/*
- * Check the word in front of the cursor for an abbreviation.
- * Called when the non-id character "c" has been entered.
- * When an abbreviation is recognized it is removed from the text with
- * backspaces and the replacement string is inserted, followed by "c".
- */
+// Check the word in front of the cursor for an abbreviation.
+// Called when the non-id character "c" has been entered.
+// When an abbreviation is recognized it is removed from the text with
+// backspaces and the replacement string is inserted, followed by "c".
static int ccheck_abbr(int c)
{
int spos = 0;
@@ -3823,7 +3801,7 @@ static int ccheck_abbr(int c)
spos = 0;
}
- return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, spos);
+ return check_abbr(c, (char_u *)ccline.cmdbuff, ccline.cmdpos, spos);
}
/// Escape special characters in "fname", depending on "what":
@@ -3964,7 +3942,7 @@ static char *get_cmdline_str(void)
if (p == NULL) {
return NULL;
}
- return (char *)vim_strnsave(p->cmdbuff, (size_t)p->cmdlen);
+ return xstrnsave(p->cmdbuff, (size_t)p->cmdlen);
}
/// Get the current command-line completion type.
@@ -4126,7 +4104,7 @@ int get_list_range(char **str, int *num1, int *num2)
*str = skipwhite((*str));
if (**str == '-' || ascii_isdigit(**str)) { // parse "from" part of range
- vim_str2nr((char_u *)(*str), NULL, &len, 0, &num, NULL, 0, false);
+ vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false);
*str += len;
*num1 = (int)num;
first = true;
@@ -4134,7 +4112,7 @@ int get_list_range(char **str, int *num1, int *num2)
*str = skipwhite((*str));
if (**str == ',') { // parse "to" part of range
*str = skipwhite((*str) + 1);
- vim_str2nr((char_u *)(*str), NULL, &len, 0, &num, NULL, 0, false);
+ vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false);
if (len > 0) {
*num2 = (int)num;
*str = skipwhite((*str) + len);
@@ -4270,7 +4248,7 @@ static int open_cmdwin(void)
i = 0;
}
if (get_histentry(histtype)[i].hisstr != NULL) {
- ml_append(lnum++, (char *)get_histentry(histtype)[i].hisstr, (colnr_T)0, false);
+ ml_append(lnum++, get_histentry(histtype)[i].hisstr, (colnr_T)0, false);
}
} while (i != *get_hisidx(histtype));
}
@@ -4278,7 +4256,7 @@ static int open_cmdwin(void)
// Replace the empty last line with the current command-line and put the
// cursor there.
- ml_replace(curbuf->b_ml.ml_line_count, (char *)ccline.cmdbuff, true);
+ ml_replace(curbuf->b_ml.ml_line_count, ccline.cmdbuff, true);
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
curwin->w_cursor.col = ccline.cmdpos;
changed_line_abv_curs();
@@ -4310,9 +4288,7 @@ static int open_cmdwin(void)
RedrawingDisabled = 0;
int save_count = save_batch_count();
- /*
- * Call the main loop until <CR> or CTRL-C is typed.
- */
+ // Call the main loop until <CR> or CTRL-C is typed.
normal_enter(true, false);
RedrawingDisabled = i;
@@ -4348,7 +4324,7 @@ static int open_cmdwin(void)
if (histtype == HIST_CMD) {
// Execute the command directly.
- ccline.cmdbuff = (char_u *)xstrdup(p);
+ ccline.cmdbuff = xstrdup(p);
cmdwin_result = CAR;
} else {
// First need to cancel what we were doing.
@@ -4362,10 +4338,10 @@ static int open_cmdwin(void)
// and don't modify the cmd window.
ccline.cmdbuff = NULL;
} else {
- ccline.cmdbuff = vim_strsave(get_cursor_line_ptr());
+ ccline.cmdbuff = xstrdup(get_cursor_line_ptr());
}
if (ccline.cmdbuff == NULL) {
- ccline.cmdbuff = vim_strsave((char_u *)"");
+ ccline.cmdbuff = xstrdup("");
ccline.cmdlen = 0;
ccline.cmdbufflen = 1;
ccline.cmdpos = 0;
diff --git a/src/nvim/ex_getln.h b/src/nvim/ex_getln.h
index 5e3ad20a31..919a6c8f11 100644
--- a/src/nvim/ex_getln.h
+++ b/src/nvim/ex_getln.h
@@ -41,7 +41,7 @@ typedef enum {
/// structure.
typedef struct cmdline_info CmdlineInfo;
struct cmdline_info {
- char_u *cmdbuff; ///< pointer to command line buffer
+ char *cmdbuff; ///< pointer to command line buffer
int cmdbufflen; ///< length of cmdbuff
int cmdlen; ///< number of chars in command line
int cmdpos; ///< current cursor position
diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c
index 8e780f4aaa..290d20b749 100644
--- a/src/nvim/extmark.c
+++ b/src/nvim/extmark.c
@@ -70,7 +70,8 @@ void extmark_set(buf_T *buf, uint32_t ns_id, uint32_t *idp, int row, colnr_T col
|| kv_size(decor->virt_lines)
|| decor->conceal
|| decor_has_sign(decor)
- || decor->ui_watched) {
+ || decor->ui_watched
+ || decor->spell) {
decor_full = true;
decor = xmemdup(decor, sizeof *decor);
}
diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c
index e87e0853f3..b3491e98c2 100644
--- a/src/nvim/file_search.c
+++ b/src/nvim/file_search.c
@@ -69,17 +69,14 @@
#include "nvim/vim.h"
#include "nvim/window.h"
-static char_u *ff_expand_buffer = NULL; // used for expanding filenames
+static char *ff_expand_buffer = NULL; // used for expanding filenames
-/*
- * type for the directory search stack
- */
+// type for the directory search stack
typedef struct ff_stack {
struct ff_stack *ffs_prev;
- /* the fix part (no wildcards) and the part containing the wildcards
- * of the search path
- */
+ // the fix part (no wildcards) and the part containing the wildcards
+ // of the search path
char_u *ffs_fix_path;
char_u *ffs_wc_path;
@@ -89,97 +86,87 @@ typedef struct ff_stack {
int ffs_filearray_size;
int ffs_filearray_cur; // needed for partly handled dirs
- /* to store status of partly handled directories
- * 0: we work on this directory for the first time
- * 1: this directory was partly searched in an earlier step
- */
+ // to store status of partly handled directories
+ // 0: we work on this directory for the first time
+ // 1: this directory was partly searched in an earlier step
int ffs_stage;
- /* How deep are we in the directory tree?
- * Counts backward from value of level parameter to vim_findfile_init
- */
+ // How deep are we in the directory tree?
+ // Counts backward from value of level parameter to vim_findfile_init
int ffs_level;
// Did we already expand '**' to an empty string?
int ffs_star_star_empty;
} ff_stack_T;
-/*
- * type for already visited directories or files.
- */
+// type for already visited directories or files.
typedef struct ff_visited {
struct ff_visited *ffv_next;
// Visited directories are different if the wildcard string are
// different. So we have to save it.
- char_u *ffv_wc_path;
+ char *ffv_wc_path;
// use FileID for comparison (needed because of links), else use filename.
bool file_id_valid;
FileID file_id;
// The memory for this struct is allocated according to the length of
// ffv_fname.
- char_u ffv_fname[1]; // actually longer
+ char ffv_fname[1]; // actually longer
} ff_visited_T;
-/*
- * We might have to manage several visited lists during a search.
- * This is especially needed for the tags option. If tags is set to:
- * "./++/tags,./++/TAGS,++/tags" (replace + with *)
- * So we have to do 3 searches:
- * 1) search from the current files directory downward for the file "tags"
- * 2) search from the current files directory downward for the file "TAGS"
- * 3) search from Vims current directory downwards for the file "tags"
- * As you can see, the first and the third search are for the same file, so for
- * the third search we can use the visited list of the first search. For the
- * second search we must start from an empty visited list.
- * The struct ff_visited_list_hdr is used to manage a linked list of already
- * visited lists.
- */
+// We might have to manage several visited lists during a search.
+// This is especially needed for the tags option. If tags is set to:
+// "./++/tags,./++/TAGS,++/tags" (replace + with *)
+// So we have to do 3 searches:
+// 1) search from the current files directory downward for the file "tags"
+// 2) search from the current files directory downward for the file "TAGS"
+// 3) search from Vims current directory downwards for the file "tags"
+// As you can see, the first and the third search are for the same file, so for
+// the third search we can use the visited list of the first search. For the
+// second search we must start from an empty visited list.
+// The struct ff_visited_list_hdr is used to manage a linked list of already
+// visited lists.
typedef struct ff_visited_list_hdr {
struct ff_visited_list_hdr *ffvl_next;
// the filename the attached visited list is for
- char_u *ffvl_filename;
+ char *ffvl_filename;
ff_visited_T *ffvl_visited_list;
} ff_visited_list_hdr_T;
-/*
- * '**' can be expanded to several directory levels.
- * Set the default maximum depth.
- */
+// '**' can be expanded to several directory levels.
+// Set the default maximum depth.
#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
-/*
- * The search context:
- * ffsc_stack_ptr: the stack for the dirs to search
- * ffsc_visited_list: the currently active visited list
- * ffsc_dir_visited_list: the currently active visited list for search dirs
- * ffsc_visited_lists_list: the list of all visited lists
- * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
- * ffsc_file_to_search: the file to search for
- * ffsc_start_dir: the starting directory, if search path was relative
- * ffsc_fix_path: the fix part of the given path (without wildcards)
- * Needed for upward search.
- * ffsc_wc_path: the part of the given path containing wildcards
- * ffsc_level: how many levels of dirs to search downwards
- * ffsc_stopdirs_v: array of stop directories for upward search
- * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
- * ffsc_tagfile: searching for tags file, don't use 'suffixesadd'
- */
+// The search context:
+// ffsc_stack_ptr: the stack for the dirs to search
+// ffsc_visited_list: the currently active visited list
+// ffsc_dir_visited_list: the currently active visited list for search dirs
+// ffsc_visited_lists_list: the list of all visited lists
+// ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
+// ffsc_file_to_search: the file to search for
+// ffsc_start_dir: the starting directory, if search path was relative
+// ffsc_fix_path: the fix part of the given path (without wildcards)
+// Needed for upward search.
+// ffsc_wc_path: the part of the given path containing wildcards
+// ffsc_level: how many levels of dirs to search downwards
+// ffsc_stopdirs_v: array of stop directories for upward search
+// ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
+// ffsc_tagfile: searching for tags file, don't use 'suffixesadd'
typedef struct ff_search_ctx_T {
ff_stack_T *ffsc_stack_ptr;
ff_visited_list_hdr_T *ffsc_visited_list;
ff_visited_list_hdr_T *ffsc_dir_visited_list;
ff_visited_list_hdr_T *ffsc_visited_lists_list;
ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
- char_u *ffsc_file_to_search;
- char_u *ffsc_start_dir;
- char_u *ffsc_fix_path;
- char_u *ffsc_wc_path;
+ char *ffsc_file_to_search;
+ char *ffsc_start_dir;
+ char *ffsc_fix_path;
+ char *ffsc_wc_path;
int ffsc_level;
- char_u **ffsc_stopdirs_v;
+ char **ffsc_stopdirs_v;
int ffsc_find_what;
int ffsc_tagfile;
} ff_search_ctx_T;
@@ -245,17 +232,15 @@ static char_u e_pathtoolong[] = N_("E854: path too long for completion");
///
/// @param tagfile expanding names of tags files
/// @param rel_fname file name to use for "."
-void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int level,
- int free_visited, int find_what, void *search_ctx_arg, int tagfile,
- char_u *rel_fname)
+void *vim_findfile_init(char *path, char *filename, char *stopdirs, int level, int free_visited,
+ int find_what, void *search_ctx_arg, int tagfile, char *rel_fname)
{
- char_u *wc_part;
+ char *wc_part;
ff_stack_T *sptr;
ff_search_ctx_T *search_ctx;
- /* If a search context is given by the caller, reuse it, else allocate a
- * new one.
- */
+ // If a search context is given by the caller, reuse it, else allocate a
+ // new one.
if (search_ctx_arg != NULL) {
search_ctx = search_ctx_arg;
} else {
@@ -271,9 +256,9 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
if (free_visited == true) {
vim_findfile_free_visited(search_ctx);
} else {
- /* Reuse old visited lists. Get the visited list for the given
- * filename. If no list for the current filename exists, creates a new
- * one. */
+ // Reuse old visited lists. Get the visited list for the given
+ // filename. If no list for the current filename exists, creates a new
+ // one.
search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
&search_ctx->ffsc_visited_lists_list);
if (search_ctx->ffsc_visited_list == NULL) {
@@ -290,25 +275,25 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
ff_expand_buffer = xmalloc(MAXPATHL);
}
- /* Store information on starting dir now if path is relative.
- * If path is absolute, we do that later. */
+ // Store information on starting dir now if path is relative.
+ // If path is absolute, we do that later.
if (path[0] == '.'
&& (vim_ispathsep(path[1]) || path[1] == NUL)
&& (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
&& rel_fname != NULL) {
- size_t len = (size_t)((char_u *)path_tail((char *)rel_fname) - rel_fname);
+ size_t len = (size_t)(path_tail(rel_fname) - rel_fname);
- if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL) {
+ if (!vim_isAbsName((char_u *)rel_fname) && len + 1 < MAXPATHL) {
// Make the start dir an absolute path name.
STRLCPY(ff_expand_buffer, rel_fname, len + 1);
- search_ctx->ffsc_start_dir = (char_u *)FullName_save((char *)ff_expand_buffer, false);
+ search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, false);
} else {
- search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
+ search_ctx->ffsc_start_dir = xstrnsave(rel_fname, len);
}
if (*++path != NUL) {
path++;
}
- } else if (*path == NUL || !vim_isAbsName(path)) {
+ } else if (*path == NUL || !vim_isAbsName((char_u *)path)) {
#ifdef BACKSLASH_IN_FILENAME
// "c:dir" needs "c:" to be expanded, otherwise use current dir
if (*path != NUL && path[1] == ':') {
@@ -325,15 +310,15 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
path += 2;
} else
#endif
- if (os_dirname(ff_expand_buffer, MAXPATHL) == FAIL) {
+ if (os_dirname((char_u *)ff_expand_buffer, MAXPATHL) == FAIL) {
goto error_return;
}
- search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
+ search_ctx->ffsc_start_dir = xstrdup(ff_expand_buffer);
#ifdef BACKSLASH_IN_FILENAME
- /* A path that starts with "/dir" is relative to the drive, not to the
- * directory (but not for "//machine/dir"). Only use the drive name. */
+ // A path that starts with "/dir" is relative to the drive, not to the
+ // directory (but not for "//machine/dir"). Only use the drive name.
if ((*path == '/' || *path == '\\')
&& path[1] != path[0]
&& search_ctx->ffsc_start_dir[1] == ':') {
@@ -342,17 +327,15 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
#endif
}
- /*
- * If stopdirs are given, split them into an array of pointers.
- * If this fails (mem allocation), there is no upward search at all or a
- * stop directory is not recognized -> continue silently.
- * If stopdirs just contains a ";" or is empty,
- * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
- * is handled as unlimited upward search. See function
- * ff_path_in_stoplist() for details.
- */
+ // If stopdirs are given, split them into an array of pointers.
+ // If this fails (mem allocation), there is no upward search at all or a
+ // stop directory is not recognized -> continue silently.
+ // If stopdirs just contains a ";" or is empty,
+ // search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
+ // is handled as unlimited upward search. See function
+ // ff_path_in_stoplist() for details.
if (stopdirs != NULL) {
- char_u *walker = stopdirs;
+ char *walker = stopdirs;
while (*walker == ';') {
walker++;
@@ -362,25 +345,21 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
search_ctx->ffsc_stopdirs_v = xmalloc(sizeof(char_u *));
do {
- char_u *helper;
+ char *helper;
void *ptr;
helper = walker;
ptr = xrealloc(search_ctx->ffsc_stopdirs_v,
(dircount + 1) * sizeof(char_u *));
search_ctx->ffsc_stopdirs_v = ptr;
- walker = (char_u *)vim_strchr((char *)walker, ';');
+ walker = vim_strchr(walker, ';');
if (walker) {
assert(walker - helper >= 0);
- search_ctx->ffsc_stopdirs_v[dircount - 1] =
- vim_strnsave(helper, (size_t)(walker - helper));
+ search_ctx->ffsc_stopdirs_v[dircount - 1] = xstrnsave(helper, (size_t)(walker - helper));
walker++;
} else {
- /* this might be "", which means ascent till top
- * of directory tree.
- */
- search_ctx->ffsc_stopdirs_v[dircount - 1] =
- vim_strsave(helper);
+ // this might be "", which means ascent till top of directory tree.
+ search_ctx->ffsc_stopdirs_v[dircount - 1] = xstrdup(helper);
}
dircount++;
@@ -390,11 +369,10 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
search_ctx->ffsc_level = level;
- /* split into:
- * -fix path
- * -wildcard_stuff (might be NULL)
- */
- wc_part = (char_u *)vim_strchr((char *)path, '*');
+ // split into:
+ // -fix path
+ // -wildcard_stuff (might be NULL)
+ wc_part = vim_strchr(path, '*');
if (wc_part != NULL) {
int64_t llevel;
int len;
@@ -402,17 +380,15 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
// save the fix part of the path
assert(wc_part - path >= 0);
- search_ctx->ffsc_fix_path = vim_strnsave(path, (size_t)(wc_part - path));
-
- /*
- * copy wc_path and add restricts to the '**' wildcard.
- * The octet after a '**' is used as a (binary) counter.
- * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
- * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
- * If no restrict is given after '**' the default is used.
- * Due to this technique the path looks awful if you print it as a
- * string.
- */
+ search_ctx->ffsc_fix_path = xstrnsave(path, (size_t)(wc_part - path));
+
+ // copy wc_path and add restricts to the '**' wildcard.
+ // The octet after a '**' is used as a (binary) counter.
+ // So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
+ // or '**76' is transposed to '**N'( 'N' is ASCII value 76).
+ // If no restrict is given after '**' the default is used.
+ // Due to this technique the path looks awful if you print it as a
+ // string.
len = 0;
while (*wc_part != NUL) {
if (len + 5 >= MAXPATHL) {
@@ -423,16 +399,16 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
ff_expand_buffer[len++] = *wc_part++;
ff_expand_buffer[len++] = *wc_part++;
- llevel = strtol((char *)wc_part, &errpt, 10);
- if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255) {
- ff_expand_buffer[len++] = (char_u)llevel;
- } else if ((char_u *)errpt != wc_part && llevel == 0) {
+ llevel = strtol(wc_part, &errpt, 10);
+ if (errpt != wc_part && llevel > 0 && llevel < 255) {
+ ff_expand_buffer[len++] = (char)llevel;
+ } else if (errpt != wc_part && llevel == 0) {
// restrict is 0 -> remove already added '**'
len -= 2;
} else {
ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
}
- wc_part = (char_u *)errpt;
+ wc_part = errpt;
if (*wc_part != NUL && !vim_ispathsep(*wc_part)) {
semsg(_(
"E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."),
@@ -444,16 +420,15 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
}
}
ff_expand_buffer[len] = NUL;
- search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
+ search_ctx->ffsc_wc_path = xstrdup(ff_expand_buffer);
} else {
- search_ctx->ffsc_fix_path = vim_strsave(path);
+ search_ctx->ffsc_fix_path = xstrdup(path);
}
if (search_ctx->ffsc_start_dir == NULL) {
- /* store the fix part as startdir.
- * This is needed if the parameter path is fully qualified.
- */
- search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
+ // store the fix part as startdir.
+ // This is needed if the parameter path is fully qualified.
+ search_ctx->ffsc_start_dir = xstrdup(search_ctx->ffsc_fix_path);
search_ctx->ffsc_fix_path[0] = NUL;
}
@@ -464,7 +439,7 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
goto error_return;
}
STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
- add_pathsep((char *)ff_expand_buffer);
+ add_pathsep(ff_expand_buffer);
{
size_t eb_len = STRLEN(ff_expand_buffer);
char_u *buf = xmalloc(eb_len + STRLEN(search_ctx->ffsc_fix_path) + 1);
@@ -473,11 +448,11 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
STRCPY(buf + eb_len, search_ctx->ffsc_fix_path);
if (os_isdir((char *)buf)) {
STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
- add_pathsep((char *)ff_expand_buffer);
+ add_pathsep(ff_expand_buffer);
} else {
- char_u *p = (char_u *)path_tail((char *)search_ctx->ffsc_fix_path);
- char_u *wc_path = NULL;
- char_u *temp = NULL;
+ char *p = path_tail(search_ctx->ffsc_fix_path);
+ char *wc_path = NULL;
+ char *temp = NULL;
int len = 0;
if (p > search_ctx->ffsc_fix_path) {
@@ -488,14 +463,14 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
xfree(buf);
goto error_return;
}
- STRLCAT(ff_expand_buffer, search_ctx->ffsc_fix_path, eb_len + (size_t)len + 1);
- add_pathsep((char *)ff_expand_buffer);
+ xstrlcat(ff_expand_buffer, search_ctx->ffsc_fix_path, eb_len + (size_t)len + 1);
+ add_pathsep(ff_expand_buffer);
} else {
len = (int)STRLEN(search_ctx->ffsc_fix_path);
}
if (search_ctx->ffsc_wc_path != NULL) {
- wc_path = vim_strsave(search_ctx->ffsc_wc_path);
+ wc_path = xstrdup(search_ctx->ffsc_wc_path);
temp = xmalloc(STRLEN(search_ctx->ffsc_wc_path)
+ STRLEN(search_ctx->ffsc_fix_path + len)
+ 1);
@@ -512,15 +487,13 @@ void *vim_findfile_init(char_u *path, char_u *filename, char_u *stopdirs, int le
sptr = ff_create_stack_element(ff_expand_buffer, search_ctx->ffsc_wc_path, level, 0);
ff_push(search_ctx, sptr);
- search_ctx->ffsc_file_to_search = vim_strsave(filename);
+ search_ctx->ffsc_file_to_search = xstrdup(filename);
return search_ctx;
error_return:
- /*
- * We clear the search context now!
- * Even when the caller gave us a (perhaps valid) context we free it here,
- * as we might have already destroyed it.
- */
+ // We clear the search context now!
+ // Even when the caller gave us a (perhaps valid) context we free it here,
+ // as we might have already destroyed it.
vim_findfile_cleanup(search_ctx);
return NULL;
}
@@ -532,8 +505,8 @@ char_u *vim_findfile_stopdir(char_u *buf)
while (*r_ptr != NUL && *r_ptr != ';') {
if (r_ptr[0] == '\\' && r_ptr[1] == ';') {
- /* Overwrite the escape char,
- * use STRLEN(r_ptr) to move the trailing '\0'. */
+ // Overwrite the escape char,
+ // use STRLEN(r_ptr) to move the trailing '\0'.
STRMOVE(r_ptr, r_ptr + 1);
r_ptr++;
}
@@ -590,16 +563,13 @@ char_u *vim_findfile(void *search_ctx_arg)
search_ctx = (ff_search_ctx_T *)search_ctx_arg;
- /*
- * filepath is used as buffer for various actions and as the storage to
- * return a found filename.
- */
+ // filepath is used as buffer for various actions and as the storage to
+ // return a found filename.
file_path = xmalloc(MAXPATHL);
// store the end of the start dir -- needed for upward search
if (search_ctx->ffsc_start_dir != NULL) {
- path_end = &search_ctx->ffsc_start_dir[
- STRLEN(search_ctx->ffsc_start_dir)];
+ path_end = (char_u *)&search_ctx->ffsc_start_dir[STRLEN(search_ctx->ffsc_start_dir)];
}
// upward search loop
@@ -618,28 +588,26 @@ char_u *vim_findfile(void *search_ctx_arg)
break;
}
- /*
- * TODO: decide if we leave this test in
- *
- * GOOD: don't search a directory(-tree) twice.
- * BAD: - check linked list for every new directory entered.
- * - check for double files also done below
- *
- * Here we check if we already searched this directory.
- * We already searched a directory if:
- * 1) The directory is the same.
- * 2) We would use the same wildcard string.
- *
- * Good if you have links on same directory via several ways
- * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
- * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
- *
- * This check is only needed for directories we work on for the
- * first time (hence stackp->ff_filearray == NULL)
- */
+ // TODO(vim): decide if we leave this test in
+ //
+ // GOOD: don't search a directory(-tree) twice.
+ // BAD: - check linked list for every new directory entered.
+ // - check for double files also done below
+ //
+ // Here we check if we already searched this directory.
+ // We already searched a directory if:
+ // 1) The directory is the same.
+ // 2) We would use the same wildcard string.
+ //
+ // Good if you have links on same directory via several ways
+ // or you have selfreferences in directories (e.g. SuSE Linux 6.3:
+ // /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
+ //
+ // This check is only needed for directories we work on for the
+ // first time (hence stackp->ff_filearray == NULL)
if (stackp->ffs_filearray == NULL
&& ff_check_visited(&search_ctx->ffsc_dir_visited_list->ffvl_visited_list,
- stackp->ffs_fix_path, stackp->ffs_wc_path) == FAIL) {
+ (char *)stackp->ffs_fix_path, (char *)stackp->ffs_wc_path) == FAIL) {
#ifdef FF_VERBOSE
if (p_verbose >= 5) {
verbose_enter_scroll();
@@ -670,18 +638,14 @@ char_u *vim_findfile(void *search_ctx_arg)
file_path[0] = NUL;
- /*
- * If no filearray till now expand wildcards
- * The function expand_wildcards() can handle an array of paths
- * and all possible expands are returned in one array. We use this
- * to handle the expansion of '**' into an empty string.
- */
+ // If no filearray till now expand wildcards
+ // The function expand_wildcards() can handle an array of paths
+ // and all possible expands are returned in one array. We use this
+ // to handle the expansion of '**' into an empty string.
if (stackp->ffs_filearray == NULL) {
char *dirptrs[2];
- /* we use filepath to build the path expand_wildcards() should
- * expand.
- */
+ // we use filepath to build the path expand_wildcards() should expand.
dirptrs[0] = (char *)file_path;
dirptrs[1] = NULL;
@@ -741,13 +705,11 @@ char_u *vim_findfile(void *search_ctx_arg)
}
}
- /*
- * Here we copy until the next path separator or the end of
- * the path. If we stop at a path separator, there is
- * still something else left. This is handled below by
- * pushing every directory returned from expand_wildcards()
- * on the stack again for further search.
- */
+ // Here we copy until the next path separator or the end of
+ // the path. If we stop at a path separator, there is
+ // still something else left. This is handled below by
+ // pushing every directory returned from expand_wildcards()
+ // on the stack again for further search.
while (*rest_of_wildcards
&& !vim_ispathsep(*rest_of_wildcards)) {
if (len + 1 >= MAXPATHL) {
@@ -763,18 +725,16 @@ char_u *vim_findfile(void *search_ctx_arg)
}
}
- /*
- * Expand wildcards like "*" and "$VAR".
- * If the path is a URL don't try this.
- */
+ // Expand wildcards like "*" and "$VAR".
+ // If the path is a URL don't try this.
if (path_with_url(dirptrs[0])) {
stackp->ffs_filearray = xmalloc(sizeof(char *));
stackp->ffs_filearray[0] = xstrdup(dirptrs[0]);
stackp->ffs_filearray_size = 1;
} else {
- /* Add EW_NOTWILD because the expanded path may contain
- * wildcard characters that are to be taken literally.
- * This is a bit of a hack. */
+ // Add EW_NOTWILD because the expanded path may contain
+ // wildcard characters that are to be taken literally.
+ // This is a bit of a hack.
expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
&stackp->ffs_filearray_size,
&stackp->ffs_filearray,
@@ -790,10 +750,8 @@ char_u *vim_findfile(void *search_ctx_arg)
if (stackp->ffs_stage == 0) {
// this is the first time we work on this directory
if (*rest_of_wildcards == NUL) {
- /*
- * We don't have further wildcards to expand, so we have to
- * check for the final file now.
- */
+ // We don't have further wildcards to expand, so we have to
+ // check for the final file now.
for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) {
if (!path_with_url(stackp->ffs_filearray[i])
&& !os_isdir(stackp->ffs_filearray[i])) {
@@ -812,10 +770,8 @@ char_u *vim_findfile(void *search_ctx_arg)
}
STRCAT(file_path, search_ctx->ffsc_file_to_search);
- /*
- * Try without extra suffix and then with suffixes
- * from 'suffixesadd'.
- */
+ // Try without extra suffix and then with suffixes
+ // from 'suffixesadd'.
len = STRLEN(file_path);
if (search_ctx->ffsc_tagfile) {
suf = "";
@@ -831,7 +787,7 @@ char_u *vim_findfile(void *search_ctx_arg)
== os_isdir((char *)file_path)))))
#ifndef FF_VERBOSE
&& (ff_check_visited(&search_ctx->ffsc_visited_list->ffvl_visited_list,
- file_path, (char_u *)"") == OK)
+ (char *)file_path, "") == OK)
#endif
) {
#ifdef FF_VERBOSE
@@ -855,10 +811,9 @@ char_u *vim_findfile(void *search_ctx_arg)
if (!path_with_url((char *)file_path)) {
simplify_filename(file_path);
}
- if (os_dirname(ff_expand_buffer, MAXPATHL)
+ if (os_dirname((char_u *)ff_expand_buffer, MAXPATHL)
== OK) {
- p = path_shorten_fname(file_path,
- ff_expand_buffer);
+ p = (char_u *)path_shorten_fname((char *)file_path, ff_expand_buffer);
if (p != NULL) {
STRMOVE(file_path, p);
}
@@ -889,8 +844,8 @@ char_u *vim_findfile(void *search_ctx_arg)
continue; // not a directory
}
ff_push(search_ctx,
- ff_create_stack_element((char_u *)stackp->ffs_filearray[i],
- rest_of_wildcards,
+ ff_create_stack_element(stackp->ffs_filearray[i],
+ (char *)rest_of_wildcards,
stackp->ffs_level - 1, 0));
}
}
@@ -898,23 +853,21 @@ char_u *vim_findfile(void *search_ctx_arg)
stackp->ffs_stage = 1;
}
- /*
- * if wildcards contains '**' we have to descent till we reach the
- * leaves of the directory tree.
- */
+ // if wildcards contains '**' we have to descent till we reach the
+ // leaves of the directory tree.
if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0) {
for (int i = stackp->ffs_filearray_cur;
i < stackp->ffs_filearray_size; i++) {
- if (FNAMECMP(stackp->ffs_filearray[i],
- stackp->ffs_fix_path) == 0) {
+ if (path_fnamecmp(stackp->ffs_filearray[i],
+ (char *)stackp->ffs_fix_path) == 0) {
continue; // don't repush same directory
}
if (!os_isdir(stackp->ffs_filearray[i])) {
continue; // not a directory
}
ff_push(search_ctx,
- ff_create_stack_element((char_u *)stackp->ffs_filearray[i],
- stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
+ ff_create_stack_element(stackp->ffs_filearray[i],
+ (char *)stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
}
}
@@ -922,27 +875,24 @@ char_u *vim_findfile(void *search_ctx_arg)
ff_free_stack_element(stackp);
}
- /* If we reached this, we didn't find anything downwards.
- * Let's check if we should do an upward search.
- */
+ // If we reached this, we didn't find anything downwards.
+ // Let's check if we should do an upward search.
if (search_ctx->ffsc_start_dir
&& search_ctx->ffsc_stopdirs_v != NULL && !got_int) {
ff_stack_T *sptr;
// is the last starting directory in the stop list?
if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
- (int)(path_end - search_ctx->ffsc_start_dir),
+ (int)(path_end - (char_u *)search_ctx->ffsc_start_dir),
search_ctx->ffsc_stopdirs_v) == true) {
break;
}
// cut of last dir
- while (path_end > search_ctx->ffsc_start_dir
- && vim_ispathsep(*path_end)) {
+ while (path_end > (char_u *)search_ctx->ffsc_start_dir && vim_ispathsep(*path_end)) {
path_end--;
}
- while (path_end > search_ctx->ffsc_start_dir
- && !vim_ispathsep(path_end[-1])) {
+ while (path_end > (char_u *)search_ctx->ffsc_start_dir && !vim_ispathsep(path_end[-1])) {
path_end--;
}
*path_end = 0;
@@ -963,7 +913,7 @@ char_u *vim_findfile(void *search_ctx_arg)
STRCAT(file_path, search_ctx->ffsc_fix_path);
// create a new stack entry
- sptr = ff_create_stack_element(file_path,
+ sptr = ff_create_stack_element((char *)file_path,
search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
ff_push(search_ctx, sptr);
} else {
@@ -1021,7 +971,7 @@ static void ff_free_visited_list(ff_visited_T *vl)
/// @return the already visited list for the given filename. If none is found it
/// allocates a new one.
-static ff_visited_list_hdr_T *ff_get_visited_list(char_u *filename,
+static ff_visited_list_hdr_T *ff_get_visited_list(char *filename,
ff_visited_list_hdr_T **list_headp)
{
ff_visited_list_hdr_T *retptr = NULL;
@@ -1030,7 +980,7 @@ static ff_visited_list_hdr_T *ff_get_visited_list(char_u *filename,
if (*list_headp != NULL) {
retptr = *list_headp;
while (retptr != NULL) {
- if (FNAMECMP(filename, retptr->ffvl_filename) == 0) {
+ if (path_fnamecmp(filename, retptr->ffvl_filename) == 0) {
#ifdef FF_VERBOSE
if (p_verbose >= 5) {
verbose_enter_scroll();
@@ -1054,13 +1004,11 @@ static ff_visited_list_hdr_T *ff_get_visited_list(char_u *filename,
}
#endif
- /*
- * if we reach this we didn't find a list and we have to allocate new list
- */
+ // if we reach this we didn't find a list and we have to allocate new list
retptr = xmalloc(sizeof(*retptr));
retptr->ffvl_visited_list = NULL;
- retptr->ffvl_filename = vim_strsave(filename);
+ retptr->ffvl_filename = xstrdup(filename);
retptr->ffvl_next = *list_headp;
*list_headp = retptr;
@@ -1111,7 +1059,7 @@ static bool ff_wc_equal(char_u *s1, char_u *s2)
///
/// @return FAIL if the given file/dir is already in the list or,
/// OK if it is newly added
-static int ff_check_visited(ff_visited_T **visited_list, char_u *fname, char_u *wc_path)
+static int ff_check_visited(ff_visited_T **visited_list, char *fname, char *wc_path)
{
ff_visited_T *vp;
bool url = false;
@@ -1119,32 +1067,30 @@ static int ff_check_visited(ff_visited_T **visited_list, char_u *fname, char_u *
FileID file_id;
// For a URL we only compare the name, otherwise we compare the
// device/inode.
- if (path_with_url((char *)fname)) {
+ if (path_with_url(fname)) {
STRLCPY(ff_expand_buffer, fname, MAXPATHL);
url = true;
} else {
ff_expand_buffer[0] = NUL;
- if (!os_fileid((char *)fname, &file_id)) {
+ if (!os_fileid(fname, &file_id)) {
return FAIL;
}
}
// check against list of already visited files
for (vp = *visited_list; vp != NULL; vp = vp->ffv_next) {
- if ((url && FNAMECMP(vp->ffv_fname, ff_expand_buffer) == 0)
+ if ((url && path_fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0)
|| (!url && vp->file_id_valid
&& os_fileid_equal(&(vp->file_id), &file_id))) {
// are the wildcard parts equal
- if (ff_wc_equal(vp->ffv_wc_path, wc_path)) {
+ if (ff_wc_equal((char_u *)vp->ffv_wc_path, (char_u *)wc_path)) {
// already visited
return FAIL;
}
}
}
- /*
- * New file/dir. Add it to the list of visited files/dirs.
- */
+ // New file/dir. Add it to the list of visited files/dirs.
vp = xmalloc(sizeof(ff_visited_T) + STRLEN(ff_expand_buffer));
if (!url) {
@@ -1157,7 +1103,7 @@ static int ff_check_visited(ff_visited_T **visited_list, char_u *fname, char_u *
}
if (wc_path != NULL) {
- vp->ffv_wc_path = vim_strsave(wc_path);
+ vp->ffv_wc_path = xstrdup(wc_path);
} else {
vp->ffv_wc_path = NULL;
}
@@ -1169,7 +1115,7 @@ static int ff_check_visited(ff_visited_T **visited_list, char_u *fname, char_u *
}
/// create stack element from given path pieces
-static ff_stack_T *ff_create_stack_element(char_u *fix_part, char_u *wc_part, int level,
+static ff_stack_T *ff_create_stack_element(char *fix_part, char *wc_part, int level,
int star_star_empty)
{
ff_stack_T *new = xmalloc(sizeof(ff_stack_T));
@@ -1184,14 +1130,14 @@ static ff_stack_T *ff_create_stack_element(char_u *fix_part, char_u *wc_part, in
// the following saves NULL pointer checks in vim_findfile
if (fix_part == NULL) {
- fix_part = (char_u *)"";
+ fix_part = "";
}
- new->ffs_fix_path = vim_strsave(fix_part);
+ new->ffs_fix_path = (char_u *)xstrdup(fix_part);
if (wc_part == NULL) {
- wc_part = (char_u *)"";
+ wc_part = "";
}
- new->ffs_wc_path = vim_strsave(wc_part);
+ new->ffs_wc_path = (char_u *)xstrdup(wc_part);
return new;
}
@@ -1199,8 +1145,8 @@ static ff_stack_T *ff_create_stack_element(char_u *fix_part, char_u *wc_part, in
/// Push a dir on the directory stack.
static void ff_push(ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr)
{
- /* check for NULL pointer, not to return an error to the user, but
- * to prevent a crash */
+ // check for NULL pointer, not to return an error to the user, but
+ // to prevent a crash
if (stack_ptr != NULL) {
stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
search_ctx->ffsc_stack_ptr = stack_ptr;
@@ -1277,7 +1223,7 @@ static void ff_clear(ff_search_ctx_T *search_ctx)
/// check if the given path is in the stopdirs
///
/// @return true if yes else false
-static int ff_path_in_stoplist(char_u *path, int path_len, char_u **stopdirs_v)
+static int ff_path_in_stoplist(char *path, int path_len, char **stopdirs_v)
{
int i = 0;
@@ -1293,16 +1239,15 @@ static int ff_path_in_stoplist(char_u *path, int path_len, char_u **stopdirs_v)
for (i = 0; stopdirs_v[i] != NULL; i++) {
if ((int)STRLEN(stopdirs_v[i]) > path_len) {
- /* match for parent directory. So '/home' also matches
- * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
- * '/home/r' would also match '/home/rks'
- */
- if (FNAMENCMP(stopdirs_v[i], path, path_len) == 0
+ // match for parent directory. So '/home' also matches
+ // '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
+ // '/home/r' would also match '/home/rks'
+ if (path_fnamencmp(stopdirs_v[i], path, (size_t)path_len) == 0
&& vim_ispathsep(stopdirs_v[i][path_len])) {
return true;
}
} else {
- if (FNAMECMP(stopdirs_v[i], path) == 0) {
+ if (path_fnamecmp(stopdirs_v[i], path) == 0) {
return true;
}
}
@@ -1346,7 +1291,7 @@ char_u *find_file_in_path(char_u *ptr, size_t len, int options, int first, char_
FINDFILE_BOTH, rel_fname, (char_u *)curbuf->b_p_sua);
}
-static char_u *ff_file_to_find = NULL;
+static char *ff_file_to_find = NULL;
static void *fdip_search_ctx = NULL;
#if defined(EXITFREE)
@@ -1392,7 +1337,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
static char *dir;
static int did_findfile_init = false;
char_u save_char;
- char_u *file_name = NULL;
+ char *file_name = NULL;
char *buf = NULL;
int rel_to_curdir;
@@ -1413,10 +1358,10 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
ptr[len] = save_char;
xfree(ff_file_to_find);
- ff_file_to_find = vim_strsave((char_u *)NameBuff);
+ ff_file_to_find = xstrdup(NameBuff);
if (options & FNAME_UNESC) {
// Change all "\ " to " ".
- for (ptr = ff_file_to_find; *ptr != NUL; ptr++) {
+ for (ptr = (char_u *)ff_file_to_find; *ptr != NUL; ptr++) {
if (ptr[0] == '\\' && ptr[1] == ' ') {
memmove(ptr, ptr + 1, STRLEN(ptr));
}
@@ -1430,7 +1375,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
|| (ff_file_to_find[1] == '.'
&& (ff_file_to_find[2] == NUL
|| vim_ispathsep(ff_file_to_find[2])))));
- if (vim_isAbsName(ff_file_to_find)
+ if (vim_isAbsName((char_u *)ff_file_to_find)
// "..", "../path", "." and "./path": don't use the path_option
|| rel_to_curdir
#if defined(WIN32)
@@ -1440,19 +1385,17 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
|| (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
#endif
) {
- /*
- * Absolute path, no need to use "path_option".
- * If this is not a first call, return NULL. We already returned a
- * filename on the first call.
- */
+ // Absolute path, no need to use "path_option".
+ // If this is not a first call, return NULL. We already returned a
+ // filename on the first call.
if (first == true) {
- if (path_with_url((char *)ff_file_to_find)) {
- file_name = vim_strsave(ff_file_to_find);
+ if (path_with_url(ff_file_to_find)) {
+ file_name = xstrdup(ff_file_to_find);
goto theend;
}
- /* When FNAME_REL flag given first use the directory of the file.
- * Otherwise or when this fails use the current directory. */
+ // When FNAME_REL flag given first use the directory of the file.
+ // Otherwise or when this fails use the current directory.
for (int run = 1; run <= 2; run++) {
size_t l = STRLEN(ff_file_to_find);
if (run == 1
@@ -1468,8 +1411,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
run = 2;
}
- /* When the file doesn't exist, try adding parts of
- * 'suffixesadd'. */
+ // When the file doesn't exist, try adding parts of 'suffixesadd'.
buf = (char *)suffixes;
for (;;) {
if (
@@ -1477,7 +1419,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
&& (find_what == FINDFILE_BOTH
|| ((find_what == FINDFILE_DIR)
== os_isdir(NameBuff))))) {
- file_name = vim_strsave((char_u *)NameBuff);
+ file_name = xstrdup(NameBuff);
goto theend;
}
if (*buf == NUL) {
@@ -1489,11 +1431,9 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
}
}
} else {
- /*
- * Loop over all paths in the 'path' or 'cdpath' option.
- * When "first" is set, first setup to the start of the option.
- * Otherwise continue to find the next match.
- */
+ // Loop over all paths in the 'path' or 'cdpath' option.
+ // When "first" is set, first setup to the start of the option.
+ // Otherwise continue to find the next match.
if (first == true) {
// vim_findfile_free_visited can handle a possible NULL pointer
vim_findfile_free_visited(fdip_search_ctx);
@@ -1503,7 +1443,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
for (;;) {
if (did_findfile_init) {
- file_name = vim_findfile(fdip_search_ctx);
+ file_name = (char *)vim_findfile(fdip_search_ctx);
if (file_name != NULL) {
break;
}
@@ -1513,8 +1453,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
char_u *r_ptr;
if (dir == NULL || *dir == NUL) {
- /* We searched all paths of the option, now we can
- * free the search context. */
+ // We searched all paths of the option, now we can free the search context.
vim_findfile_cleanup(fdip_search_ctx);
fdip_search_ctx = NULL;
break;
@@ -1528,9 +1467,9 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
// get the stopdir string
r_ptr = vim_findfile_stopdir((char_u *)buf);
- fdip_search_ctx = vim_findfile_init((char_u *)buf, ff_file_to_find,
- r_ptr, 100, false, find_what,
- fdip_search_ctx, false, rel_fname);
+ fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
+ (char *)r_ptr, 100, false, find_what,
+ fdip_search_ctx, false, (char *)rel_fname);
if (fdip_search_ctx != NULL) {
did_findfile_init = true;
}
@@ -1559,7 +1498,7 @@ char_u *find_file_in_path_option(char_u *ptr, size_t len, int options, int first
}
theend:
- return file_name;
+ return (char_u *)file_name;
}
void do_autocmd_dirchanged(char *new_dir, CdScope scope, CdCause cause, bool pre)
diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c
index 517424f4c1..0bc7f736bc 100644
--- a/src/nvim/fileio.c
+++ b/src/nvim/fileio.c
@@ -82,17 +82,15 @@
#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... */
+// When converting, a read() or write() may leave some bytes to be converted
+// for the next call. The value is guessed...
#define CONV_RESTLEN 30
-/* We have to guess how much a sequence of bytes may expand when converting
- * with iconv() to be able to allocate a buffer. */
+// We have to guess how much a sequence of bytes may expand when converting
+// with iconv() to be able to allocate a buffer.
#define ICONV_MULT 8
-/*
- * Structure to pass arguments from buf_write() to buf_write_bytes().
- */
+// Structure to pass arguments from buf_write() to buf_write_bytes().
struct bw_info {
int bw_fd; // file descriptor
char_u *bw_buf; // buffer with data to be written
@@ -119,7 +117,7 @@ struct bw_info {
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)
+void filemess(buf_T *buf, char *name, char *s, int attr)
{
int msg_scroll_save;
@@ -128,7 +126,7 @@ void filemess(buf_T *buf, char_u *name, char_u *s, int attr)
}
add_quoted_fname((char *)IObuff, IOSIZE - 100, buf, (const char *)name);
// Avoid an over-long translation to cause trouble.
- STRLCAT(IObuff, s, IOSIZE);
+ xstrlcat(IObuff, s, IOSIZE);
// For the first message may have to start a new line.
// For further ones overwrite the previous one, reset msg_scroll before
// calling filemess().
@@ -257,12 +255,10 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
- /*
- * If there is no file name yet, use the one for the read file.
- * BF_NOTEDITED is set to reflect this.
- * Don't do this for a read from a filter.
- * Only do this when 'cpoptions' contains the 'f' flag.
- */
+ // If there is no file name yet, use the one for the read file.
+ // BF_NOTEDITED is set to reflect this.
+ // Don't do this for a read from a filter.
+ // Only do this when 'cpoptions' contains the 'f' flag.
if (curbuf->b_ffname == NULL
&& !filtering
&& fname != NULL
@@ -354,7 +350,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
// If the name is too long we might crash further on, quit here.
if (namelen >= MAXPATHL) {
- filemess(curbuf, (char_u *)fname, (char_u *)_("Illegal file name"), 0);
+ filemess(curbuf, fname, _("Illegal file name"), 0);
msg_end();
msg_scroll = msg_save;
return FAIL;
@@ -365,7 +361,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
// swap file may destroy it! Reported on MS-DOS and Win 95.
if (after_pathsep(fname, fname + namelen)) {
if (!silent) {
- filemess(curbuf, (char_u *)fname, (char_u *)_(msg_is_a_directory), 0);
+ filemess(curbuf, fname, _(msg_is_a_directory), 0);
}
msg_end();
msg_scroll = msg_save;
@@ -387,10 +383,10 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
) {
if (S_ISDIR(perm)) {
if (!silent) {
- filemess(curbuf, (char_u *)fname, (char_u *)_(msg_is_a_directory), 0);
+ filemess(curbuf, fname, _(msg_is_a_directory), 0);
}
} else {
- filemess(curbuf, (char_u *)fname, (char_u *)_("is not a file"), 0);
+ filemess(curbuf, fname, _("is not a file"), 0);
}
msg_end();
msg_scroll = msg_save;
@@ -401,12 +397,10 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
// Set default or forced 'fileformat' and 'binary'.
set_file_options(set_options, eap);
- /*
- * When opening a new file we take the readonly flag from the file.
- * Default is r/w, can be set to r/o below.
- * Don't reset it when in readonly mode
- * Only set/reset b_p_ro when BF_CHECK_RO is set.
- */
+ // When opening a new file we take the readonly flag from the file.
+ // Default is r/w, can be set to r/o below.
+ // Don't reset it when in readonly mode
+ // Only set/reset b_p_ro when BF_CHECK_RO is set.
check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
if (check_readonly && !readonlymode) {
curbuf->b_p_ro = false;
@@ -419,17 +413,15 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
curbuf->b_mtime_read = curbuf->b_mtime;
curbuf->b_mtime_read_ns = curbuf->b_mtime_ns;
#ifdef UNIX
- /*
- * Use the protection bits of the original file for the swap file.
- * This makes it possible for others to read the name of the
- * edited file from the swapfile, but only if they can read the
- * edited file.
- * Remove the "write" and "execute" bits for group and others
- * (they must not write the swapfile).
- * Add the "read" and "write" bits for the user, otherwise we may
- * not be able to write to the file ourselves.
- * Setting the bits is done below, after creating the swap file.
- */
+ // Use the protection bits of the original file for the swap file.
+ // This makes it possible for others to read the name of the
+ // edited file from the swapfile, but only if they can read the
+ // edited file.
+ // Remove the "write" and "execute" bits for group and others
+ // (they must not write the swapfile).
+ // Add the "read" and "write" bits for the user, otherwise we may
+ // not be able to write to the file ourselves.
+ // Setting the bits is done below, after creating the swap file.
swap_mode = ((int)file_info.stat.st_mode & 0644) | 0600;
#endif
} else {
@@ -483,9 +475,9 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
}
if (!silent) {
if (dir_of_file_exists((char_u *)fname)) {
- filemess(curbuf, (char_u *)sfname, (char_u *)new_file_message(), 0);
+ filemess(curbuf, sfname, new_file_message(), 0);
} else {
- filemess(curbuf, (char_u *)sfname, (char_u *)_("[New DIRECTORY]"), 0);
+ filemess(curbuf, sfname, _("[New DIRECTORY]"), 0);
}
}
// Even though this is a new file, it might have been
@@ -505,25 +497,23 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
}
return OK; // a new file is not an error
} else {
- filemess(curbuf, (char_u *)sfname, (char_u *)((fd == UV_EFBIG) ? _("[File too big]") :
+ filemess(curbuf, sfname, ((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);
+ _("[Permission Denied]")), 0);
curbuf->b_p_ro = true; // must use "w!" now
}
return FAIL;
}
- /*
- * Only set the 'ro' flag for readonly files the first time they are
- * loaded. Help files always get readonly mode
- */
+ // Only set the 'ro' flag for readonly files the first time they are
+ // loaded. Help files always get readonly mode
if ((check_readonly && file_readonly) || curbuf->b_help) {
curbuf->b_p_ro = true;
}
@@ -645,13 +635,11 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
curbuf->b_p_ro = true; // must use "w!" now
return FAIL;
}
- /*
- * Don't allow the autocommands to change the current buffer.
- * Try to re-open the file.
- *
- * Don't allow the autocommands to change the buffer name either
- * (cd for example) if it invalidates fname or sfname.
- */
+ // Don't allow the autocommands to change the current buffer.
+ // Try to re-open the file.
+ //
+ // Don't allow the autocommands to change the buffer name either
+ // (cd for example) if it invalidates fname or sfname.
if (!read_stdin && (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname))
@@ -673,16 +661,14 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
if (!recoverymode && !filtering && !(flags & READ_DUMMY) && !silent) {
if (!read_stdin && !read_buffer) {
- filemess(curbuf, (char_u *)sfname, (char_u *)"", 0);
+ filemess(curbuf, sfname, "", 0);
}
}
msg_scroll = false; // overwrite the file message
- /*
- * Set linecnt now, before the "retry" caused by a wrong guess for
- * fileformat, and after the autocommands, which may change them.
- */
+ // Set linecnt now, before the "retry" caused by a wrong guess for
+ // fileformat, and after the autocommands, which may change them.
linecnt = curbuf->b_ml.ml_line_count;
// "++bad=" argument.
@@ -695,9 +681,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
curbuf->b_bad_char = 0;
}
- /*
- * Decide which 'encoding' to use or use first.
- */
+ // Decide which 'encoding' to use or use first.
if (eap != NULL && eap->force_enc != 0) {
fenc = enc_canonize(eap->cmd + eap->force_enc);
fenc_alloced = true;
@@ -719,28 +703,26 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
fenc_alloced = false;
} else {
fenc_next = p_fencs; // try items in 'fileencodings'
- fenc = (char *)next_fenc(&fenc_next, &fenc_alloced);
- }
-
- /*
- * Jump back here to retry reading the file in different ways.
- * Reasons to retry:
- * - encoding conversion failed: try another one from "fenc_next"
- * - BOM detected and fenc was set, need to setup conversion
- * - "fileformat" check failed: try another
- *
- * Variables set for special retry actions:
- * "file_rewind" Rewind the file to start reading it again.
- * "advance_fenc" Advance "fenc" using "fenc_next".
- * "skip_read" Re-use already read bytes (BOM detected).
- * "did_iconv" iconv() conversion failed, try 'charconvert'.
- * "keep_fileformat" Don't reset "fileformat".
- *
- * Other status indicators:
- * "tmpname" When != NULL did conversion with 'charconvert'.
- * Output file has to be deleted afterwards.
- * "iconv_fd" When != -1 did conversion with iconv().
- */
+ fenc = next_fenc(&fenc_next, &fenc_alloced);
+ }
+
+ // Jump back here to retry reading the file in different ways.
+ // Reasons to retry:
+ // - encoding conversion failed: try another one from "fenc_next"
+ // - BOM detected and fenc was set, need to setup conversion
+ // - "fileformat" check failed: try another
+ //
+ // Variables set for special retry actions:
+ // "file_rewind" Rewind the file to start reading it again.
+ // "advance_fenc" Advance "fenc" using "fenc_next".
+ // "skip_read" Re-use already read bytes (BOM detected).
+ // "did_iconv" iconv() conversion failed, try 'charconvert'.
+ // "keep_fileformat" Don't reset "fileformat".
+ //
+ // Other status indicators:
+ // "tmpname" When != NULL did conversion with 'charconvert'.
+ // Output file has to be deleted afterwards.
+ // "iconv_fd" When != -1 did conversion with iconv().
retry:
if (file_rewind) {
@@ -764,10 +746,8 @@ retry:
conv_error = 0;
}
- /*
- * When retrying with another "fenc" and the first time "fileformat"
- * will be reset.
- */
+ // When retrying with another "fenc" and the first time "fileformat"
+ // will be reset.
if (keep_fileformat) {
keep_fileformat = false;
} else {
@@ -793,9 +773,7 @@ retry:
#endif
if (advance_fenc) {
- /*
- * Try the next entry in 'fileencodings'.
- */
+ // Try the next entry in 'fileencodings'.
advance_fenc = false;
if (eap != NULL && eap->force_enc != 0) {
@@ -813,7 +791,7 @@ retry:
xfree(fenc);
}
if (fenc_next != NULL) {
- fenc = (char *)next_fenc(&fenc_next, &fenc_alloced);
+ fenc = next_fenc(&fenc_next, &fenc_alloced);
} else {
fenc = "";
fenc_alloced = false;
@@ -825,16 +803,14 @@ retry:
}
}
- /*
- * Conversion may be required when the encoding of the file is different
- * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
- */
+ // Conversion may be required when the encoding of the file is different
+ // from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
fio_flags = 0;
- converted = need_conversion((char_u *)fenc);
+ 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) {
+ if (strcmp(fenc, ENC_UCSBOM) == 0) {
fio_flags = FIO_UCSBOM;
} else {
// Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
@@ -855,10 +831,8 @@ retry:
}
#endif
- /*
- * Use the 'charconvert' expression when conversion is required
- * and we can't do it internally or with iconv().
- */
+ // Use the 'charconvert' expression when conversion is required
+ // and we can't do it internally or with iconv().
if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
&& !read_fifo
#ifdef HAVE_ICONV
@@ -922,12 +896,10 @@ retry:
}
while (!error && !got_int) {
- /*
- * We allocate as much space for the file as we can get, plus
- * space for the old line plus room for one terminating NUL.
- * The amount is limited by the fact that read() only can read
- * up to max_unsigned characters (and other things).
- */
+ // We allocate as much space for the file as we can get, plus
+ // space for the old line plus room for one terminating NUL.
+ // The amount is limited by the fact that read() only can read
+ // up to max_unsigned characters (and other things).
{
if (!skip_read) {
// Use buffer >= 64K. Add linerest to double the size if the
@@ -999,10 +971,8 @@ retry:
}
if (read_buffer) {
- /*
- * Read bytes from curbuf. Used for converting text read
- * from stdin.
- */
+ // Read bytes from curbuf. Used for converting text read
+ // from stdin.
if (read_buf_lnum > from) {
size = 0;
} else {
@@ -1052,9 +1022,7 @@ retry:
}
}
} else {
- /*
- * Read bytes from the file.
- */
+ // Read bytes from the file.
size = read_eintr(fd, ptr, (size_t)size);
}
@@ -1062,10 +1030,8 @@ retry:
if (size < 0) { // read error
error = true;
} else if (conv_restlen > 0) {
- /*
- * Reached end-of-file but some trailing bytes could
- * not be converted. Truncated file?
- */
+ // Reached end-of-file but some trailing bytes could
+ // not be converted. Truncated file?
// When we did a conversion report an error.
if (fio_flags != 0
@@ -1118,12 +1084,10 @@ retry:
skip_read = false;
- /*
- * At start of file: Check for BOM.
- * Also check for a BOM for other Unicode encodings, but not after
- * converting with 'charconvert' or when a BOM has already been
- * found.
- */
+ // At start of file: Check for BOM.
+ // Also check for a BOM for other Unicode encodings, but not after
+ // converting with 'charconvert' or when a BOM has already been
+ // found.
if ((filesize == 0)
&& (fio_flags == FIO_UCSBOM
|| (!curbuf->b_p_bomb
@@ -1172,9 +1136,7 @@ retry:
ptr -= conv_restlen;
size += conv_restlen;
conv_restlen = 0;
- /*
- * Break here for a read error or end-of-file.
- */
+ // Break here for a read error or end-of-file.
if (size <= 0) {
break;
}
@@ -1188,11 +1150,9 @@ retry:
char *top = ptr;
size_t to_size = (size_t)(real_size - size);
- /*
- * If there is conversion error or not enough room try using
- * another conversion. Except for when there is no
- * alternative (help files).
- */
+ // If there is conversion error or not enough room try using
+ // another conversion. Except for when there is no
+ // alternative (help files).
while ((iconv(iconv_fd, (void *)&fromp, &from_size,
&top, &to_size)
== (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
@@ -1493,9 +1453,7 @@ rewind_retry:
// count the number of characters (after conversion!)
filesize += size;
- /*
- * when reading the first part of a file: guess EOL type
- */
+ // when reading the first part of a file: guess EOL type
if (fileformat == EOL_UNKNOWN) {
// First try finding a NL, for Dos and Unix
if (try_dos || try_unix) {
@@ -1560,10 +1518,8 @@ rewind_retry:
}
}
- /*
- * This loop is executed once for every character read.
- * Keep it fast!
- */
+ // This loop is executed once for every character read.
+ // Keep it fast!
if (fileformat == EOL_MAC) {
ptr--;
while (++ptr, --size >= 0) {
@@ -1665,11 +1621,9 @@ failed:
error = false;
}
- /*
- * If we get EOF in the middle of a line, note the fact and
- * complete the line ourselves.
- * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
- */
+ // If we get EOF in the middle of a line, note the fact and
+ // complete the line ourselves.
+ // In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
if (!error
&& !got_int
&& linerest != 0
@@ -1738,9 +1692,7 @@ failed:
}
no_wait_return--; // may wait for return now
- /*
- * In recovery mode everything but autocommands is skipped.
- */
+ // In recovery mode everything but autocommands is skipped.
if (!recoverymode) {
// need to delete the last line, which comes from the empty buffer
if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY)) {
@@ -1767,18 +1719,16 @@ failed:
appended_lines_mark(from, linecnt);
}
- /*
- * If we were reading from the same terminal as where messages go,
- * the screen will have been messed up.
- * Switch on raw mode now and clear the screen.
- */
+ // If we were reading from the same terminal as where messages go,
+ // the screen will have been messed up.
+ // Switch on raw mode now and clear the screen.
if (read_stdin) {
screenclear();
}
if (got_int) {
if (!(flags & READ_DUMMY)) {
- filemess(curbuf, (char_u *)sfname, (char_u *)_(e_interr), 0);
+ filemess(curbuf, sfname, _(e_interr), 0);
if (newfile) {
curbuf->b_p_ro = true; // must use "w!" now
}
@@ -1878,10 +1828,8 @@ failed:
u_clearline(); // cannot use "U" command after adding lines
- /*
- * In Ex mode: cursor at last new line.
- * Otherwise: cursor at first new line.
- */
+ // In Ex mode: cursor at last new line.
+ // Otherwise: cursor at first new line.
if (exmode_active) {
curwin->w_cursor.lnum = from + linecnt;
} else {
@@ -1900,17 +1848,13 @@ failed:
}
msg_scroll = msg_save;
- /*
- * Get the marks before executing autocommands, so they can be used there.
- */
+ // Get the marks before executing autocommands, so they can be used there.
check_marks_read();
- /*
- * We remember if the last line of the read didn't have
- * an eol even when 'binary' is off, to support turning 'fixeol' off,
- * or writing the read again with 'binary' on. The latter is required
- * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
- */
+ // We remember if the last line of the read didn't have
+ // an eol even when 'binary' is off, to support turning 'fixeol' off,
+ // or writing the read again with 'binary' on. The latter is required
+ // for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
curbuf->b_no_eol_lnum = read_no_eol_lnum;
// When reloading a buffer put the cursor at the first line that is
@@ -1919,9 +1863,7 @@ failed:
u_find_first_changed();
}
- /*
- * When opening a new file locate undo info and read it.
- */
+ // When opening a new file locate undo info and read it.
if (read_undo_file) {
char_u hash[UNDO_HASH_SIZE];
@@ -1939,11 +1881,9 @@ failed:
save_file_ff(curbuf);
}
- /*
- * The output from the autocommands should not overwrite anything and
- * should not be overwritten: Set msg_scroll, restore its value if no
- * output was done.
- */
+ // The output from the autocommands should not overwrite anything and
+ // should not be overwritten: Set msg_scroll, restore its value if no
+ // output was done.
msg_scroll = true;
if (filtering) {
apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
@@ -2068,25 +2008,25 @@ void set_forced_fenc(exarg_T *eap)
/// NULL.
/// When *pp is not set to NULL, the result is in allocated memory and "alloced"
/// is set to true.
-static char_u *next_fenc(char **pp, bool *alloced)
+static char *next_fenc(char **pp, bool *alloced)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
{
- char_u *p;
- char_u *r;
+ char *p;
+ char *r;
*alloced = false;
if (**pp == NUL) {
*pp = NULL;
- return (char_u *)"";
+ return "";
}
- p = (char_u *)vim_strchr((*pp), ',');
+ p = vim_strchr((*pp), ',');
if (p == NULL) {
- r = (char_u *)enc_canonize(*pp);
+ r = enc_canonize(*pp);
*pp += STRLEN(*pp);
} else {
- r = vim_strnsave((char_u *)(*pp), (size_t)(p - (char_u *)(*pp)));
- *pp = (char *)p + 1;
- p = (char_u *)enc_canonize((char *)r);
+ r = xstrnsave(*pp, (size_t)(p - *pp));
+ *pp = p + 1;
+ p = enc_canonize(r);
xfree(r);
r = p;
}
@@ -2109,7 +2049,7 @@ static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp)
char_u *tmpname;
char *errmsg = NULL;
- tmpname = vim_tempname();
+ tmpname = (char_u *)vim_tempname();
if (tmpname == NULL) {
errmsg = _("Can't find temp file for conversion");
} else {
@@ -2151,8 +2091,8 @@ static void check_marks_read(void)
shada_read_marks();
}
- /* Always set b_marks_read; needed when 'shada' is changed to include
- * the ' parameter after opening a buffer. */
+ // Always set b_marks_read; needed when 'shada' is changed to include
+ // the ' parameter after opening a buffer.
curbuf->b_marks_read = true;
}
@@ -2237,8 +2177,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
int wb_flags = 0;
#endif
#ifdef HAVE_ACL
- vim_acl_T acl = NULL; /* ACL copied from original file to
- backup or new file */
+ vim_acl_T acl = NULL; // ACL copied from original file to
+ // backup or new file
#endif
int write_undo_file = false;
context_sha256_T sha_ctx;
@@ -2250,16 +2190,14 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
return FAIL;
}
if (buf->b_ml.ml_mfp == NULL) {
- /* This can happen during startup when there is a stray "w" in the
- * vimrc file. */
+ // This can happen during startup when there is a stray "w" in the
+ // vimrc file.
emsg(_(e_emptybuf));
return FAIL;
}
- /*
- * Disallow writing from .exrc and .vimrc in current directory for
- * security reasons.
- */
+ // Disallow writing from .exrc and .vimrc in current directory for
+ // security reasons.
if (check_secure()) {
return FAIL;
}
@@ -2279,17 +2217,15 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
write_info.bw_iconv_fd = (iconv_t)-1;
#endif
- /* After writing a file changedtick changes but we don't want to display
- * the line. */
+ // After writing a file changedtick changes but we don't want to display
+ // the line.
ex_no_reprint = true;
- /*
- * If there is no file name yet, use the one for the written file.
- * BF_NOTEDITED is set to reflect this (in case the write fails).
- * Don't do this when the write is for a filter command.
- * Don't do this when appending.
- * Only do this when 'cpoptions' contains the 'F' flag.
- */
+ // If there is no file name yet, use the one for the written file.
+ // BF_NOTEDITED is set to reflect this (in case the write fails).
+ // Don't do this when the write is for a filter command.
+ // Don't do this when appending.
+ // Only do this when 'cpoptions' contains the 'F' flag.
if (buf->b_ffname == NULL
&& reset_changed
&& whole
@@ -2317,7 +2253,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
fname = sfname;
#endif
- if (buf->b_ffname != NULL && FNAMECMP(ffname, buf->b_ffname) == 0) {
+ if (buf->b_ffname != NULL && path_fnamecmp(ffname, buf->b_ffname) == 0) {
overwriting = true;
} else {
overwriting = false;
@@ -2325,9 +2261,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
no_wait_return++; // don't wait for return yet
- /*
- * Set '[ and '] marks to the lines to be written.
- */
+ // Set '[ and '] marks to the lines to be written.
buf->b_op_start.lnum = start;
buf->b_op_start.col = 0;
buf->b_op_end.lnum = end;
@@ -2344,11 +2278,9 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
int empty_memline = (buf->b_ml.ml_mfp == NULL);
bufref_T bufref;
- /*
- * Apply PRE autocommands.
- * Set curbuf to the buffer to be written.
- * Careful: The autocommands may call buf_write() recursively!
- */
+ // Apply PRE autocommands.
+ // Set curbuf to the buffer to be written.
+ // Careful: The autocommands may call buf_write() recursively!
if (ffname == buf->b_ffname) {
buf_ffname = true;
}
@@ -2386,9 +2318,9 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
sfname, sfname, false, curbuf, eap);
if (did_cmd) {
if (was_changed && !curbufIsChanged()) {
- /* Written everything correctly and BufWriteCmd has reset
- * 'modified': Correct the undo information so that an
- * undo now sets 'modified'. */
+ // Written everything correctly and BufWriteCmd has reset
+ // 'modified': Correct the undo information so that an
+ // undo now sets 'modified'.
u_unchanged(curbuf);
u_update_save_nr(curbuf);
}
@@ -2439,14 +2371,14 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
if (nofile_err
|| aborting()) {
- /* An aborting error, interrupt or exception in the
- * autocommands. */
+ // An aborting error, interrupt or exception in the
+ // autocommands.
return FAIL;
}
if (did_cmd) {
if (buf == NULL) {
- /* The buffer was deleted. We assume it was written
- * (can't retry anyway). */
+ // The buffer was deleted. We assume it was written
+ // (can't retry anyway).
return OK;
}
if (overwriting) {
@@ -2471,12 +2403,10 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
return FAIL;
}
- /*
- * The autocommands may have changed the number of lines in the file.
- * When writing the whole file, adjust the end.
- * When writing part of the file, assume that the autocommands only
- * changed the number of lines that are to be written (tricky!).
- */
+ // The autocommands may have changed the number of lines in the file.
+ // When writing the whole file, adjust the end.
+ // When writing part of the file, assume that the autocommands only
+ // changed the number of lines that are to be written (tricky!).
if (buf->b_ml.ml_line_count != old_line_count) {
if (whole) { // write all
end = buf->b_ml.ml_line_count;
@@ -2493,10 +2423,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
}
}
- /*
- * The autocommands may have changed the name of the buffer, which may
- * be kept in fname, ffname and sfname.
- */
+ // The autocommands may have changed the name of the buffer, which may
+ // be kept in fname, ffname and sfname.
if (buf_ffname) {
ffname = buf->b_ffname;
}
@@ -2527,9 +2455,9 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
#ifndef UNIX
(char_u *)sfname,
#else
- (char_u *)fname,
+ fname,
#endif
- (char_u *)"", 0); // show that we are busy
+ "", 0); // show that we are busy
}
msg_scroll = false; // always overwrite the file message now
@@ -2543,9 +2471,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
bufsize = BUFSIZE;
}
- /*
- * Get information about original file (if there is one).
- */
+ // Get information about original file (if there is one).
FileInfo file_info_old;
#if defined(UNIX)
perm = -1;
@@ -2562,8 +2488,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
SET_ERRMSG_NUM("E503", _("is not a file or writable device"));
goto fail;
}
- /* It's a device of some kind (or a fifo) which we can write to
- * but for which we can't make a backup. */
+ // It's a device of some kind (or a fifo) which we can write to
+ // but for which we can't make a backup.
device = true;
newfile = true;
perm = -1;
@@ -2595,10 +2521,8 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
#endif // !UNIX
if (!device && !newfile) {
- /*
- * Check if the file is really writable (when renaming the file to
- * make a backup we won't discover it later).
- */
+ // Check if the file is really writable (when renaming the file to
+ // make a backup we won't discover it later).
file_readonly = !os_file_is_writable(fname);
if (!forceit && file_readonly) {
@@ -2610,9 +2534,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
goto fail;
}
- /*
- * Check if the timestamp hasn't changed since reading the file.
- */
+ // Check if the timestamp hasn't changed since reading the file.
if (overwriting) {
retval = check_mtime(buf, &file_info_old);
if (retval == FAIL) {
@@ -2622,41 +2544,33 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
}
#ifdef HAVE_ACL
- /*
- * For systems that support ACL: get the ACL from the original file.
- */
+ // For systems that support ACL: get the ACL from the original file.
if (!newfile) {
acl = mch_get_acl((char_u *)fname);
}
#endif
- /*
- * If 'backupskip' is not empty, don't make a backup for some files.
- */
+ // If 'backupskip' is not empty, don't make a backup for some files.
dobackup = (p_wb || p_bk || *p_pm != NUL);
if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, (char_u *)sfname, (char_u *)ffname)) {
dobackup = false;
}
- /*
- * Save the value of got_int and reset it. We don't want a previous
- * interruption cancel writing, only hitting CTRL-C while writing should
- * abort it.
- */
+ // Save the value of got_int and reset it. We don't want a previous
+ // interruption cancel writing, only hitting CTRL-C while writing should
+ // abort it.
prev_got_int = got_int;
got_int = false;
// Mark the buffer as 'being saved' to prevent changed buffer warnings
buf->b_saving = true;
- /*
- * If we are not appending or filtering, the file exists, and the
- * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
- * When 'patchmode' is set also make a backup when appending.
- *
- * Do not make any backup, if 'writebackup' and 'backup' are both switched
- * off. This helps when editing large files on almost-full disks.
- */
+ // If we are not appending or filtering, the file exists, and the
+ // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
+ // When 'patchmode' is set also make a backup when appending.
+ //
+ // Do not make any backup, if 'writebackup' and 'backup' are both switched
+ // off. This helps when editing large files on almost-full disks.
if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup) {
FileInfo file_info;
const bool no_prepend_dot = false;
@@ -2666,27 +2580,23 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
} else if ((bkc & BKC_AUTO)) { // "auto"
int i;
- /*
- * Don't rename the file when:
- * - it's a hard link
- * - it's a symbolic link
- * - we don't have write permission in the directory
- */
+ // Don't rename the file when:
+ // - it's a hard link
+ // - it's a symbolic link
+ // - we don't have write permission in the directory
if (os_fileinfo_hardlinks(&file_info_old) > 1
|| !os_fileinfo_link(fname, &file_info)
|| !os_fileinfo_id_equal(&file_info, &file_info_old)) {
backup_copy = true;
} else {
- /*
- * Check if we can create a file and set the owner/group to
- * the ones from the original file.
- * First find a file name that doesn't exist yet (use some
- * arbitrary numbers).
- */
+ // Check if we can create a file and set the owner/group to
+ // the ones from the original file.
+ // First find a file name that doesn't exist yet (use some
+ // arbitrary numbers).
STRCPY(IObuff, fname);
for (i = 4913;; i += 123) {
char *tail = path_tail((char *)IObuff);
- size_t size = (size_t)((char_u *)tail - IObuff);
+ size_t size = (size_t)(tail - IObuff);
snprintf(tail, IOSIZE - size, "%d", i);
if (!os_fileinfo_link((char *)IObuff, &file_info)) {
break;
@@ -2706,17 +2616,15 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
backup_copy = true;
}
#endif
- /* Close the file before removing it, on MS-Windows we
- * can't delete an open file. */
+ // Close the file before removing it, on MS-Windows we
+ // can't delete an open file.
close(fd);
os_remove((char *)IObuff);
}
}
}
- /*
- * Break symlinks and/or hardlinks if we've been asked to.
- */
+ // Break symlinks and/or hardlinks if we've been asked to.
if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK)) {
#ifdef UNIX
bool file_info_link_ok = os_fileinfo_link(fname, &file_info);
@@ -2752,23 +2660,19 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
char *rootname;
char *p;
- /*
- * Try to make the backup in each directory in the 'bdir' option.
- *
- * Unix semantics has it, that we may have a writable file,
- * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
- * - the directory is not writable,
- * - the file may be a symbolic link,
- * - the file may belong to another user/group, etc.
- *
- * For these reasons, the existing writable file must be truncated
- * and reused. Creation of a backup COPY will be attempted.
- */
+ // Try to make the backup in each directory in the 'bdir' option.
+ //
+ // Unix semantics has it, that we may have a writable file,
+ // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
+ // - the directory is not writable,
+ // - the file may be a symbolic link,
+ // - the file may belong to another user/group, etc.
+ //
+ // For these reasons, the existing writable file must be truncated
+ // and reused. Creation of a backup COPY will be attempted.
dirp = p_bdir;
while (*dirp) {
- /*
- * Isolate one directory name, using an entry in 'bdir'.
- */
+ // Isolate one directory name, using an entry in 'bdir'.
size_t dir_len = copy_option_part(&dirp, (char *)IObuff, IOSIZE, ",");
p = (char *)IObuff + dir_len;
bool trailing_pathseps = after_pathsep((char *)IObuff, p) && p[-1] == p[-2];
@@ -2793,7 +2697,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
}
}
- rootname = (char *)get_file_in_dir((char_u *)fname, IObuff);
+ rootname = get_file_in_dir(fname, (char *)IObuff);
if (rootname == NULL) {
some_error = true; // out of memory
goto nobackup;
@@ -2814,9 +2718,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
goto nobackup;
}
- /*
- * Check if backup file already exists.
- */
+ // Check if backup file already exists.
if (os_fileinfo(backup, &file_info_new)) {
if (os_fileinfo_id_equal(&file_info_new, &file_info_old)) {
//
@@ -2848,9 +2750,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
}
xfree(rootname);
- /*
- * Try to create the backup file
- */
+ // Try to create the backup file
if (backup != NULL) {
// remove old backup, if present
os_remove(backup);
@@ -2906,30 +2806,22 @@ nobackup:
char *p;
char *rootname;
- /*
- * Make a backup by renaming the original file.
- */
- /*
- * If 'cpoptions' includes the "W" flag, we don't want to
- * overwrite a read-only file. But rename may be possible
- * anyway, thus we need an extra check here.
- */
+ // Make a backup by renaming the original file.
+
+ // If 'cpoptions' includes the "W" flag, we don't want to
+ // overwrite a read-only file. But rename may be possible
+ // anyway, thus we need an extra check here.
if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL) {
SET_ERRMSG_NUM("E504", _(err_readonly));
goto fail;
}
- /*
- *
- * Form the backup file name - change path/fo.o.h to
- * path/fo.o.h.bak Try all directories in 'backupdir', first one
- * that works is used.
- */
+ // Form the backup file name - change path/fo.o.h to
+ // path/fo.o.h.bak Try all directories in 'backupdir', first one
+ // that works is used.
dirp = p_bdir;
while (*dirp) {
- /*
- * Isolate one directory name and make the backup file name.
- */
+ // Isolate one directory name and make the backup file name.
size_t dir_len = copy_option_part(&dirp, (char *)IObuff, IOSIZE, ",");
p = (char *)IObuff + dir_len;
bool trailing_pathseps = after_pathsep((char *)IObuff, p) && p[-1] == p[-2];
@@ -2955,7 +2847,7 @@ nobackup:
}
if (backup == NULL) {
- rootname = (char *)get_file_in_dir((char_u *)fname, IObuff);
+ rootname = get_file_in_dir(fname, (char *)IObuff);
if (rootname == NULL) {
backup = NULL;
} else {
@@ -2965,11 +2857,9 @@ nobackup:
}
if (backup != NULL) {
- /*
- * If we are not going to keep the backup file, don't
- * delete an existing one, try to use another name.
- * Change one character, just before the extension.
- */
+ // If we are not going to keep the backup file, don't
+ // delete an existing one, try to use another name.
+ // Change one character, just before the extension.
if (!p_bk && os_path_exists(backup)) {
p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
if (p < backup) { // empty file name ???
@@ -2994,7 +2884,7 @@ nobackup:
// If the renaming of the original file to the backup file
// works, quit here.
///
- if (vim_rename((char_u *)fname, (char_u *)backup) == 0) {
+ if (vim_rename(fname, backup) == 0) {
break;
}
@@ -3062,7 +2952,7 @@ nobackup:
}
// Check if the file needs to be converted.
- converted = need_conversion((char_u *)fenc);
+ converted = need_conversion(fenc);
// Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
// Latin1 to Unicode conversion. This is handled in buf_write_bytes().
@@ -3099,13 +2989,11 @@ nobackup:
} else {
#endif
- /*
- * When the file needs to be converted with 'charconvert' after
- * writing, write to a temp file instead and let the conversion
- * overwrite the original file.
- */
+ // When the file needs to be converted with 'charconvert' after
+ // writing, write to a temp file instead and let the conversion
+ // overwrite the original file.
if (*p_ccv != NUL) {
- wfname = (char *)vim_tempname();
+ wfname = vim_tempname();
if (wfname == NULL) { // Can't write without a tempfile!
SET_ERRMSG(_("E214: Can't find temp file for writing"));
goto restore_backup;
@@ -3212,7 +3100,7 @@ restore_backup:
// In that case we leave the copy around.
// If file does not exist, put the copy in its place
if (!os_path_exists(fname)) {
- vim_rename((char_u *)backup, (char_u *)fname);
+ vim_rename(backup, fname);
}
// if original file does exist throw away the copy
if (os_path_exists(fname)) {
@@ -3220,7 +3108,7 @@ restore_backup:
}
} else {
// try to put the original file back
- vim_rename((char_u *)backup, (char_u *)fname);
+ vim_rename(backup, fname);
}
}
@@ -3282,7 +3170,7 @@ restore_backup:
for (lnum = start; lnum <= end; lnum++) {
// The next while loop is done once for each character written.
// Keep it fast!
- ptr = (char *)ml_get_buf(buf, lnum, false) - 1;
+ ptr = ml_get_buf(buf, lnum, false) - 1;
if (write_undo_file) {
sha256_update(&sha_ctx, (char_u *)ptr + 1, (uint32_t)(STRLEN(ptr + 1) + 1));
}
@@ -3487,7 +3375,7 @@ restore_backup:
end = 1; // success
}
} else {
- if (vim_rename((char_u *)backup, (char_u *)fname) == 0) {
+ if (vim_rename(backup, fname) == 0) {
end = 1;
}
}
@@ -3545,8 +3433,8 @@ restore_backup:
set_keep_msg(msg_trunc_attr((char *)IObuff, false, 0), 0);
}
- /* When written everything correctly: reset 'modified'. Unless not
- * writing to the original file and '+' is not in 'cpoptions'. */
+ // When written everything correctly: reset 'modified'. Unless not
+ // writing to the original file and '+' is not in 'cpoptions'.
if (reset_changed && whole && !append
&& !write_info.bw_conv_error
&& (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) {
@@ -3561,10 +3449,8 @@ restore_backup:
u_update_save_nr(buf);
}
- /*
- * If written to the current file, update the timestamp of the swap file
- * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
- */
+ // If written to the current file, update the timestamp of the swap file
+ // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
if (overwriting) {
ml_timestamp(buf);
if (append) {
@@ -3574,22 +3460,18 @@ restore_backup:
}
}
- /*
- * If we kept a backup until now, and we are in patch mode, then we make
- * the backup file our 'original' file.
- */
+ // If we kept a backup until now, and we are in patch mode, then we make
+ // the backup file our 'original' file.
if (*p_pm && dobackup) {
char *const org = modname(fname, p_pm, false);
if (backup != NULL) {
- /*
- * If the original file does not exist yet
- * the current backup file becomes the original file
- */
+ // If the original file does not exist yet
+ // the current backup file becomes the original file
if (org == NULL) {
emsg(_("E205: Patchmode: can't save original file"));
} else if (!os_path_exists(org)) {
- vim_rename((char_u *)backup, (char_u *)org);
+ vim_rename(backup, org);
XFREE_CLEAR(backup); // don't delete the file
#ifdef UNIX
os_file_settime(org,
@@ -3597,12 +3479,9 @@ restore_backup:
(double)file_info_old.stat.st_mtim.tv_sec);
#endif
}
- }
- /*
- * If there is no backup file, remember that a (new) file was
- * created.
- */
- else {
+ } else {
+ // If there is no backup file, remember that a (new) file was
+ // created.
int empty_fd;
if (org == NULL
@@ -3620,9 +3499,7 @@ restore_backup:
}
}
- /*
- * Remove the backup unless 'backup' option is set
- */
+ // Remove the backup unless 'backup' option is set
if (!p_bk && backup != NULL
&& !write_info.bw_conv_error
&& os_remove(backup) != 0) {
@@ -3631,9 +3508,7 @@ restore_backup:
goto nofail;
- /*
- * Finish up. We get here either after failure or success.
- */
+ // Finish up. We get here either after failure or success.
fail:
no_wait_return--; // may wait for return now
nofail:
@@ -3698,10 +3573,8 @@ nofail:
}
msg_scroll = msg_save;
- /*
- * When writing the whole file and 'undofile' is set, also write the undo
- * file.
- */
+ // When writing the whole file and 'undofile' is set, also write the undo
+ // file.
if (retval == OK && write_undo_file) {
char hash[UNDO_HASH_SIZE];
@@ -3714,10 +3587,8 @@ nofail:
curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
- /*
- * Apply POST autocommands.
- * Careful: The autocommands may call buf_write() recursively!
- */
+ // Apply POST autocommands.
+ // Careful: The autocommands may call buf_write() recursively!
aucmd_prepbuf(&aco, buf);
if (append) {
@@ -3845,20 +3716,20 @@ void msg_add_lines(int insert_space, long lnum, off_T nchars)
{
char_u *p;
- p = IObuff + STRLEN(IObuff);
+ p = (char_u *)IObuff + STRLEN(IObuff);
if (insert_space) {
*p++ = ' ';
}
if (shortmess(SHM_LINES)) {
- vim_snprintf((char *)p, (size_t)(IOSIZE - (p - IObuff)), "%" PRId64 "L, %" PRId64 "B",
+ vim_snprintf((char *)p, (size_t)(IOSIZE - (p - (char_u *)IObuff)), "%" PRId64 "L, %" PRId64 "B",
(int64_t)lnum, (int64_t)nchars);
} else {
- vim_snprintf((char *)p, (size_t)(IOSIZE - (p - IObuff)),
+ vim_snprintf((char *)p, (size_t)(IOSIZE - (p - (char_u *)IObuff)),
NGETTEXT("%" PRId64 " line, ", "%" PRId64 " lines, ", lnum),
(int64_t)lnum);
p += STRLEN(p);
- vim_snprintf((char *)p, (size_t)(IOSIZE - (p - IObuff)),
+ vim_snprintf((char *)p, (size_t)(IOSIZE - (p - (char_u *)IObuff)),
NGETTEXT("%" PRId64 " byte", "%" PRId64 " bytes", nchars),
(int64_t)nchars);
}
@@ -3918,18 +3789,14 @@ static int buf_write_bytes(struct bw_info *ip)
int flags = ip->bw_flags; // extra flags
#endif
- /*
- * Skip conversion when writing the BOM.
- */
+ // Skip conversion when writing the BOM.
if (!(flags & FIO_NOCONVERT)) {
char_u *p;
unsigned c;
int n;
if (flags & FIO_UTF8) {
- /*
- * Convert latin1 in the buffer to UTF-8 in the file.
- */
+ // Convert latin1 in the buffer to UTF-8 in the file.
p = ip->bw_conv_buf; // translate to buffer
for (wlen = 0; wlen < len; wlen++) {
p += utf_char2bytes(buf[wlen], (char *)p);
@@ -3937,10 +3804,8 @@ static int buf_write_bytes(struct bw_info *ip)
buf = ip->bw_conv_buf;
len = (int)(p - ip->bw_conv_buf);
} else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) {
- /*
- * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
- * Latin1 chars in the file.
- */
+ // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
+ // Latin1 chars in the file.
if (flags & FIO_LATIN1) {
p = buf; // translate in-place (can only get shorter)
} else {
@@ -3950,9 +3815,9 @@ static int buf_write_bytes(struct bw_info *ip)
if (wlen == 0 && ip->bw_restlen != 0) {
int l;
- /* Use remainder of previous call. Append the start of
- * buf[] to get a full sequence. Might still be too
- * short! */
+ // Use remainder of previous call. Append the start of
+ // buf[] to get a full sequence. Might still be too
+ // short!
l = CONV_RESTLEN - ip->bw_restlen;
if (l > len) {
l = len;
@@ -3960,9 +3825,9 @@ static int buf_write_bytes(struct bw_info *ip)
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. */
+ // 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) {
return FAIL;
}
@@ -3986,9 +3851,9 @@ static int buf_write_bytes(struct bw_info *ip)
} else {
n = utf_ptr2len_len(buf + wlen, len - wlen);
if (n > len - wlen) {
- /* 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. */
+ // 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) {
return FAIL;
}
@@ -4031,9 +3896,9 @@ static int buf_write_bytes(struct bw_info *ip)
if (ip->bw_restlen > 0) {
char *fp;
- /* Need to concatenate the remainder of the previous call and
- * the bytes of the current call. Use the end of the
- * conversion buffer for this. */
+ // Need to concatenate the remainder of the previous call and
+ // the bytes of the current call. Use the end of the
+ // conversion buffer for this.
fromlen = (size_t)len + (size_t)ip->bw_restlen;
fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
@@ -4053,9 +3918,8 @@ static int buf_write_bytes(struct bw_info *ip)
// 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
- * wide-spread) which sets "to" to NULL and messes up "tolen".
- */
+ // There is a bug in iconv() on Linux (which appears to be
+ // wide-spread) which sets "to" to NULL and messes up "tolen".
if (to == NULL) {
to = (char *)ip->bw_conv_buf;
tolen = save_len;
@@ -4063,9 +3927,7 @@ static int buf_write_bytes(struct bw_info *ip)
ip->bw_first = false;
}
- /*
- * If iconv() has an error or there is not enough room, fail.
- */
+ // If iconv() has an error or there is not enough room, fail.
if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
== (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
|| fromlen > CONV_RESTLEN) {
@@ -4121,8 +3983,8 @@ static bool ucs2bytes(unsigned c, char_u **pp, int flags) FUNC_ATTR_NONNULL_ALL
} else if (flags & (FIO_UCS2 | FIO_UTF16)) {
if (c >= 0x10000) {
if (flags & FIO_UTF16) {
- /* Make two words, ten bits of the character in each. First
- * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
+ // Make two words, ten bits of the character in each. First
+ // word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff
c -= 0x10000;
if (c >= 0x100000) {
error = true;
@@ -4166,21 +4028,21 @@ static bool ucs2bytes(unsigned c, char_u **pp, int flags) FUNC_ATTR_NONNULL_ALL
/// @param fenc file encoding to check
///
/// @return true if conversion is required
-static bool need_conversion(const char_u *fenc)
+static bool need_conversion(const char *fenc)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
int same_encoding;
int enc_flags;
int fenc_flags;
- if (*fenc == NUL || STRCMP(p_enc, fenc) == 0) {
+ if (*fenc == NUL || strcmp(p_enc, fenc) == 0) {
same_encoding = true;
fenc_flags = 0;
} else {
// Ignore difference between "ansi" and "latin1", "ucs-4" and
// "ucs-4be", etc.
enc_flags = get_fio_flags((char_u *)p_enc);
- fenc_flags = get_fio_flags(fenc);
+ fenc_flags = get_fio_flags((char_u *)fenc);
same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
}
if (same_encoding) {
@@ -4327,7 +4189,7 @@ void shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
if (buf->b_sfname != buf->b_ffname) {
XFREE_CLEAR(buf->b_sfname);
}
- p = (char *)path_shorten_fname((char_u *)buf->b_ffname, dirname);
+ p = path_shorten_fname(buf->b_ffname, (char *)dirname);
if (p != NULL) {
buf->b_sfname = xstrdup(p);
buf->b_fname = buf->b_sfname;
@@ -4619,7 +4481,7 @@ int put_time(FILE *fd, time_t time_)
/// function will (attempts to?) copy the file across if rename fails -- webb
///
/// @return -1 for failure, 0 for success
-int vim_rename(const char_u *from, const char_u *to)
+int vim_rename(const char *from, const char *to)
FUNC_ATTR_NONNULL_ALL
{
int fd_in;
@@ -4633,13 +4495,11 @@ int vim_rename(const char_u *from, const char_u *to)
#endif
bool use_tmp_file = false;
- /*
- * When the names are identical, there is nothing to do. When they refer
- * to the same file (ignoring case and slash/backslash differences) but
- * the file name differs we need to go through a temp file.
- */
- if (FNAMECMP(from, to) == 0) {
- if (p_fic && (STRCMP(path_tail((char *)from), path_tail((char *)to))
+ // When the names are identical, there is nothing to do. When they refer
+ // to the same file (ignoring case and slash/backslash differences) but
+ // the file name differs we need to go through a temp file.
+ if (path_fnamecmp(from, to) == 0) {
+ if (p_fic && (strcmp(path_tail((char *)from), path_tail((char *)to))
!= 0)) {
use_tmp_file = true;
} else {
@@ -4665,10 +4525,8 @@ int vim_rename(const char_u *from, const char_u *to)
if (use_tmp_file) {
char_u tempname[MAXPATHL + 1];
- /*
- * Find a name that doesn't exist and is in the same directory.
- * Rename "from" to "tempname" and then rename "tempname" to "to".
- */
+ // Find a name that doesn't exist and is in the same directory.
+ // Rename "from" to "tempname" and then rename "tempname" to "to".
if (STRLEN(from) >= MAXPATHL - 5) {
return -1;
}
@@ -4678,13 +4536,13 @@ int vim_rename(const char_u *from, const char_u *to)
snprintf(tail, (size_t)((MAXPATHL + 1) - (tail - (char *)tempname - 1)), "%d", n);
if (!os_path_exists((char *)tempname)) {
- if (os_rename(from, tempname) == OK) {
- if (os_rename(tempname, to) == OK) {
+ if (os_rename((char_u *)from, tempname) == OK) {
+ if (os_rename(tempname, (char_u *)to) == OK) {
return 0;
}
// Strange, the second step failed. Try moving the
// file back and return failure.
- (void)os_rename(tempname, from);
+ (void)os_rename(tempname, (char_u *)from);
return -1;
}
// If it fails for one temp name it will most likely fail
@@ -4695,28 +4553,22 @@ int vim_rename(const char_u *from, const char_u *to)
return -1;
}
- /*
- * Delete the "to" file, this is required on some systems to make the
- * os_rename() work, on other systems it makes sure that we don't have
- * two files when the os_rename() fails.
- */
+ // Delete the "to" file, this is required on some systems to make the
+ // os_rename() work, on other systems it makes sure that we don't have
+ // two files when the os_rename() fails.
os_remove((char *)to);
- /*
- * First try a normal rename, return if it works.
- */
- if (os_rename(from, to) == OK) {
+ // First try a normal rename, return if it works.
+ if (os_rename((char_u *)from, (char_u *)to) == OK) {
return 0;
}
- /*
- * Rename() failed, try copying the file.
- */
- perm = os_getperm((const char *)from);
+ // Rename() failed, try copying the file.
+ perm = os_getperm(from);
#ifdef HAVE_ACL
// For systems that support ACL: get the ACL from the original file.
- acl = mch_get_acl(from);
+ acl = mch_get_acl((char_u *)from);
#endif
fd_in = os_open((char *)from, O_RDONLY, 0);
if (fd_in < 0) {
@@ -4769,7 +4621,7 @@ int vim_rename(const char_u *from, const char_u *to)
os_setperm((const char *)to, perm);
#endif
#ifdef HAVE_ACL
- mch_set_acl(to, acl);
+ mch_set_acl((char_u *)to, acl);
mch_free_acl(acl);
#endif
if (errmsg != NULL) {
@@ -4852,13 +4704,13 @@ static int move_lines(buf_T *frombuf, buf_T *tobuf)
buf_T *tbuf = curbuf;
int retval = OK;
linenr_T lnum;
- char_u *p;
+ char *p;
// 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));
- if (ml_append(lnum - 1, (char *)p, 0, false) == FAIL) {
+ p = xstrdup(ml_get_buf(frombuf, lnum, false));
+ if (ml_append(lnum - 1, p, 0, false) == FAIL) {
xfree(p);
retval = FAIL;
break;
@@ -4893,7 +4745,7 @@ int buf_check_timestamp(buf_T *buf)
FUNC_ATTR_NONNULL_ALL
{
int retval = 0;
- char_u *path;
+ char *path;
char *mesg = NULL;
char *mesg2 = "";
bool helpmesg = false;
@@ -4908,7 +4760,7 @@ int buf_check_timestamp(buf_T *buf)
uint64_t orig_size = buf->b_orig_size;
int orig_mode = buf->b_orig_mode;
static bool busy = false;
- char_u *s;
+ char *s;
char *reason;
bufref_T bufref;
@@ -4983,12 +4835,12 @@ int buf_check_timestamp(buf_T *buf)
if (!bufref_valid(&bufref)) {
emsg(_("E246: FileChangedShell autocommand deleted buffer"));
}
- s = (char_u *)get_vim_var_str(VV_FCS_CHOICE);
- if (STRCMP(s, "reload") == 0 && *reason != 'd') {
+ s = get_vim_var_str(VV_FCS_CHOICE);
+ if (strcmp(s, "reload") == 0 && *reason != 'd') {
reload = RELOAD_NORMAL;
- } else if (STRCMP(s, "edit") == 0) {
+ } else if (strcmp(s, "edit") == 0) {
reload = RELOAD_DETECT;
- } else if (STRCMP(s, "ask") == 0) {
+ } else if (strcmp(s, "ask") == 0) {
n = false;
} else {
return 2;
@@ -5036,7 +4888,7 @@ int buf_check_timestamp(buf_T *buf)
}
if (mesg != NULL) {
- path = (char_u *)home_replace_save(buf, buf->b_fname);
+ path = home_replace_save(buf, buf->b_fname);
if (!helpmesg) {
mesg2 = "";
}
@@ -5506,7 +5358,7 @@ static bool vim_settempdir(char *tempdir)
///
/// @return pointer to the temp file name or NULL if Nvim can't create
/// temporary directory for its own temporary files.
-char_u *vim_tempname(void)
+char *vim_tempname(void)
{
// Temp filename counter.
static uint64_t temp_count;
@@ -5518,10 +5370,10 @@ char_u *vim_tempname(void)
// There is no need to check if the file exists, because we own the directory
// and nobody else creates a file in it.
- char_u template[TEMP_FILE_PATH_MAXLEN];
- snprintf((char *)template, TEMP_FILE_PATH_MAXLEN,
+ char template[TEMP_FILE_PATH_MAXLEN];
+ snprintf(template, TEMP_FILE_PATH_MAXLEN,
"%s%" PRIu64, tempdir, temp_count++);
- return vim_strsave(template);
+ return xstrdup(template);
}
/// Tries matching a filename with a "pattern" ("prog" is NULL), or use the
@@ -5553,12 +5405,10 @@ bool match_file_pat(char *pattern, regprog_T **prog, char *fname, char *sfname,
}
}
- /*
- * Try for a match with the pattern with:
- * 1. the full file name, when the pattern has a '/'.
- * 2. the short file name, when the pattern has a '/'.
- * 3. the tail of the file name, when the pattern has no '/'.
- */
+ // Try for a match with the pattern with:
+ // 1. the full file name, when the pattern has a '/'.
+ // 2. the short file name, when the pattern has a '/'.
+ // 3. the tail of the file name, when the pattern has no '/'.
if (regmatch.regprog != NULL
&& ((allow_dirs
&& (vim_regexec(&regmatch, fname, (colnr_T)0)
diff --git a/src/nvim/fold.c b/src/nvim/fold.c
index 0f085df3d0..2e8d282ede 100644
--- a/src/nvim/fold.c
+++ b/src/nvim/fold.c
@@ -1582,7 +1582,7 @@ static void foldAddMarker(buf_T *buf, pos_T pos, const char *marker, size_t mark
linenr_T lnum = pos.lnum;
// Allocate a new line: old-line + 'cms'-start + marker + 'cms'-end
- char *line = (char *)ml_get_buf(buf, lnum, false);
+ char *line = ml_get_buf(buf, lnum, false);
size_t line_len = STRLEN(line);
size_t added = 0;
@@ -1640,7 +1640,7 @@ static void foldDelMarker(buf_T *buf, linenr_T lnum, char *marker, size_t marker
}
char *cms = buf->b_p_cms;
- char *line = (char *)ml_get_buf(buf, lnum, false);
+ char *line = ml_get_buf(buf, lnum, false);
for (char *p = line; *p != NUL; p++) {
if (STRNCMP(p, marker, markerlen) != 0) {
continue;
@@ -2848,7 +2848,7 @@ static void foldlevelIndent(fline_T *flp)
linenr_T lnum = flp->lnum + flp->off;
buf_T *buf = flp->wp->w_buffer;
- char *s = skipwhite((char *)ml_get_buf(buf, lnum, false));
+ char *s = skipwhite(ml_get_buf(buf, lnum, false));
// empty line or lines starting with a character in 'foldignore': level
// depends on surrounding lines
@@ -3010,7 +3010,7 @@ static void foldlevelMarker(fline_T *flp)
flp->start = 0;
flp->lvl_next = flp->lvl;
- char *s = (char *)ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off, false);
+ char *s = ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off, false);
while (*s) {
if (*s == cstart
&& STRNCMP(s + 1, startmarker, foldstartmarkerlen - 1) == 0) {
diff --git a/src/nvim/fold.h b/src/nvim/fold.h
index f34e6d43c3..395cd8e30a 100644
--- a/src/nvim/fold.h
+++ b/src/nvim/fold.h
@@ -8,10 +8,8 @@
#include "nvim/pos.h"
#include "nvim/types.h"
-/*
- * Info used to pass info about a fold from the fold-detection code to the
- * code that displays the foldcolumn.
- */
+// Info used to pass info about a fold from the fold-detection code to the
+// code that displays the foldcolumn.
typedef struct foldinfo {
linenr_T fi_lnum; // line number where fold starts
int fi_level; // level of the fold; when this is zero the
diff --git a/src/nvim/garray.c b/src/nvim/garray.c
index 1afabe4e10..adc3eda5ca 100644
--- a/src/nvim/garray.c
+++ b/src/nvim/garray.c
@@ -123,7 +123,7 @@ void ga_remove_duplicate_strings(garray_T *gap)
// loop over the growing array in reverse
for (int i = gap->ga_len - 1; i > 0; i--) {
- if (FNAMECMP(fnames[i - 1], fnames[i]) == 0) {
+ if (path_fnamecmp(fnames[i - 1], fnames[i]) == 0) {
xfree(fnames[i]);
// close the gap (move all strings one slot lower)
diff --git a/src/nvim/generators/gen_options.lua b/src/nvim/generators/gen_options.lua
index 0454c54faf..24b4739fc7 100644
--- a/src/nvim/generators/gen_options.lua
+++ b/src/nvim/generators/gen_options.lua
@@ -115,7 +115,7 @@ local value_dumpers = {
}
local get_value = function(v)
- return '(char_u *) ' .. value_dumpers[type(v)](v)
+ return '(char *) ' .. value_dumpers[type(v)](v)
end
local get_defaults = function(d,n)
diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c
index 4d7339f3b5..0f0e3aece1 100644
--- a/src/nvim/getchar.c
+++ b/src/nvim/getchar.c
@@ -87,25 +87,23 @@ static int block_redo = false;
static int KeyNoremap = 0; // remapping flags
-/*
- * Variables used by vgetorpeek() and flush_buffers()
- *
- * typebuf.tb_buf[] contains all characters that are not consumed yet.
- * typebuf.tb_buf[typebuf.tb_off] is the first valid character.
- * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
- * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
- * The head of the buffer may contain the result of mappings, abbreviations
- * and @a commands. The length of this part is typebuf.tb_maplen.
- * typebuf.tb_silent is the part where <silent> applies.
- * After the head are characters that come from the terminal.
- * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
- * should not be considered for abbreviations.
- * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
- * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
- * contains RM_NONE for the characters that are not to be remapped.
- * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
- * (typebuf has been put in globals.h, because check_termcode() needs it).
- */
+// Variables used by vgetorpeek() and flush_buffers()
+//
+// typebuf.tb_buf[] contains all characters that are not consumed yet.
+// typebuf.tb_buf[typebuf.tb_off] is the first valid character.
+// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
+// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
+// The head of the buffer may contain the result of mappings, abbreviations
+// and @a commands. The length of this part is typebuf.tb_maplen.
+// typebuf.tb_silent is the part where <silent> applies.
+// After the head are characters that come from the terminal.
+// typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
+// should not be considered for abbreviations.
+// Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
+// in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
+// contains RM_NONE for the characters that are not to be remapped.
+// typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
+// (typebuf has been put in globals.h, because check_termcode() needs it).
#define RM_YES 0 // tb_noremap: remap
#define RM_NONE 1 // tb_noremap: don't remap
#define RM_SCRIPT 2 // tb_noremap: remap local script mappings
@@ -124,9 +122,7 @@ static size_t last_recorded_len = 0; // number of last recorded chars
# include "getchar.c.generated.h"
#endif
-/*
- * Free and clear a buffer.
- */
+// Free and clear a buffer.
void free_buff(buffheader_T *buf)
{
buffblock_T *p, *np;
@@ -180,20 +176,16 @@ char_u *get_recorded(void)
p = get_buffcont(&recordbuff, true);
free_buff(&recordbuff);
- /*
- * Remove the characters that were added the last time, these must be the
- * (possibly mapped) characters that stopped the recording.
- */
+ // Remove the characters that were added the last time, these must be the
+ // (possibly mapped) characters that stopped the recording.
len = STRLEN(p);
if (len >= last_recorded_len) {
len -= last_recorded_len;
p[len] = NUL;
}
- /*
- * When stopping recording from Insert mode with CTRL-O q, also remove the
- * CTRL-O.
- */
+ // When stopping recording from Insert mode with CTRL-O q, also remove the
+ // CTRL-O.
if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O) {
p[len - 1] = NUL;
}
@@ -351,9 +343,7 @@ static int read_readbuf(buffheader_T *buf, int advance)
return c;
}
-/*
- * Prepare the read buffers for reading (if they contain something).
- */
+// Prepare the read buffers for reading (if they contain something).
static void start_stuff(void)
{
if (readbuf1.bh_first.b_next != NULL) {
@@ -381,19 +371,15 @@ int readbuf1_empty(void)
return (readbuf1.bh_first.b_next == NULL);
}
-/*
- * Set a typeahead character that won't be flushed.
- */
+// Set a typeahead character that won't be flushed.
void typeahead_noflush(int c)
{
typeahead_char = c;
}
-/*
- * Remove the contents of the stuff buffer and the mapped characters in the
- * typeahead buffer (used in case of an error). If "flush_typeahead" is true,
- * flush all typeahead characters (used when interrupted by a CTRL-C).
- */
+// Remove the contents of the stuff buffer and the mapped characters in the
+// typeahead buffer (used in case of an error). If "flush_typeahead" is true,
+// flush all typeahead characters (used when interrupted by a CTRL-C).
void flush_buffers(flush_buffers_T flush_typeahead)
{
init_typebuf();
@@ -437,10 +423,8 @@ void beep_flush(void)
}
}
-/*
- * The previous contents of the redo buffer is kept in old_redobuffer.
- * This is used for the CTRL-O <.> command in insert mode.
- */
+// The previous contents of the redo buffer is kept in old_redobuffer.
+// This is used for the CTRL-O <.> command in insert mode.
void ResetRedobuff(void)
{
if (!block_redo) {
@@ -450,10 +434,8 @@ void ResetRedobuff(void)
}
}
-/*
- * Discard the contents of the redo buffer and restore the previous redo
- * buffer.
- */
+// Discard the contents of the redo buffer and restore the previous redo
+// buffer.
void CancelRedo(void)
{
if (!block_redo) {
@@ -559,9 +541,7 @@ void AppendCharToRedobuff(int c)
}
}
-/*
- * Append a number to the redo buffer.
- */
+// Append a number to the redo buffer.
void AppendNumberToRedobuff(long n)
{
if (!block_redo) {
@@ -615,9 +595,7 @@ void stuffcharReadbuff(int c)
add_char_buff(&readbuf1, c);
}
-/*
- * Append a number to the stuff buffer.
- */
+// Append a number to the stuff buffer.
void stuffnumReadbuff(long n)
{
add_num_buff(&readbuf1, n);
@@ -783,11 +761,9 @@ int start_redo(long count, bool old_redo)
return OK;
}
-/*
- * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
- * the redo buffer into readbuf2.
- * return FAIL for failure, OK otherwise
- */
+// Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
+// the redo buffer into readbuf2.
+// return FAIL for failure, OK otherwise
int start_redo_ins(void)
{
int c;
@@ -818,11 +794,9 @@ void stop_redo_ins(void)
block_redo = false;
}
-/*
- * Initialize typebuf.tb_buf to point to typebuf_init.
- * alloc() cannot be used here: In out-of-memory situations it would
- * be impossible to type anything.
- */
+// Initialize typebuf.tb_buf to point to typebuf_init.
+// alloc() cannot be used here: In out-of-memory situations it would
+// be impossible to type anything.
static void init_typebuf(void)
{
if (typebuf.tb_buf == NULL) {
@@ -939,14 +913,12 @@ int ins_typebuf(char *str, int noremap, int offset, bool nottyped, bool silent)
val = RM_NONE;
}
- /*
- * Adjust typebuf.tb_noremap[] for the new characters:
- * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
- * (sometimes) not remappable
- * If noremap == REMAP_YES: all the new characters are mappable
- * If noremap > 0: "noremap" characters are not remappable, the rest
- * mappable
- */
+ // Adjust typebuf.tb_noremap[] for the new characters:
+ // If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
+ // (sometimes) not remappable
+ // If noremap == REMAP_YES: all the new characters are mappable
+ // If noremap > 0: "noremap" characters are not remappable, the rest
+ // mappable
if (noremap == REMAP_SKIP) {
nrm = 1;
} else if (noremap < 0) {
@@ -1016,18 +988,14 @@ int typebuf_typed(void)
return typebuf.tb_maplen == 0;
}
-/*
- * Return the number of characters that are mapped (or not typed).
- */
+// Return the number of characters that are mapped (or not typed).
int typebuf_maplen(void)
FUNC_ATTR_PURE
{
return typebuf.tb_maplen;
}
-/*
- * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
- */
+// remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
void del_typebuf(int len, int offset)
{
int i;
@@ -1038,21 +1006,14 @@ void del_typebuf(int len, int offset)
typebuf.tb_len -= len;
- /*
- * Easy case: Just increase typebuf.tb_off.
- */
+ // Easy case: Just increase typebuf.tb_off.
if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
>= 3 * MAXMAPLEN + 3) {
typebuf.tb_off += len;
- }
- /*
- * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
- */
- else {
+ } else {
+ // Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
i = typebuf.tb_off + offset;
- /*
- * Leave some extra room at the end to avoid reallocation.
- */
+ // Leave some extra room at the end to avoid reallocation.
if (typebuf.tb_off > MAXMAPLEN) {
memmove(typebuf.tb_buf + MAXMAPLEN,
typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
@@ -1101,10 +1062,8 @@ void del_typebuf(int len, int offset)
}
}
-/*
- * Write typed characters to script file.
- * If recording is on put the character in the recordbuffer.
- */
+// Write typed characters to script file.
+// If recording is on put the character in the recordbuffer.
static void gotchars(const char_u *chars, size_t len)
FUNC_ATTR_NONNULL_ALL
{
@@ -1161,14 +1120,12 @@ void ungetchars(int len)
}
}
-/*
- * Sync undo. Called when typed characters are obtained from the typeahead
- * buffer, or when a menu is used.
- * Do not sync:
- * - In Insert mode, unless cursor key has been used.
- * - While reading a script file.
- * - When no_u_sync is non-zero.
- */
+// Sync undo. Called when typed characters are obtained from the typeahead
+// buffer, or when a menu is used.
+// Do not sync:
+// - In Insert mode, unless cursor key has been used.
+// - While reading a script file.
+// - When no_u_sync is non-zero.
void may_sync_undo(void)
{
if ((!(State & (MODE_INSERT | MODE_CMDLINE)) || arrow_used)
@@ -1177,9 +1134,7 @@ void may_sync_undo(void)
}
}
-/*
- * Make "typebuf" empty and allocate new buffers.
- */
+// Make "typebuf" empty and allocate new buffers.
void alloc_typebuf(void)
{
typebuf.tb_buf = xmalloc(TYPELEN_INIT);
@@ -1195,9 +1150,7 @@ void alloc_typebuf(void)
}
}
-/*
- * Free the buffers of "typebuf".
- */
+// Free the buffers of "typebuf".
void free_typebuf(void)
{
if (typebuf.tb_buf == typebuf_init) {
@@ -1212,10 +1165,8 @@ void free_typebuf(void)
}
}
-/*
- * When doing ":so! file", the current typeahead needs to be saved, and
- * restored when "file" has been read completely.
- */
+// When doing ":so! file", the current typeahead needs to be saved, and
+// restored when "file" has been read completely.
static typebuf_T saved_typebuf[NSCRIPT];
void save_typebuf(void)
@@ -1239,9 +1190,7 @@ static bool can_get_old_char(void)
return old_char != -1 && (old_KeyStuffed || stuff_empty());
}
-/*
- * Save all three kinds of typeahead, so that the user must type at a prompt.
- */
+// Save all three kinds of typeahead, so that the user must type at a prompt.
void save_typeahead(tasave_T *tp)
{
tp->save_typebuf = typebuf;
@@ -1257,10 +1206,8 @@ void save_typeahead(tasave_T *tp)
readbuf2.bh_first.b_next = NULL;
}
-/*
- * Restore the typeahead to what it was before calling save_typeahead().
- * The allocated memory is freed, can only be called once!
- */
+// Restore the typeahead to what it was before calling save_typeahead().
+// The allocated memory is freed, can only be called once!
void restore_typeahead(tasave_T *tp)
{
if (tp->typebuf_valid) {
@@ -1314,12 +1261,10 @@ void openscript(char *name, bool directly)
}
save_typebuf();
- /*
- * Execute the commands from the file right now when using ":source!"
- * after ":global" or ":argdo" or in a loop. Also when another command
- * follows. This means the display won't be updated. Don't do this
- * always, "make test" would fail.
- */
+ // Execute the commands from the file right now when using ":source!"
+ // after ":global" or ":argdo" or in a loop. Also when another command
+ // follows. This means the display won't be updated. Don't do this
+ // always, "make test" would fail.
if (directly) {
oparg_T oa;
int oldcurscript;
@@ -1348,9 +1293,7 @@ void openscript(char *name, bool directly)
}
}
-/*
- * Close the currently active input script.
- */
+// Close the currently active input script.
static void closescript(void)
{
free_typebuf();
@@ -1452,10 +1395,8 @@ int vgetc(void)
garbage_collect(false);
}
- /*
- * If a character was put back with vungetc, it was already processed.
- * Return it directly.
- */
+ // If a character was put back with vungetc, it was already processed.
+ // Return it directly.
if (can_get_old_char()) {
c = old_char;
old_char = -1;
@@ -1628,11 +1569,9 @@ int vgetc(void)
last_vgetc_recorded_len = last_recorded_len;
}
- /*
- * In the main loop "may_garbage_collect" can be set to do garbage
- * collection in the first next vgetc(). It's disabled after that to
- * avoid internally used Lists and Dicts to be freed.
- */
+ // In the main loop "may_garbage_collect" can be set to do garbage
+ // collection in the first next vgetc(). It's disabled after that to
+ // avoid internally used Lists and Dicts to be freed.
may_garbage_collect = false;
// Execute Lua on_key callbacks.
@@ -1641,10 +1580,8 @@ int vgetc(void)
return c;
}
-/*
- * Like vgetc(), but never return a NUL when called recursively, get a key
- * directly from the user (ignoring typeahead).
- */
+// Like vgetc(), but never return a NUL when called recursively, get a key
+// directly from the user (ignoring typeahead).
int safe_vgetc(void)
{
int c;
@@ -1656,10 +1593,8 @@ int safe_vgetc(void)
return c;
}
-/*
- * Like safe_vgetc(), but loop to handle K_IGNORE.
- * Also ignore scrollbar events.
- */
+// Like safe_vgetc(), but loop to handle K_IGNORE.
+// Also ignore scrollbar events.
int plain_vgetc(void)
{
int c;
@@ -1672,12 +1607,10 @@ int plain_vgetc(void)
return c;
}
-/*
- * Check if a character is available, such that vgetc() will not block.
- * If the next character is a special character or multi-byte, the returned
- * character is not valid!.
- * Returns NUL if no character is available.
- */
+// Check if a character is available, such that vgetc() will not block.
+// If the next character is a special character or multi-byte, the returned
+// character is not valid!.
+// Returns NUL if no character is available.
int vpeekc(void)
{
if (can_get_old_char()) {
@@ -1686,11 +1619,9 @@ int vpeekc(void)
return vgetorpeek(false);
}
-/*
- * Check if any character is available, also half an escape sequence.
- * Trick: when no typeahead found, but there is something in the typeahead
- * buffer, it must be an ESC that is recognized as the start of a key code.
- */
+// Check if any character is available, also half an escape sequence.
+// Trick: when no typeahead found, but there is something in the typeahead
+// buffer, it must be an ESC that is recognized as the start of a key code.
int vpeekc_any(void)
{
int c;
@@ -1702,10 +1633,8 @@ int vpeekc_any(void)
return c;
}
-/*
- * Call vpeekc() without causing anything to be mapped.
- * Return true if a character is available, false otherwise.
- */
+// Call vpeekc() without causing anything to be mapped.
+// Return true if a character is available, false otherwise.
int char_avail(void)
{
int retval;
@@ -1769,6 +1698,7 @@ static void getchar_common(typval_T *argvars, typval_T *rettv)
if (!ui_has_messages()) {
// redraw the screen after getchar()
update_screen(UPD_NOT_VALID);
+ clear_cmdline = true;
}
set_vim_var_nr(VV_MOUSE_WIN, 0);
@@ -1778,26 +1708,26 @@ static void getchar_common(typval_T *argvars, typval_T *rettv)
rettv->vval.v_number = n;
if (n != 0 && (IS_SPECIAL(n) || mod_mask != 0)) {
- char_u temp[10]; // modifier: 3, mbyte-char: 6, NUL: 1
+ char temp[10]; // modifier: 3, mbyte-char: 6, NUL: 1
int i = 0;
// Turn a special key into three bytes, plus modifier.
if (mod_mask != 0) {
- temp[i++] = K_SPECIAL;
- temp[i++] = KS_MODIFIER;
- temp[i++] = (char_u)mod_mask;
+ temp[i++] = (char)K_SPECIAL;
+ temp[i++] = (char)KS_MODIFIER;
+ temp[i++] = (char)mod_mask;
}
if (IS_SPECIAL(n)) {
- temp[i++] = K_SPECIAL;
- temp[i++] = (char_u)K_SECOND(n);
- temp[i++] = K_THIRD(n);
+ temp[i++] = (char)K_SPECIAL;
+ temp[i++] = (char)K_SECOND(n);
+ temp[i++] = (char)K_THIRD(n);
} else {
- i += utf_char2bytes((int)n, (char *)temp + i);
+ i += utf_char2bytes((int)n, temp + i);
}
assert(i < 10);
temp[i++] = NUL;
rettv->v_type = VAR_STRING;
- rettv->vval.v_string = (char *)vim_strsave(temp);
+ rettv->vval.v_string = xstrdup(temp);
if (is_mouse_key((int)n)) {
int row = mouse_row;
@@ -2205,7 +2135,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// complete match
if (keylen >= 0 && keylen <= typebuf.tb_len) {
- char_u *map_str = NULL;
+ char *map_str = NULL;
// Write chars to script file(s).
// Note: :lmap mappings are written *after* being applied. #5658
@@ -2245,8 +2175,8 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
char save_m_expr = mp->m_expr;
int save_m_noremap = mp->m_noremap;
char save_m_silent = mp->m_silent;
- char_u *save_m_keys = NULL; // only saved when needed
- char_u *save_m_str = NULL; // only saved when needed
+ char *save_m_keys = NULL; // only saved when needed
+ char *save_m_str = NULL; // only saved when needed
LuaRef save_m_luaref = mp->m_luaref;
// Handle ":map <expr>": evaluate the {rhs} as an
@@ -2263,9 +2193,9 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
vgetc_busy = 0;
may_garbage_collect = false;
- save_m_keys = vim_strsave(mp->m_keys);
+ save_m_keys = xstrdup((char *)mp->m_keys);
if (save_m_luaref == LUA_NOREF) {
- save_m_str = vim_strsave((char_u *)mp->m_str);
+ save_m_str = xstrdup(mp->m_str);
}
map_str = eval_map_expr(mp, NUL);
@@ -2277,13 +2207,13 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// If an error was displayed and the expression returns an empty
// string, generate a <Nop> to allow for a redraw.
if (prev_did_emsg != did_emsg && (map_str == NULL || *map_str == NUL)) {
- char_u buf[4];
+ char buf[4];
xfree(map_str);
- buf[0] = K_SPECIAL;
- buf[1] = KS_EXTRA;
+ buf[0] = (char)K_SPECIAL;
+ buf[1] = (char)KS_EXTRA;
buf[2] = KE_IGNORE;
buf[3] = NUL;
- map_str = vim_strsave(buf);
+ map_str = xstrdup(buf);
if (State & MODE_CMDLINE) {
// redraw the command below the error
msg_didout = true;
@@ -2297,7 +2227,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
vgetc_busy = save_vgetc_busy;
may_garbage_collect = save_may_garbage_collect;
} else {
- map_str = (char_u *)mp->m_str;
+ map_str = mp->m_str;
}
// Insert the 'to' part in the typebuf.tb_buf.
@@ -2312,18 +2242,18 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// If this is a LANGMAP mapping, then we didn't record the keys
// at the start of the function and have to record them now.
if (keylen > typebuf.tb_maplen && (mp->m_mode & MODE_LANGMAP) != 0) {
- gotchars(map_str, STRLEN(map_str));
+ gotchars((char_u *)map_str, STRLEN(map_str));
}
if (save_m_noremap != REMAP_YES) {
noremap = save_m_noremap;
- } else if (STRNCMP(map_str, save_m_keys != NULL ? save_m_keys : mp->m_keys,
+ } else if (STRNCMP(map_str, save_m_keys != NULL ? save_m_keys : (char *)mp->m_keys,
(size_t)keylen) != 0) {
noremap = REMAP_YES;
} else {
noremap = REMAP_SKIP;
}
- i = ins_typebuf((char *)map_str, noremap, 0, true, cmd_silent || save_m_silent);
+ i = ins_typebuf(map_str, noremap, 0, true, cmd_silent || save_m_silent);
if (save_m_expr) {
xfree(map_str);
}
@@ -2566,7 +2496,7 @@ static int vgetorpeek(bool advance)
// white-space, so find the last non-white
// character -- webb
curwin->w_wcol = 0;
- ptr = get_cursor_line_ptr();
+ ptr = (char_u *)get_cursor_line_ptr();
chartabsize_T cts;
init_chartabsize_arg(&cts, curwin,
curwin->w_cursor.lnum, 0, (char *)ptr, (char *)ptr);
@@ -2596,7 +2526,7 @@ static int vgetorpeek(bool advance)
if (col > 0 && curwin->w_wcol > 0) {
// Correct when the cursor is on the right halve
// of a double-wide character.
- ptr = get_cursor_line_ptr();
+ ptr = (char_u *)get_cursor_line_ptr();
col -= utf_head_off((char *)ptr, (char *)ptr + col);
if (utf_ptr2cells((char *)ptr + col) > 1) {
curwin->w_wcol--;
@@ -2851,11 +2781,9 @@ int inchar(char_u *buf, int maxlen, long wait_time)
ui_flush();
}
- /*
- * Don't reset these when at the hit-return prompt, otherwise an endless
- * recursive loop may result (write error in swapfile, hit-return, timeout
- * on char wait, flush swapfile, write error....).
- */
+ // Don't reset these when at the hit-return prompt, otherwise an endless
+ // recursive loop may result (write error in swapfile, hit-return, timeout
+ // on char wait, flush swapfile, write error....).
if (State != MODE_HITRETURN) {
did_outofmem_msg = false; // display out of memory message (again)
did_swapwrite_msg = false; // display swap file write error again
diff --git a/src/nvim/globals.h b/src/nvim/globals.h
index 060db3b3b1..1cd8db6266 100644
--- a/src/nvim/globals.h
+++ b/src/nvim/globals.h
@@ -599,7 +599,7 @@ EXTERN int inhibit_delete_count INIT(= 0);
#define DBCS_DEBUG (-1)
/// Encoding used when 'fencs' is set to "default"
-EXTERN char_u *fenc_default INIT(= NULL);
+EXTERN char *fenc_default INIT(= NULL);
/// "State" is the main state of Vim.
/// There are other variables that modify the state:
@@ -670,7 +670,7 @@ EXTERN bool cmd_silent INIT(= false); // don't echo the command line
EXTERN int swap_exists_action INIT(= SEA_NONE); ///< For dialog when swap file already exists.
EXTERN bool swap_exists_did_quit INIT(= false); ///< Selected "quit" at the dialog.
-EXTERN char_u IObuff[IOSIZE]; ///< Buffer for sprintf, I/O, etc.
+EXTERN char IObuff[IOSIZE]; ///< Buffer for sprintf, I/O, etc.
EXTERN char NameBuff[MAXPATHL]; ///< Buffer for expanding file names
EXTERN char msg_buf[MSG_BUF_LEN]; ///< Small buffer for messages
EXTERN char os_buf[ ///< Buffer for the os/ layer
diff --git a/src/nvim/grid.c b/src/nvim/grid.c
index 329adfda12..63bb945f73 100644
--- a/src/nvim/grid.c
+++ b/src/nvim/grid.c
@@ -46,14 +46,14 @@ void grid_adjust(ScreenGrid **grid, int *row_off, int *col_off)
}
/// Put a unicode char, and up to MAX_MCO composing chars, in a screen cell.
-int schar_from_cc(char_u *p, int c, int u8cc[MAX_MCO])
+int schar_from_cc(char *p, int c, int u8cc[MAX_MCO])
{
- int len = utf_char2bytes(c, (char *)p);
+ int len = utf_char2bytes(c, p);
for (int i = 0; i < MAX_MCO; i++) {
if (u8cc[i] == 0) {
break;
}
- len += utf_char2bytes(u8cc[i], (char *)p + len);
+ len += utf_char2bytes(u8cc[i], p + len);
}
p[len] = 0;
return len;
@@ -140,7 +140,7 @@ void grid_getbytes(ScreenGrid *grid, int row, int col, char_u *bytes, int *attrp
if (grid->chars != NULL && row < grid->rows && col < grid->cols) {
off = grid->line_offset[row] + (size_t)col;
*attrp = grid->attrs[off];
- schar_copy(bytes, grid->chars[off]);
+ schar_copy((char *)bytes, grid->chars[off]);
}
}
@@ -171,7 +171,7 @@ void grid_puts_line_start(ScreenGrid *grid, int row)
put_dirty_grid = grid;
}
-void grid_put_schar(ScreenGrid *grid, int row, int col, char_u *schar, int attr)
+void grid_put_schar(ScreenGrid *grid, int row, int col, char *schar, int attr)
{
assert(put_dirty_row == row);
size_t off = grid->line_offset[row] + (size_t)col;
@@ -240,7 +240,7 @@ void grid_puts_len(ScreenGrid *grid, char *text, int textlen, int row, int col,
c = (unsigned char)(*ptr);
// check if this is the first byte of a multibyte
mbyte_blen = len > 0
- ? utfc_ptr2len_len((char_u *)ptr, (int)((text + len) - ptr))
+ ? utfc_ptr2len_len(ptr, (int)((text + len) - ptr))
: utfc_ptr2len(ptr);
u8c = len >= 0
? utfc_ptr2char_len((char_u *)ptr, u8cc, (int)((text + len) - ptr))
diff --git a/src/nvim/grid.h b/src/nvim/grid.h
index 6a93bf3d90..0e79183c14 100644
--- a/src/nvim/grid.h
+++ b/src/nvim/grid.h
@@ -29,30 +29,30 @@ EXTERN sattr_T *linebuf_attr INIT(= NULL);
// screen grid.
/// Put a ASCII character in a screen cell.
-static inline void schar_from_ascii(char_u *p, const char c)
+static inline void schar_from_ascii(char *p, const char c)
{
- p[0] = (char_u)c;
+ p[0] = c;
p[1] = 0;
}
/// Put a unicode character in a screen cell.
-static inline int schar_from_char(char_u *p, int c)
+static inline int schar_from_char(char *p, int c)
{
- int len = utf_char2bytes(c, (char *)p);
+ int len = utf_char2bytes(c, p);
p[len] = NUL;
return len;
}
/// compare the contents of two screen cells.
-static inline int schar_cmp(char_u *sc1, char_u *sc2)
+static inline int schar_cmp(char *sc1, char *sc2)
{
- return strncmp((char *)sc1, (char *)sc2, sizeof(schar_T));
+ return strncmp(sc1, sc2, sizeof(schar_T));
}
/// copy the contents of screen cell `sc2` into cell `sc1`
-static inline void schar_copy(char_u *sc1, char_u *sc2)
+static inline void schar_copy(char *sc1, char *sc2)
{
- xstrlcpy((char *)sc1, (char *)sc2, sizeof(schar_T));
+ xstrlcpy(sc1, sc2, sizeof(schar_T));
}
#ifdef INCLUDE_GENERATED_DECLARATIONS
diff --git a/src/nvim/grid_defs.h b/src/nvim/grid_defs.h
index 9252b8a371..57b3817bc6 100644
--- a/src/nvim/grid_defs.h
+++ b/src/nvim/grid_defs.h
@@ -10,7 +10,7 @@
#define MAX_MCO 6 // fixed value for 'maxcombine'
// The characters and attributes drawn on grids.
-typedef char_u schar_T[(MAX_MCO + 1) * 4 + 1];
+typedef char schar_T[(MAX_MCO + 1) * 4 + 1];
typedef int sattr_T;
enum {
diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c
index d7f5730943..b530e2c5ec 100644
--- a/src/nvim/hardcopy.c
+++ b/src/nvim/hardcopy.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * hardcopy.c: printing to paper
- */
+// hardcopy.c: printing to paper
#include <assert.h>
#include <inttypes.h>
@@ -36,64 +34,62 @@
#include "nvim/version.h"
#include "nvim/vim.h"
-/*
- * To implement printing on a platform, the following functions must be
- * defined:
- *
- * int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
- * Called once. Code should display printer dialogue (if appropriate) and
- * determine printer font and margin settings. Reset has_color if the printer
- * doesn't support colors at all.
- * Returns FAIL to abort.
- *
- * int mch_print_begin(prt_settings_T *settings)
- * Called to start the print job.
- * Return false to abort.
- *
- * int mch_print_begin_page(char_u *msg)
- * Called at the start of each page.
- * "msg" indicates the progress of the print job, can be NULL.
- * Return false to abort.
- *
- * int mch_print_end_page()
- * Called at the end of each page.
- * Return false to abort.
- *
- * int mch_print_blank_page()
- * Called to generate a blank page for collated, duplex, multiple copy
- * document. Return false to abort.
- *
- * void mch_print_end(prt_settings_T *psettings)
- * Called at normal end of print job.
- *
- * void mch_print_cleanup()
- * Called if print job ends normally or is abandoned. Free any memory, close
- * devices and handles. Also called when mch_print_begin() fails, but not
- * when mch_print_init() fails.
- *
- * void mch_print_set_font(int Bold, int Italic, int Underline);
- * Called whenever the font style changes.
- *
- * void mch_print_set_bg(uint32_t bgcol);
- * Called to set the background color for the following text. Parameter is an
- * RGB value.
- *
- * void mch_print_set_fg(uint32_t fgcol);
- * Called to set the foreground color for the following text. Parameter is an
- * RGB value.
- *
- * mch_print_start_line(int margin, int page_line)
- * Sets the current position at the start of line "page_line".
- * If margin is true start in the left margin (for header and line number).
- *
- * int mch_print_text_out(char_u *p, size_t len);
- * Output one character of text p[len] at the current position.
- * Return true if there is no room for another character in the same line.
- *
- * Note that the generic code has no idea of margins. The machine code should
- * simply make the page look smaller! The header and the line numbers are
- * printed in the margin.
- */
+// To implement printing on a platform, the following functions must be
+// defined:
+//
+// int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
+// Called once. Code should display printer dialogue (if appropriate) and
+// determine printer font and margin settings. Reset has_color if the printer
+// doesn't support colors at all.
+// Returns FAIL to abort.
+//
+// int mch_print_begin(prt_settings_T *settings)
+// Called to start the print job.
+// Return false to abort.
+//
+// int mch_print_begin_page(char_u *msg)
+// Called at the start of each page.
+// "msg" indicates the progress of the print job, can be NULL.
+// Return false to abort.
+//
+// int mch_print_end_page()
+// Called at the end of each page.
+// Return false to abort.
+//
+// int mch_print_blank_page()
+// Called to generate a blank page for collated, duplex, multiple copy
+// document. Return false to abort.
+//
+// void mch_print_end(prt_settings_T *psettings)
+// Called at normal end of print job.
+//
+// void mch_print_cleanup()
+// Called if print job ends normally or is abandoned. Free any memory, close
+// devices and handles. Also called when mch_print_begin() fails, but not
+// when mch_print_init() fails.
+//
+// void mch_print_set_font(int Bold, int Italic, int Underline);
+// Called whenever the font style changes.
+//
+// void mch_print_set_bg(uint32_t bgcol);
+// Called to set the background color for the following text. Parameter is an
+// RGB value.
+//
+// void mch_print_set_fg(uint32_t fgcol);
+// Called to set the foreground color for the following text. Parameter is an
+// RGB value.
+//
+// mch_print_start_line(int margin, int page_line)
+// Sets the current position at the start of line "page_line".
+// If margin is true start in the left margin (for header and line number).
+//
+// int mch_print_text_out(char_u *p, size_t len);
+// Output one character of text p[len] at the current position.
+// Return true if there is no room for another character in the same line.
+//
+// Note that the generic code has no idea of margins. The machine code should
+// simply make the page look smaller! The header and the line numbers are
+// printed in the margin.
static option_table_T printer_opts[OPT_PRINT_NUM_OPTIONS] = {
{ "top", true, 0, NULL, 0, false },
@@ -154,9 +150,7 @@ static option_table_T mbfont_opts[OPT_MBFONT_NUM_OPTIONS] =
{ "o", false, 0, NULL, 0, false },
};
-/*
- * These values determine the print position on a page.
- */
+// These values determine the print position on a page.
typedef struct {
int lead_spaces; // remaining spaces for a TAB
int print_pos; // virtual column for computing TABs
@@ -182,8 +176,8 @@ struct prt_ps_font_S {
char *(ps_fontname[4]);
};
-/* Structures to map user named encoding and mapping to PS equivalents for
- * building CID font name */
+// Structures to map user named encoding and mapping to PS equivalents for
+// building CID font name
struct prt_ps_encoding_S {
char *encoding;
char *cmap_encoding;
@@ -241,8 +235,8 @@ struct prt_dsc_line_S {
int len;
};
-/* Static buffer to read initial comments in a resource file, some can have a
- * couple of KB of comments! */
+// Static buffer to read initial comments in a resource file, some can have a
+// couple of KB of comments!
#define PRT_FILE_BUFFER_LEN (2048)
struct prt_resfile_buffer_S {
char_u buffer[PRT_FILE_BUFFER_LEN];
@@ -255,33 +249,27 @@ struct prt_resfile_buffer_S {
# include "hardcopy.c.generated.h"
#endif
-/*
- * Parse 'printoptions' and set the flags in "printer_opts".
- * Returns an error message or NULL;
- */
+// Parse 'printoptions' and set the flags in "printer_opts".
+// Returns an error message or NULL;
char *parse_printoptions(void)
{
return parse_list_options((char_u *)p_popt, printer_opts, OPT_PRINT_NUM_OPTIONS);
}
-/*
- * Parse 'printoptions' and set the flags in "printer_opts".
- * Returns an error message or NULL;
- */
+// Parse 'printoptions' and set the flags in "printer_opts".
+// Returns an error message or NULL;
char *parse_printmbfont(void)
{
return parse_list_options((char_u *)p_pmfn, mbfont_opts, OPT_MBFONT_NUM_OPTIONS);
}
-/*
- * Parse a list of options in the form
- * option:value,option:value,option:value
- *
- * "value" can start with a number which is parsed out, e.g. margin:12mm
- *
- * Returns an error message for an illegal option, NULL otherwise.
- * Only used for the printer at the moment...
- */
+// Parse a list of options in the form
+// option:value,option:value,option:value
+//
+// "value" can start with a number which is parsed out, e.g. margin:12mm
+//
+// Returns an error message for an illegal option, NULL otherwise.
+// Only used for the printer at the moment...
static char *parse_list_options(char_u *option_str, option_table_T *table, size_t table_size)
{
option_table_T *old_opts;
@@ -301,9 +289,7 @@ static char *parse_list_options(char_u *option_str, option_table_T *table, size_
table[idx].present = false;
}
- /*
- * Repeat for all comma separated parts.
- */
+ // Repeat for all comma separated parts.
stringp = option_str;
while (*stringp) {
colonp = (char_u *)vim_strchr((char *)stringp, ':');
@@ -361,10 +347,8 @@ static char *parse_list_options(char_u *option_str, option_table_T *table, size_
return ret;
}
-/*
- * If using a dark background, the colors will probably be too bright to show
- * up well on white paper, so reduce their brightness.
- */
+// If using a dark background, the colors will probably be too bright to show
+// up well on white paper, so reduce their brightness.
static uint32_t darken_rgb(uint32_t rgb)
{
return ((rgb >> 17) << 16)
@@ -489,9 +473,7 @@ static void prt_line_number(prt_settings_T *const psettings, const int page_line
}
}
-/*
- * Get the currently effective header height.
- */
+// Get the currently effective header height.
int prt_header_height(void)
{
if (printer_opts[OPT_PRINT_HEADERHEIGHT].present) {
@@ -507,10 +489,8 @@ int prt_use_number(void)
&& TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y';
}
-/*
- * Return the unit used in a margin item in 'printoptions'.
- * Returns PRT_UNIT_NONE if not recognized.
- */
+// Return the unit used in a margin item in 'printoptions'.
+// Returns PRT_UNIT_NONE if not recognized.
int prt_get_unit(int idx)
{
int u = PRT_UNIT_NONE;
@@ -546,12 +526,10 @@ static void prt_header(prt_settings_T *const psettings, const int pagenum, const
linenr_T tmp_lnum, tmp_topline, tmp_botline;
int use_sandbox = false;
- /*
- * Need to (temporarily) set current line number and first/last line
- * number on the 'window'. Since we don't know how long the page is,
- * set the first and current line number to the top line, and guess
- * that the page length is 64.
- */
+ // Need to (temporarily) set current line number and first/last line
+ // number on the 'window'. Since we don't know how long the page is,
+ // set the first and current line number to the top line, and guess
+ // that the page length is 64.
tmp_lnum = curwin->w_cursor.lnum;
tmp_topline = curwin->w_topline;
tmp_botline = curwin->w_botline;
@@ -606,9 +584,7 @@ static void prt_header(prt_settings_T *const psettings, const int pagenum, const
}
}
-/*
- * Display a print status message.
- */
+// Display a print status message.
static void prt_message(char_u *s)
{
// TODO(bfredl): delete this
@@ -644,13 +620,11 @@ void ex_hardcopy(exarg_T *eap)
settings.arguments = (char_u *)eap->arg;
}
- /*
- * Initialise for printing. Ask the user for settings, unless forceit is
- * set.
- * The mch_print_init() code should set up margins if applicable. (It may
- * not be a real printer - for example the engine might generate HTML or
- * PS.)
- */
+ // Initialise for printing. Ask the user for settings, unless forceit is
+ // set.
+ // The mch_print_init() code should set up margins if applicable. (It may
+ // not be a real printer - for example the engine might generate HTML or
+ // PS.)
if (mch_print_init(&settings,
curbuf->b_fname == NULL ? (char_u *)buf_spname(curbuf) : curbuf->b_sfname ==
NULL ? (char_u *)curbuf->b_fname : (char_u *)curbuf->b_sfname,
@@ -687,9 +661,7 @@ void ex_hardcopy(exarg_T *eap)
prt_get_attr(id, &settings.number, settings.modec);
}
- /*
- * Estimate the total lines to be printed
- */
+ // Estimate the total lines to be printed
for (lnum = eap->line1; lnum <= eap->line2; lnum++) {
bytes_to_print += STRLEN(skipwhite((char *)ml_get(lnum)));
}
@@ -717,9 +689,7 @@ void ex_hardcopy(exarg_T *eap)
goto print_fail_no_begin;
}
- /*
- * Loop over collated copies: 1 2 3, 1 2 3, ...
- */
+ // Loop over collated copies: 1 2 3, 1 2 3, ...
page_count = 0;
for (collated_copies = 0;
collated_copies < settings.n_collated_copies;
@@ -740,9 +710,7 @@ void ex_hardcopy(exarg_T *eap)
}
}
- /*
- * Loop over all pages in the print job: 1 2 3 ...
- */
+ // Loop over all pages in the print job: 1 2 3 ...
for (page_count = 0; prtpos.file_line <= eap->line2; page_count++) {
// Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ...
// For duplex: 12 12 12 34 34 34, ...
@@ -752,9 +720,7 @@ void ex_hardcopy(exarg_T *eap)
// Set the print position to the start of this page.
prtpos = page_prtpos;
- /*
- * Do front and rear side of a page.
- */
+ // Do front and rear side of a page.
for (side = 0; side <= settings.duplex; side++) {
// Print one page.
@@ -768,7 +734,7 @@ void ex_hardcopy(exarg_T *eap)
sprintf((char *)IObuff, _("Printing page %d (%zu%%)"),
page_count + 1 + side,
prtpos.bytes_printed * 100 / bytes_to_print);
- if (!mch_print_begin_page(IObuff)) {
+ if (!mch_print_begin_page((char_u *)IObuff)) {
goto print_fail;
}
@@ -778,11 +744,9 @@ void ex_hardcopy(exarg_T *eap)
collated_copies + 1,
settings.n_collated_copies);
}
- prt_message(IObuff);
+ prt_message((char_u *)IObuff);
- /*
- * Output header if required
- */
+ // Output header if required
if (prt_header_height() > 0) {
prt_header(&settings, page_count + 1 + side,
prtpos.file_line);
@@ -814,10 +778,8 @@ void ex_hardcopy(exarg_T *eap)
}
}
- /*
- * Extra blank page for duplexing with odd number of pages and
- * more copies to come.
- */
+ // Extra blank page for duplexing with odd number of pages and
+ // more copies to come.
if (prtpos.file_line > eap->line2 && settings.duplex
&& side == 0
&& uncollated_copies + 1 < settings.n_uncollated_copies) {
@@ -836,13 +798,13 @@ void ex_hardcopy(exarg_T *eap)
vim_snprintf((char *)IObuff, IOSIZE, _("Printed: %s"),
settings.jobname);
- prt_message(IObuff);
+ prt_message((char_u *)IObuff);
}
print_fail:
if (got_int || settings.user_abort) {
- sprintf((char *)IObuff, "%s", _("Printing aborted"));
- prt_message(IObuff);
+ snprintf(IObuff, IOSIZE, "%s", _("Printing aborted"));
+ prt_message((char_u *)IObuff);
}
mch_print_end(&settings);
@@ -850,10 +812,8 @@ print_fail_no_begin:
mch_print_cleanup();
}
-/*
- * Print one page line.
- * Return the next column to print, or zero if the line is finished.
- */
+// Print one page line.
+// Return the next column to print, or zero if the line is finished.
static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T *ppos)
{
colnr_T col;
@@ -881,9 +841,7 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T
mch_print_start_line(false, page_line);
line = (char_u *)ml_get(ppos->file_line);
- /*
- * Loop over the columns until the end of the file line or right margin.
- */
+ // Loop over the columns until the end of the file line or right margin.
for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen) {
if ((outputlen = utfc_ptr2len((char *)line + col)) < 1) {
outputlen = 1;
@@ -908,9 +866,7 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T
}
}
- /*
- * Appropriately expand any tabs to spaces.
- */
+ // Appropriately expand any tabs to spaces.
if (line[col] == TAB || tab_spaces != 0) {
if (tab_spaces == 0) {
tab_spaces = tabstop_padding(print_pos,
@@ -945,10 +901,8 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T
ppos->lead_spaces = tab_spaces;
ppos->print_pos = print_pos;
- /*
- * Start next line of file if we clip lines, or have reached end of the
- * line, unless we are doing a formfeed.
- */
+ // Start next line of file if we clip lines, or have reached end of the
+ // line, unless we are doing a formfeed.
if (!ppos->ff
&& (line[col] == NUL
|| (printer_opts[OPT_PRINT_WRAP].present
@@ -959,34 +913,32 @@ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T
return col;
}
-/*
- * PS printer stuff.
- *
- * Sources of information to help maintain the PS printing code:
- *
- * 1. PostScript Language Reference, 3rd Edition,
- * Addison-Wesley, 1999, ISBN 0-201-37922-8
- * 2. PostScript Language Program Design,
- * Addison-Wesley, 1988, ISBN 0-201-14396-8
- * 3. PostScript Tutorial and Cookbook,
- * Addison Wesley, 1985, ISBN 0-201-10179-3
- * 4. PostScript Language Document Structuring Conventions Specification,
- * version 3.0,
- * Adobe Technote 5001, 25th September 1992
- * 5. PostScript Printer Description File Format Specification, Version 4.3,
- * Adobe technote 5003, 9th February 1996
- * 6. Adobe Font Metrics File Format Specification, Version 4.1,
- * Adobe Technote 5007, 7th October 1998
- * 7. Adobe CMap and CIDFont Files Specification, Version 1.0,
- * Adobe Technote 5014, 8th October 1996
- * 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts,
- * Adoboe Technote 5094, 8th September, 2001
- * 9. CJKV Information Processing, 2nd Edition,
- * O'Reilly, 2002, ISBN 1-56592-224-7
- *
- * Some of these documents can be found in PDF form on Adobe's web site -
- * http://www.adobe.com
- */
+// PS printer stuff.
+//
+// Sources of information to help maintain the PS printing code:
+//
+// 1. PostScript Language Reference, 3rd Edition,
+// Addison-Wesley, 1999, ISBN 0-201-37922-8
+// 2. PostScript Language Program Design,
+// Addison-Wesley, 1988, ISBN 0-201-14396-8
+// 3. PostScript Tutorial and Cookbook,
+// Addison Wesley, 1985, ISBN 0-201-10179-3
+// 4. PostScript Language Document Structuring Conventions Specification,
+// version 3.0,
+// Adobe Technote 5001, 25th September 1992
+// 5. PostScript Printer Description File Format Specification, Version 4.3,
+// Adobe technote 5003, 9th February 1996
+// 6. Adobe Font Metrics File Format Specification, Version 4.1,
+// Adobe Technote 5007, 7th October 1998
+// 7. Adobe CMap and CIDFont Files Specification, Version 1.0,
+// Adobe Technote 5014, 8th October 1996
+// 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts,
+// Adoboe Technote 5094, 8th September, 2001
+// 9. CJKV Information Processing, 2nd Edition,
+// O'Reilly, 2002, ISBN 1-56592-224-7
+//
+// Some of these documents can be found in PDF form on Adobe's web site -
+// http://www.adobe.com
#define PRT_PS_DEFAULT_DPI (72) // Default user space resolution
#define PRT_PS_DEFAULT_FONTSIZE (10)
@@ -1210,16 +1162,15 @@ static struct prt_ps_mbfont_S prt_ps_mbfonts[] =
}
};
-/* The PS prolog file version number has to match - if the prolog file is
- * updated, increment the number in the file and here. Version checking was
- * added as of VIM 6.2.
- * The CID prolog file version number behaves as per PS prolog.
- * Table of VIM and prolog versions:
- *
- * VIM Prolog CIDProlog
- * 6.2 1.3
- * 7.0 1.4 1.0
- */
+// The PS prolog file version number has to match - if the prolog file is
+// updated, increment the number in the file and here. Version checking was
+// added as of VIM 6.2.
+// The CID prolog file version number behaves as per PS prolog.
+// Table of VIM and prolog versions:
+//
+// VIM Prolog CIDProlog
+// 6.2 1.3
+// 7.0 1.4 1.0
#define PRT_PROLOG_VERSION ((char_u *)"1.4")
#define PRT_CID_PROLOG_VERSION ((char_u *)"1.0")
@@ -1230,8 +1181,8 @@ static struct prt_ps_mbfont_S prt_ps_mbfonts[] =
#define PRT_RESOURCE_ENCODING "Encoding"
#define PRT_RESOURCE_CMAP "CMap"
-/* Data for table based DSC comment recognition, easy to extend if VIM needs to
- * read more comments. */
+// Data for table based DSC comment recognition, easy to extend if VIM needs to
+// read more comments.
#define PRT_DSC_MISC_TYPE (-1)
#define PRT_DSC_TITLE_TYPE (1)
#define PRT_DSC_VERSION_TYPE (2)
@@ -1251,17 +1202,13 @@ static struct prt_dsc_comment_S prt_dsc_table[] =
PRT_DSC_ENDCOMMENTS_TYPE }
};
-/*
- * Variables for the output PostScript file.
- */
+// Variables for the output PostScript file.
static FILE *prt_ps_fd;
static bool prt_file_error;
static char_u *prt_ps_file_name = NULL;
-/*
- * Various offsets and dimensions in default PostScript user space (points).
- * Used for text positioning calculations
- */
+// Various offsets and dimensions in default PostScript user space (points).
+// Used for text positioning calculations
static double prt_page_width;
static double prt_page_height;
static double prt_left_margin;
@@ -1276,10 +1223,8 @@ static double prt_bgcol_offset;
static double prt_pos_x_moveto = 0.0;
static double prt_pos_y_moveto = 0.0;
-/*
- * Various control variables used to decide when and how to change the
- * PostScript graphics state.
- */
+// Various control variables used to decide when and how to change the
+// PostScript graphics state.
static bool prt_need_moveto;
static bool prt_do_moveto;
static bool prt_need_font;
@@ -1298,9 +1243,7 @@ static double prt_text_run;
static int prt_page_num;
static int prt_bufsiz;
-/*
- * Variables controlling physical printing.
- */
+// Variables controlling physical printing.
static int prt_media;
static int prt_portrait;
static int prt_num_copies;
@@ -1308,9 +1251,7 @@ static int prt_duplex;
static int prt_tumble;
static int prt_collate;
-/*
- * Buffers used when generating PostScript output
- */
+// Buffers used when generating PostScript output
static char prt_line_buffer[257];
static garray_T prt_ps_buffer = GA_EMPTY_INIT_VALUE;
@@ -1345,36 +1286,28 @@ static void prt_write_file_len(char_u *buffer, size_t bytes)
prt_write_file_raw_len(buffer, bytes);
}
-/*
- * Write a string.
- */
+// Write a string.
static void prt_write_string(char *s)
{
vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer), "%s", s);
prt_write_file(prt_line_buffer);
}
-/*
- * Write an int and a space.
- */
+// Write an int and a space.
static void prt_write_int(int i)
{
snprintf(prt_line_buffer, sizeof(prt_line_buffer), "%d ", i);
prt_write_file(prt_line_buffer);
}
-/*
- * Write a boolean and a space.
- */
+// Write a boolean and a space.
static void prt_write_boolean(int b)
{
snprintf(prt_line_buffer, sizeof(prt_line_buffer), "%s ", (b ? "T" : "F"));
prt_write_file(prt_line_buffer);
}
-/*
- * Write PostScript to re-encode and define the font.
- */
+// Write PostScript to re-encode and define the font.
static void prt_def_font(char *new_name, char *encoding, int height, char *font)
{
vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer),
@@ -1390,9 +1323,7 @@ static void prt_def_font(char *new_name, char *encoding, int height, char *font)
prt_write_file(prt_line_buffer);
}
-/*
- * Write a line to define the CID font.
- */
+// Write a line to define the CID font.
static void prt_def_cidfont(char *new_name, int height, char *cidfont)
{
vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer),
@@ -1403,9 +1334,7 @@ static void prt_def_cidfont(char *new_name, int height, char *cidfont)
prt_write_file(prt_line_buffer);
}
-/*
- * Write a line to define a duplicate of a CID font
- */
+// Write a line to define a duplicate of a CID font
static void prt_dup_cidfont(char *original_name, char *new_name)
{
vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer),
@@ -1413,11 +1342,9 @@ static void prt_dup_cidfont(char *original_name, char *new_name)
prt_write_file(prt_line_buffer);
}
-/*
- * Convert a real value into an integer and fractional part as integers, with
- * the fractional part being in the range [0,10^precision). The fractional part
- * is also rounded based on the precision + 1'th fractional digit.
- */
+// Convert a real value into an integer and fractional part as integers, with
+// the fractional part being in the range [0,10^precision). The fractional part
+// is also rounded based on the precision + 1'th fractional digit.
static void prt_real_bits(double real, int precision, int *pinteger, int *pfraction)
{
int integer = (int)real;
@@ -1433,11 +1360,9 @@ static void prt_real_bits(double real, int precision, int *pinteger, int *pfract
*pfraction = (int)(fraction + 0.5);
}
-/*
- * Write a real and a space. Save bytes if real value has no fractional part!
- * We use prt_real_bits() as %f in sprintf uses the locale setting to decide
- * what decimal point character to use, but PS always requires a '.'.
- */
+// Write a real and a space. Save bytes if real value has no fractional part!
+// We use prt_real_bits() as %f in sprintf uses the locale setting to decide
+// what decimal point character to use, but PS always requires a '.'.
static void prt_write_real(double val, int prec)
{
int integer;
@@ -1463,9 +1388,7 @@ static void prt_write_real(double val, int prec)
prt_write_file(prt_line_buffer);
}
-/*
- * Write a line to define a numeric variable.
- */
+// Write a line to define a numeric variable.
static void prt_def_var(char *name, double value, int prec)
{
vim_snprintf(prt_line_buffer, sizeof(prt_line_buffer),
@@ -1570,8 +1493,8 @@ static int prt_find_resource(char *name, struct prt_ps_resource_S *resource)
// Look for named resource file in runtimepath
STRCPY(buffer, "print");
add_pathsep(buffer);
- STRLCAT(buffer, name, MAXPATHL);
- STRLCAT(buffer, ".ps", MAXPATHL);
+ xstrlcat(buffer, name, MAXPATHL);
+ xstrlcat(buffer, ".ps", MAXPATHL);
resource->filename[0] = NUL;
retval = (do_in_runtimepath(buffer, 0, prt_resource_name, resource->filename)
&& resource->filename[0] != NUL);
@@ -1649,8 +1572,9 @@ static int prt_resfile_skip_ws(int offset)
return -1;
}
-/* prt_next_dsc() - returns detail on next DSC comment line found. Returns true
- * if a DSC comment is found, else false */
+/// Returns detail on next DSC comment line found.
+///
+/// @return true if a DSC comment is found, else false
static bool prt_next_dsc(struct prt_dsc_line_S *p_dsc_line)
FUNC_ATTR_NONNULL_ALL
{
@@ -2020,9 +1944,7 @@ static double to_device_units(int idx, double physsize, int def_number)
return ret;
}
-/*
- * Calculate margins for given width and height from printoptions settings.
- */
+// Calculate margins for given width and height from printoptions settings.
static void prt_page_margins(double width, double height, double *left, double *right, double *top,
double *bottom)
{
@@ -2062,18 +1984,14 @@ static void prt_build_cid_fontname(int font, char_u *name, int name_len)
prt_ps_mb_font.ps_fontname[font] = fontname;
}
-/*
- * Get number of lines of text that fit on a page (excluding the header).
- */
+// Get number of lines of text that fit on a page (excluding the header).
static int prt_get_lpp(void)
{
int lpp;
- /*
- * Calculate offset to lower left corner of background rect based on actual
- * font height (based on its bounding box) and the line height, handling the
- * case where the font height can exceed the line height.
- */
+ // Calculate offset to lower left corner of background rect based on actual
+ // font height (based on its bounding box) and the line height, handling the
+ // case where the font height can exceed the line height.
prt_bgcol_offset = PRT_PS_FONT_TO_USER(prt_line_height,
prt_ps_font->bbox_min_y);
if ((prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y) < 1000.0) {
@@ -2270,9 +2188,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
prt_ps_font = &prt_ps_courier_font;
}
- /*
- * Find the size of the paper and set the margins.
- */
+ // Find the size of the paper and set the margins.
prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present
|| TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) ==
'y');
@@ -2295,13 +2211,11 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
}
prt_media = i;
- /*
- * Set PS pagesize based on media dimensions and print orientation.
- * Note: Media and page sizes have defined meanings in PostScript and should
- * be kept distinct. Media is the paper (or transparency, or ...) that is
- * printed on, whereas the page size is the area that the PostScript
- * interpreter renders into.
- */
+ // Set PS pagesize based on media dimensions and print orientation.
+ // Note: Media and page sizes have defined meanings in PostScript and should
+ // be kept distinct. Media is the paper (or transparency, or ...) that is
+ // printed on, whereas the page size is the area that the PostScript
+ // interpreter renders into.
if (prt_portrait) {
prt_page_width = prt_mediasize[i].width;
prt_page_height = prt_mediasize[i].height;
@@ -2320,9 +2234,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
prt_top_margin = top;
prt_bottom_margin = bottom;
- /*
- * Set up the font size.
- */
+ // Set up the font size.
fontsize = PRT_PS_DEFAULT_FONTSIZE;
for (p = (char_u *)p_pfn; (p = (char_u *)vim_strchr((char *)p, ':')) != NULL; p++) {
if (p[1] == 'h' && ascii_isdigit(p[2])) {
@@ -2331,10 +2243,8 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
}
prt_font_metrics(fontsize);
- /*
- * Return the number of characters per line, and lines per page for the
- * generic print code.
- */
+ // Return the number of characters per line, and lines per page for the
+ // generic print code.
psettings->chars_per_line = prt_get_cpl();
psettings->lines_per_page = prt_get_lpp();
@@ -2343,12 +2253,10 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
return FAIL;
}
- /*
- * Sort out the number of copies to be printed. PS by default will do
- * uncollated copies for you, so once we know how many uncollated copies are
- * wanted cache it away and lie to the generic code that we only want one
- * uncollated copy.
- */
+ // Sort out the number of copies to be printed. PS by default will do
+ // uncollated copies for you, so once we know how many uncollated copies are
+ // wanted cache it away and lie to the generic code that we only want one
+ // uncollated copy.
psettings->n_collated_copies = 1;
psettings->n_uncollated_copies = 1;
prt_num_copies = 1;
@@ -2364,10 +2272,8 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
psettings->jobname = jobname;
- /*
- * Set up printer duplex and tumble based on Duplex option setting - default
- * is long sided duplex printing (i.e. no tumble).
- */
+ // Set up printer duplex and tumble based on Duplex option setting - default
+ // is long sided duplex printing (i.e. no tumble).
prt_duplex = true;
prt_tumble = false;
psettings->duplex = 1;
@@ -2386,7 +2292,7 @@ int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
// If the user didn't specify a file name, use a temp file.
if (psettings->outfile == NULL) {
- prt_ps_file_name = vim_tempname();
+ prt_ps_file_name = (char_u *)vim_tempname();
if (prt_ps_file_name == NULL) {
emsg(_(e_notmp));
return FAIL;
@@ -2491,9 +2397,7 @@ bool mch_print_begin(prt_settings_T *psettings)
struct prt_ps_resource_S res_cidfont;
struct prt_ps_resource_S res_cmap;
- /*
- * PS DSC Header comments - no PS code!
- */
+ // PS DSC Header comments - no PS code!
prt_dsc_start();
prt_dsc_textline("Title", (char *)psettings->jobname);
if (os_get_username(buffer, 256) == FAIL) {
@@ -2685,9 +2589,7 @@ bool mch_print_begin(prt_settings_T *psettings)
prt_num_copies);
prt_dsc_noarg("EndComments");
- /*
- * PS Document page defaults
- */
+ // PS Document page defaults
prt_dsc_noarg("BeginDefaults");
// List font resources most likely common to all pages
@@ -2707,9 +2609,7 @@ bool mch_print_begin(prt_settings_T *psettings)
prt_dsc_noarg("EndDefaults");
- /*
- * PS Document prolog inclusion - all required procsets.
- */
+ // PS Document prolog inclusion - all required procsets.
prt_dsc_noarg("BeginProlog");
// Add required procsets - NOTE: order is important!
@@ -2736,9 +2636,7 @@ bool mch_print_begin(prt_settings_T *psettings)
prt_dsc_noarg("EndProlog");
- /*
- * PS Document setup - must appear after the prolog
- */
+ // PS Document setup - must appear after the prolog
prt_dsc_noarg("BeginSetup");
// Device setup - page size and number of uncollated copies
@@ -2847,9 +2745,7 @@ void mch_print_end(prt_settings_T *psettings)
{
prt_dsc_noarg("Trailer");
- /*
- * Output any info we don't know in toto until we finish
- */
+ // Output any info we don't know in toto until we finish
prt_dsc_ints("Pages", 1, &prt_page_num);
prt_dsc_noarg("EOF");
diff --git a/src/nvim/hardcopy.h b/src/nvim/hardcopy.h
index 9ef4eb0074..ce562cd3e6 100644
--- a/src/nvim/hardcopy.h
+++ b/src/nvim/hardcopy.h
@@ -8,9 +8,7 @@
#include "nvim/globals.h" // for TriState
#include "nvim/types.h" // for char_u
-/*
- * Structure to hold printing color and font attributes.
- */
+// Structure to hold printing color and font attributes.
typedef struct {
uint32_t fg_color;
uint32_t bg_color;
@@ -23,9 +21,7 @@ typedef struct {
int underdashed;
} prt_text_attr_T;
-/*
- * Structure passed back to the generic printer code.
- */
+// Structure passed back to the generic printer code.
typedef struct {
int n_collated_copies;
int n_uncollated_copies;
@@ -42,9 +38,7 @@ typedef struct {
char_u *arguments;
} prt_settings_T;
-/*
- * Generic option table item, only used for printer at the moment.
- */
+// Generic option table item, only used for printer at the moment.
typedef struct {
const char *name;
int hasnum;
diff --git a/src/nvim/help.c b/src/nvim/help.c
index 245d80489f..507c5904b3 100644
--- a/src/nvim/help.c
+++ b/src/nvim/help.c
@@ -180,7 +180,7 @@ void ex_help(exarg_T *eap)
// It is needed for do_tag top open folds under the cursor.
KeyTyped = old_KeyTyped;
- do_tag((char_u *)tag, DT_HELP, 1, false, true);
+ do_tag(tag, DT_HELP, 1, false, true);
// Delete the empty buffer if we're not using it. Careful: autocommands
// may have jumped to another window, check that the buffer is not in a
@@ -367,7 +367,7 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep
// the table, it is taken literally (but ~ is escaped). Otherwise '?'
// is recognized as a wildcard.
for (i = (int)ARRAY_SIZE(expr_table); --i >= 0;) {
- if (STRCMP(arg + 5, expr_table[i]) == 0) {
+ if (strcmp(arg + 5, expr_table[i]) == 0) {
for (int si = 0, di = 0;; si++) {
if (arg[si] == '~') {
d[di++] = '\\';
@@ -384,7 +384,7 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep
// Recognize a few exceptions to the rule. Some strings that contain
// '*'are changed to "star", otherwise '*' is recognized as a wildcard.
for (i = 0; except_tbl[i][0] != NULL; i++) {
- if (STRCMP(arg, except_tbl[i][0]) == 0) {
+ if (strcmp(arg, except_tbl[i][0]) == 0) {
STRCPY(d, except_tbl[i][1]);
break;
}
@@ -428,7 +428,7 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep
// completion.
// Insert a backslash before '~', '$' and '.' to avoid their
// special meaning.
- if ((char_u *)d - IObuff > IOSIZE - 10) { // getting too long!?
+ if (d - IObuff > IOSIZE - 10) { // getting too long!?
break;
}
switch (*s) {
@@ -459,7 +459,7 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep
if (*s < ' '
|| (*s == '^' && s[1]
&& (ASCII_ISALPHA(s[1]) || vim_strchr("?@[\\]^", s[1]) != NULL))) {
- if ((char_u *)d > IObuff && d[-1] != '_' && d[-1] != '\\') {
+ if (d > IObuff && d[-1] != '_' && d[-1] != '\\') {
*d++ = '_'; // prepend a '_' to make x_CTRL-x
}
STRCPY(d, "CTRL-");
@@ -513,15 +513,15 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep
*d = NUL;
if (*IObuff == '`') {
- if ((char_u *)d > IObuff + 2 && d[-1] == '`') {
+ if (d > IObuff + 2 && d[-1] == '`') {
// remove the backticks from `command`
memmove(IObuff, IObuff + 1, STRLEN(IObuff));
d[-2] = NUL;
- } else if ((char_u *)d > IObuff + 3 && d[-2] == '`' && d[-1] == ',') {
+ } else if (d > IObuff + 3 && d[-2] == '`' && d[-1] == ',') {
// remove the backticks and comma from `command`,
memmove(IObuff, IObuff + 1, STRLEN(IObuff));
d[-3] = NUL;
- } else if ((char_u *)d > IObuff + 4 && d[-3] == '`'
+ } else if (d > IObuff + 4 && d[-3] == '`'
&& d[-2] == '\\' && d[-1] == '.') {
// remove the backticks and dot from `command`\.
memmove(IObuff, IObuff + 1, STRLEN(IObuff));
@@ -556,8 +556,8 @@ int find_help_tags(const char *arg, int *num_matches, char ***matches, bool keep
/// tag matches it. Otherwise remove "@en" if "en" is the only language.
void cleanup_help_tags(int num_file, char **file)
{
- char_u buf[4];
- char_u *p = buf;
+ char buf[4];
+ char_u *p = (char_u *)buf;
if (p_hlg[0] != NUL && (p_hlg[0] != 'e' || p_hlg[1] != 'n')) {
*p++ = '@';
@@ -571,7 +571,7 @@ void cleanup_help_tags(int num_file, char **file)
if (len <= 0) {
continue;
}
- if (STRCMP(file[i] + len, "@en") == 0) {
+ if (strcmp(file[i] + len, "@en") == 0) {
// Sorting on priority means the same item in another language may
// be anywhere. Search all items for a match up to the "@en".
int j;
@@ -595,7 +595,7 @@ void cleanup_help_tags(int num_file, char **file)
if (len <= 0) {
continue;
}
- if (STRCMP(file[i] + len, buf) == 0) {
+ if (strcmp(file[i] + len, buf) == 0) {
// remove the default language
file[i][len] = NUL;
}
@@ -615,7 +615,7 @@ void prepare_help_buffer(void)
// latin1 word characters (for translated help files).
// Only set it when needed, buf_init_chartab() is some work.
char *p = "!-~,^*,^|,^\",192-255";
- if (STRCMP(curbuf->b_p_isk, p) != 0) {
+ if (strcmp(curbuf->b_p_isk, p) != 0) {
set_string_option_direct("isk", -1, p, OPT_FREE|OPT_LOCAL, 0);
check_buf_options(curbuf);
(void)buf_init_chartab(curbuf, false);
@@ -650,7 +650,7 @@ void fix_help_buffer(void)
bool in_example = false;
// Set filetype to "help".
- if (STRCMP(curbuf->b_p_ft, "help") != 0) {
+ if (strcmp(curbuf->b_p_ft, "help") != 0) {
curbuf->b_ro_locked++;
set_option_value_give_err("ft", 0L, "help", OPT_LOCAL);
curbuf->b_ro_locked--;
@@ -658,13 +658,13 @@ void fix_help_buffer(void)
if (!syntax_present(curwin)) {
for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; lnum++) {
- line = (char *)ml_get_buf(curbuf, lnum, false);
+ 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.
if (line[0] == '<') {
// blank-out a '<' in the first column
- line = (char *)ml_get_buf(curbuf, lnum, true);
+ line = ml_get_buf(curbuf, lnum, true);
line[0] = ' ';
}
in_example = false;
@@ -672,12 +672,12 @@ void fix_help_buffer(void)
if (!in_example && len > 0) {
if (line[len - 1] == '>' && (len == 1 || line[len - 2] == ' ')) {
// blank-out a '>' in the last column (start of example)
- line = (char *)ml_get_buf(curbuf, lnum, true);
+ line = ml_get_buf(curbuf, lnum, true);
line[len - 1] = ' ';
in_example = true;
} else if (line[len - 1] == '~') {
// blank-out a '~' at the end of line (header marker)
- line = (char *)ml_get_buf(curbuf, lnum, true);
+ line = ml_get_buf(curbuf, lnum, true);
line[len - 1] = ' ';
}
}
@@ -687,14 +687,14 @@ void fix_help_buffer(void)
// In the "help.txt" and "help.abx" file, add the locally added help
// files. This uses the very first line in the help file.
char *const fname = path_tail(curbuf->b_fname);
- if (FNAMECMP(fname, "help.txt") == 0
- || (FNAMENCMP(fname, "help.", 5) == 0
+ if (path_fnamecmp(fname, "help.txt") == 0
+ || (path_fnamencmp(fname, "help.", 5) == 0
&& ASCII_ISALPHA(fname[5])
&& ASCII_ISALPHA(fname[6])
&& TOLOWER_ASC(fname[7]) == 'x'
&& fname[8] == NUL)) {
for (lnum = 1; lnum < curbuf->b_ml.ml_line_count; lnum++) {
- line = (char *)ml_get_buf(curbuf, lnum, false);
+ line = ml_get_buf(curbuf, lnum, false);
if (strstr(line, "*local-additions*") == NULL) {
continue;
}
@@ -715,8 +715,8 @@ void fix_help_buffer(void)
// Find all "doc/ *.txt" files in this directory.
if (!add_pathsep((char *)NameBuff)
- || STRLCAT(NameBuff, "doc/*.??[tx]", // NOLINT
- sizeof(NameBuff)) >= MAXPATHL) {
+ || xstrlcat(NameBuff, "doc/*.??[tx]", // NOLINT
+ sizeof(NameBuff)) >= MAXPATHL) {
emsg(_(e_fnametoolong));
continue;
}
@@ -746,18 +746,18 @@ void fix_help_buffer(void)
if (e1 == NULL || e2 == NULL) {
continue;
}
- if (FNAMECMP(e1, ".txt") != 0
- && FNAMECMP(e1, fname + 4) != 0) {
+ if (path_fnamecmp(e1, ".txt") != 0
+ && path_fnamecmp(e1, fname + 4) != 0) {
// Not .txt and not .abx, remove it.
XFREE_CLEAR(fnames[i1]);
continue;
}
if (e1 - f1 != e2 - f2
- || FNAMENCMP(f1, f2, e1 - f1) != 0) {
+ || path_fnamencmp(f1, f2, (size_t)(e1 - f1)) != 0) {
continue;
}
- if (FNAMECMP(e1, ".txt") == 0
- && FNAMECMP(e2, fname + 4) == 0) {
+ if (path_fnamecmp(e1, ".txt") == 0
+ && path_fnamecmp(e2, fname + 4) == 0) {
// use .abx instead of .txt
XFREE_CLEAR(fnames[i1]);
}
@@ -772,7 +772,7 @@ void fix_help_buffer(void)
if (fd == NULL) {
continue;
}
- vim_fgets(IObuff, IOSIZE, fd);
+ vim_fgets((char_u *)IObuff, IOSIZE, fd);
if (IObuff[0] == '*'
&& (s = vim_strchr((char *)IObuff + 1, '*'))
!= NULL) {
@@ -819,7 +819,7 @@ void fix_help_buffer(void)
convert_setup(&vc, NULL, NULL);
ml_append(lnum, cp, (colnr_T)0, false);
- if ((char_u *)cp != IObuff) {
+ if (cp != IObuff) {
xfree(cp);
}
lnum++;
@@ -871,8 +871,8 @@ static void helptags_one(char *dir, const char *ext, const char *tagfname, bool
// Find all *.txt files.
size_t dirlen = STRLCPY(NameBuff, dir, sizeof(NameBuff));
if (dirlen >= MAXPATHL
- || STRLCAT(NameBuff, "/**/*", sizeof(NameBuff)) >= MAXPATHL // NOLINT
- || STRLCAT(NameBuff, ext, sizeof(NameBuff)) >= MAXPATHL) {
+ || xstrlcat(NameBuff, "/**/*", sizeof(NameBuff)) >= MAXPATHL // NOLINT
+ || xstrlcat(NameBuff, ext, sizeof(NameBuff)) >= MAXPATHL) {
emsg(_(e_fnametoolong));
return;
}
@@ -896,7 +896,7 @@ static void helptags_one(char *dir, const char *ext, const char *tagfname, bool
// Do this before scanning through all the files.
memcpy(NameBuff, dir, dirlen + 1);
if (!add_pathsep((char *)NameBuff)
- || STRLCAT(NameBuff, tagfname, sizeof(NameBuff)) >= MAXPATHL) {
+ || xstrlcat(NameBuff, tagfname, sizeof(NameBuff)) >= MAXPATHL) {
emsg(_(e_fnametoolong));
return;
}
@@ -931,7 +931,7 @@ static void helptags_one(char *dir, const char *ext, const char *tagfname, bool
const char *const fname = files[fi] + dirlen + 1;
bool firstline = true;
- while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int) {
+ while (!vim_fgets((char_u *)IObuff, IOSIZE, fd) && !got_int) {
if (firstline) {
// Detect utf-8 file by a non-ASCII char in the first line.
TriState this_utf8 = kNone;
@@ -974,7 +974,7 @@ static void helptags_one(char *dir, const char *ext, const char *tagfname, bool
// characters, there is white space before it and is
// followed by a white character or end-of-line.
if (s == p2
- && ((char_u *)p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
+ && (p1 == IObuff || p1[-1] == ' ' || p1[-1] == '\t')
&& (vim_strchr(" \t\n\r", s[1]) != NULL
|| s[1] == '\0')) {
*p2 = '\0';
@@ -1067,7 +1067,7 @@ static void do_helptags(char *dirname, bool add_help_tags, bool ignore_writeerr)
// Get a list of all files in the help directory and in subdirectories.
STRLCPY(NameBuff, dirname, sizeof(NameBuff));
if (!add_pathsep((char *)NameBuff)
- || STRLCAT(NameBuff, "**", sizeof(NameBuff)) >= MAXPATHL) {
+ || xstrlcat(NameBuff, "**", sizeof(NameBuff)) >= MAXPATHL) {
emsg(_(e_fnametoolong));
return;
}
@@ -1162,13 +1162,12 @@ void ex_helptags(exarg_T *eap)
eap->arg = skipwhite(eap->arg + 3);
}
- if (STRCMP(eap->arg, "ALL") == 0) {
+ if (strcmp(eap->arg, "ALL") == 0) {
do_in_path(p_rtp, "doc", DIP_ALL + DIP_DIR, helptags_cb, &add_help_tags);
} else {
ExpandInit(&xpc);
xpc.xp_context = EXPAND_DIRECTORIES;
- dirname = (char *)ExpandOne(&xpc, (char_u *)eap->arg, NULL,
- WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE);
+ dirname = ExpandOne(&xpc, eap->arg, NULL, WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE);
if (dirname == NULL || !os_isdir(dirname)) {
semsg(_("E150: Not a directory: %s"), eap->arg);
} else {
diff --git a/src/nvim/highlight_group.c b/src/nvim/highlight_group.c
index 5c07784db3..2cb8fabfb4 100644
--- a/src/nvim/highlight_group.c
+++ b/src/nvim/highlight_group.c
@@ -186,7 +186,6 @@ static const char *highlight_init_both[] = {
"default link DiagnosticSignInfo DiagnosticInfo",
"default link DiagnosticSignHint DiagnosticHint",
- "default link @error Error",
"default link @text.underline Underlined",
"default link @todo Todo",
"default link @debug Debug",
@@ -554,12 +553,12 @@ void init_highlight(bool both, bool reset)
// Try finding the color scheme file. Used when a color file was loaded
// and 'background' or 't_Co' is changed.
- char_u *p = get_var_value("g:colors_name");
+ char *p = (char *)get_var_value("g:colors_name");
if (p != NULL) {
// Value of g:colors_name could be freed in load_colors() and make
// p invalid, so copy it.
- char_u *copy_p = vim_strsave(p);
- bool okay = load_colors(copy_p);
+ char *copy_p = xstrdup(p);
+ bool okay = load_colors((char_u *)copy_p);
xfree(copy_p);
if (okay) {
return;
@@ -792,7 +791,7 @@ void set_hl_group(int id, HlAttrs attrs, Dict(highlight) *dict, int link_id)
g->sg_attr = hl_get_syn_attr(0, id, attrs);
// 'Normal' is special
- if (STRCMP(g->sg_name_u, "NORMAL") == 0) {
+ if (strcmp(g->sg_name_u, "NORMAL") == 0) {
cterm_normal_fg_color = g->sg_cterm_fg;
cterm_normal_bg_color = g->sg_cterm_bg;
normal_fg = g->sg_rgb_fg;
@@ -989,7 +988,7 @@ void do_highlight(const char *line, const bool forceit, const bool init)
// Make a copy so we can check if any attribute actually changed
item_before = hl_table[idx];
- is_normal_group = (STRCMP(hl_table[idx].sg_name_u, "NORMAL") == 0);
+ is_normal_group = (strcmp(hl_table[idx].sg_name_u, "NORMAL") == 0);
// Clear the highlighting for ":hi clear {group}" and ":hi clear".
if (doclear || (forceit && init)) {
@@ -1120,9 +1119,9 @@ 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) {
+ } else if (strcmp(key, "CTERMFG") == 0 || strcmp(key, "CTERMBG") == 0) {
if (!init || !(hl_table[idx].sg_set & SG_CTERM)) {
if (!init) {
hl_table[idx].sg_set |= SG_CTERM;
@@ -1240,7 +1239,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) {
int *indexp = &hl_table[idx].sg_rgb_bg_idx;
if (!init || !(hl_table[idx].sg_set & SG_GUI)) {
@@ -1251,7 +1250,7 @@ void do_highlight(const char *line, const bool forceit, const bool init)
RgbValue old_color = hl_table[idx].sg_rgb_bg;
int old_idx = hl_table[idx].sg_rgb_bg_idx;
- if (STRCMP(arg, "NONE") != 0) {
+ if (strcmp(arg, "NONE") != 0) {
hl_table[idx].sg_rgb_bg = name_to_color(arg, indexp);
} else {
hl_table[idx].sg_rgb_bg = -1;
diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c
index e54bffb587..719899d0b8 100644
--- a/src/nvim/if_cscope.c
+++ b/src/nvim/if_cscope.c
@@ -1,13 +1,11 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * CSCOPE support for Vim added by Andy Kahn <kahn@zk3.dec.com>
- * Ported to Win32 by Sergey Khorev <sergey.khorev@gmail.com>
- *
- * The basic idea/structure of cscope for Vim was borrowed from Nvi. There
- * might be a few lines of code that look similar to what Nvi has.
- */
+// CSCOPE support for Vim added by Andy Kahn <kahn@zk3.dec.com>
+// Ported to Win32 by Sergey Khorev <sergey.khorev@gmail.com>
+//
+// The basic idea/structure of cscope for Vim was borrowed from Nvi. There
+// might be a few lines of code that look similar to what Nvi has.
#include <assert.h>
#include <errno.h>
@@ -78,10 +76,8 @@ static enum {
EXP_CSCOPE_KILL, // expand ":cscope kill" arguments
} expand_what;
-/*
- * Function given to ExpandGeneric() to obtain the cscope command
- * expansion.
- */
+// Function given to ExpandGeneric() to obtain the cscope command
+// expansion.
char *get_cscope_name(expand_T *xp, int idx)
{
int current_idx;
@@ -140,9 +136,7 @@ char *get_cscope_name(expand_T *xp, int idx)
}
}
-/*
- * Handle command line completion for :cscope command.
- */
+// Handle command line completion for :cscope command.
void set_context_in_cscope_cmd(expand_T *xp, const char *arg, cmdidx_T cmdidx)
{
// Default: expand subcommands.
@@ -234,16 +228,16 @@ void ex_cstag(exarg_T *eap)
}
if (cs_check_for_tags()) {
- ret = do_tag((char_u *)eap->arg, DT_JUMP, 0, eap->forceit, false);
+ ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, false);
}
}
} else if (cs_check_for_tags()) {
- ret = do_tag((char_u *)eap->arg, DT_JUMP, 0, eap->forceit, false);
+ ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, false);
}
break;
case 1:
if (cs_check_for_tags()) {
- ret = do_tag((char_u *)eap->arg, DT_JUMP, 0, eap->forceit, false);
+ ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, false);
if (ret == false) {
if (msg_col) {
msg_putchar('\n');
@@ -304,33 +298,31 @@ void cs_print_tags(void)
cs_manage_matches(NULL, NULL, 0, Print);
}
-/*
- * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
- *
- * Checks for the existence of a |cscope| connection. If no
- * parameters are specified, then the function returns:
- *
- * 0, if cscope was not available (not compiled in), or if there
- * are no cscope connections; or
- * 1, if there is at least one cscope connection.
- *
- * If parameters are specified, then the value of {num}
- * determines how existence of a cscope connection is checked:
- *
- * {num} Description of existence check
- * ----- ------------------------------
- * 0 Same as no parameters (e.g., "cscope_connection()").
- * 1 Ignore {prepend}, and use partial string matches for
- * {dbpath}.
- * 2 Ignore {prepend}, and use exact string matches for
- * {dbpath}.
- * 3 Use {prepend}, use partial string matches for both
- * {dbpath} and {prepend}.
- * 4 Use {prepend}, use exact string matches for both
- * {dbpath} and {prepend}.
- *
- * Note: All string comparisons are case sensitive!
- */
+// "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
+//
+// Checks for the existence of a |cscope| connection. If no
+// parameters are specified, then the function returns:
+//
+// 0, if cscope was not available (not compiled in), or if there
+// are no cscope connections; or
+// 1, if there is at least one cscope connection.
+//
+// If parameters are specified, then the value of {num}
+// determines how existence of a cscope connection is checked:
+//
+// {num} Description of existence check
+// ----- ------------------------------
+// 0 Same as no parameters (e.g., "cscope_connection()").
+// 1 Ignore {prepend}, and use partial string matches for
+// {dbpath}.
+// 2 Ignore {prepend}, and use exact string matches for
+// {dbpath}.
+// 3 Use {prepend}, use partial string matches for both
+// {dbpath} and {prepend}.
+// 4 Use {prepend}, use exact string matches for both
+// {dbpath} and {prepend}.
+//
+// Note: All string comparisons are case sensitive!
bool cs_connection(int num, char_u *dbpath, char_u *ppath)
{
if (num < 0 || num > 4 || (num > 0 && !dbpath)) {
@@ -379,9 +371,8 @@ bool cs_connection(int num, char_u *dbpath, char_u *ppath)
return false;
} // cs_connection
-/*
- * PRIVATE functions
- ****************************************************************************/
+// PRIVATE functions
+// **************************************************************************
/// Add cscope database or a directory name (to look for cscope.out)
/// to the cscope connection list.
@@ -684,10 +675,8 @@ static int cs_create_connection(size_t i)
char *prog, *cmd, *ppath = NULL;
#if defined(UNIX)
- /*
- * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from
- * from_cs[0] and writes to to_cs[1].
- */
+ // Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from
+ // from_cs[0] and writes to to_cs[1].
to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1;
if (pipe(to_cs) < 0 || pipe(from_cs) < 0) {
(void)emsg(_("E566: Could not create cscope pipes"));
@@ -896,10 +885,8 @@ static int cs_find(exarg_T *eap)
return false;
}
- /*
- * Let's replace the NULs written by strtok() with spaces - we need the
- * spaces to correctly display the quickfix/location list window's title.
- */
+ // Let's replace the NULs written by strtok() with spaces - we need the
+ // spaces to correctly display the quickfix/location list window's title.
for (int i = 0; i < eap_arg_len; i++) {
if (NUL == eap->arg[i]) {
eap->arg[i] = ' ';
@@ -1016,7 +1003,7 @@ static bool cs_find_common(char *opt, char *pat, int forceit, int verbose, bool
if (qfpos != NULL && *qfpos != '0') {
// Fill error list.
FILE *f;
- char_u *tmp = vim_tempname();
+ char_u *tmp = (char_u *)vim_tempname();
qf_info_T *qi = NULL;
win_T *wp = NULL;
@@ -1041,10 +1028,8 @@ static bool cs_find_common(char *opt, char *pat, int forceit, int verbose, bool
apply_autocmds(EVENT_QUICKFIXCMDPOST, "cscope", curbuf->b_fname, true, curbuf);
if (use_ll) {
- /*
- * In the location list window, use the displayed location
- * list. Otherwise, use the location list for the window.
- */
+ // In the location list window, use the displayed location
+ // list. Otherwise, use the location list for the window.
qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)
? wp->w_llist_ref : wp->w_llist;
}
@@ -1068,7 +1053,7 @@ static bool cs_find_common(char *opt, char *pat, int forceit, int verbose, bool
(void)cs_manage_matches(matches, contexts, matched, Store);
- return do_tag((char_u *)pat, DT_CSCOPE, 0, forceit, verbose);
+ return do_tag(pat, DT_CSCOPE, 0, forceit, verbose);
}
}
@@ -1431,11 +1416,9 @@ retry:
}
*p = '\0';
- /*
- * cscope output is in the following format:
- *
- * <filename> <context> <line number> <pattern>
- */
+ // cscope output is in the following format:
+ //
+ // <filename> <context> <line number> <pattern>
char *saveptr = NULL;
if ((name = os_strtok(buf, (const char *)" ", &saveptr)) == NULL) {
return NULL;
@@ -1786,9 +1769,7 @@ static int cs_read_prompt(size_t i)
}
#if defined(UNIX) && defined(SIGALRM)
-/*
- * Used to catch and ignore SIGALRM below.
- */
+// Used to catch and ignore SIGALRM below.
static void sig_handler(int s)
{
// do nothing
@@ -1847,25 +1828,21 @@ static void cs_release_csp(size_t i, bool freefnpp)
os_delay(50L, false); // sleep 50 ms
}
# endif
- /*
- * If the cscope process is still running: kill it.
- * Safety check: If the PID would be zero here, the entire X session
- * would be killed. -1 and 1 are dangerous as well.
- */
+ // If the cscope process is still running: kill it.
+ // Safety check: If the PID would be zero here, the entire X session
+ // would be killed. -1 and 1 are dangerous as well.
if (pid < 0 && csinfo[i].pid > 1) {
# ifdef ECHILD
bool alive = true;
if (waitpid_errno == ECHILD) {
- /*
- * When using 'vim -g', vim is forked and cscope process is
- * no longer a child process but a sibling. So waitpid()
- * fails with errno being ECHILD (No child processes).
- * Don't send SIGKILL to cscope immediately but wait
- * (polling) for it to exit normally as result of sending
- * the "q" command, hence giving it a chance to clean up
- * its temporary files.
- */
+ // When using 'vim -g', vim is forked and cscope process is
+ // no longer a child process but a sibling. So waitpid()
+ // fails with errno being ECHILD (No child processes).
+ // Don't send SIGKILL to cscope immediately but wait
+ // (polling) for it to exit normally as result of sending
+ // the "q" command, hence giving it a chance to clean up
+ // its temporary files.
int waited;
sleep(0);
@@ -1974,11 +1951,9 @@ static char *cs_resolve_file(size_t i, char *name)
char *fullname;
char_u *csdir = NULL;
- /*
- * Ppath is freed when we destroy the cscope connection.
- * Fullname is freed after cs_make_vim_style_matches, after it's been
- * copied into the tag buffer used by Vim.
- */
+ // Ppath is freed when we destroy the cscope connection.
+ // Fullname is freed after cs_make_vim_style_matches, after it's been
+ // copied into the tag buffer used by Vim.
size_t len = strlen(name) + 2;
if (csinfo[i].ppath != NULL) {
len += strlen(csinfo[i].ppath);
diff --git a/src/nvim/indent.c b/src/nvim/indent.c
index da4bcf6934..0f7a5a8e44 100644
--- a/src/nvim/indent.c
+++ b/src/nvim/indent.c
@@ -343,7 +343,7 @@ int get_sts_value(void)
// Count the size (in window cells) of the indent in the current line.
int get_indent(void)
{
- return get_indent_str_vtab((char *)get_cursor_line_ptr(),
+ return get_indent_str_vtab(get_cursor_line_ptr(),
curbuf->b_p_ts,
curbuf->b_p_vts_array,
false);
@@ -362,7 +362,7 @@ int get_indent_lnum(linenr_T lnum)
// "buf".
int get_indent_buf(buf_T *buf, linenr_T lnum)
{
- return get_indent_str_vtab((char *)ml_get_buf(buf, lnum, false),
+ return get_indent_str_vtab(ml_get_buf(buf, lnum, false),
curbuf->b_p_ts,
buf->b_p_vts_array,
false);
@@ -454,7 +454,7 @@ int set_indent(int size, int flags)
// characters needed for the indent.
todo = size;
ind_len = 0;
- p = oldline = get_cursor_line_ptr();
+ p = oldline = (char_u *)get_cursor_line_ptr();
// Calculate the buffer size for the new indent, and check to see if it
// isn't already set.
@@ -721,7 +721,7 @@ int get_number_indent(linenr_T lnum)
// start matching for the flp beyond any comment leader...
if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0)) {
pos.lnum = lnum;
- pos.col = (colnr_T)(*regmatch.endp - (char_u *)ml_get(lnum));
+ pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
pos.coladd = 0;
}
vim_regfree(regmatch.regprog);
@@ -857,7 +857,7 @@ int inindent(int extra)
char_u *ptr;
colnr_T col;
- for (col = 0, ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr); col++) {
+ for (col = 0, ptr = (char_u *)get_cursor_line_ptr(); ascii_iswhite(*ptr); col++) {
ptr++;
}
@@ -874,7 +874,7 @@ bool may_do_si(void)
return curbuf->b_p_si && !curbuf->b_p_cin && *curbuf->b_p_inde == NUL && !p_paste;
}
-// Get indent level from 'indentexpr'.
+/// Get indent level from 'indentexpr'.
int get_expr_indent(void)
{
int indent = -1;
@@ -898,8 +898,8 @@ int get_expr_indent(void)
// Need to make a copy, the 'indentexpr' option could be changed while
// evaluating it.
- char_u *inde_copy = vim_strsave((char_u *)curbuf->b_p_inde);
- indent = (int)eval_to_number((char *)inde_copy);
+ char *inde_copy = xstrdup(curbuf->b_p_inde);
+ indent = (int)eval_to_number(inde_copy);
xfree(inde_copy);
if (use_sandbox) {
@@ -979,7 +979,7 @@ int get_lisp_indent(void)
continue;
}
- for (that = get_cursor_line_ptr(); *that != NUL; that++) {
+ for (that = (char_u *)get_cursor_line_ptr(); *that != NUL; that++) {
if (*that == ';') {
while (*(that + 1) != NUL) {
that++;
@@ -1029,7 +1029,7 @@ int get_lisp_indent(void)
curwin->w_cursor.col = pos->col;
col = pos->col;
- that = get_cursor_line_ptr();
+ that = (char_u *)get_cursor_line_ptr();
if (vi_lisp && (get_indent() == 0)) {
amount = 2;
diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c
index ccee4dd48a..c7f37790b6 100644
--- a/src/nvim/indent_c.c
+++ b/src/nvim/indent_c.c
@@ -27,11 +27,9 @@ typedef struct {
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "indent_c.c.generated.h"
#endif
-/*
- * Find the start of a comment, not knowing if we are in a comment right now.
- * Search starts at w_cursor.lnum and goes backwards.
- * Return NULL when not inside a comment.
- */
+// Find the start of a comment, not knowing if we are in a comment right now.
+// Search starts at w_cursor.lnum and goes backwards.
+// Return NULL when not inside a comment.
static pos_T *ind_find_start_comment(void) // XXX
{
return find_start_comment(curbuf->b_ind_maxcomment);
@@ -48,10 +46,8 @@ pos_T *find_start_comment(int ind_maxcomment) // XXX
break;
}
- /*
- * Check if the comment start we found is inside a string.
- * If it is then restrict the search to below this line and try again.
- */
+ // Check if the comment start we found is inside a string.
+ // If it is then restrict the search to below this line and try again.
if (!is_pos_in_string((char_u *)ml_get(pos->lnum), pos->col)) {
break;
}
@@ -97,11 +93,9 @@ static pos_T *ind_find_start_CORS(linenr_T *is_raw)
return comment_pos;
}
-/*
- * Find the start of a raw string, not knowing if we are in one right now.
- * Search starts at w_cursor.lnum and goes backwards.
- * Return NULL when not inside a raw string.
- */
+// Find the start of a raw string, not knowing if we are in one right now.
+// Search starts at w_cursor.lnum and goes backwards.
+// Return NULL when not inside a raw string.
static pos_T *find_start_rawstring(int ind_maxcomment) // XXX
{
pos_T *pos;
@@ -127,17 +121,13 @@ static pos_T *find_start_rawstring(int ind_maxcomment) // XXX
return pos;
}
-/*
- * Skip to the end of a "string" and a 'c' character.
- * If there is no string or character, return argument unmodified.
- */
+// Skip to the end of a "string" and a 'c' character.
+// If there is no string or character, return argument unmodified.
static const char_u *skip_string(const char_u *p)
{
int i;
- /*
- * We loop, because strings may be concatenated: "date""time".
- */
+ // We loop, because strings may be concatenated: "date""time".
for (;; p++) {
if (p[0] == '\'') { // 'c' or '\n' or '\000'
if (p[1] == NUL) { // ' at end of line
@@ -204,13 +194,10 @@ int is_pos_in_string(const char_u *line, colnr_T col)
return !((colnr_T)(p - line) <= col);
}
-/*
- * Functions for C-indenting.
- * Most of this originally comes from Eric Fischer.
- */
-/*
- * Below "XXX" means that this function may unlock the current line.
- */
+// Functions for C-indenting.
+// Most of this originally comes from Eric Fischer.
+
+// Below "XXX" means that this function may unlock the current line.
/// @return true if the string "line" starts with a word from 'cinwords'.
bool cin_is_cinword(const char *line)
@@ -235,10 +222,8 @@ bool cin_is_cinword(const char *line)
return retval;
}
-/*
- * Skip over white space and C comments within the line.
- * Also skip over Perl/shell comments if desired.
- */
+// Skip over white space and C comments within the line.
+// Also skip over Perl/shell comments if desired.
static const char_u *cin_skipcomment(const char_u *s)
{
while (*s) {
@@ -246,8 +231,8 @@ static const char_u *cin_skipcomment(const char_u *s)
s = (char_u *)skipwhite((char *)s);
- /* Perl/shell # comment comment continues until eol. Require a space
- * before # to avoid recognizing $#array. */
+ // Perl/shell # comment comment continues until eol. Require a space
+ // before # to avoid recognizing $#array.
if (curbuf->b_ind_hash_comment != 0 && s != prev_s && *s == '#') {
s += STRLEN(s);
break;
@@ -280,9 +265,7 @@ static int cin_nocode(const char_u *s)
return *cin_skipcomment(s) == NUL;
}
-/*
- * Check previous lines for a "//" line comment, skipping over blank lines.
- */
+// Check previous lines for a "//" line comment, skipping over blank lines.
static pos_T *find_line_comment(void) // XXX
{
static pos_T pos;
@@ -355,7 +338,7 @@ static bool cin_islabel_skip(const char_u **s)
// Note: curwin->w_cursor must be where we are looking for the label.
bool cin_islabel(void) // XXX
{
- const char_u *s = cin_skipcomment(get_cursor_line_ptr());
+ const char_u *s = cin_skipcomment((char_u *)get_cursor_line_ptr());
// Exclude "default" from labels, since it should be indented
// like a switch label. Same for C++ scope declarations.
@@ -369,10 +352,8 @@ bool cin_islabel(void) // XXX
return false;
}
- /*
- * Only accept a label if the previous line is terminated or is a case
- * label.
- */
+ // Only accept a label if the previous line is terminated or is a case
+ // label.
pos_T cursor_save;
pos_T *trypos;
const char_u *line;
@@ -381,16 +362,14 @@ bool cin_islabel(void) // XXX
while (curwin->w_cursor.lnum > 1) {
curwin->w_cursor.lnum--;
- /*
- * If we're in a comment or raw string now, skip to the start of
- * it.
- */
+ // If we're in a comment or raw string now, skip to the start of
+ // it.
curwin->w_cursor.col = 0;
if ((trypos = ind_find_start_CORS(NULL)) != NULL) { // XXX
curwin->w_cursor = *trypos;
}
- line = get_cursor_line_ptr();
+ line = (char_u *)get_cursor_line_ptr();
if (cin_ispreproc(line)) { // ignore #defines, #if, etc.
continue;
}
@@ -411,17 +390,15 @@ bool cin_islabel(void) // XXX
return true; // label at start of file???
}
-/*
- * Recognize structure initialization and enumerations:
- * "[typedef] [static|public|protected|private] enum"
- * "[typedef] [static|public|protected|private] = {"
- */
+// Recognize structure initialization and enumerations:
+// "[typedef] [static|public|protected|private] enum"
+// "[typedef] [static|public|protected|private] = {"
static int cin_isinit(void)
{
const char_u *s;
static char *skip[] = { "static", "public", "protected", "private" };
- s = cin_skipcomment(get_cursor_line_ptr());
+ s = cin_skipcomment((char_u *)get_cursor_line_ptr());
if (cin_starts_with(s, "typedef")) {
s = cin_skipcomment(s + 7);
@@ -495,9 +472,7 @@ bool cin_iscase(const char_u *s, bool strict)
return false;
}
-/*
- * Recognize a "default" switch label.
- */
+// Recognize a "default" switch label.
static int cin_isdefault(const char_u *s)
{
return STRNCMP(s, "default", 7) == 0
@@ -576,12 +551,10 @@ static bool cin_is_cpp_namespace(const char_u *s)
return false;
}
-/*
- * Return a pointer to the first non-empty non-comment character after a ':'.
- * Return NULL if not found.
- * case 234: a = b;
- * ^
- */
+// Return a pointer to the first non-empty non-comment character after a ':'.
+// Return NULL if not found.
+// case 234: a = b;
+// ^
static const char_u *after_label(const char_u *l)
{
for (; *l; l++) {
@@ -605,10 +578,8 @@ static const char_u *after_label(const char_u *l)
return l;
}
-/*
- * Get indent of line "lnum", skipping a label.
- * Return 0 if there is nothing after the label.
- */
+// Get indent of line "lnum", skipping a label.
+// Return 0 if there is nothing after the label.
static int get_indent_nolabel(linenr_T lnum) // XXX
{
const char_u *l;
@@ -628,12 +599,10 @@ static int get_indent_nolabel(linenr_T lnum) // XXX
return (int)col;
}
-/*
- * Find indent for line "lnum", ignoring any case or jump label.
- * Also return a pointer to the text (after the label) in "pp".
- * label: if (asdf && asdfasdf)
- * ^
- */
+// Find indent for line "lnum", ignoring any case or jump label.
+// Also return a pointer to the text (after the label) in "pp".
+// label: if (asdf && asdfasdf)
+// ^
static int skip_label(linenr_T lnum, const char_u **pp)
{
const char_u *l;
@@ -642,17 +611,17 @@ static int skip_label(linenr_T lnum, const char_u **pp)
cursor_save = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
// XXX
if (cin_iscase(l, false) || cin_isscopedecl(l) || cin_islabel()) {
amount = get_indent_nolabel(lnum);
- l = after_label(get_cursor_line_ptr());
+ l = after_label((char_u *)get_cursor_line_ptr());
if (l == NULL) { // just in case
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
}
} else {
amount = get_indent();
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
}
*pp = l;
@@ -660,13 +629,11 @@ static int skip_label(linenr_T lnum, const char_u **pp)
return amount;
}
-/*
- * Return the indent of the first variable name after a type in a declaration.
- * int a, indent of "a"
- * static struct foo b, indent of "b"
- * enum bla c, indent of "c"
- * Returns zero when it doesn't look like a declaration.
- */
+// Return the indent of the first variable name after a type in a declaration.
+// int a, indent of "a"
+// static struct foo b, indent of "b"
+// enum bla c, indent of "c"
+// Returns zero when it doesn't look like a declaration.
static int cin_first_id_amount(void)
{
char_u *line, *p, *s;
@@ -674,7 +641,7 @@ static int cin_first_id_amount(void)
pos_T fp;
colnr_T col;
- line = get_cursor_line_ptr();
+ line = (char_u *)get_cursor_line_ptr();
p = (char_u *)skipwhite((char *)line);
len = (int)((char_u *)skiptowhite((char *)p) - p);
if (len == 6 && STRNCMP(p, "static", 6) == 0) {
@@ -707,15 +674,13 @@ static int cin_first_id_amount(void)
return (int)col;
}
-/*
- * Return the indent of the first non-blank after an equal sign.
- * char *foo = "here";
- * Return zero if no (useful) equal sign found.
- * Return -1 if the line above "lnum" ends in a backslash.
- * foo = "asdf\
- * asdf\
- * here";
- */
+// Return the indent of the first non-blank after an equal sign.
+// char *foo = "here";
+// Return zero if no (useful) equal sign found.
+// Return -1 if the line above "lnum" ends in a backslash.
+// foo = "asdf{backslash}
+// asdf{backslash}
+// here";
static int cin_get_equal_amount(linenr_T lnum)
{
const char_u *line;
@@ -758,9 +723,7 @@ static int cin_get_equal_amount(linenr_T lnum)
return (int)col;
}
-/*
- * Recognize a preprocessor statement: Any line that starts with '#'.
- */
+// Recognize a preprocessor statement: Any line that starts with '#'.
static int cin_ispreproc(const char_u *s)
{
if (*skipwhite((char *)s) == '#') {
@@ -808,17 +771,13 @@ static int cin_ispreproc_cont(const char_u **pp, linenr_T *lnump, int *amount)
return retval;
}
-/*
- * Recognize the start of a C or C++ comment.
- */
+// Recognize the start of a C or C++ comment.
static int cin_iscomment(const char_u *p)
{
return p[0] == '/' && (p[1] == '*' || p[1] == '/');
}
-/*
- * Recognize the start of a "//" comment.
- */
+// Recognize the start of a "//" comment.
static int cin_islinecomment(const char_u *p)
{
return p[0] == '/' && p[1] == '/';
@@ -957,10 +916,10 @@ static int cin_isfuncdecl(const char_u **sp, linenr_T first_lnum, linenr_T min_l
if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s)) {
int comma = (*s == ',');
- /* ',' at the end: continue looking in the next line.
- * At the end: check for ',' in the next line, for this style:
- * func(arg1
- * , arg2) */
+ // ',' at the end: continue looking in the next line.
+ // At the end: check for ',' in the next line, for this style:
+ // func(arg1
+ // , arg2)
for (;;) {
if (lnum >= curbuf->b_ml.ml_line_count) {
break;
@@ -1014,11 +973,9 @@ static int cin_isdo(const char_u *p)
return STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]);
}
-/*
- * Check if this is a "while" that should have a matching "do".
- * We only accept a "while (condition) ;", with only white space between the
- * ')' and ';'. The condition may be spread over several lines.
- */
+// Check if this is a "while" that should have a matching "do".
+// We only accept a "while (condition) ;", with only white space between the
+// ')' and ';'. The condition may be spread over several lines.
static int cin_iswhileofdo(const char_u *p, linenr_T lnum) // XXX
{
pos_T cursor_save;
@@ -1033,7 +990,7 @@ static int cin_iswhileofdo(const char_u *p, linenr_T lnum) // XXX
cursor_save = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
curwin->w_cursor.col = 0;
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
while (*p && *p != 'w') { // skip any '}', until the 'w' of the "while"
p++;
curwin->w_cursor.col++;
@@ -1047,12 +1004,10 @@ static int cin_iswhileofdo(const char_u *p, linenr_T lnum) // XXX
return retval;
}
-/*
- * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
- * Return 0 if there is none.
- * Otherwise return !0 and update "*poffset" to point to the place where the
- * string was found.
- */
+// Check whether in "p" there is an "if", "for" or "while" before "*poffset".
+// Return 0 if there is none.
+// Otherwise return !0 and update "*poffset" to point to the place where the
+// string was found.
static int cin_is_if_for_while_before_offset(const char_u *line, int *poffset)
{
int offset = *poffset;
@@ -1110,14 +1065,14 @@ static int cin_iswhileofdo_end(int terminated)
return false;
}
- p = line = get_cursor_line_ptr();
+ p = line = (char_u *)get_cursor_line_ptr();
while (*p != NUL) {
p = cin_skipcomment(p);
if (*p == ')') {
s = (char_u *)skipwhite((char *)p + 1);
if (*s == ';' && cin_nocode(s + 1)) {
- /* Found ");" at end of the line, now check there is "while"
- * before the matching '('. XXX */
+ // Found ");" at end of the line, now check there is "while"
+ // before the matching '('. XXX
i = (int)(p - line);
curwin->w_cursor.col = i;
trypos = find_match_paren(curbuf->b_ind_maxparen);
@@ -1133,7 +1088,7 @@ static int cin_iswhileofdo_end(int terminated)
}
// Searching may have made "line" invalid, get it again.
- line = get_cursor_line_ptr();
+ line = (char_u *)get_cursor_line_ptr();
p = line + i;
}
}
@@ -1149,26 +1104,24 @@ static int cin_isbreak(const char_u *p)
return STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]);
}
-/*
- * Find the position of a C++ base-class declaration or
- * constructor-initialization. eg:
- *
- * class MyClass :
- * baseClass <-- here
- * class MyClass : public baseClass,
- * anotherBaseClass <-- here (should probably lineup ??)
- * MyClass::MyClass(...) :
- * baseClass(...) <-- here (constructor-initialization)
- *
- * This is a lot of guessing. Watch out for "cond ? func() : foo".
- */
+// Find the position of a C++ base-class declaration or
+// constructor-initialization. eg:
+//
+// class MyClass :
+// baseClass <-- here
+// class MyClass : public baseClass,
+// anotherBaseClass <-- here (should probably lineup ??)
+// MyClass::MyClass(...) :
+// baseClass(...) <-- here (constructor-initialization)
+//
+// This is a lot of guessing. Watch out for "cond ? func() : foo".
static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached)
{
lpos_T *pos = &cached->lpos; // find position
const char_u *s;
int class_or_struct, lookfor_ctor_init, cpp_base_class;
linenr_T lnum = curwin->w_cursor.lnum;
- const char_u *line = get_cursor_line_ptr();
+ const char_u *line = (char_u *)get_cursor_line_ptr();
if (pos->lnum <= lnum) {
return cached->found; // Use the cached result
@@ -1187,19 +1140,18 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached)
cpp_base_class = lookfor_ctor_init = class_or_struct = false;
- /* Search for a line starting with '#', empty, ending in ';' or containing
- * '{' or '}' and start below it. This handles the following situations:
- * a = cond ?
- * func() :
- * asdf;
- * func::foo()
- * : something
- * {}
- * Foo::Foo (int one, int two)
- * : something(4),
- * somethingelse(3)
- * {}
- */
+ // Search for a line starting with '#', empty, ending in ';' or containing
+ // '{' or '}' and start below it. This handles the following situations:
+ // a = cond ?
+ // func() :
+ // asdf;
+ // func::foo()
+ // : something
+ // {}
+ // Foo::Foo (int one, int two)
+ // : something(4),
+ // somethingelse(3)
+ // {}
while (lnum > 1) {
line = (char_u *)ml_get(lnum - 1);
s = (char_u *)skipwhite((char *)line);
@@ -1249,13 +1201,13 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached)
s = skip_string(s) + 1;
} else if (s[0] == ':') {
if (s[1] == ':') {
- /* skip double colon. It can't be a constructor
- * initialization any more */
+ // skip double colon. It can't be a constructor
+ // initialization any more
lookfor_ctor_init = false;
s = cin_skipcomment(s + 2);
} else if (lookfor_ctor_init || class_or_struct) {
- /* we have something found, that looks like the start of
- * cpp-base-class-declaration or constructor-initialization */
+ // we have something found, that looks like the start of
+ // cpp-base-class-declaration or constructor-initialization
cpp_base_class = true;
lookfor_ctor_init = class_or_struct = false;
pos->col = 0;
@@ -1277,8 +1229,8 @@ static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached)
if (s[0] == '{' || s[0] == '}' || s[0] == ';') {
cpp_base_class = lookfor_ctor_init = class_or_struct = false;
} else if (s[0] == ')') {
- /* Constructor-initialization is assumed if we come across
- * something like "):" */
+ // Constructor-initialization is assumed if we come across
+ // something like "):"
class_or_struct = false;
lookfor_ctor_init = true;
} else if (s[0] == '?') {
@@ -1322,11 +1274,11 @@ static int get_baseclass_amount(int col)
if (col == 0) {
amount = get_indent();
- if (find_last_paren(get_cursor_line_ptr(), '(', ')')
+ if (find_last_paren((char_u *)get_cursor_line_ptr(), '(', ')')
&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
amount = get_indent_lnum(trypos->lnum); // XXX
}
- if (!cin_ends_in(get_cursor_line_ptr(), (char_u *)",", NULL)) {
+ if (!cin_ends_in((char_u *)get_cursor_line_ptr(), (char_u *)",", NULL)) {
amount += curbuf->b_ind_cpp_baseclass;
}
} else {
@@ -1411,10 +1363,8 @@ static int cin_is_cpp_extern_c(const char_u *s)
return false;
}
-/*
- * Skip strings, chars and comments until at or past "trypos".
- * Return the column found.
- */
+// Skip strings, chars and comments until at or past "trypos".
+// Return the column found.
static int cin_skip2pos(pos_T *trypos)
{
const char_u *line;
@@ -1438,11 +1388,10 @@ static int cin_skip2pos(pos_T *trypos)
return (int)(p - line);
}
-/*
- * Find the '{' at the start of the block we are in.
- * Return NULL if no match found.
- * Ignore a '{' that is in a comment, makes indenting the next three lines
- * work. */
+// Find the '{' at the start of the block we are in.
+// Return NULL if no match found.
+// Ignore a '{' that is in a comment, makes indenting the next three lines
+// work.
// foo()
// {
// }
@@ -1542,12 +1491,10 @@ static pos_T *find_match_paren_after_brace(int ind_maxparen)
return trypos;
}
-/*
- * Return ind_maxparen corrected for the difference in line number between the
- * cursor position and "startpos". This makes sure that searching for a
- * matching paren above the cursor line doesn't find a match because of
- * looking a few lines further.
- */
+// Return ind_maxparen corrected for the difference in line number between the
+// cursor position and "startpos". This makes sure that searching for a
+// matching paren above the cursor line doesn't find a match because of
+// looking a few lines further.
static int corr_ind_maxparen(pos_T *startpos)
{
long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
@@ -1558,10 +1505,8 @@ static int corr_ind_maxparen(pos_T *startpos)
return curbuf->b_ind_maxparen;
}
-/*
- * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
- * line "l". "l" must point to the start of the line.
- */
+// Set w_cursor.col to the column number of the last unmatched ')' or '{' in
+// line "l". "l" must point to the start of the line.
static int find_last_paren(const char_u *l, int start, int end)
{
int i;
@@ -1587,10 +1532,8 @@ static int find_last_paren(const char_u *l, int start, int end)
return retval;
}
-/*
- * Parse 'cinoptions' and set the values in "curbuf".
- * Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes.
- */
+// Parse 'cinoptions' and set the values in "curbuf".
+// Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes.
void parse_cino(buf_T *buf)
{
char *p;
@@ -1599,39 +1542,37 @@ void parse_cino(buf_T *buf)
int fraction = 0;
int sw = get_sw_value(buf);
- /*
- * Set the default values.
- */
- /* Spaces from a block's opening brace the prevailing indent for that
- * block should be. */
+ // Set the default values.
+ // Spaces from a block's opening brace the prevailing indent for that
+ // block should be.
buf->b_ind_level = sw;
- /* Spaces from the edge of the line an open brace that's at the end of a
- * line is imagined to be. */
+ // Spaces from the edge of the line an open brace that's at the end of a
+ // line is imagined to be.
buf->b_ind_open_imag = 0;
- /* Spaces from the prevailing indent for a line that is not preceded by
- * an opening brace. */
+ // Spaces from the prevailing indent for a line that is not preceded by
+ // an opening brace.
buf->b_ind_no_brace = 0;
// Column where the first { of a function should be located }.
buf->b_ind_first_open = 0;
- /* Spaces from the prevailing indent a leftmost open brace should be
- * located. */
+ // Spaces from the prevailing indent a leftmost open brace should be
+ // located.
buf->b_ind_open_extra = 0;
- /* Spaces from the matching open brace (real location for one at the left
- * edge; imaginary location from one that ends a line) the matching close
- * brace should be located. */
+ // Spaces from the matching open brace (real location for one at the left
+ // edge; imaginary location from one that ends a line) the matching close
+ // brace should be located.
buf->b_ind_close_extra = 0;
- /* Spaces from the edge of the line an open brace sitting in the leftmost
- * column is imagined to be. */
+ // Spaces from the edge of the line an open brace sitting in the leftmost
+ // column is imagined to be.
buf->b_ind_open_left_imag = 0;
- /* Spaces jump labels should be shifted to the left if N is non-negative,
- * otherwise the jump label will be put to column 1. */
+ // Spaces jump labels should be shifted to the left if N is non-negative,
+ // otherwise the jump label will be put to column 1.
buf->b_ind_jump_label = -1;
// Spaces from the switch() indent a "case xx" label should be located.
@@ -1643,8 +1584,8 @@ void parse_cino(buf_T *buf)
// Lineup break at end of case in switch() with case label.
buf->b_ind_case_break = 0;
- /* Spaces from the class declaration indent a scope declaration label
- * should be located. */
+ // Spaces from the class declaration indent a scope declaration label
+ // should be located.
buf->b_ind_scopedecl = sw;
// Spaces from the scope declaration label code should be located.
@@ -1656,32 +1597,32 @@ void parse_cino(buf_T *buf)
// Amount a function type spec should be indented.
buf->b_ind_func_type = sw;
- /* Amount a cpp base class declaration or constructor initialization
- * should be indented. */
+ // Amount a cpp base class declaration or constructor initialization
+ // should be indented.
buf->b_ind_cpp_baseclass = sw;
- /* additional spaces beyond the prevailing indent a continuation line
- * should be located. */
+ // additional spaces beyond the prevailing indent a continuation line
+ // should be located.
buf->b_ind_continuation = sw;
// Spaces from the indent of the line with an unclosed parentheses.
buf->b_ind_unclosed = sw * 2;
- /* Spaces from the indent of the line with an unclosed parentheses, which
- * itself is also unclosed. */
+ // Spaces from the indent of the line with an unclosed parentheses, which
+ // itself is also unclosed.
buf->b_ind_unclosed2 = sw;
// Suppress ignoring spaces from the indent of a line starting with an
// unclosed parenthesis.
buf->b_ind_unclosed_noignore = 0;
- /* If the opening paren is the last nonwhite character on the line, and
- * b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer
- * context (for very long lines). */
+ // If the opening paren is the last nonwhite character on the line, and
+ // b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer
+ // context (for very long lines).
buf->b_ind_unclosed_wrapped = 0;
- /* Suppress ignoring white space when lining up with the character after
- * an unclosed parentheses. */
+ // Suppress ignoring white space when lining up with the character after
+ // an unclosed parentheses.
buf->b_ind_unclosed_whiteok = 0;
// Indent a closing parenthesis under the line start of the matching
@@ -1697,8 +1638,8 @@ void parse_cino(buf_T *buf)
// Spaces from the comment opener when there is nothing after it.
buf->b_ind_in_comment = 3;
- /* Boolean: if non-zero, use b_ind_in_comment even if there is something
- * after the comment opener. */
+ // Boolean: if non-zero, use b_ind_in_comment even if there is something
+ // after the comment opener.
buf->b_ind_in_comment2 = 0;
// Max lines to search for an open paren.
@@ -1719,8 +1660,8 @@ void parse_cino(buf_T *buf)
// Handle C++ namespace.
buf->b_ind_cpp_namespace = 0;
- /* Handle continuation lines containing conditions of if(), for() and
- * while(). */
+ // Handle continuation lines containing conditions of if(), for() and
+ // while().
buf->b_ind_if_for_while = 0;
// indentation for # comments
@@ -1766,8 +1707,8 @@ void parse_cino(buf_T *buf)
n = -n;
}
- /* When adding an entry here, also update the default 'cinoptions' in
- * doc/indent.txt, and add explanation for it! */
+ // When adding an entry here, also update the default 'cinoptions' in
+ // doc/indent.txt, and add explanation for it!
switch (*l) {
case '>':
buf->b_ind_level = n;
@@ -1887,10 +1828,8 @@ void parse_cino(buf_T *buf)
}
}
-/*
- * Return the desired indent for C code.
- * Return -1 if the indent should be left alone (inside a raw string).
- */
+// Return the desired indent for C code.
+// Return -1 if the indent should be left alone (inside a raw string).
int get_c_indent(void)
{
pos_T cur_curpos;
@@ -1899,7 +1838,7 @@ int get_c_indent(void)
int cur_amount = MAXCOL;
colnr_T col;
char_u *theline;
- char_u *linecopy;
+ char *linecopy;
pos_T *trypos;
pos_T *comment_pos;
pos_T *tryposBrace = NULL;
@@ -1951,25 +1890,23 @@ int get_c_indent(void)
return 0;
}
- /* Get a copy of the current contents of the line.
- * This is required, because only the most recent line obtained with
- * ml_get is valid! */
- linecopy = vim_strsave((char_u *)ml_get(cur_curpos.lnum));
+ // Get a copy of the current contents of the line.
+ // This is required, because only the most recent line obtained with
+ // ml_get is valid!
+ linecopy = xstrdup(ml_get(cur_curpos.lnum));
- /*
- * In insert mode and the cursor is on a ')' truncate the line at the
- * cursor position. We don't want to line up with the matching '(' when
- * inserting new stuff.
- * For unknown reasons the cursor might be past the end of the line, thus
- * check for that.
- */
+ // In insert mode and the cursor is on a ')' truncate the line at the
+ // cursor position. We don't want to line up with the matching '(' when
+ // inserting new stuff.
+ // For unknown reasons the cursor might be past the end of the line, thus
+ // check for that.
if ((State & MODE_INSERT)
&& curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
&& linecopy[curwin->w_cursor.col] == ')') {
linecopy[curwin->w_cursor.col] = NUL;
}
- theline = (char_u *)skipwhite((char *)linecopy);
+ theline = (char_u *)skipwhite(linecopy);
// move the cursor to the start of the line
@@ -1977,10 +1914,8 @@ int get_c_indent(void)
original_line_islabel = cin_islabel(); // XXX
- /*
- * If we are inside a raw string don't change the indent.
- * Ignore a raw string inside a comment.
- */
+ // If we are inside a raw string don't change the indent.
+ // Ignore a raw string inside a comment.
comment_pos = ind_find_start_comment();
if (comment_pos != NULL) {
// findmatchlimit() static pos is overwritten, make a copy
@@ -2010,10 +1945,8 @@ int get_c_indent(void)
amount = 0;
goto theend;
}
- /*
- * If we're inside a "//" comment and there is a "//" comment in a
- * previous line, lineup with that one.
- */
+ // If we're inside a "//" comment and there is a "//" comment in a
+ // previous line, lineup with that one.
if (cin_islinecomment(theline)) {
pos_T linecomment_pos;
@@ -2034,10 +1967,8 @@ int get_c_indent(void)
goto theend;
}
}
- /*
- * If we're inside a comment and not looking at the start of the
- * comment, try using the 'comments' option.
- */
+ // If we're inside a comment and not looking at the start of the
+ // comment, try using the 'comments' option.
if (!cin_iscomment(theline) && comment_pos != NULL) { // XXX
int lead_start_len = 2;
int lead_middle_len = 1;
@@ -2086,16 +2017,16 @@ int get_c_indent(void)
STRCPY(lead_middle, lead_end);
lead_middle_len = (int)STRLEN(lead_middle);
} else if (what == COM_END) {
- /* If our line starts with the middle comment string, line it
- * up with the comment opener per the 'comments' option. */
+ // If our line starts with the middle comment string, line it
+ // up with the comment opener per the 'comments' option.
if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
&& STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0) {
done = true;
if (curwin->w_cursor.lnum > 1) {
- /* If the start comment string matches in the previous
- * line, use the indent of that line plus offset. If
- * the middle comment string matches in the previous
- * line, use the indent of that line. XXX */
+ // If the start comment string matches in the previous
+ // line, use the indent of that line plus offset. If
+ // the middle comment string matches in the previous
+ // line, use the indent of that line. XXX
look = (char_u *)skipwhite(ml_get(curwin->w_cursor.lnum - 1));
if (STRNCMP(look, lead_start, lead_start_len) == 0) {
amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
@@ -2117,8 +2048,8 @@ int get_c_indent(void)
break;
}
- /* If our line starts with the end comment string, line it up
- * with the middle comment */
+ // If our line starts with the end comment string, line it up
+ // with the middle comment
if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
&& STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0) {
amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
@@ -2134,10 +2065,9 @@ int get_c_indent(void)
}
}
- /* If our line starts with an asterisk, line up with the
- * asterisk in the comment opener; otherwise, line up
- * with the first character of the comment text.
- */
+ // If our line starts with an asterisk, line up with the
+ // asterisk in the comment opener; otherwise, line up
+ // with the first character of the comment text.
if (done) {
// skip
} else if (theline[0] == '*') {
@@ -2187,8 +2117,8 @@ int get_c_indent(void)
|| (tryposBrace = find_start_brace()) != NULL
|| trypos != NULL) {
if (trypos != NULL && tryposBrace != NULL) {
- /* Both an unmatched '(' and '{' is found. Use the one which is
- * closer to the current cursor position, set the other to NULL. */
+ // Both an unmatched '(' and '{' is found. Use the one which is
+ // closer to the current cursor position, set the other to NULL.
if (trypos->lnum != tryposBrace->lnum
? trypos->lnum < tryposBrace->lnum
: trypos->col < tryposBrace->col) {
@@ -2200,10 +2130,8 @@ int get_c_indent(void)
if (trypos != NULL) {
our_paren_pos = *trypos;
- /*
- * If the matching paren is more than one line away, use the indent of
- * a previous non-empty line that matches the same paren.
- */
+ // If the matching paren is more than one line away, use the indent of
+ // a previous non-empty line that matches the same paren.
if (theline[0] == ')' && curbuf->b_ind_paren_prev) {
// Line up with the start of the matching paren line.
amount = get_indent_lnum(curwin->w_cursor.lnum - 1); // XXX
@@ -2243,18 +2171,16 @@ int get_c_indent(void)
}
}
- /*
- * Line up with line where the matching paren is. XXX
- * If the line starts with a '(' or the indent for unclosed
- * parentheses is zero, line up with the unclosed parentheses.
- */
+ // Line up with line where the matching paren is. XXX
+ // If the line starts with a '(' or the indent for unclosed
+ // parentheses is zero, line up with the unclosed parentheses.
if (amount == -1) {
int ignore_paren_col = 0;
int is_if_for_while = 0;
if (curbuf->b_ind_if_for_while) {
- /* Look for the outermost opening parenthesis on this line
- * and check whether it belongs to an "if", "for" or "while". */
+ // Look for the outermost opening parenthesis on this line
+ // and check whether it belongs to an "if", "for" or "while".
pos_T cursor_save = curwin->w_cursor;
pos_T outermost;
@@ -2284,10 +2210,10 @@ int get_c_indent(void)
char_u *line;
int look_col;
- /* Ignore a '(' in front of the line that has a match before
- * our matching '('. */
+ // Ignore a '(' in front of the line that has a match before
+ // our matching '('.
curwin->w_cursor.lnum = our_paren_pos.lnum;
- line = get_cursor_line_ptr();
+ line = (char_u *)get_cursor_line_ptr();
look_col = (int)(look - line);
curwin->w_cursor.col = look_col + 1;
if ((trypos = findmatchlimit(NULL, ')', 0,
@@ -2305,22 +2231,20 @@ int get_c_indent(void)
&& is_if_for_while == 0)
|| (!curbuf->b_ind_unclosed_noignore && *look == '('
&& ignore_paren_col == 0)) {
- /*
- * If we're looking at a close paren, line up right there;
- * otherwise, line up with the next (non-white) character.
- * When b_ind_unclosed_wrapped is set and the matching paren is
- * the last nonwhite character of the line, use either the
- * indent of the current line or the indentation of the next
- * outer paren and add b_ind_unclosed_wrapped (for very long
- * lines).
- */
+ // If we're looking at a close paren, line up right there;
+ // otherwise, line up with the next (non-white) character.
+ // When b_ind_unclosed_wrapped is set and the matching paren is
+ // the last nonwhite character of the line, use either the
+ // indent of the current line or the indentation of the next
+ // outer paren and add b_ind_unclosed_wrapped (for very long
+ // lines).
if (theline[0] != ')') {
cur_amount = MAXCOL;
l = (char_u *)ml_get(our_paren_pos.lnum);
if (curbuf->b_ind_unclosed_wrapped
&& cin_ends_in(l, (char_u *)"(", NULL)) {
- /* look for opening unmatched paren, indent one level
- * for each additional level */
+ // look for opening unmatched paren, indent one level
+ // for each additional level
n = 1;
for (col = 0; col < our_paren_pos.col; col++) {
switch (l[col]) {
@@ -2355,10 +2279,8 @@ int get_c_indent(void)
}
}
- /*
- * Find how indented the paren is, or the character after it
- * if we did the above "if".
- */
+ // Find how indented the paren is, or the character after it
+ // if we did the above "if".
if (our_paren_pos.col > 0) {
getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
if (cur_amount > (int)col) {
@@ -2376,8 +2298,8 @@ int get_c_indent(void)
amount = cur_amount;
}
} else {
- /* Add b_ind_unclosed2 for each '(' before our matching one,
- * but ignore (void) before the line (ignore_paren_col). */
+ // Add b_ind_unclosed2 for each '(' before our matching one,
+ // but ignore (void) before the line (ignore_paren_col).
col = our_paren_pos.col;
while ((int)our_paren_pos.col > ignore_paren_col) {
our_paren_pos.col--;
@@ -2393,8 +2315,8 @@ int get_c_indent(void)
}
}
- /* Use b_ind_unclosed once, when the first '(' is not inside
- * braces */
+ // Use b_ind_unclosed once, when the first '(' is not inside
+ // braces
if (col == MAXCOL) {
amount += curbuf->b_ind_unclosed;
} else {
@@ -2410,14 +2332,12 @@ int get_c_indent(void)
}
}
}
- /*
- * For a line starting with ')' use the minimum of the two
- * positions, to avoid giving it more indent than the previous
- * lines:
- * func_long_name( if (x
- * arg && yy
- * ) ^ not here ) ^ not here
- */
+ // For a line starting with ')' use the minimum of the two
+ // positions, to avoid giving it more indent than the previous
+ // lines:
+ // func_long_name( if (x
+ // arg && yy
+ // ) ^ not here ) ^ not here
if (cur_amount < amount) {
amount = cur_amount;
}
@@ -2439,12 +2359,10 @@ int get_c_indent(void)
ourscope = trypos->lnum;
start = (char_u *)ml_get(ourscope);
- /*
- * Now figure out how indented the line is in general.
- * If the brace was at the start of the line, we use that;
- * otherwise, check out the indentation of the line as
- * a whole and then add the "imaginary indent" to that.
- */
+ // Now figure out how indented the line is in general.
+ // If the brace was at the start of the line, we use that;
+ // otherwise, check out the indentation of the line as
+ // a whole and then add the "imaginary indent" to that.
look = (char_u *)skipwhite((char *)start);
if (*look == '{') {
getvcol(curwin, trypos, &col, NULL, NULL);
@@ -2472,7 +2390,7 @@ int get_c_indent(void)
// ldfd) {
// }
if ((curbuf->b_ind_js || curbuf->b_ind_keep_case_label)
- && cin_iscase((char_u *)skipwhite((char *)get_cursor_line_ptr()), false)) {
+ && cin_iscase((char_u *)skipwhite(get_cursor_line_ptr()), false)) {
amount = get_indent();
} else if (curbuf->b_ind_js) {
amount = get_indent_lnum(lnum);
@@ -2490,18 +2408,14 @@ int get_c_indent(void)
// we want to be. Otherwise, add the amount of room
// that an indent is supposed to be.
if (theline[0] == '}') {
- /*
- * they may want closing braces to line up with something
- * other than the open brace. indulge them, if so.
- */
+ // they may want closing braces to line up with something
+ // other than the open brace. indulge them, if so.
amount += curbuf->b_ind_close_extra;
} else {
- /*
- * If we're looking at an "else", try to find an "if"
- * to match it with.
- * If we're looking at a "while", try to find a "do"
- * to match it with.
- */
+ // If we're looking at an "else", try to find an "if"
+ // to match it with.
+ // If we're looking at a "while", try to find a "do"
+ // to match it with.
lookfor = LOOKFOR_INITIAL;
if (cin_iselse(theline)) {
lookfor = LOOKFOR_IF;
@@ -2516,18 +2430,14 @@ int get_c_indent(void)
}
}
- /*
- * We get here if we are not on an "while-of-do" or "else" (or
- * failed to find a matching "if").
- * Search backwards for something to line up with.
- * First set amount for when we don't find anything.
- */
+ // We get here if we are not on an "while-of-do" or "else" (or
+ // failed to find a matching "if").
+ // Search backwards for something to line up with.
+ // First set amount for when we don't find anything.
- /*
- * if the '{' is _really_ at the left margin, use the imaginary
- * location of a left-margin brace. Otherwise, correct the
- * location for b_ind_open_extra.
- */
+ // if the '{' is _really_ at the left margin, use the imaginary
+ // location of a left-margin brace. Otherwise, correct the
+ // location for b_ind_open_extra.
if (start_brace == BRACE_IN_COL0) { // '{' is in column 0
amount = curbuf->b_ind_open_left_imag;
@@ -2539,7 +2449,7 @@ int get_c_indent(void)
if (start_brace == BRACE_AT_END) { // '{' is at end of line
amount += curbuf->b_ind_open_imag;
- l = (char_u *)skipwhite((char *)get_cursor_line_ptr());
+ l = (char_u *)skipwhite(get_cursor_line_ptr());
if (cin_is_cpp_namespace(l)) {
amount += curbuf->b_ind_cpp_namespace;
} else if (cin_is_cpp_extern_c(l)) {
@@ -2586,10 +2496,8 @@ int get_c_indent(void)
curwin->w_cursor.lnum--;
curwin->w_cursor.col = 0;
- /*
- * If we went all the way back to the start of our scope, line
- * up with it.
- */
+ // If we went all the way back to the start of our scope, line
+ // up with it.
if (curwin->w_cursor.lnum <= ourscope) {
// We reached end of scope:
// If looking for a enum or structure initialization
@@ -2603,9 +2511,9 @@ int get_c_indent(void)
if (curwin->w_cursor.lnum == 0
|| curwin->w_cursor.lnum
< ourscope - curbuf->b_ind_maxparen) {
- /* nothing found (abuse curbuf->b_ind_maxparen as
- * limit) assume terminated line (i.e. a variable
- * initialization) */
+ // nothing found (abuse curbuf->b_ind_maxparen as
+ // limit) assume terminated line (i.e. a variable
+ // initialization)
if (cont_amount > 0) {
amount = cont_amount;
} else if (!curbuf->b_ind_js) {
@@ -2614,12 +2522,10 @@ int get_c_indent(void)
break;
}
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
- /*
- * If we're in a comment or raw string now, skip to
- * the start of it.
- */
+ // If we're in a comment or raw string now, skip to
+ // the start of it.
trypos = ind_find_start_CORS(NULL);
if (trypos != NULL) {
curwin->w_cursor.lnum = trypos->lnum + 1;
@@ -2640,27 +2546,23 @@ int get_c_indent(void)
terminated = cin_isterminated(l, false, true);
- /*
- * If we are at top level and the line looks like a
- * function declaration, we are done
- * (it's a variable declaration).
- */
+ // If we are at top level and the line looks like a
+ // function declaration, we are done
+ // (it's a variable declaration).
if (start_brace != BRACE_IN_COL0
|| !cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0)) {
- /* if the line is terminated with another ','
- * it is a continued variable initialization.
- * don't add extra indent.
- * TODO: does not work, if a function
- * declaration is split over multiple lines:
- * cin_isfuncdecl returns false then.
- */
+ // if the line is terminated with another ','
+ // it is a continued variable initialization.
+ // don't add extra indent.
+ // TODO(vim): does not work, if a function
+ // declaration is split over multiple lines:
+ // cin_isfuncdecl returns false then.
if (terminated == ',') {
break;
}
- /* if it is an enum declaration or an assignment,
- * we are done.
- */
+ // if it is an enum declaration or an assignment,
+ // we are done.
if (terminated != ';' && cin_isinit()) {
break;
}
@@ -2692,11 +2594,10 @@ int get_c_indent(void)
}
}
- /* it's a variable declaration, add indentation
- * like in
- * int a,
- * b;
- */
+ // it's a variable declaration, add indentation
+ // like in
+ // int a,
+ // b;
if (cont_amount > 0) {
amount = cont_amount;
} else {
@@ -2720,10 +2621,8 @@ int get_c_indent(void)
}
if (lookfor_cpp_namespace) {
- /*
- * Looking for C++ namespace, need to look further
- * back.
- */
+ // Looking for C++ namespace, need to look further
+ // back.
if (curwin->w_cursor.lnum == ourscope) {
continue;
}
@@ -2734,10 +2633,10 @@ int get_c_indent(void)
break;
}
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
- /* If we're in a comment or raw string now, skip
- * to the start of it. */
+ // If we're in a comment or raw string now, skip
+ // to the start of it.
trypos = ind_find_start_CORS(NULL);
if (trypos != NULL) {
curwin->w_cursor.lnum = trypos->lnum + 1;
@@ -2777,22 +2676,20 @@ int get_c_indent(void)
continue;
}
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
- /*
- * If this is a switch() label, may line up relative to that.
- * If this is a C++ scope declaration, do the same.
- */
+ // If this is a switch() label, may line up relative to that.
+ // If this is a C++ scope declaration, do the same.
bool iscase = cin_iscase(l, false);
if (iscase || cin_isscopedecl(l)) {
- /* we are only looking for cpp base class
- * declaration/initialization any longer */
+ // we are only looking for cpp base class
+ // declaration/initialization any longer
if (lookfor == LOOKFOR_CPP_BASECLASS) {
break;
}
- /* When looking for a "do" we are not interested in
- * labels. */
+ // When looking for a "do" we are not interested in
+ // labels.
if (whilelevel > 0) {
continue;
}
@@ -2853,7 +2750,7 @@ int get_c_indent(void)
// -> y = y + 1;
if (n) {
amount = n;
- l = after_label(get_cursor_line_ptr());
+ l = after_label((char_u *)get_cursor_line_ptr());
if (l != NULL && cin_is_cinword((char *)l)) {
if (theline[0] == '{') {
amount += curbuf->b_ind_open_extra;
@@ -2865,14 +2762,12 @@ int get_c_indent(void)
break;
}
- /*
- * Try to get the indent of a statement before the switch
- * label. If nothing is found, line up relative to the
- * switch label.
- * break; <- may line up with this line
- * case xx:
- * -> y = 1;
- */
+ // Try to get the indent of a statement before the switch
+ // label. If nothing is found, line up relative to the
+ // switch label.
+ // break; <- may line up with this line
+ // case xx:
+ // -> y = 1;
scope_amount = get_indent() + (iscase // XXX
? curbuf->b_ind_case_code
: curbuf->b_ind_scopedecl_code);
@@ -2881,10 +2776,8 @@ int get_c_indent(void)
continue;
}
- /*
- * Looking for a switch() label or C++ scope declaration,
- * ignore other lines, skip {}-blocks.
- */
+ // Looking for a switch() label or C++ scope declaration,
+ // ignore other lines, skip {}-blocks.
if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL) {
if (find_last_paren(l, '{', '}')
&& (trypos = find_start_brace()) != NULL) {
@@ -2894,23 +2787,19 @@ int get_c_indent(void)
continue;
}
- /*
- * Ignore jump labels with nothing after them.
- */
+ // Ignore jump labels with nothing after them.
if (!curbuf->b_ind_js && cin_islabel()) {
- l = after_label(get_cursor_line_ptr());
+ l = after_label((char_u *)get_cursor_line_ptr());
if (l == NULL || cin_nocode(l)) {
continue;
}
}
- /*
- * Ignore #defines, #if, etc.
- * Ignore comment and empty lines.
- * (need to get the line again, cin_islabel() may have
- * unlocked it)
- */
- l = get_cursor_line_ptr();
+ // Ignore #defines, #if, etc.
+ // Ignore comment and empty lines.
+ // (need to get the line again, cin_islabel() may have
+ // unlocked it)
+ l = (char_u *)get_cursor_line_ptr();
if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)
|| cin_nocode(l)) {
continue;
@@ -2922,7 +2811,7 @@ int get_c_indent(void)
n = 0;
if (lookfor != LOOKFOR_TERM && curbuf->b_ind_cpp_baseclass > 0) {
n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
}
if (n) {
if (lookfor == LOOKFOR_UNTERM) {
@@ -2942,9 +2831,8 @@ int get_c_indent(void)
}
break;
} else if (lookfor == LOOKFOR_CPP_BASECLASS) {
- /* only look, whether there is a cpp base class
- * declaration or initialization before the opening brace.
- */
+ // only look, whether there is a cpp base class
+ // declaration or initialization before the opening brace.
if (cin_isterminated(l, true, false)) {
break;
} else {
@@ -2952,17 +2840,15 @@ int get_c_indent(void)
}
}
- /*
- * What happens next depends on the line being terminated.
- * If terminated with a ',' only consider it terminating if
- * there is another unterminated statement behind, eg:
- * 123,
- * sizeof
- * here
- * Otherwise check whether it is an enumeration or structure
- * initialisation (not indented) or a variable declaration
- * (indented).
- */
+ // What happens next depends on the line being terminated.
+ // If terminated with a ',' only consider it terminating if
+ // there is another unterminated statement behind, eg:
+ // 123,
+ // sizeof
+ // here
+ // Otherwise check whether it is an enumeration or structure
+ // initialisation (not indented) or a variable declaration
+ // (indented).
terminated = cin_isterminated(l, false, true);
if (js_cur_has_key) {
@@ -3032,14 +2918,12 @@ int get_c_indent(void)
}
if (trypos != NULL) {
- /*
- * Check if we are on a case label now. This is
- * handled above.
- * case xx: if ( asdf &&
- * asdf)
- */
+ // Check if we are on a case label now. This is
+ // handled above.
+ // case xx: if ( asdf &&
+ // asdf)
curwin->w_cursor = *trypos;
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
if (cin_iscase(l, false) || cin_isscopedecl(l)) {
curwin->w_cursor.lnum++;
curwin->w_cursor.col = 0;
@@ -3047,13 +2931,11 @@ int get_c_indent(void)
}
}
- /*
- * Skip over continuation lines to find the one to get the
- * indent from
- * char *usethis = "bla\
- * bla",
- * here;
- */
+ // Skip over continuation lines to find the one to get the
+ // indent from
+ // char *usethis = "bla{backslash}
+ // bla",
+ // here;
if (terminated == ',') {
while (curwin->w_cursor.lnum > 1) {
l = (char_u *)ml_get(curwin->w_cursor.lnum - 1);
@@ -3065,49 +2947,41 @@ int get_c_indent(void)
}
}
- /*
- * Get indent and pointer to text for current line,
- * ignoring any jump label. XXX
- */
+ // Get indent and pointer to text for current line,
+ // ignoring any jump label. XXX
if (curbuf->b_ind_js) {
cur_amount = get_indent();
} else {
cur_amount = skip_label(curwin->w_cursor.lnum, &l);
}
- /*
- * If this is just above the line we are indenting, and it
- * starts with a '{', line it up with this line.
- * while (not)
- * -> {
- * }
- */
+ // If this is just above the line we are indenting, and it
+ // starts with a '{', line it up with this line.
+ // while (not)
+ // -> {
+ // }
if (terminated != ',' && lookfor != LOOKFOR_TERM
&& theline[0] == '{') {
amount = cur_amount;
- /*
- * Only add b_ind_open_extra when the current line
- * doesn't start with a '{', which must have a match
- * in the same line (scope is the same). Probably:
- * { 1, 2 },
- * -> { 3, 4 }
- */
+ // Only add b_ind_open_extra when the current line
+ // doesn't start with a '{', which must have a match
+ // in the same line (scope is the same). Probably:
+ // { 1, 2 },
+ // -> { 3, 4 }
if (*skipwhite((char *)l) != '{') {
amount += curbuf->b_ind_open_extra;
}
if (curbuf->b_ind_cpp_baseclass && !curbuf->b_ind_js) {
- /* have to look back, whether it is a cpp base
- * class declaration or initialization */
+ // have to look back, whether it is a cpp base
+ // class declaration or initialization
lookfor = LOOKFOR_CPP_BASECLASS;
continue;
}
break;
}
- /*
- * Check if we are after an "if", "while", etc.
- * Also allow " } else".
- */
+ // Check if we are after an "if", "while", etc.
+ // Also allow " } else".
if (cin_is_cinword((char *)l) || cin_iselse((char_u *)skipwhite((char *)l))) {
// Found an unterminated line after an if (), line up
// with the last one.
@@ -3124,19 +2998,17 @@ int get_c_indent(void)
break;
}
- /*
- * If this is just above the line we are indenting, we
- * are finished.
- * while (not)
- * -> here;
- * Otherwise this indent can be used when the line
- * before this is terminated.
- * yyy;
- * if (stat)
- * while (not)
- * xxx;
- * -> here;
- */
+ // If this is just above the line we are indenting, we
+ // are finished.
+ // while (not)
+ // -> here;
+ // Otherwise this indent can be used when the line
+ // before this is terminated.
+ // yyy;
+ // if (stat)
+ // while (not)
+ // xxx;
+ // -> here;
amount = cur_amount;
if (theline[0] == '{') {
amount += curbuf->b_ind_open_extra;
@@ -3147,14 +3019,12 @@ int get_c_indent(void)
break;
}
- /*
- * Special trick: when expecting the while () after a
- * do, line up with the while()
- * do
- * x = 1;
- * -> here
- */
- l = (char_u *)skipwhite((char *)get_cursor_line_ptr());
+ // Special trick: when expecting the while () after a
+ // do, line up with the while()
+ // do
+ // x = 1;
+ // -> here
+ l = (char_u *)skipwhite(get_cursor_line_ptr());
if (cin_isdo(l)) {
if (whilelevel == 0) {
break;
@@ -3162,19 +3032,17 @@ int get_c_indent(void)
whilelevel--;
}
- /*
- * When searching for a terminated line, don't use the
- * one between the "if" and the matching "else".
- * Need to use the scope of this "else". XXX
- * If whilelevel != 0 continue looking for a "do {".
- */
+ // When searching for a terminated line, don't use the
+ // one between the "if" and the matching "else".
+ // Need to use the scope of this "else". XXX
+ // If whilelevel != 0 continue looking for a "do {".
if (cin_iselse(l) && whilelevel == 0) {
- /* If we're looking at "} else", let's make sure we
- * find the opening brace of the enclosing scope,
- * not the one from "if () {". */
+ // If we're looking at "} else", let's make sure we
+ // find the opening brace of the enclosing scope,
+ // not the one from "if () {".
if (*l == '}') {
curwin->w_cursor.col =
- (colnr_T)(l - get_cursor_line_ptr()) + 1;
+ (colnr_T)(l - (char_u *)get_cursor_line_ptr()) + 1;
}
if ((trypos = find_start_brace()) == NULL
@@ -3183,21 +3051,17 @@ int get_c_indent(void)
break;
}
}
- }
- /*
- * If we're below an unterminated line that is not an
- * "if" or something, we may line up with this line or
- * add something for a continuation line, depending on
- * the line before this one.
- */
- else {
- /*
- * Found two unterminated lines on a row, line up with
- * the last one.
- * c = 99 +
- * 100 +
- * -> here;
- */
+ } else {
+ // If we're below an unterminated line that is not an
+ // "if" or something, we may line up with this line or
+ // add something for a continuation line, depending on
+ // the line before this one.
+
+ // Found two unterminated lines on a row, line up with
+ // the last one.
+ // c = 99 +
+ // 100 +
+ // -> here;
if (lookfor == LOOKFOR_UNTERM) {
// When line ends in a comma add extra indent
if (terminated == ',') {
@@ -3207,11 +3071,11 @@ int get_c_indent(void)
}
if (lookfor == LOOKFOR_ENUM_OR_INIT) {
- /* Found two lines ending in ',', lineup with the
- * lowest one, but check for cpp base class
- * declaration/initialization, if it is an
- * opening brace or we are looking just for
- * enumerations/initializations. */
+ // Found two lines ending in ',', lineup with the
+ // lowest one, but check for cpp base class
+ // declaration/initialization, if it is an
+ // opening brace or we are looking just for
+ // enumerations/initializations.
if (terminated == ',') {
if (curbuf->b_ind_cpp_baseclass == 0) {
break;
@@ -3231,7 +3095,7 @@ int get_c_indent(void)
// line up with this line, remember its indent
// 100 + // NOLINT(whitespace/tab)
// -> here; // NOLINT(whitespace/tab)
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
amount = cur_amount;
n = (int)STRLEN(l);
@@ -3296,19 +3160,14 @@ int get_c_indent(void)
}
}
}
- }
- /*
- * Check if we are after a while (cond);
- * If so: Ignore until the matching "do".
- */
- else if (cin_iswhileofdo_end(terminated)) { // XXX
- /*
- * Found an unterminated line after a while ();, line up
- * with the last one.
- * while (cond);
- * 100 + <- line up with this one
- * -> here;
- */
+ // Check if we are after a while (cond);
+ // If so: Ignore until the matching "do".
+ } else if (cin_iswhileofdo_end(terminated)) { // XXX
+ // Found an unterminated line after a while ();, line up
+ // with the last one.
+ // while (cond);
+ // 100 + <- line up with this one
+ // -> here;
if (lookfor == LOOKFOR_UNTERM
|| lookfor == LOOKFOR_ENUM_OR_INIT) {
if (cont_amount > 0) {
@@ -3327,30 +3186,24 @@ int get_c_indent(void)
}
}
whilelevel++;
- }
- /*
- * We are after a "normal" statement.
- * If we had another statement we can stop now and use the
- * indent of that other statement.
- * Otherwise the indent of the current statement may be used,
- * search backwards for the next "normal" statement.
- */
- else {
- /*
- * Skip single break line, if before a switch label. It
- * may be lined up with the case label.
- */
+ } else {
+ // We are after a "normal" statement.
+ // If we had another statement we can stop now and use the
+ // indent of that other statement.
+ // Otherwise the indent of the current statement may be used,
+ // search backwards for the next "normal" statement.
+
+ // Skip single break line, if before a switch label. It
+ // may be lined up with the case label.
if (lookfor == LOOKFOR_NOBREAK
- && cin_isbreak((char_u *)skipwhite((char *)get_cursor_line_ptr()))) {
+ && cin_isbreak((char_u *)skipwhite(get_cursor_line_ptr()))) {
lookfor = LOOKFOR_ANY;
continue;
}
- /*
- * Handle "do {" line.
- */
+ // Handle "do {" line.
if (whilelevel > 0) {
- l = cin_skipcomment(get_cursor_line_ptr());
+ l = cin_skipcomment((char_u *)get_cursor_line_ptr());
if (cin_isdo(l)) {
amount = get_indent(); // XXX
whilelevel--;
@@ -3358,17 +3211,15 @@ int get_c_indent(void)
}
}
- /*
- * Found a terminated line above an unterminated line. Add
- * the amount for a continuation line.
- * x = 1;
- * y = foo +
- * -> here;
- * or
- * int x = 1;
- * int foo,
- * -> here;
- */
+ // Found a terminated line above an unterminated line. Add
+ // the amount for a continuation line.
+ // x = 1;
+ // y = foo +
+ // -> here;
+ // or
+ // int x = 1;
+ // int foo,
+ // -> here;
if (lookfor == LOOKFOR_UNTERM
|| lookfor == LOOKFOR_ENUM_OR_INIT) {
if (cont_amount > 0) {
@@ -3379,36 +3230,30 @@ int get_c_indent(void)
break;
}
- /*
- * Found a terminated line above a terminated line or "if"
- * etc. line. Use the amount of the line below us.
- * x = 1; x = 1;
- * if (asdf) y = 2;
- * while (asdf) ->here;
- * here;
- * ->foo;
- */
+ // Found a terminated line above a terminated line or "if"
+ // etc. line. Use the amount of the line below us.
+ // x = 1; x = 1;
+ // if (asdf) y = 2;
+ // while (asdf) ->here;
+ // here;
+ // ->foo;
if (lookfor == LOOKFOR_TERM) {
if (!lookfor_break && whilelevel == 0) {
break;
}
- }
- /*
- * First line above the one we're indenting is terminated.
- * To know what needs to be done look further backward for
- * a terminated line.
- */
- else {
- /*
- * position the cursor over the rightmost paren, so
- * that matching it will take us back to the start of
- * the line. Helps for:
- * func(asdr,
- * asdfasdf);
- * here;
- */
+ } else {
+ // First line above the one we're indenting is terminated.
+ // To know what needs to be done look further backward for
+ // a terminated line.
+
+ // position the cursor over the rightmost paren, so
+ // that matching it will take us back to the start of
+ // the line. Helps for:
+ // func(asdr,
+ // asdfasdf);
+ // here;
term_again:
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
if (find_last_paren(l, '(', ')')
&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
// Check if we are on a case label now. This is
@@ -3416,7 +3261,7 @@ term_again:
// case xx: if ( asdf &&
// asdf)
curwin->w_cursor = *trypos;
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
if (cin_iscase(l, false) || cin_isscopedecl(l)) {
curwin->w_cursor.lnum++;
curwin->w_cursor.col = 0;
@@ -3424,21 +3269,18 @@ term_again:
}
}
- /* When aligning with the case statement, don't align
- * with a statement after it.
- * case 1: { <-- don't use this { position
- * stat;
- * }
- * case 2:
- * stat;
- * }
- */
+ // When aligning with the case statement, don't align
+ // with a statement after it.
+ // case 1: { <-- don't use this { position
+ // stat;
+ // }
+ // case 2:
+ // stat;
+ // }
iscase = curbuf->b_ind_keep_case_label && cin_iscase(l, false);
- /*
- * Get indent and pointer to text for current line,
- * ignoring any jump label.
- */
+ // Get indent and pointer to text for current line,
+ // ignoring any jump label.
amount = skip_label(curwin->w_cursor.lnum, &l);
if (theline[0] == '{') {
@@ -3451,14 +3293,12 @@ term_again:
}
lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
- /*
- * When a terminated line starts with "else" skip to
- * the matching "if":
- * else 3;
- * indent this;
- * Need to use the scope of this "else". XXX
- * If whilelevel != 0 continue looking for a "do {".
- */
+ // When a terminated line starts with "else" skip to
+ // the matching "if":
+ // else 3;
+ // indent this;
+ // Need to use the scope of this "else". XXX
+ // If whilelevel != 0 continue looking for a "do {".
if (lookfor == LOOKFOR_TERM
&& *l != '}'
&& cin_iselse(l)
@@ -3471,17 +3311,15 @@ term_again:
continue;
}
- /*
- * If we're at the end of a block, skip to the start of
- * that block.
- */
- l = get_cursor_line_ptr();
+ // If we're at the end of a block, skip to the start of
+ // that block.
+ l = (char_u *)get_cursor_line_ptr();
if (find_last_paren(l, '{', '}') // XXX
&& (trypos = find_start_brace()) != NULL) {
curwin->w_cursor = *trypos;
// if not "else {" check for terminated again
// but skip block for "} else {"
- l = cin_skipcomment(get_cursor_line_ptr());
+ l = cin_skipcomment((char_u *)get_cursor_line_ptr());
if (*l == '}' || !cin_iselse(l)) {
goto term_again;
}
@@ -3521,13 +3359,11 @@ term_again:
amount = curbuf->b_ind_first_open;
goto theend;
}
- /*
- * If the NEXT line is a function declaration, the current
- * line needs to be indented as a function type spec.
- * Don't do this if the current line looks like a comment or if the
- * current line is terminated, ie. ends in ';', or if the current line
- * contains { or }: "void f() {\n if (1)"
- */
+ // If the NEXT line is a function declaration, the current
+ // line needs to be indented as a function type spec.
+ // Don't do this if the current line looks like a comment or if the
+ // current line is terminated, ie. ends in ';', or if the current line
+ // contains { or }: "void f() {\n if (1)"
if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
&& !cin_nocode(theline)
&& vim_strchr((char *)theline, '{') == NULL
@@ -3547,7 +3383,7 @@ term_again:
curwin->w_cursor.lnum--;
curwin->w_cursor.col = 0;
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
// If we're in a comment or raw string now, skip to the start
// of it.
@@ -3563,7 +3399,7 @@ term_again:
n = 0;
if (curbuf->b_ind_cpp_baseclass != 0) {
n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
}
if (n) {
// XXX
@@ -3582,18 +3418,16 @@ term_again:
continue;
}
- /*
- * If the previous line ends in ',', use one level of
- * indentation:
- * int foo,
- * bar;
- * do this before checking for '}' in case of eg.
- * enum foobar
- * {
- * ...
- * } foo,
- * bar;
- */
+ // If the previous line ends in ',', use one level of
+ // indentation:
+ // int foo,
+ // bar;
+ // do this before checking for '}' in case of eg.
+ // enum foobar
+ // {
+ // ...
+ // } foo,
+ // bar;
if (cin_ends_in(l, (char_u *)",", NULL)
|| (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\')) {
// take us back to opening paren
@@ -3602,12 +3436,11 @@ term_again:
curwin->w_cursor = *trypos;
}
- /* For a line ending in ',' that is a continuation line go
- * back to the first line with a backslash:
- * char *foo = "bla\
- * bla",
- * here;
- */
+ // For a line ending in ',' that is a continuation line go
+ // back to the first line with a backslash:
+ // char *foo = "bla{backslash}
+ // bla",
+ // here;
while (n == 0 && curwin->w_cursor.lnum > 1) {
l = (char_u *)ml_get(curwin->w_cursor.lnum - 1);
if (*l == NUL || l[STRLEN(l) - 1] != '\\') {
@@ -3628,19 +3461,15 @@ term_again:
break;
}
- /*
- * If the line looks like a function declaration, and we're
- * not in a comment, put it the left margin.
- */
+ // If the line looks like a function declaration, and we're
+ // not in a comment, put it the left margin.
if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0)) { // XXX
break;
}
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
- /*
- * Finding the closing '}' of a previous function. Put
- * current line at the left margin. For when 'cino' has "fs".
- */
+ // Finding the closing '}' of a previous function. Put
+ // current line at the left margin. For when 'cino' has "fs".
if (*skipwhite((char *)l) == '}') {
break;
}
@@ -3663,11 +3492,9 @@ term_again:
break;
}
- /*
- * Find a line only has a semicolon that belongs to a previous
- * line ending in '}', e.g. before an #endif. Don't increase
- * indent then.
- */
+ // Find a line only has a semicolon that belongs to a previous
+ // line ending in '}', e.g. before an #endif. Don't increase
+ // indent then.
if (*(look = (char_u *)skipwhite((char *)l)) == ';' && cin_nocode(look + 1)) {
pos_T curpos_save = curwin->w_cursor;
@@ -3686,39 +3513,33 @@ term_again:
curwin->w_cursor = curpos_save;
}
- /*
- * If the PREVIOUS line is a function declaration, the current
- * line (and the ones that follow) needs to be indented as
- * parameters.
- */
+ // If the PREVIOUS line is a function declaration, the current
+ // line (and the ones that follow) needs to be indented as
+ // parameters.
if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0)) {
amount = curbuf->b_ind_param;
break;
}
- /*
- * If the previous line ends in ';' and the line before the
- * previous line ends in ',' or '\', ident to column zero:
- * int foo,
- * bar;
- * indent_to_0 here;
- */
+ // If the previous line ends in ';' and the line before the
+ // previous line ends in ',' or '\', ident to column zero:
+ // int foo,
+ // bar;
+ // indent_to_0 here;
if (cin_ends_in(l, (char_u *)";", NULL)) {
l = (char_u *)ml_get(curwin->w_cursor.lnum - 1);
if (cin_ends_in(l, (char_u *)",", NULL)
|| (*l != NUL && l[STRLEN(l) - 1] == '\\')) {
break;
}
- l = get_cursor_line_ptr();
+ l = (char_u *)get_cursor_line_ptr();
}
- /*
- * Doesn't look like anything interesting -- so just
- * use the indent of this line.
- *
- * Position the cursor over the rightmost paren, so that
- * matching it will take us back to the start of the line.
- */
+ // Doesn't look like anything interesting -- so just
+ // use the indent of this line.
+ //
+ // Position the cursor over the rightmost paren, so that
+ // matching it will take us back to the start of the line.
(void)find_last_paren(l, '(', ')');
if ((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
@@ -3786,7 +3607,7 @@ static int find_match(int lookfor, linenr_T ourscope)
curwin->w_cursor.lnum--;
curwin->w_cursor.col = 0;
- look = cin_skipcomment(get_cursor_line_ptr());
+ look = cin_skipcomment((char_u *)get_cursor_line_ptr());
if (!cin_iselse(look)
&& !cin_isif(look)
&& !cin_isdo(look) // XXX
@@ -3794,39 +3615,31 @@ static int find_match(int lookfor, linenr_T ourscope)
continue;
}
- /*
- * if we've gone outside the braces entirely,
- * we must be out of scope...
- */
+ // if we've gone outside the braces entirely,
+ // we must be out of scope...
theirscope = find_start_brace(); // XXX
if (theirscope == NULL) {
break;
}
- /*
- * and if the brace enclosing this is further
- * back than the one enclosing the else, we're
- * out of luck too.
- */
+ // and if the brace enclosing this is further
+ // back than the one enclosing the else, we're
+ // out of luck too.
if (theirscope->lnum < ourscope) {
break;
}
- /*
- * and if they're enclosed in a *deeper* brace,
- * then we can ignore it because it's in a
- * different scope...
- */
+ // and if they're enclosed in a *deeper* brace,
+ // then we can ignore it because it's in a
+ // different scope...
if (theirscope->lnum > ourscope) {
continue;
}
- /*
- * if it was an "else" (that's not an "else if")
- * then we need to go back to another if, so
- * increment elselevel
- */
- look = cin_skipcomment(get_cursor_line_ptr());
+ // if it was an "else" (that's not an "else if")
+ // then we need to go back to another if, so
+ // increment elselevel
+ look = cin_skipcomment((char_u *)get_cursor_line_ptr());
if (cin_iselse(look)) {
mightbeif = cin_skipcomment(look + 4);
if (!cin_isif(mightbeif)) {
@@ -3835,23 +3648,19 @@ static int find_match(int lookfor, linenr_T ourscope)
continue;
}
- /*
- * if it was a "while" then we need to go back to
- * another "do", so increment whilelevel. XXX
- */
+ // if it was a "while" then we need to go back to
+ // another "do", so increment whilelevel. XXX
if (cin_iswhileofdo(look, curwin->w_cursor.lnum)) {
whilelevel++;
continue;
}
// If it's an "if" decrement elselevel
- look = cin_skipcomment(get_cursor_line_ptr());
+ look = cin_skipcomment((char_u *)get_cursor_line_ptr());
if (cin_isif(look)) {
- elselevel--;
- /*
- * When looking for an "if" ignore "while"s that
- * get in the way.
- */
+ elselevel--; // NOLINT(readability/braces)
+ // When looking for an "if" ignore "while"s that
+ // get in the way.
if (elselevel == 0 && lookfor == LOOKFOR_IF) {
whilelevel = 0;
}
@@ -3862,11 +3671,9 @@ static int find_match(int lookfor, linenr_T ourscope)
whilelevel--;
}
- /*
- * if we've used up all the elses, then
- * this must be the if that we want!
- * match the indent level of that if.
- */
+ // if we've used up all the elses, then
+ // this must be the if that we want!
+ // match the indent level of that if.
if (elselevel <= 0 && whilelevel <= 0) {
return OK;
}
@@ -3874,9 +3681,7 @@ static int find_match(int lookfor, linenr_T ourscope)
return FAIL;
}
-/*
- * Do C or expression indenting on the current line.
- */
+// Do C or expression indenting on the current line.
void do_c_expr_indent(void)
{
if (*curbuf->b_p_inde != NUL) {
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c
index a530061280..a5e7929525 100644
--- a/src/nvim/insexpand.c
+++ b/src/nvim/insexpand.c
@@ -132,10 +132,10 @@ 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
+ char *cp_str; ///< matched text
+ char *(cp_text[CPT_COUNT]); ///< text for the menu
typval_T cp_user_data;
- char_u *cp_fname; ///< file containing the match, allocated when
+ char *cp_fname; ///< file containing the match, allocated when
///< cp_flags has CP_FREE_FNAME
int cp_flags; ///< CP_ values
int cp_number; ///< sequence number
@@ -191,7 +191,7 @@ static bool 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 *compl_leader = NULL;
static bool compl_get_longest = false; ///< put longest common string in compl_leader
@@ -231,7 +231,7 @@ static pos_T compl_startpos;
static int compl_length = 0;
static colnr_T compl_col = 0; ///< column where the text starts
///< that is being completed
-static char_u *compl_orig_text = NULL; ///< text as it was before
+static char *compl_orig_text = NULL; ///< text as it was before
///< completion started
static int compl_cont_mode = 0;
static expand_T compl_xp;
@@ -587,7 +587,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_
// Rule 1: Were any chars converted to lower?
{
- const char_u *p = compl_orig_text;
+ const char_u *p = (char_u *)compl_orig_text;
for (int i = 0; i < min_len; i++) {
const int c = mb_ptr2char_adv(&p);
if (mb_islower(c)) {
@@ -606,7 +606,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_
// Rule 2: No lower case, 2nd consecutive letter converted to
// upper case.
if (!has_lower) {
- const char_u *p = compl_orig_text;
+ const char_u *p = (char_u *)compl_orig_text;
for (int i = 0; i < min_len; i++) {
const int c = mb_ptr2char_adv(&p);
if (was_letter && mb_isupper(c) && mb_islower(wca[i])) {
@@ -622,7 +622,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_
// Copy the original case of the part we typed.
{
- const char_u *p = compl_orig_text;
+ const char_u *p = (char_u *)compl_orig_text;
for (int i = 0; i < min_len; i++) {
const int c = mb_ptr2char_adv(&p);
if (mb_islower(c)) {
@@ -665,7 +665,7 @@ static char_u *ins_compl_infercase_gettext(char_u *str, int char_len, int compl_
}
*p = NUL;
- return IObuff;
+ return (char_u *)IObuff;
}
/// This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
@@ -699,7 +699,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname,
// Find actual length of original text.
{
- const char_u *p = compl_orig_text;
+ const char_u *p = (char_u *)compl_orig_text;
compl_char_len = 0;
while (*p != NUL) {
MB_PTR_ADV(p);
@@ -720,7 +720,7 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname,
flags |= CP_ICASE;
}
- int res = ins_compl_add(str, len, fname, NULL, false, NULL, dir, flags, false);
+ int res = ins_compl_add((char *)str, len, (char *)fname, NULL, false, NULL, dir, flags, false);
xfree(tofree);
return res;
}
@@ -748,9 +748,9 @@ int ins_compl_add_infercase(char_u *str_arg, int len, bool icase, char_u *fname,
/// @return NOTDONE if the given string is already in the list of completions,
/// otherwise it is added to the list and OK is returned. FAIL will be
/// returned in case of error.
-static int ins_compl_add(char_u *const str, int len, char_u *const fname,
- char_u *const *const cptext, const bool cptext_allocated,
- typval_T *user_data, const Direction cdir, int flags_arg, const bool adup)
+static int ins_compl_add(char *const str, int len, char *const fname, char *const *const cptext,
+ const bool cptext_allocated, typval_T *user_data, const Direction cdir,
+ int flags_arg, const bool adup)
FUNC_ATTR_NONNULL_ARG(1)
{
compl_T *match;
@@ -802,7 +802,7 @@ static int ins_compl_add(char_u *const str, int len, char_u *const fname,
if (flags & CP_ORIGINAL_TEXT) {
match->cp_number = 0;
}
- match->cp_str = vim_strnsave(str, (size_t)len);
+ match->cp_str = xstrnsave(str, (size_t)len);
// match-fname is:
// - compl_curr_match->cp_fname if it is a string equal to fname.
@@ -811,10 +811,10 @@ static int ins_compl_add(char_u *const str, int len, char_u *const fname,
if (fname != NULL
&& compl_curr_match != NULL
&& compl_curr_match->cp_fname != NULL
- && STRCMP(fname, compl_curr_match->cp_fname) == 0) {
+ && strcmp(fname, compl_curr_match->cp_fname) == 0) {
match->cp_fname = compl_curr_match->cp_fname;
} else if (fname != NULL) {
- match->cp_fname = vim_strsave(fname);
+ match->cp_fname = xstrdup(fname);
flags |= CP_FREE_FNAME;
} else {
match->cp_fname = NULL;
@@ -829,9 +829,7 @@ static int ins_compl_add(char_u *const str, int len, char_u *const fname,
continue;
}
if (*cptext[i] != NUL) {
- match->cp_text[i] = (cptext_allocated
- ? cptext[i]
- : (char_u *)xstrdup((char *)cptext[i]));
+ match->cp_text[i] = (cptext_allocated ? cptext[i] : xstrdup(cptext[i]));
} else if (cptext_allocated) {
xfree(cptext[i]);
}
@@ -898,11 +896,11 @@ static void ins_compl_longest_match(compl_T *match)
if (compl_leader == NULL) {
// First match, use it as a whole.
- compl_leader = vim_strsave(match->cp_str);
+ compl_leader = xstrdup(match->cp_str);
had_match = (curwin->w_cursor.col > compl_col);
ins_compl_delete();
- ins_bytes((char *)compl_leader + get_compl_len());
+ ins_bytes(compl_leader + get_compl_len());
ins_redraw(false);
// When the match isn't there (to avoid matching itself) remove it
@@ -916,8 +914,8 @@ static void ins_compl_longest_match(compl_T *match)
}
// Reduce the text if this match differs from compl_leader.
- p = compl_leader;
- s = match->cp_str;
+ p = (char_u *)compl_leader;
+ s = (char_u *)match->cp_str;
while (*p != NUL) {
c1 = utf_ptr2char((char *)p);
c2 = utf_ptr2char((char *)s);
@@ -936,7 +934,7 @@ static void ins_compl_longest_match(compl_T *match)
*p = NUL;
had_match = (curwin->w_cursor.col > compl_col);
ins_compl_delete();
- ins_bytes((char *)compl_leader + get_compl_len());
+ ins_bytes(compl_leader + get_compl_len());
ins_redraw(false);
// When the match isn't there (to avoid matching itself) remove it
@@ -957,7 +955,7 @@ static void ins_compl_add_matches(int num_matches, char **matches, int icase)
Direction dir = compl_direction;
for (int i = 0; i < num_matches && add_r != FAIL; i++) {
- if ((add_r = ins_compl_add((char_u *)matches[i], -1, NULL, NULL, false, NULL, dir,
+ if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, false, NULL, dir,
CP_FAST | (icase ? CP_ICASE : 0),
false)) == OK) {
// If dir was BACKWARD then honor it just once.
@@ -1131,7 +1129,7 @@ static int ins_compl_build_pum(void)
do {
if (!match_at_original_text(compl)
&& (compl_leader == NULL
- || ins_compl_equal(compl, compl_leader, (size_t)lead_len))) {
+ || ins_compl_equal(compl, (char_u *)compl_leader, (size_t)lead_len))) {
compl_match_arraysize++;
}
compl = compl->cp_next;
@@ -1156,7 +1154,7 @@ static int ins_compl_build_pum(void)
do {
if (!match_at_original_text(compl)
&& (compl_leader == NULL
- || ins_compl_equal(compl, compl_leader, (size_t)lead_len))) {
+ || ins_compl_equal(compl, (char_u *)compl_leader, (size_t)lead_len))) {
if (!shown_match_ok) {
if (compl == compl_shown_match || did_find_shown_match) {
// This item is the shown match or this is the
@@ -1173,16 +1171,16 @@ static int ins_compl_build_pum(void)
}
if (compl->cp_text[CPT_ABBR] != NULL) {
- compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR];
+ compl_match_array[i].pum_text = (char_u *)compl->cp_text[CPT_ABBR];
} else {
- compl_match_array[i].pum_text = compl->cp_str;
+ compl_match_array[i].pum_text = (char_u *)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];
+ compl_match_array[i].pum_kind = (char_u *)compl->cp_text[CPT_KIND];
+ compl_match_array[i].pum_info = (char_u *)compl->cp_text[CPT_INFO];
if (compl->cp_text[CPT_MENU] != NULL) {
- compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU];
+ compl_match_array[i++].pum_extra = (char_u *)compl->cp_text[CPT_MENU];
} else {
- compl_match_array[i++].pum_extra = compl->cp_fname;
+ compl_match_array[i++].pum_extra = (char_u *)compl->cp_fname;
}
}
@@ -1236,8 +1234,8 @@ void ins_compl_show_pum(void)
} else {
// popup menu already exists, only need to find the current item.
for (int i = 0; i < compl_match_arraysize; i++) {
- if (compl_match_array[i].pum_text == compl_shown_match->cp_str
- || compl_match_array[i].pum_text == compl_shown_match->cp_text[CPT_ABBR]) {
+ if (compl_match_array[i].pum_text == (char_u *)compl_shown_match->cp_str
+ || compl_match_array[i].pum_text == (char_u *)compl_shown_match->cp_text[CPT_ABBR]) {
cur = i;
break;
}
@@ -1334,7 +1332,7 @@ static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, i
// 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,
@@ -1351,7 +1349,7 @@ static void ins_compl_dictionaries(char_u *dict_start, char_u *pat, int flags, i
} else {
ptr = pat;
}
- spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
+ spell_dump_compl((char *)ptr, regmatch.rm_ic, &dir, 0);
} else if (count > 0) { // avoid warning for using "files" uninit
ins_compl_files(count, files, thesaurus, flags,
&regmatch, (char_u *)buf, &dir);
@@ -1445,20 +1443,20 @@ static void ins_compl_files(int count, char **files, int thesaurus, int flags, r
while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp)) {
ptr = buf;
while (vim_regexec(regmatch, (char *)buf, (colnr_T)(ptr - buf))) {
- ptr = regmatch->startp[0];
+ ptr = (char_u *)regmatch->startp[0];
if (ctrl_x_mode_line_or_eval()) {
ptr = find_line_end(ptr);
} else {
ptr = find_word_end(ptr);
}
- add_r = ins_compl_add_infercase(regmatch->startp[0],
- (int)(ptr - regmatch->startp[0]),
+ add_r = ins_compl_add_infercase((char_u *)regmatch->startp[0],
+ (int)(ptr - (char_u *)regmatch->startp[0]),
p_ic, (char_u *)files[i], *dir, false);
if (thesaurus) {
// For a thesaurus, add all the words in the line
ptr = buf;
add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
- regmatch->startp[0]);
+ (char_u *)regmatch->startp[0]);
}
if (add_r == OK) {
// if dir was BACKWARD then honor it just once
@@ -1621,8 +1619,8 @@ int ins_compl_len(void)
/// to be got from the user.
int ins_compl_bs(void)
{
- char_u *line = get_cursor_line_ptr();
- char_u *p = line + curwin->w_cursor.col;
+ char *line = get_cursor_line_ptr();
+ char *p = line + curwin->w_cursor.col;
MB_PTR_BACK(line, p);
ptrdiff_t p_off = p - line;
@@ -1649,7 +1647,7 @@ int ins_compl_bs(void)
line = get_cursor_line_ptr();
xfree(compl_leader);
- compl_leader = vim_strnsave(line + compl_col, (size_t)(p_off - (ptrdiff_t)compl_col));
+ compl_leader = xstrnsave(line + compl_col, (size_t)(p_off - (ptrdiff_t)compl_col));
ins_compl_new_leader();
if (compl_shown_match != NULL) {
@@ -1678,7 +1676,7 @@ static void ins_compl_new_leader(void)
{
ins_compl_del_pum();
ins_compl_delete();
- ins_bytes((char *)compl_leader + get_compl_len());
+ ins_bytes(compl_leader + get_compl_len());
compl_used_match = false;
if (compl_started) {
@@ -1743,8 +1741,8 @@ void ins_compl_addleader(int c)
}
xfree(compl_leader);
- compl_leader = vim_strnsave(get_cursor_line_ptr() + compl_col,
- (size_t)(curwin->w_cursor.col - compl_col));
+ compl_leader = xstrnsave(get_cursor_line_ptr() + compl_col,
+ (size_t)(curwin->w_cursor.col - compl_col));
ins_compl_new_leader();
}
@@ -1764,7 +1762,7 @@ static void ins_compl_restart(void)
}
/// Set the first match, the original text.
-static void ins_compl_set_original_text(char_u *str)
+static void ins_compl_set_original_text(char *str)
FUNC_ATTR_NONNULL_ALL
{
// Replace the original text entry.
@@ -1772,11 +1770,11 @@ static void ins_compl_set_original_text(char_u *str)
// be at the last item for backward completion
if (match_at_original_text(compl_first_match)) { // safety check
xfree(compl_first_match->cp_str);
- compl_first_match->cp_str = vim_strsave(str);
+ compl_first_match->cp_str = xstrdup(str);
} else if (compl_first_match->cp_prev != NULL
&& match_at_original_text(compl_first_match->cp_prev)) {
xfree(compl_first_match->cp_prev->cp_str);
- compl_first_match->cp_prev->cp_str = vim_strsave(str);
+ compl_first_match->cp_prev->cp_str = xstrdup(str);
}
}
@@ -1789,7 +1787,7 @@ void ins_compl_addfrommatch(void)
int c;
compl_T *cp;
assert(compl_shown_match != NULL);
- p = compl_shown_match->cp_str;
+ p = (char_u *)compl_shown_match->cp_str;
if ((int)STRLEN(p) <= len) { // the match is too short
// When still at the original match use the first entry that matches
// the leader.
@@ -1801,8 +1799,8 @@ void ins_compl_addfrommatch(void)
for (cp = compl_shown_match->cp_next; cp != NULL
&& !is_first_match(cp); cp = cp->cp_next) {
if (compl_leader == NULL
- || ins_compl_equal(cp, compl_leader, STRLEN(compl_leader))) {
- p = cp->cp_str;
+ || ins_compl_equal(cp, (char_u *)compl_leader, STRLEN(compl_leader))) {
+ p = (char_u *)cp->cp_str;
break;
}
}
@@ -1955,7 +1953,7 @@ static bool ins_compl_stop(const int c, const int prev_mode, bool retval)
// CTRL-E then don't use the current match.
char_u *ptr;
if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) {
- ptr = compl_curr_match->cp_str;
+ ptr = (char_u *)compl_curr_match->cp_str;
} else {
ptr = NULL;
}
@@ -2006,9 +2004,9 @@ static bool ins_compl_stop(const int c, const int prev_mode, bool retval)
ins_compl_delete();
char_u *p = NULL;
if (compl_leader != NULL) {
- p = compl_leader;
+ p = (char_u *)compl_leader;
} else if (compl_first_match != NULL) {
- p = compl_orig_text;
+ p = (char_u *)compl_orig_text;
}
if (p != NULL) {
const int compl_len = get_compl_len();
@@ -2168,13 +2166,13 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
if (ptr == NULL) {
if (compl_leader != NULL) {
- ptr = compl_leader;
+ ptr = (char_u *)compl_leader;
} else {
return; // nothing to do
}
}
if (compl_orig_text != NULL) {
- p = compl_orig_text;
+ p = (char_u *)compl_orig_text;
for (len = 0; p[len] != NUL && p[len] == ptr[len]; len++) {}
if (len > 0) {
len -= utf_head_off((char *)p, (char *)p + len);
@@ -2360,7 +2358,7 @@ static int ins_compl_add_tv(typval_T *const tv, const Direction dir, bool fast)
tv_clear(&user_data);
return FAIL;
}
- int status = ins_compl_add((char_u *)word, -1, NULL, (char_u **)cptext, true,
+ int status = ins_compl_add((char *)word, -1, NULL, cptext, true,
&user_data, dir, flags, dup);
if (status != OK) {
tv_clear(&user_data);
@@ -2430,8 +2428,8 @@ static void set_completion(colnr_T startcol, list_T *list)
compl_col = startcol;
compl_length = (int)curwin->w_cursor.col - (int)startcol;
// compl_pattern doesn't need to be set
- compl_orig_text = vim_strnsave(get_cursor_line_ptr() + compl_col,
- (size_t)compl_length);
+ compl_orig_text = xstrnsave(get_cursor_line_ptr() + compl_col,
+ (size_t)compl_length);
if (p_ic) {
flags |= CP_ICASE;
}
@@ -2590,15 +2588,15 @@ static void get_complete_info(list_T *what_list, dict_T *retdict)
; item = TV_LIST_ITEM_NEXT(what_list, item)) {
const char *what = tv_get_string(TV_LIST_ITEM_TV(item));
- if (STRCMP(what, "mode") == 0) {
+ if (strcmp(what, "mode") == 0) {
what_flag |= CI_WHAT_MODE;
- } else if (STRCMP(what, "pum_visible") == 0) {
+ } else if (strcmp(what, "pum_visible") == 0) {
what_flag |= CI_WHAT_PUM_VISIBLE;
- } else if (STRCMP(what, "items") == 0) {
+ } else if (strcmp(what, "items") == 0) {
what_flag |= CI_WHAT_ITEMS;
- } else if (STRCMP(what, "selected") == 0) {
+ } else if (strcmp(what, "selected") == 0) {
what_flag |= CI_WHAT_SELECTED;
- } else if (STRCMP(what, "inserted") == 0) {
+ } else if (strcmp(what, "inserted") == 0) {
what_flag |= CI_WHAT_INSERTED;
}
}
@@ -2919,14 +2917,14 @@ static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_p
bool *cont_s_ipos)
{
*match_len = 0;
- char_u *ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, false) + cur_match_pos->col;
+ char_u *ptr = (char_u *)ml_get_buf(ins_buf, cur_match_pos->lnum, false) + cur_match_pos->col;
int len;
if (ctrl_x_mode_line_or_eval()) {
if (compl_status_adding()) {
if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count) {
return NULL;
}
- ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, false);
+ ptr = (char_u *)ml_get_buf(ins_buf, cur_match_pos->lnum + 1, false);
if (!p_paste) {
ptr = (char_u *)skipwhite((char *)ptr);
}
@@ -2954,7 +2952,7 @@ static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_p
// normal command "J" was used. IOSIZE is always greater than
// compl_length, so the next STRNCPY always works -- Acevedo
STRNCPY(IObuff, ptr, len); // NOLINT(runtime/printf)
- ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, false);
+ ptr = (char_u *)ml_get_buf(ins_buf, cur_match_pos->lnum + 1, false);
tmp_ptr = ptr = (char_u *)skipwhite((char *)ptr);
// Find start of next word.
tmp_ptr = find_word_start(tmp_ptr);
@@ -2982,7 +2980,7 @@ static char_u *ins_comp_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_p
*cont_s_ipos = true;
}
IObuff[len] = NUL;
- ptr = IObuff;
+ ptr = (char_u *)IObuff;
}
if (len == compl_length) {
return NULL;
@@ -3275,7 +3273,7 @@ static int ins_compl_get_exp(pos_T *ini)
static void ins_compl_update_shown_match(void)
{
while (!ins_compl_equal(compl_shown_match,
- compl_leader, STRLEN(compl_leader))
+ (char_u *)compl_leader, STRLEN(compl_leader))
&& compl_shown_match->cp_next != NULL
&& !is_first_match(compl_shown_match->cp_next)) {
compl_shown_match = compl_shown_match->cp_next;
@@ -3284,10 +3282,10 @@ static void ins_compl_update_shown_match(void)
// If we didn't find it searching forward, and compl_shows_dir is
// backward, find the last match.
if (compl_shows_dir_backward()
- && !ins_compl_equal(compl_shown_match, compl_leader, STRLEN(compl_leader))
+ && !ins_compl_equal(compl_shown_match, (char_u *)compl_leader, STRLEN(compl_leader))
&& (compl_shown_match->cp_next == NULL
|| is_first_match(compl_shown_match->cp_next))) {
- while (!ins_compl_equal(compl_shown_match, compl_leader, STRLEN(compl_leader))
+ while (!ins_compl_equal(compl_shown_match, (char_u *)compl_leader, STRLEN(compl_leader))
&& compl_shown_match->cp_prev != NULL
&& !is_first_match(compl_shown_match->cp_prev)) {
compl_shown_match = compl_shown_match->cp_prev;
@@ -3321,7 +3319,7 @@ void ins_compl_delete(void)
/// "in_compl_func" is true when called from complete_check().
void ins_compl_insert(bool in_compl_func)
{
- ins_bytes((char *)compl_shown_match->cp_str + get_compl_len());
+ ins_bytes(compl_shown_match->cp_str + get_compl_len());
compl_used_match = !match_at_original_text(compl_shown_match);
dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
@@ -3346,7 +3344,7 @@ static void ins_compl_show_filename(void)
// the text that fits in "space" between "s" and "e".
char *s;
char *e;
- for (s = e = (char *)compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e)) {
+ for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e)) {
space -= ptr2cells(e);
while (space < 0) {
space += ptr2cells(s);
@@ -3355,7 +3353,7 @@ static void ins_compl_show_filename(void)
}
msg_hist_off = true;
vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
- (char_u *)s > compl_shown_match->cp_fname ? "<" : "", s);
+ s > compl_shown_match->cp_fname ? "<" : "", s);
msg((char *)IObuff);
msg_hist_off = false;
redraw_cmdline = false; // don't overwrite!
@@ -3432,7 +3430,7 @@ static int find_next_completion_match(bool allow_get_expansion, int todo, bool a
if (!match_at_original_text(compl_shown_match)
&& compl_leader != NULL
&& !ins_compl_equal(compl_shown_match,
- compl_leader, STRLEN(compl_leader))) {
+ (char_u *)compl_leader, STRLEN(compl_leader))) {
todo++;
} else {
// Remember a matching item.
@@ -3513,13 +3511,13 @@ static int ins_compl_next(bool allow_get_expansion, int count, bool insert_match
// Insert the text of the new completion, or the compl_leader.
if (compl_no_insert && !started) {
- ins_bytes((char *)compl_orig_text + get_compl_len());
+ ins_bytes(compl_orig_text + get_compl_len());
compl_used_match = false;
} else if (insert_match) {
if (!compl_get_longest || compl_used_match) {
ins_compl_insert(in_compl_func);
} else {
- ins_bytes((char *)compl_leader + get_compl_len());
+ ins_bytes(compl_leader + get_compl_len());
}
} else {
compl_used_match = false;
@@ -3697,7 +3695,7 @@ static bool ins_compl_use_match(int c)
/// completion)
/// Sets the global variables: compl_col, compl_length and compl_pattern.
/// Uses the global variables: compl_cont_status and ctrl_x_mode
-static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
+static int get_normal_compl_info(char *line, int startcol, colnr_T curs_col)
{
if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines()) {
if (!compl_status_adding()) {
@@ -3706,25 +3704,25 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
compl_length = curs_col - startcol;
}
if (p_ic) {
- compl_pattern = (char *)str_foldcase(line + compl_col, compl_length, NULL, 0);
+ compl_pattern = (char *)str_foldcase((char_u *)line + compl_col, compl_length, NULL, 0);
} else {
- compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length);
+ compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length);
}
} else if (compl_status_adding()) {
char_u *prefix = (char_u *)"\\<";
// we need up to 2 extra chars for the prefix
- compl_pattern = xmalloc(quote_meta(NULL, line + compl_col,
- compl_length) + 2);
- if (!vim_iswordp(line + compl_col)
- || (compl_col > 0 && (vim_iswordp(mb_prevptr(line, line + compl_col))))) {
+ compl_pattern = xmalloc(quote_meta(NULL, (char_u *)line + compl_col, compl_length) + 2);
+ if (!vim_iswordp((char_u *)line + compl_col)
+ || (compl_col > 0
+ && (vim_iswordp(mb_prevptr((char_u *)line, (char_u *)line + compl_col))))) {
prefix = (char_u *)"";
}
STRCPY(compl_pattern, prefix);
(void)quote_meta((char_u *)compl_pattern + STRLEN(prefix),
- line + compl_col, compl_length);
+ (char_u *)line + compl_col, compl_length);
} else if (--startcol < 0
- || !vim_iswordp(mb_prevptr(line, line + startcol + 1))) {
+ || !vim_iswordp(mb_prevptr((char_u *)line, (char_u *)line + startcol + 1))) {
// Match any word of at least two chars
compl_pattern = xstrdup("\\<\\k\\k");
compl_col += curs_col;
@@ -3732,11 +3730,11 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
} else {
// Search the point of change class of multibyte character
// or not a word single byte character backward.
- startcol -= utf_head_off((char *)line, (char *)line + startcol);
- int base_class = mb_get_class(line + startcol);
+ startcol -= utf_head_off(line, line + startcol);
+ int base_class = mb_get_class((char_u *)line + startcol);
while (--startcol >= 0) {
- int head_off = utf_head_off((char *)line, (char *)line + startcol);
- if (base_class != mb_get_class(line + startcol - head_off)) {
+ int head_off = utf_head_off(line, line + startcol);
+ if (base_class != mb_get_class((char_u *)line + startcol - head_off)) {
break;
}
startcol -= head_off;
@@ -3749,13 +3747,13 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
// xmalloc(7) is enough -- Acevedo
compl_pattern = xmalloc(7);
STRCPY(compl_pattern, "\\<");
- (void)quote_meta((char_u *)compl_pattern + 2, line + compl_col, 1);
+ (void)quote_meta((char_u *)compl_pattern + 2, (char_u *)line + compl_col, 1);
STRCAT(compl_pattern, "\\k");
} else {
- compl_pattern = xmalloc(quote_meta(NULL, line + compl_col,
+ compl_pattern = xmalloc(quote_meta(NULL, (char_u *)line + compl_col,
compl_length) + 2);
STRCPY(compl_pattern, "\\<");
- (void)quote_meta((char_u *)compl_pattern + 2, line + compl_col, compl_length);
+ (void)quote_meta((char_u *)compl_pattern + 2, (char_u *)line + compl_col, compl_length);
}
}
@@ -3765,17 +3763,17 @@ static int get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
/// Get the pattern, column and length for whole line completion or for the
/// complete() function.
/// Sets the global variables: compl_col, compl_length and compl_pattern.
-static int get_wholeline_compl_info(char_u *line, colnr_T curs_col)
+static int get_wholeline_compl_info(char *line, colnr_T curs_col)
{
- compl_col = (colnr_T)getwhitecols((char *)line);
+ compl_col = (colnr_T)getwhitecols(line);
compl_length = (int)curs_col - (int)compl_col;
if (compl_length < 0) { // cursor in indent: empty pattern
compl_length = 0;
}
if (p_ic) {
- compl_pattern = (char *)str_foldcase(line + compl_col, compl_length, NULL, 0);
+ compl_pattern = (char *)str_foldcase((char_u *)line + compl_col, compl_length, NULL, 0);
} else {
- compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length);
+ compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length);
}
return OK;
@@ -3802,16 +3800,16 @@ static int get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
compl_col += startcol;
compl_length = (int)curs_col - startcol;
- compl_pattern = (char *)addstar(line + compl_col, (size_t)compl_length, EXPAND_FILES);
+ compl_pattern = addstar((char *)line + compl_col, (size_t)compl_length, EXPAND_FILES);
return OK;
}
/// Get the pattern, column and length for command-line completion.
/// Sets the global variables: compl_col, compl_length and compl_pattern.
-static int get_cmdline_compl_info(char_u *line, colnr_T curs_col)
+static int get_cmdline_compl_info(char *line, colnr_T curs_col)
{
- compl_pattern = (char *)vim_strnsave(line, (size_t)curs_col);
+ compl_pattern = xstrnsave(line, (size_t)curs_col);
set_cmd_context(&compl_xp, (char_u *)compl_pattern, (int)STRLEN(compl_pattern), curs_col, false);
if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
|| compl_xp.xp_context == EXPAND_NOTHING) {
@@ -3893,9 +3891,9 @@ static int get_userdefined_compl_info(colnr_T curs_col)
// Setup variables for completion. Need to obtain "line" again,
// it may have become invalid.
- char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum);
+ char *line = ml_get(curwin->w_cursor.lnum);
compl_length = curs_col - compl_col;
- compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length);
+ compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length);
return OK;
}
@@ -3919,8 +3917,8 @@ static int get_spell_compl_info(int startcol, colnr_T curs_col)
compl_length = (int)curs_col - compl_col;
}
// Need to obtain "line" again, it may have become invalid.
- char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum);
- compl_pattern = (char *)vim_strnsave(line + compl_col, (size_t)compl_length);
+ char *line = ml_get(curwin->w_cursor.lnum);
+ compl_pattern = xstrnsave(line + compl_col, (size_t)compl_length);
return OK;
}
@@ -3939,13 +3937,13 @@ static int compl_get_info(char_u *line, int startcol, colnr_T curs_col, bool *li
if (ctrl_x_mode_normal()
|| ((ctrl_x_mode & CTRL_X_WANT_IDENT)
&& !thesaurus_func_complete(ctrl_x_mode))) {
- return get_normal_compl_info(line, startcol, curs_col);
+ return get_normal_compl_info((char *)line, startcol, curs_col);
} else if (ctrl_x_mode_line_or_eval()) {
- return get_wholeline_compl_info(line, curs_col);
+ return get_wholeline_compl_info((char *)line, curs_col);
} else if (ctrl_x_mode_files()) {
return get_filename_compl_info(line, startcol, curs_col);
} else if (ctrl_x_mode == CTRL_X_CMDLINE) {
- return get_cmdline_compl_info(line, curs_col);
+ return get_cmdline_compl_info((char *)line, curs_col);
} else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
|| thesaurus_func_complete(ctrl_x_mode)) {
if (get_userdefined_compl_info(curs_col) == FAIL) {
@@ -4036,7 +4034,7 @@ static int ins_compl_start(void)
return FAIL;
}
- char_u *line = (char_u *)ml_get(curwin->w_cursor.lnum);
+ char *line = ml_get(curwin->w_cursor.lnum);
colnr_T curs_col = curwin->w_cursor.col;
compl_pending = 0;
@@ -4044,7 +4042,7 @@ static int ins_compl_start(void)
&& compl_cont_mode == ctrl_x_mode) {
// this same ctrl-x_mode was interrupted previously. Continue the
// completion.
- ins_compl_continue_search(line);
+ ins_compl_continue_search((char_u *)line);
} else {
compl_cont_status &= CONT_LOCAL;
}
@@ -4064,7 +4062,7 @@ static int ins_compl_start(void)
// Work out completion pattern and original text -- webb
bool line_invalid = false;
- if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL) {
+ if (compl_get_info((char_u *)line, startcol, curs_col, &line_invalid) == FAIL) {
if (ctrl_x_mode_function() || ctrl_x_mode_omni()
|| thesaurus_func_complete(ctrl_x_mode)) {
// restore did_ai, so that adding comment leader works
@@ -4074,7 +4072,7 @@ static int ins_compl_start(void)
}
// If "line" was changed while getting completion info get it again.
if (line_invalid) {
- line = (char_u *)ml_get(curwin->w_cursor.lnum);
+ line = ml_get(curwin->w_cursor.lnum);
}
if (compl_status_adding()) {
@@ -4108,7 +4106,7 @@ static int ins_compl_start(void)
// Always add completion for the original text.
xfree(compl_orig_text);
- compl_orig_text = vim_strnsave(line + compl_col, (size_t)compl_length);
+ compl_orig_text = xstrnsave(line + compl_col, (size_t)compl_length);
int flags = CP_ORIGINAL_TEXT;
if (p_ic) {
flags |= CP_ICASE;
diff --git a/src/nvim/keycodes.c b/src/nvim/keycodes.c
index 2b00d371f0..a3763ea9bb 100644
--- a/src/nvim/keycodes.c
+++ b/src/nvim/keycodes.c
@@ -650,7 +650,7 @@ int find_special_key(const char_u **const srcp, const size_t src_len, int *const
if (*bp == '-') {
last_dash = bp;
if (bp + 1 <= end) {
- l = utfc_ptr2len_len(bp + 1, (int)(end - bp) + 1);
+ l = utfc_ptr2len_len((char *)bp + 1, (int)(end - bp) + 1);
// Anything accepted, like <C-?>.
// <C-"> or <M-"> are not special in strings as " is
// the string delimiter. With a backslash it works: <M-\">
@@ -665,7 +665,7 @@ int find_special_key(const char_u **const srcp, const size_t src_len, int *const
if (end - bp > 3 && bp[0] == 't' && bp[1] == '_') {
bp += 3; // skip t_xx, xx may be '-' or '>'
} else if (end - bp > 4 && STRNICMP(bp, "char-", 5) == 0) {
- vim_str2nr(bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true);
+ vim_str2nr((char *)bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true);
if (l == 0) {
emsg(_(e_invarg));
return 0;
@@ -695,7 +695,7 @@ int find_special_key(const char_u **const srcp, const size_t src_len, int *const
if (STRNICMP(last_dash + 1, "char-", 5) == 0
&& ascii_isdigit(last_dash[6])) {
// <Char-123> or <Char-033> or <Char-0x33>
- vim_str2nr(last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true);
+ vim_str2nr((char *)last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true);
if (l == 0) {
emsg(_(e_invarg));
return 0;
@@ -993,7 +993,7 @@ char *replace_termcodes(const char *const from, const size_t from_len, char **co
}
// skip multibyte char correctly
- for (i = utfc_ptr2len_len(src, (int)(end - src) + 1); i > 0; i--) {
+ for (i = utfc_ptr2len_len((char *)src, (int)(end - src) + 1); i > 0; i--) {
// If the character is K_SPECIAL, replace it with K_SPECIAL
// KS_SPECIAL KE_FILLER.
if (*src == K_SPECIAL) {
diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c
index 49d49f76b9..735a75a6f1 100644
--- a/src/nvim/lua/converter.c
+++ b/src/nvim/lua/converter.c
@@ -385,15 +385,12 @@ nlua_pop_typval_table_processing_end:
break;
}
case LUA_TFUNCTION: {
- LuaCFunctionState *state = xmalloc(sizeof(LuaCFunctionState));
- state->lua_callable.func_ref = nlua_ref_global(lstate, -1);
+ LuaRef func = nlua_ref_global(lstate, -1);
- char_u *name = register_cfunc(&nlua_CFunction_func_call,
- &nlua_CFunction_func_free,
- state);
+ char *name = (char *)register_luafunc(func);
cur.tv->v_type = VAR_FUNC;
- cur.tv->vval.v_string = (char *)vim_strsave(name);
+ cur.tv->vval.v_string = xstrdup(name);
break;
}
case LUA_TUSERDATA: {
@@ -476,8 +473,8 @@ static bool typval_conv_special = false;
#define TYPVAL_ENCODE_CONV_FUNC_START(tv, fun) \
do { \
ufunc_T *fp = find_func(fun); \
- if (fp != NULL && fp->uf_cb == nlua_CFunction_func_call) { \
- nlua_pushref(lstate, ((LuaCFunctionState *)fp->uf_cb_state)->lua_callable.func_ref); \
+ if (fp != NULL && fp->uf_flags & FC_LUAREF) { \
+ nlua_pushref(lstate, fp->uf_luaref); \
} else { \
TYPVAL_ENCODE_CONV_NIL(tv); \
} \
diff --git a/src/nvim/lua/converter.h b/src/nvim/lua/converter.h
index f6a85900ba..ddc0acfbfa 100644
--- a/src/nvim/lua/converter.h
+++ b/src/nvim/lua/converter.h
@@ -9,14 +9,6 @@
#include "nvim/eval/typval.h"
#include "nvim/func_attr.h"
-typedef struct {
- LuaRef func_ref;
-} LuaCallable;
-
-typedef struct {
- LuaCallable lua_callable;
-} LuaCFunctionState;
-
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "lua/converter.h.generated.h"
#endif
diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c
index 2315ecd874..78ac051308 100644
--- a/src/nvim/lua/executor.c
+++ b/src/nvim/lua/executor.c
@@ -1044,7 +1044,7 @@ static int nlua_debug(lua_State *lstate)
if (input.v_type != VAR_STRING
|| input.vval.v_string == NULL
|| *input.vval.v_string == NUL
- || STRCMP(input.vval.v_string, "cont") == 0) {
+ || strcmp(input.vval.v_string, "cont") == 0) {
tv_clear(&input);
return 0;
}
@@ -1425,12 +1425,11 @@ int nlua_source_using_linegetter(LineGetter fgetline, void *cookie, char *name)
/// @param[in] argcount Count of typval arguments
/// @param[in] argvars Typval Arguments
/// @param[out] rettv The return value from the called function.
-int typval_exec_lua_callable(lua_State *lstate, LuaCallable lua_cb, int argcount, typval_T *argvars,
- typval_T *rettv)
+int typval_exec_lua_callable(LuaRef lua_cb, int argcount, typval_T *argvars, typval_T *rettv)
{
- LuaRef cb = lua_cb.func_ref;
+ lua_State *lstate = global_lstate;
- nlua_pushref(lstate, cb);
+ nlua_pushref(lstate, lua_cb);
PUSH_ALL_TYPVALS(lstate, argvars, argcount, false);
@@ -1833,26 +1832,6 @@ static int nlua_is_thread(lua_State *lstate)
return 1;
}
-// Required functions for lua c functions as VimL callbacks
-
-int nlua_CFunction_func_call(int argcount, typval_T *argvars, typval_T *rettv, void *state)
-{
- lua_State *const lstate = global_lstate;
- LuaCFunctionState *funcstate = (LuaCFunctionState *)state;
-
- return typval_exec_lua_callable(lstate, funcstate->lua_callable,
- argcount, argvars, rettv);
-}
-
-void nlua_CFunction_func_free(void *state)
-{
- lua_State *const lstate = global_lstate;
- LuaCFunctionState *funcstate = (LuaCFunctionState *)state;
-
- nlua_unref_global(lstate, funcstate->lua_callable.func_ref);
- xfree(funcstate);
-}
-
bool nlua_is_table_from_lua(typval_T *const arg)
{
if (arg->v_type == VAR_DICT) {
@@ -1898,11 +1877,9 @@ char_u *nlua_register_table_as_callable(typval_T *const arg)
}
lua_pop(lstate, 2); // [table]
- LuaCFunctionState *state = xmalloc(sizeof(LuaCFunctionState));
- state->lua_callable.func_ref = nlua_ref_global(lstate, -1);
+ LuaRef func = nlua_ref_global(lstate, -1);
- char_u *name = register_cfunc(&nlua_CFunction_func_call,
- &nlua_CFunction_func_free, state);
+ char_u *name = register_luafunc(func);
lua_pop(lstate, 1); // []
assert(top == lua_gettop(lstate));
@@ -2082,7 +2059,7 @@ int nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap, bool preview)
lua_newtable(lstate); // smods table
- lua_pushinteger(lstate, cmdmod.cmod_tab);
+ lua_pushinteger(lstate, cmdmod.cmod_tab - 1);
lua_setfield(lstate, -2, "tab");
lua_pushinteger(lstate, cmdmod.cmod_verbose - 1);
diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c
index 1b874e673a..9b1890403e 100644
--- a/src/nvim/lua/stdlib.c
+++ b/src/nvim/lua/stdlib.c
@@ -60,8 +60,8 @@ static int regex_match(lua_State *lstate, regprog_T **prog, char_u *str)
*prog = rm.regprog;
if (match) {
- lua_pushinteger(lstate, (lua_Integer)(rm.startp[0] - str));
- lua_pushinteger(lstate, (lua_Integer)(rm.endp[0] - str));
+ lua_pushinteger(lstate, (lua_Integer)(rm.startp[0] - (char *)str));
+ lua_pushinteger(lstate, (lua_Integer)(rm.endp[0] - (char *)str));
return 2;
}
return 0;
@@ -111,7 +111,7 @@ static int regex_match_line(lua_State *lstate)
return luaL_error(lstate, "invalid row");
}
- char_u *line = ml_get_buf(buf, rownr + 1, false);
+ char_u *line = (char_u *)ml_get_buf(buf, rownr + 1, false);
size_t len = STRLEN(line);
if (start < 0 || (size_t)start > len) {
@@ -499,7 +499,7 @@ static int nlua_iconv(lua_State *lstate)
vimconv_T vimconv;
vimconv.vc_type = CONV_NONE;
- convert_setup_ext(&vimconv, from, false, to, false);
+ convert_setup_ext(&vimconv, (char *)from, false, (char *)to, false);
char_u *ret = (char_u *)string_convert(&vimconv, (char *)str, &str_len);
diff --git a/src/nvim/lua/treesitter.c b/src/nvim/lua/treesitter.c
index 7ff4fbbff4..f3c67e265f 100644
--- a/src/nvim/lua/treesitter.c
+++ b/src/nvim/lua/treesitter.c
@@ -332,7 +332,7 @@ static const char *input_cb(void *payload, uint32_t byte_index, TSPoint position
*bytes_read = 0;
return "";
}
- char *line = (char *)ml_get_buf(bp, (linenr_T)position.row + 1, false);
+ char *line = ml_get_buf(bp, (linenr_T)position.row + 1, false);
size_t len = STRLEN(line);
if (position.column > len) {
*bytes_read = 0;
@@ -834,7 +834,7 @@ static int node_field(lua_State *L)
do {
const char *current_field = ts_tree_cursor_current_field_name(&cursor);
- if (current_field != NULL && !STRCMP(field_name, current_field)) {
+ if (current_field != NULL && !strcmp(field_name, current_field)) {
push_node(L, ts_tree_cursor_current_node(&cursor), 1); // [table, node]
lua_rawseti(L, -2, (int)++curr_index);
}
@@ -1276,8 +1276,8 @@ int tslua_parse_query(lua_State *L)
TSQuery *query = ts_query_new(lang, src, (uint32_t)len, &error_offset, &error_type);
if (!query) {
- return luaL_error(L, "query: %s at position %d",
- query_err_string(error_type), (int)error_offset);
+ return luaL_error(L, "query: %s at position %d for language %s",
+ query_err_string(error_type), (int)error_offset, lang_name);
}
TSQuery **ud = lua_newuserdata(L, sizeof(TSQuery *)); // [udata]
diff --git a/src/nvim/macros.h b/src/nvim/macros.h
index b84539852f..1024ca5015 100644
--- a/src/nvim/macros.h
+++ b/src/nvim/macros.h
@@ -54,7 +54,7 @@
#define ASCII_ISALNUM(c) (ASCII_ISALPHA(c) || ascii_isdigit(c))
// Returns empty string if it is NULL.
-#define EMPTY_IF_NULL(x) (char *)((x) ? (x) : (char_u *)"")
+#define EMPTY_IF_NULL(x) ((x) ? (x) : "")
/// Adjust chars in a language according to 'langmap' option.
/// NOTE that there is no noticeable overhead if 'langmap' is not set.
diff --git a/src/nvim/main.c b/src/nvim/main.c
index 1c7cfea768..a73c465042 100644
--- a/src/nvim/main.c
+++ b/src/nvim/main.c
@@ -1390,10 +1390,9 @@ scripterror:
TIME_MSG("parsing arguments");
}
-/*
- * Many variables are in "params" so that we can pass them to invoked
- * functions without a lot of arguments. "argc" and "argv" are also
- * copied, so that they can be changed. */
+// Many variables are in "params" so that we can pass them to invoked
+// functions without a lot of arguments. "argc" and "argv" are also
+// copied, so that they can be changed.
static void init_params(mparm_T *paramp, int argc, char **argv)
{
CLEAR_POINTER(paramp);
@@ -1465,9 +1464,7 @@ static char_u *get_fname(mparm_T *parmp, char_u *cwd)
return (char_u *)alist_name(&GARGLIST[0]);
}
-/*
- * Decide about window layout for diff mode after reading vimrc.
- */
+// Decide about window layout for diff mode after reading vimrc.
static void set_window_layout(mparm_T *paramp)
{
if (paramp->diff_mode && paramp->window_layout == 0) {
@@ -1479,10 +1476,8 @@ static void set_window_layout(mparm_T *paramp)
}
}
-/*
- * "-q errorfile": Load the error file now.
- * If the error file can't be read, exit before doing anything else.
- */
+// "-q errorfile": Load the error file now.
+// If the error file can't be read, exit before doing anything else.
static void handle_quickfix(mparm_T *paramp)
{
if (paramp->edit_type == EDIT_QF) {
@@ -1498,10 +1493,8 @@ static void handle_quickfix(mparm_T *paramp)
}
}
-/*
- * Need to jump to the tag before executing the '-c command'.
- * Makes "vim -c '/return' -t main" work.
- */
+// Need to jump to the tag before executing the '-c command'.
+// Makes "vim -c '/return' -t main" work.
static void handle_tag(char_u *tagname)
{
if (tagname != NULL) {
@@ -1540,18 +1533,14 @@ static void read_stdin(void)
check_swap_exists_action();
}
-/*
- * Create the requested number of windows and edit buffers in them.
- * Also does recovery if "recoverymode" set.
- */
+// Create the requested number of windows and edit buffers in them.
+// Also does recovery if "recoverymode" set.
static void create_windows(mparm_T *parmp)
{
int dorewind;
int done = 0;
- /*
- * Create the number of windows that was requested.
- */
+ // Create the number of windows that was requested.
if (parmp->window_count == -1) { // was not set
parmp->window_count = 1;
}
@@ -1670,9 +1659,7 @@ static void edit_buffers(mparm_T *parmp, char_u *cwd)
win_T *win;
char *p_shm_save = NULL;
- /*
- * Don't execute Win/Buf Enter/Leave autocommands here
- */
+ // Don't execute Win/Buf Enter/Leave autocommands here
autocmd_no_enter++;
autocmd_no_leave++;
@@ -1781,9 +1768,7 @@ static void edit_buffers(mparm_T *parmp, char_u *cwd)
}
}
-/*
- * Execute the commands from --cmd arguments "cmds[cnt]".
- */
+// Execute the commands from --cmd arguments "cmds[cnt]".
static void exe_pre_commands(mparm_T *parmp)
{
char **cmds = parmp->pre_commands;
@@ -1803,18 +1788,14 @@ static void exe_pre_commands(mparm_T *parmp)
}
}
-/*
- * Execute "+", "-c" and "-S" arguments.
- */
+// Execute "+", "-c" and "-S" arguments.
static void exe_commands(mparm_T *parmp)
{
int i;
- /*
- * We start commands on line 0, make "vim +/pat file" match a
- * pattern on line 1. But don't move the cursor when an autocommand
- * with g`" was used.
- */
+ // We start commands on line 0, make "vim +/pat file" match a
+ // pattern on line 1. But don't move the cursor when an autocommand
+ // with g`" was used.
msg_scroll = true;
if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1) {
curwin->w_cursor.lnum = 0;
@@ -2137,11 +2118,9 @@ static void usage(void)
mch_msg(_("\nSee \":help startup-options\" for all options.\n"));
}
-/*
- * Check the result of the ATTENTION dialog:
- * When "Quit" selected, exit Vim.
- * When "Recover" selected, recover the file.
- */
+// Check the result of the ATTENTION dialog:
+// When "Quit" selected, exit Vim.
+// When "Recover" selected, recover the file.
static void check_swap_exists_action(void)
{
if (swap_exists_action == SEA_QUIT) {
diff --git a/src/nvim/mapping.c b/src/nvim/mapping.c
index 923eea145c..9f169427f5 100644
--- a/src/nvim/mapping.c
+++ b/src/nvim/mapping.c
@@ -303,7 +303,7 @@ static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len
// NB: replace_termcodes may produce an empty string even if orig_rhs is non-empty
// (e.g. a single ^V, see :h map-empty-rhs)
mapargs->rhs_is_noop = orig_rhs_len != 0 && mapargs->rhs_len == 0;
- mapargs->rhs = (char_u *)replaced;
+ mapargs->rhs = replaced;
}
} else {
char tmp_buf[64];
@@ -313,7 +313,7 @@ static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len
// stores <lua>ref_no<cr> in map_str
mapargs->rhs_len = (size_t)vim_snprintf(S_LEN(tmp_buf), "%c%c%c%d\r", K_SPECIAL,
(char_u)KS_EXTRA, KE_LUA, rhs_lua);
- mapargs->rhs = vim_strsave((char_u *)tmp_buf);
+ mapargs->rhs = xstrdup(tmp_buf);
}
}
@@ -439,7 +439,7 @@ static int str_to_mapargs(const char_u *strargs, bool is_unmap, MapArguments *ma
/// and "desc" fields are used.
/// "rhs", "rhs_lua", "orig_rhs" fields are cleared if "simplified" is false.
/// @param sid -1 to use current_sctx
-static void map_add(buf_T *buf, mapblock_T **map_table, mapblock_T **abbr_table, const char_u *keys,
+static void map_add(buf_T *buf, mapblock_T **map_table, mapblock_T **abbr_table, const char *keys,
MapArguments *args, int noremap, int mode, bool is_abbr, scid_T sid,
linenr_T lnum, bool simplified)
{
@@ -454,8 +454,8 @@ static void map_add(buf_T *buf, mapblock_T **map_table, mapblock_T **abbr_table,
}
}
- mp->m_keys = vim_strsave(keys);
- mp->m_str = (char *)args->rhs;
+ mp->m_keys = (uint8_t *)xstrdup(keys);
+ mp->m_str = args->rhs;
mp->m_orig_str = (char *)args->orig_rhs;
mp->m_luaref = args->rhs_lua;
if (!simplified) {
@@ -767,7 +767,7 @@ static int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev,
XFREE_CLEAR(mp->m_str);
XFREE_CLEAR(mp->m_orig_str);
}
- mp->m_str = (char *)args->rhs;
+ mp->m_str = args->rhs;
mp->m_orig_str = (char *)args->orig_rhs;
mp->m_luaref = args->rhs_lua;
if (!keyround1_simplified) {
@@ -846,7 +846,7 @@ static int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev,
}
// Get here when adding a new entry to the maphash[] list or abbrlist.
- map_add(buf, map_table, abbr_table, lhs, args, noremap, mode, is_abbrev,
+ map_add(buf, map_table, abbr_table, (char *)lhs, args, noremap, mode, is_abbrev,
-1, // sid
0, // lnum
keyround1_simplified);
@@ -971,12 +971,12 @@ static int get_map_mode(char **cmdp, bool forceit)
/// Clear all mappings (":mapclear") or abbreviations (":abclear").
/// "abbr" should be false for mappings, true for abbreviations.
/// This function used to be called map_clear().
-static void do_mapclear(char *cmdp, char_u *arg, int forceit, int abbr)
+static void do_mapclear(char *cmdp, char *arg, int forceit, int abbr)
{
int mode;
int local;
- local = (STRCMP(arg, "<buffer>") == 0);
+ local = (strcmp(arg, "<buffer>") == 0);
if (!local && *arg != NUL) {
emsg(_(e_invarg));
return;
@@ -1265,7 +1265,7 @@ int ExpandMappings(regmatch_T *regmatch, int *num_file, char ***file)
int hash;
int count;
int round;
- char_u *p;
+ char *p;
int i;
*num_file = 0; // return values in case of FAIL
@@ -1278,28 +1278,28 @@ int ExpandMappings(regmatch_T *regmatch, int *num_file, char ***file)
for (i = 0; i < 7; i++) {
if (i == 0) {
- p = (char_u *)"<silent>";
+ p = "<silent>";
} else if (i == 1) {
- p = (char_u *)"<unique>";
+ p = "<unique>";
} else if (i == 2) {
- p = (char_u *)"<script>";
+ p = "<script>";
} else if (i == 3) {
- p = (char_u *)"<expr>";
+ p = "<expr>";
} else if (i == 4 && !expand_buffer) {
- p = (char_u *)"<buffer>";
+ p = "<buffer>";
} else if (i == 5) {
- p = (char_u *)"<nowait>";
+ p = "<nowait>";
} else if (i == 6) {
- p = (char_u *)"<special>";
+ p = "<special>";
} else {
continue;
}
- if (vim_regexec(regmatch, (char *)p, (colnr_T)0)) {
+ if (vim_regexec(regmatch, p, (colnr_T)0)) {
if (round == 1) {
count++;
} else {
- (*file)[count++] = (char *)vim_strsave(p);
+ (*file)[count++] = xstrdup(p);
}
}
}
@@ -1317,12 +1317,12 @@ int ExpandMappings(regmatch_T *regmatch, int *num_file, char ***file)
}
for (; mp; mp = mp->m_next) {
if (mp->m_mode & expand_mapmodes) {
- p = translate_mapping(mp->m_keys, CPO_TO_CPO_FLAGS);
- if (p != NULL && vim_regexec(regmatch, (char *)p, (colnr_T)0)) {
+ p = (char *)translate_mapping(mp->m_keys, CPO_TO_CPO_FLAGS);
+ if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0)) {
if (round == 1) {
count++;
} else {
- (*file)[count++] = (char *)p;
+ (*file)[count++] = p;
p = NULL;
}
}
@@ -1350,7 +1350,7 @@ int ExpandMappings(regmatch_T *regmatch, int *num_file, char ***file)
char **ptr3 = ptr1 + count;
while (ptr2 < ptr3) {
- if (STRCMP(*ptr1, *ptr2)) {
+ if (strcmp(*ptr1, *ptr2)) {
*++ptr1 = *ptr2++;
} else {
xfree(*ptr2++);
@@ -1447,20 +1447,20 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
(mp = mp->m_next)) {
int qlen = mp->m_keylen;
- char_u *q = mp->m_keys;
+ char *q = (char *)mp->m_keys;
int match;
if (strchr((const char *)mp->m_keys, K_SPECIAL) != NULL) {
// Might have K_SPECIAL escaped mp->m_keys.
- q = vim_strsave(mp->m_keys);
- vim_unescape_ks(q);
+ q = xstrdup((char *)mp->m_keys);
+ vim_unescape_ks((char_u *)q);
qlen = (int)STRLEN(q);
}
// find entries with right mode and keys
match = (mp->m_mode & State)
&& qlen == len
&& !STRNCMP(q, ptr, (size_t)len);
- if (q != mp->m_keys) {
+ if (q != (char *)mp->m_keys) {
xfree(q);
}
if (match) {
@@ -1510,7 +1510,7 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
(void)ins_typebuf((char *)tb, 1, 0, true, mp->m_silent);
}
if (mp->m_expr) {
- s = eval_map_expr(mp, c);
+ s = (char_u *)eval_map_expr(mp, c);
} else {
s = (char_u *)mp->m_str;
}
@@ -1540,16 +1540,16 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
/// special characters.
///
/// @param c NUL or typed character for abbreviation
-char_u *eval_map_expr(mapblock_T *mp, int c)
+char *eval_map_expr(mapblock_T *mp, int c)
{
- char_u *p = NULL;
- char_u *expr = NULL;
+ char *p = NULL;
+ char *expr = NULL;
// Remove escaping of K_SPECIAL, because "str" is in a format to be used as
// typeahead.
if (mp->m_luaref == LUA_NOREF) {
- expr = vim_strsave((char_u *)mp->m_str);
- vim_unescape_ks(expr);
+ expr = xstrdup(mp->m_str);
+ vim_unescape_ks((char_u *)expr);
}
// Forbid changing text or using ":normal" to avoid most of the bad side
@@ -1565,7 +1565,7 @@ char_u *eval_map_expr(mapblock_T *mp, int c)
Array args = ARRAY_DICT_INIT;
Object ret = nlua_call_ref(mp->m_luaref, NULL, args, true, &err);
if (ret.type == kObjectTypeString) {
- p = (char_u *)xstrndup(ret.data.string.data, ret.data.string.size);
+ p = xstrndup(ret.data.string.data, ret.data.string.size);
}
api_free_object(ret);
if (err.type != kErrorTypeNone) {
@@ -1573,7 +1573,7 @@ char_u *eval_map_expr(mapblock_T *mp, int c)
api_clear_error(&err);
}
} else {
- p = (char_u *)eval_to_string((char *)expr, NULL, false);
+ p = eval_to_string(expr, NULL, false);
xfree(expr);
}
textlock--;
@@ -1586,13 +1586,13 @@ char_u *eval_map_expr(mapblock_T *mp, int c)
return NULL;
}
- char_u *res = NULL;
+ char *res = NULL;
if (mp->m_replace_keycodes) {
- replace_termcodes((char *)p, STRLEN(p), (char **)&res, REPTERM_DO_LT, NULL, CPO_TO_CPO_FLAGS);
+ replace_termcodes(p, STRLEN(p), &res, REPTERM_DO_LT, NULL, CPO_TO_CPO_FLAGS);
} else {
// Escape K_SPECIAL in the result to be able to use the string as typeahead.
- res = (char_u *)vim_strsave_escape_ks((char *)p);
+ res = vim_strsave_escape_ks(p);
}
xfree(p);
@@ -2204,10 +2204,10 @@ void f_mapset(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
xfree(unmap_args.orig_rhs);
if (lhsrawalt != NULL) {
- map_add(curbuf, map_table, abbr_table, (char_u *)lhsrawalt, &args, noremap, mode, is_abbr,
+ map_add(curbuf, map_table, abbr_table, lhsrawalt, &args, noremap, mode, is_abbr,
sid, lnum, true);
}
- map_add(curbuf, map_table, abbr_table, (char_u *)lhsraw, &args, noremap, mode, is_abbr,
+ map_add(curbuf, map_table, abbr_table, lhsraw, &args, noremap, mode, is_abbr,
sid, lnum, false);
}
@@ -2457,13 +2457,13 @@ void ex_unmap(exarg_T *eap)
/// ":mapclear" and friends.
void ex_mapclear(exarg_T *eap)
{
- do_mapclear(eap->cmd, (char_u *)eap->arg, eap->forceit, false);
+ do_mapclear(eap->cmd, eap->arg, eap->forceit, false);
}
/// ":abclear" and friends.
void ex_abclear(exarg_T *eap)
{
- do_mapclear(eap->cmd, (char_u *)eap->arg, true, true);
+ do_mapclear(eap->cmd, eap->arg, true, true);
}
/// Set, tweak, or remove a mapping in a mode. Acts as the implementation for
diff --git a/src/nvim/mapping.h b/src/nvim/mapping.h
index 7c48c3bce2..182d1a48cb 100644
--- a/src/nvim/mapping.h
+++ b/src/nvim/mapping.h
@@ -35,7 +35,7 @@ struct map_arguments {
char_u alt_lhs[MAXMAPLEN + 1];
size_t alt_lhs_len;
- char_u *rhs; /// The {rhs} of the mapping.
+ char *rhs; /// The {rhs} of the mapping.
size_t rhs_len;
LuaRef rhs_lua; /// lua function as {rhs}
bool rhs_is_noop; /// True when the {rhs} should be <Nop>.
diff --git a/src/nvim/mark.c b/src/nvim/mark.c
index 7eab37e797..6f8aecb3ff 100644
--- a/src/nvim/mark.c
+++ b/src/nvim/mark.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * mark.c: functions for setting marks and jumping to them
- */
+// mark.c: functions for setting marks and jumping to them
#include <assert.h>
#include <inttypes.h>
@@ -39,17 +37,13 @@
#include "nvim/ui.h"
#include "nvim/vim.h"
-/*
- * This file contains routines to maintain and manipulate marks.
- */
+// This file contains routines to maintain and manipulate marks.
-/*
- * If a named file mark's lnum is non-zero, it is valid.
- * If a named file mark's fnum is non-zero, it is for an existing buffer,
- * otherwise it is from .shada and namedfm[n].fname is the file name.
- * There are marks 'A - 'Z (set by user) and '0 to '9 (set when writing
- * shada).
- */
+// If a named file mark's lnum is non-zero, it is valid.
+// If a named file mark's fnum is non-zero, it is for an existing buffer,
+// otherwise it is from .shada and namedfm[n].fname is the file name.
+// There are marks 'A - 'Z (set by user) and '0 to '9 (set when writing
+// shada).
/// Global marks (marks with file number or name)
static xfmark_T namedfm[NGLOBALMARKS];
@@ -57,10 +51,9 @@ static xfmark_T namedfm[NGLOBALMARKS];
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "mark.c.generated.h"
#endif
-/*
- * Set named mark "c" at current cursor position.
- * Returns OK on success, FAIL if bad name given.
- */
+
+// Set named mark "c" at current cursor position.
+// Returns OK on success, FAIL if bad name given.
int setmark(int c)
{
fmarkv_T view = mark_view_make(curwin->w_topline, curwin->w_cursor);
@@ -88,11 +81,9 @@ void clear_fmark(fmark_T *fm)
CLEAR_POINTER(fm);
}
-/*
- * Set named mark "c" to position "pos".
- * When "c" is upper case use file "fnum".
- * Returns OK on success, FAIL if bad name given.
- */
+// Set named mark "c" to position "pos".
+// When "c" is upper case use file "fnum".
+// Returns OK on success, FAIL if bad name given.
int setmark_pos(int c, pos_T *pos, int fnum, fmarkv_T *view_pt)
{
int i;
@@ -166,10 +157,8 @@ int setmark_pos(int c, pos_T *pos, int fnum, fmarkv_T *view_pt)
return FAIL;
}
-/*
- * Set the previous context mark to the current position and add it to the
- * jump list.
- */
+// Set the previous context mark to the current position and add it to the
+// jump list.
void setpcmark(void)
{
xfmark_T *fm;
@@ -210,12 +199,10 @@ void setpcmark(void)
SET_XFMARK(fm, curwin->w_pcmark, curbuf->b_fnum, view, NULL);
}
-/*
- * To change context, call setpcmark(), then move the current position to
- * where ever, then call checkpcmark(). This ensures that the previous
- * context will only be changed if the cursor moved to a different line.
- * If pcmark was deleted (with "dG") the previous mark is restored.
- */
+// To change context, call setpcmark(), then move the current position to
+// where ever, then call checkpcmark(). This ensures that the previous
+// context will only be changed if the cursor moved to a different line.
+// If pcmark was deleted (with "dG") the previous mark is restored.
void checkpcmark(void)
{
if (curwin->w_prev_pcmark.lnum != 0
@@ -653,20 +640,16 @@ fmark_T *getnextmark(pos_T *startpos, int dir, int begin_line)
return result;
}
-/*
- * For an xtended filemark: set the fnum from the fname.
- * This is used for marks obtained from the .shada file. It's postponed
- * until the mark is used to avoid a long startup delay.
- */
+// For an xtended filemark: set the fnum from the fname.
+// This is used for marks obtained from the .shada file. It's postponed
+// until the mark is used to avoid a long startup delay.
static void fname2fnum(xfmark_T *fm)
{
char_u *p;
if (fm->fname != NULL) {
- /*
- * First expand "~/" in the file name to the home directory.
- * Don't expand the whole name, it may contain other '~' chars.
- */
+ // First expand "~/" in the file name to the home directory.
+ // Don't expand the whole name, it may contain other '~' chars.
if (fm->fname[0] == '~' && (fm->fname[1] == '/'
#ifdef BACKSLASH_IN_FILENAME
|| fm->fname[1] == '\\'
@@ -682,19 +665,17 @@ static void fname2fnum(xfmark_T *fm)
}
// Try to shorten the file name.
- os_dirname(IObuff, IOSIZE);
- p = path_shorten_fname((char_u *)NameBuff, IObuff);
+ os_dirname((char_u *)IObuff, IOSIZE);
+ p = (char_u *)path_shorten_fname(NameBuff, (char *)IObuff);
// buflist_new() will call fmarks_check_names()
(void)buflist_new((char *)NameBuff, (char *)p, (linenr_T)1, 0);
}
}
-/*
- * Check all file marks for a name that matches the file name in buf.
- * May replace the name with an fnum.
- * Used for marks that come from the .shada file.
- */
+// Check all file marks for a name that matches the file name in buf.
+// May replace the name with an fnum.
+// Used for marks that come from the .shada file.
void fmarks_check_names(buf_T *buf)
{
char_u *name = (char_u *)buf->b_ffname;
@@ -705,21 +686,21 @@ void fmarks_check_names(buf_T *buf)
}
for (i = 0; i < NGLOBALMARKS; i++) {
- fmarks_check_one(&namedfm[i], name, buf);
+ fmarks_check_one(&namedfm[i], (char *)name, buf);
}
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
for (i = 0; i < wp->w_jumplistlen; i++) {
- fmarks_check_one(&wp->w_jumplist[i], name, buf);
+ fmarks_check_one(&wp->w_jumplist[i], (char *)name, buf);
}
}
}
-static void fmarks_check_one(xfmark_T *fm, char_u *name, buf_T *buf)
+static void fmarks_check_one(xfmark_T *fm, char *name, buf_T *buf)
{
if (fm->fmark.fnum == 0
&& fm->fname != NULL
- && FNAMECMP(name, fm->fname) == 0) {
+ && path_fnamecmp(name, fm->fname) == 0) {
fm->fmark.fnum = buf->b_fnum;
XFREE_CLEAR(fm->fname);
}
@@ -792,39 +773,35 @@ void clrallmarks(buf_T *const buf)
buf->b_changelistlen = 0;
}
-/*
- * Get name of file from a filemark.
- * When it's in the current buffer, return the text at the mark.
- * Returns an allocated string.
- */
+// Get name of file from a filemark.
+// When it's in the current buffer, return the text at the mark.
+// Returns an allocated string.
char_u *fm_getname(fmark_T *fmark, int lead_len)
{
if (fmark->fnum == curbuf->b_fnum) { // current buffer
- return mark_line(&(fmark->mark), lead_len);
+ return (char_u *)mark_line(&(fmark->mark), lead_len);
}
return (char_u *)buflist_nr2name(fmark->fnum, false, true);
}
-/*
- * Return the line at mark "mp". Truncate to fit in window.
- * The returned string has been allocated.
- */
-static char_u *mark_line(pos_T *mp, int lead_len)
+/// Return the line at mark "mp". Truncate to fit in window.
+/// The returned string has been allocated.
+static char *mark_line(pos_T *mp, int lead_len)
{
- char_u *s, *p;
+ char *s, *p;
int len;
if (mp->lnum == 0 || mp->lnum > curbuf->b_ml.ml_line_count) {
- return vim_strsave((char_u *)"-invalid-");
+ return xstrdup("-invalid-");
}
assert(Columns >= 0);
// Allow for up to 5 bytes per character.
- s = vim_strnsave((char_u *)skipwhite(ml_get(mp->lnum)), (size_t)Columns * 5);
+ s = xstrnsave(skipwhite(ml_get(mp->lnum)), (size_t)Columns * 5);
// Truncate the line to fit it in the window
len = 0;
for (p = s; *p != NUL; MB_PTR_ADV(p)) {
- len += ptr2cells((char *)p);
+ len += ptr2cells(p);
if (len >= Columns - lead_len) {
break;
}
@@ -833,9 +810,7 @@ static char_u *mark_line(pos_T *mp, int lead_len)
return s;
}
-/*
- * print the marks
- */
+// print the marks
void ex_marks(exarg_T *eap)
{
char_u *arg = (char_u *)eap->arg;
@@ -908,7 +883,7 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu
&& p->lnum != 0) {
// don't output anything if 'q' typed at --more-- prompt
if (name == NULL && current) {
- name = mark_line(p, 15);
+ name = (char_u *)mark_line(p, 15);
mustfree = true;
}
if (!message_filtered((char *)name)) {
@@ -932,9 +907,7 @@ static void show_one_mark(int c, char_u *arg, pos_T *p, char_u *name_arg, int cu
}
}
-/*
- * ":delmarks[!] [marks]"
- */
+// ":delmarks[!] [marks]"
void ex_delmarks(exarg_T *eap)
{
char_u *p;
@@ -1015,28 +988,26 @@ void ex_delmarks(exarg_T *eap)
}
}
-/*
- * print the jumplist
- */
+// print the jumplist
void ex_jumps(exarg_T *eap)
{
int i;
- char_u *name;
+ char *name;
cleanup_jumplist(curwin, true);
// Highlight title
msg_puts_title(_("\n jump line col file/text"));
for (i = 0; i < curwin->w_jumplistlen && !got_int; i++) {
if (curwin->w_jumplist[i].fmark.mark.lnum != 0) {
- name = fm_getname(&curwin->w_jumplist[i].fmark, 16);
+ name = (char *)fm_getname(&curwin->w_jumplist[i].fmark, 16);
// Make sure to output the current indicator, even when on an wiped
// out buffer. ":filter" may still skip it.
if (name == NULL && i == curwin->w_jumplistidx) {
- name = vim_strsave((char_u *)"-invalid-");
+ name = xstrdup("-invalid-");
}
// apply :filter /pat/ or file name not available
- if (name == NULL || message_filtered((char *)name)) {
+ if (name == NULL || message_filtered(name)) {
xfree(name);
continue;
}
@@ -1051,7 +1022,7 @@ void ex_jumps(exarg_T *eap)
i > curwin->w_jumplistidx ? i - curwin->w_jumplistidx : curwin->w_jumplistidx - i,
curwin->w_jumplist[i].fmark.mark.lnum, curwin->w_jumplist[i].fmark.mark.col);
msg_outtrans((char *)IObuff);
- msg_outtrans_attr((char *)name,
+ msg_outtrans_attr(name,
curwin->w_jumplist[i].fmark.fnum == curbuf->b_fnum
? HL_ATTR(HLF_D) : 0);
xfree(name);
@@ -1070,9 +1041,7 @@ void ex_clearjumps(exarg_T *eap)
curwin->w_jumplistidx = 0;
}
-/*
- * print the changelist
- */
+// print the changelist
void ex_changes(exarg_T *eap)
{
int i;
@@ -1094,7 +1063,7 @@ void ex_changes(exarg_T *eap)
(long)curbuf->b_changelist[i].mark.lnum,
curbuf->b_changelist[i].mark.col);
msg_outtrans((char *)IObuff);
- name = mark_line(&curbuf->b_changelist[i].mark, 17);
+ name = (char_u *)mark_line(&curbuf->b_changelist[i].mark, 17);
msg_outtrans_attr((char *)name, HL_ATTR(HLF_D));
xfree(name);
os_breakcheck();
@@ -1134,17 +1103,15 @@ void ex_changes(exarg_T *eap)
*lp += amount_after; \
}
-/*
- * Adjust marks between line1 and line2 (inclusive) to move 'amount' lines.
- * Must be called before changed_*(), appended_lines() or deleted_lines().
- * May be called before or after changing the text.
- * When deleting lines line1 to line2, use an 'amount' of MAXLNUM: The marks
- * within this range are made invalid.
- * If 'amount_after' is non-zero adjust marks after line2.
- * Example: Delete lines 34 and 35: mark_adjust(34, 35, MAXLNUM, -2);
- * Example: Insert two lines below 55: mark_adjust(56, MAXLNUM, 2, 0);
- * or: mark_adjust(56, 55, MAXLNUM, 2);
- */
+// Adjust marks between line1 and line2 (inclusive) to move 'amount' lines.
+// Must be called before changed_*(), appended_lines() or deleted_lines().
+// May be called before or after changing the text.
+// When deleting lines line1 to line2, use an 'amount' of MAXLNUM: The marks
+// within this range are made invalid.
+// If 'amount_after' is non-zero adjust marks after line2.
+// Example: Delete lines 34 and 35: mark_adjust(34, 35, MAXLNUM, -2);
+// Example: Insert two lines below 55: mark_adjust(56, MAXLNUM, 2, 0);
+// or: mark_adjust(56, 55, MAXLNUM, 2);
void mark_adjust(linenr_T line1, linenr_T line2, linenr_T amount, linenr_T amount_after,
ExtmarkOp op)
{
@@ -1239,9 +1206,7 @@ static void mark_adjust_internal(linenr_T line1, linenr_T line2, linenr_T amount
ONE_ADJUST_NODEL(&(saved_cursor.lnum));
}
- /*
- * Adjust items in all windows related to the current buffer.
- */
+ // Adjust items in all windows related to the current buffer.
FOR_ALL_TAB_WINDOWS(tab, win) {
if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
// Marks in the jumplist. When deleting lines, this may create
@@ -1383,9 +1348,7 @@ void mark_col_adjust(linenr_T lnum, colnr_T mincol, linenr_T lnum_amount, long c
// saved cursor for formatting
COL_ADJUST(&saved_cursor);
- /*
- * Adjust items in all windows related to the current buffer.
- */
+ // Adjust items in all windows related to the current buffer.
FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
// marks in the jumplist
for (i = 0; i < win->w_jumplistlen; i++) {
@@ -1483,9 +1446,7 @@ void cleanup_jumplist(win_T *wp, bool checktail)
}
}
-/*
- * Copy the jumplist from window "from" to window "to".
- */
+// Copy the jumplist from window "from" to window "to".
void copy_jumplist(win_T *from, win_T *to)
{
int i;
@@ -1707,9 +1668,7 @@ bool mark_set_local(const char name, buf_T *const buf, const fmark_T fm, const b
return true;
}
-/*
- * Free items in the jumplist of window "wp".
- */
+// Free items in the jumplist of window "wp".
void free_jumplist(win_T *wp)
{
int i;
@@ -1751,7 +1710,7 @@ void mark_mb_adjustpos(buf_T *buf, pos_T *lp)
FUNC_ATTR_NONNULL_ALL
{
if (lp->col > 0 || lp->coladd > 1) {
- const char_u *const p = ml_get_buf(buf, lp->lnum, false);
+ const char_u *const p = (char_u *)ml_get_buf(buf, lp->lnum, false);
if (*p == NUL || (int)STRLEN(p) < lp->col) {
lp->col = 0;
} else {
diff --git a/src/nvim/mark_defs.h b/src/nvim/mark_defs.h
index a78056c5f9..f9df0028db 100644
--- a/src/nvim/mark_defs.h
+++ b/src/nvim/mark_defs.h
@@ -5,10 +5,8 @@
#include "nvim/os/time.h"
#include "nvim/pos.h"
-/*
- * marks: positions in a file
- * (a normal mark is a lnum/col pair, the same as a file position)
- */
+// marks: positions in a file
+// (a normal mark is a lnum/col pair, the same as a file position)
/// Flags for outcomes when moving to a mark.
typedef enum {
@@ -88,4 +86,4 @@ typedef struct xfilemark {
#define INIT_XFMARK { INIT_FMARK, NULL }
-#endif // NVIM_MARK_DEFS_H
+#endif // NVIM_MARK_DEFS_H
diff --git a/src/nvim/match.c b/src/nvim/match.c
index 48f0d0fc05..cd8c65cc02 100644
--- a/src/nvim/match.c
+++ b/src/nvim/match.c
@@ -446,7 +446,7 @@ static void next_search_hl(win_T *win, match_T *search_hl, match_T *shl, linenr_
char_u *ml;
matchcol = shl->rm.startpos[0].col;
- ml = ml_get_buf(shl->buf, lnum, false) + matchcol;
+ ml = (char_u *)ml_get_buf(shl->buf, lnum, false) + matchcol;
if (*ml == NUL) {
matchcol++;
shl->lnum = 0;
@@ -613,7 +613,7 @@ bool prepare_search_hl_line(win_T *wp, linenr_T lnum, colnr_T mincol, char_u **l
// Need to get the line again, a multi-line regexp may have made it
// invalid.
- *line = ml_get_buf(wp->w_buffer, lnum, false);
+ *line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
if (shl->lnum != 0 && shl->lnum <= lnum) {
if (shl->lnum == lnum) {
@@ -721,7 +721,7 @@ int update_search_hl(win_T *wp, linenr_T lnum, colnr_T col, char_u **line, match
// Need to get the line again, a multi-line regexp
// may have made it invalid.
- *line = ml_get_buf(wp->w_buffer, lnum, false);
+ *line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
if (shl->lnum == lnum) {
shl->startcol = shl->rm.startpos[0].col;
@@ -1159,9 +1159,9 @@ void f_matchdelete(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
/// skipping commands to find the next command.
void ex_match(exarg_T *eap)
{
- char_u *p;
- char_u *g = NULL;
- char_u *end;
+ char *p;
+ char *g = NULL;
+ char *end;
int c;
int id;
@@ -1178,25 +1178,25 @@ void ex_match(exarg_T *eap)
}
if (ends_excmd(*eap->arg)) {
- end = (char_u *)eap->arg;
+ end = eap->arg;
} else if ((STRNICMP(eap->arg, "none", 4) == 0
&& (ascii_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4])))) {
- end = (char_u *)eap->arg + 4;
+ end = eap->arg + 4;
} else {
- p = (char_u *)skiptowhite(eap->arg);
+ p = skiptowhite(eap->arg);
if (!eap->skip) {
- g = vim_strnsave((char_u *)eap->arg, (size_t)(p - (char_u *)eap->arg));
+ g = xstrnsave(eap->arg, (size_t)(p - eap->arg));
}
- p = (char_u *)skipwhite((char *)p);
+ p = skipwhite(p);
if (*p == NUL) {
// There must be two arguments.
xfree(g);
semsg(_(e_invarg2), eap->arg);
return;
}
- end = (char_u *)skip_regexp((char *)p + 1, *p, true, NULL);
+ end = skip_regexp(p + 1, *p, true, NULL);
if (!eap->skip) {
- if (*end != NUL && !ends_excmd(*skipwhite((char *)end + 1))) {
+ if (*end != NUL && !ends_excmd(*skipwhite(end + 1))) {
xfree(g);
eap->errmsg = ex_errmsg(e_trailing_arg, (const char *)end);
return;
@@ -1207,13 +1207,13 @@ void ex_match(exarg_T *eap)
return;
}
- c = *end;
+ c = (uint8_t)(*end);
*end = NUL;
match_add(curwin, (const char *)g, (const char *)p + 1, 10, id,
NULL, NULL);
xfree(g);
- *end = (char_u)c;
+ *end = (char)c;
}
}
- eap->nextcmd = find_nextcmd((char *)end);
+ eap->nextcmd = find_nextcmd(end);
}
diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c
index 947594be4f..310ad05196 100644
--- a/src/nvim/mbyte.c
+++ b/src/nvim/mbyte.c
@@ -132,10 +132,8 @@ const uint8_t utf8len_tab_zero[] = {
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // F?
};
-/*
- * Canonical encoding names and their properties.
- * "iso-8859-n" is handled by enc_canonize() directly.
- */
+// Canonical encoding names and their properties.
+// "iso-8859-n" is handled by enc_canonize() directly.
static struct
{ const char *name; int prop; int codepage; }
enc_canon_table[] =
@@ -269,9 +267,7 @@ enc_canon_table[] =
#define IDX_COUNT 59
};
-/*
- * Aliases for encoding names.
- */
+// Aliases for encoding names.
static struct
{ const char *name; int canon; }
enc_alias_table[] =
@@ -342,29 +338,25 @@ enc_alias_table[] =
{ NULL, 0 }
};
-/*
- * Find encoding "name" in the list of canonical encoding names.
- * Returns -1 if not found.
- */
-static int enc_canon_search(const char_u *name)
+/// Find encoding "name" in the list of canonical encoding names.
+/// Returns -1 if not found.
+static int enc_canon_search(const char *name)
FUNC_ATTR_PURE
{
for (int i = 0; i < IDX_COUNT; i++) {
- if (STRCMP(name, enc_canon_table[i].name) == 0) {
+ if (strcmp(name, enc_canon_table[i].name) == 0) {
return i;
}
}
return -1;
}
-/*
- * Find canonical encoding "name" in the list and return its properties.
- * Returns 0 if not found.
- */
+// Find canonical encoding "name" in the list and return its properties.
+// Returns 0 if not found.
int enc_canon_props(const char_u *name)
FUNC_ATTR_PURE
{
- int i = enc_canon_search(name);
+ int i = enc_canon_search((char *)name);
if (i >= 0) {
return enc_canon_table[i].prop;
} else if (STRNCMP(name, "2byte-", 6) == 0) {
@@ -375,13 +367,11 @@ int enc_canon_props(const char_u *name)
return 0;
}
-/*
- * Return the size of the BOM for the current buffer:
- * 0 - no BOM
- * 2 - UCS-2 or UTF-16 BOM
- * 4 - UCS-4 BOM
- * 3 - UTF-8 BOM
- */
+// Return the size of the BOM for the current buffer:
+// 0 - no BOM
+// 2 - UCS-2 or UTF-16 BOM
+// 4 - UCS-4 BOM
+// 3 - UTF-8 BOM
int bomb_size(void)
FUNC_ATTR_PURE
{
@@ -389,7 +379,7 @@ int bomb_size(void)
if (curbuf->b_p_bomb && !curbuf->b_p_bin) {
if (*curbuf->b_p_fenc == NUL
- || STRCMP(curbuf->b_p_fenc, "utf-8") == 0) {
+ || strcmp(curbuf->b_p_fenc, "utf-8") == 0) {
n = 3;
} else if (STRNCMP(curbuf->b_p_fenc, "ucs-2", 5) == 0
|| STRNCMP(curbuf->b_p_fenc, "utf-16", 6) == 0) {
@@ -401,9 +391,7 @@ int bomb_size(void)
return n;
}
-/*
- * Remove all BOM from "s" by moving remaining text.
- */
+// Remove all BOM from "s" by moving remaining text.
void remove_bom(char_u *s)
{
char *p = (char *)s;
@@ -417,13 +405,11 @@ void remove_bom(char_u *s)
}
}
-/*
- * Get class of pointer:
- * 0 for blank or NUL
- * 1 for punctuation
- * 2 for an (ASCII) word character
- * >2 for other word characters
- */
+// Get class of pointer:
+// 0 for blank or NUL
+// 1 for punctuation
+// 2 for an (ASCII) word character
+// >2 for other word characters
int mb_get_class(const char_u *p)
FUNC_ATTR_PURE
{
@@ -445,9 +431,7 @@ int mb_get_class_tab(const char_u *p, const uint64_t *const chartab)
return utf_class_tab(utf_ptr2char((char *)p), chartab);
}
-/*
- * Return true if "c" is in "table".
- */
+// Return true if "c" is in "table".
static bool intable(const struct interval *table, size_t n_items, int c)
FUNC_ATTR_PURE
{
@@ -587,7 +571,7 @@ size_t mb_string2cells_len(const char *str, size_t size)
size_t clen = 0;
for (const char_u *p = (char_u *)str; *p != NUL && p < (char_u *)str + size;
- p += utfc_ptr2len_len(p, (int)size + (int)(p - (char_u *)str))) {
+ p += utfc_ptr2len_len((char *)p, (int)size + (int)(p - (char_u *)str))) {
clen += (size_t)utf_ptr2cells((char *)p);
}
@@ -646,22 +630,20 @@ int utf_ptr2char(const char *const p_in)
return p[0];
}
-/*
- * Convert a UTF-8 byte sequence to a wide character.
- * String is assumed to be terminated by NUL or after "n" bytes, whichever
- * comes first.
- * The function is safe in the sense that it never accesses memory beyond the
- * first "n" bytes of "s".
- *
- * On success, returns decoded codepoint, advances "s" to the beginning of
- * next character and decreases "n" accordingly.
- *
- * If end of string was reached, returns 0 and, if "n" > 0, advances "s" past
- * NUL byte.
- *
- * If byte sequence is illegal or incomplete, returns -1 and does not advance
- * "s".
- */
+// Convert a UTF-8 byte sequence to a wide character.
+// String is assumed to be terminated by NUL or after "n" bytes, whichever
+// comes first.
+// The function is safe in the sense that it never accesses memory beyond the
+// first "n" bytes of "s".
+//
+// On success, returns decoded codepoint, advances "s" to the beginning of
+// next character and decreases "n" accordingly.
+//
+// If end of string was reached, returns 0 and, if "n" > 0, advances "s" past
+// NUL byte.
+//
+// If byte sequence is illegal or incomplete, returns -1 and does not advance
+// "s".
static int utf_safe_read_char_adv(const char_u **s, size_t *n)
{
int c;
@@ -701,10 +683,8 @@ static int utf_safe_read_char_adv(const char_u **s, size_t *n)
return -1;
}
-/*
- * Get character at **pp and advance *pp to the next character.
- * Note: composing characters are skipped!
- */
+// Get character at **pp and advance *pp to the next character.
+// Note: composing characters are skipped!
int mb_ptr2char_adv(const char_u **const pp)
{
int c;
@@ -714,10 +694,8 @@ int mb_ptr2char_adv(const char_u **const pp)
return c;
}
-/*
- * Get character at **pp and advance *pp to the next character.
- * Note: composing characters are returned as separate characters.
- */
+// Get character at **pp and advance *pp to the next character.
+// Note: composing characters are returned as separate characters.
int mb_cptr2char_adv(const char_u **pp)
{
int c;
@@ -727,12 +705,10 @@ int mb_cptr2char_adv(const char_u **pp)
return c;
}
-/*
- * Check if the character pointed to by "p2" is a composing character when it
- * comes after "p1". For Arabic sometimes "ab" is replaced with "c", which
- * behaves like a composing character.
- */
-bool utf_composinglike(const char_u *p1, const char_u *p2)
+/// Check if the character pointed to by "p2" is a composing character when it
+/// comes after "p1". For Arabic sometimes "ab" is replaced with "c", which
+/// behaves like a composing character.
+bool utf_composinglike(const char *p1, const char *p2)
{
int c2;
@@ -765,7 +741,7 @@ int utfc_ptr2char(const char *p_in, int *pcc)
// Only accept a composing char when the first char isn't illegal.
if ((len > 1 || *p < 0x80)
&& p[len] >= 0x80
- && utf_composinglike(p, p + len)) {
+ && utf_composinglike((char *)p, (char *)p + len)) {
int cc = utf_ptr2char((char *)p + len);
for (;;) {
pcc[i++] = cc;
@@ -786,12 +762,10 @@ int utfc_ptr2char(const char *p_in, int *pcc)
return c;
}
-/*
- * Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO
- * composing characters. Use no more than p[maxlen].
- *
- * @param [out] pcc: composing chars, last one is 0
- */
+// Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO
+// composing characters. Use no more than p[maxlen].
+//
+// @param [out] pcc: composing chars, last one is 0
int utfc_ptr2char_len(const char_u *p, int *pcc, int maxlen)
{
assert(maxlen > 0);
@@ -809,7 +783,7 @@ int utfc_ptr2char_len(const char_u *p, int *pcc, int maxlen)
int len_cc = utf_ptr2len_len(p + len, maxlen - len);
safe = len_cc > 1 && len_cc <= maxlen - len;
if (!safe || (pcc[i] = utf_ptr2char((char *)p + len)) < 0x80
- || !(i == 0 ? utf_composinglike(p, p + len) : utf_iscomposing(pcc[i]))) {
+ || !(i == 0 ? utf_composinglike((char *)p, (char *)p + len) : utf_iscomposing(pcc[i]))) {
break;
}
len += len_cc;
@@ -847,24 +821,20 @@ int utf_ptr2len(const char *const p_in)
return len;
}
-/*
- * Return length of UTF-8 character, obtained from the first byte.
- * "b" must be between 0 and 255!
- * Returns 1 for an invalid first byte value.
- */
+// Return length of UTF-8 character, obtained from the first byte.
+// "b" must be between 0 and 255!
+// Returns 1 for an invalid first byte value.
int utf_byte2len(int b)
{
return utf8len_tab[b];
}
-/*
- * Get the length of UTF-8 byte sequence "p[size]". Does not include any
- * following composing characters.
- * Returns 1 for "".
- * Returns 1 for an illegal byte sequence (also in incomplete byte seq.).
- * Returns number > "size" for an incomplete byte sequence.
- * Never returns zero.
- */
+// Get the length of UTF-8 byte sequence "p[size]". Does not include any
+// following composing characters.
+// Returns 1 for "".
+// Returns 1 for an illegal byte sequence (also in incomplete byte seq.).
+// Returns number > "size" for an incomplete byte sequence.
+// Never returns zero.
int utf_ptr2len_len(const char_u *p, int size)
{
int len;
@@ -916,7 +886,7 @@ int utfc_ptr2len(const char *const p_in)
// skip all of them (otherwise the cursor would get stuck).
int prevlen = 0;
for (;;) {
- if (p[len] < 0x80 || !utf_composinglike(p + prevlen, p + len)) {
+ if (p[len] < 0x80 || !utf_composinglike((char *)p + prevlen, (char *)p + len)) {
return len;
}
@@ -926,13 +896,11 @@ int utfc_ptr2len(const char *const p_in)
}
}
-/*
- * Return the number of bytes the UTF-8 encoding of the character at "p[size]"
- * takes. This includes following composing characters.
- * Returns 0 for an empty string.
- * Returns 1 for an illegal char or an incomplete byte sequence.
- */
-int utfc_ptr2len_len(const char_u *p, int size)
+/// Return the number of bytes the UTF-8 encoding of the character at "p[size]"
+/// takes. This includes following composing characters.
+/// Returns 0 for an empty string.
+/// Returns 1 for an illegal char or an incomplete byte sequence.
+int utfc_ptr2len_len(const char *p, int size)
{
int len;
int prevlen;
@@ -940,35 +908,31 @@ int utfc_ptr2len_len(const char_u *p, int size)
if (size < 1 || *p == NUL) {
return 0;
}
- if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) { // be quick for ASCII
+ if ((uint8_t)p[0] < 0x80 && (size == 1 || (uint8_t)p[1] < 0x80)) { // be quick for ASCII
return 1;
}
// Skip over first UTF-8 char, stopping at a NUL byte.
- len = utf_ptr2len_len(p, size);
+ len = utf_ptr2len_len((char_u *)p, size);
// Check for illegal byte and incomplete byte sequence.
- if ((len == 1 && p[0] >= 0x80) || len > size) {
+ if ((len == 1 && (uint8_t)p[0] >= 0x80) || len > size) {
return 1;
}
- /*
- * Check for composing characters. We can handle only the first six, but
- * skip all of them (otherwise the cursor would get stuck).
- */
+ // Check for composing characters. We can handle only the first six, but
+ // skip all of them (otherwise the cursor would get stuck).
prevlen = 0;
while (len < size) {
int len_next_char;
- if (p[len] < 0x80) {
+ if ((uint8_t)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);
+ // Next character length should not go beyond size to ensure that
+ // utf_composinglike(...) does not read beyond size.
+ len_next_char = utf_ptr2len_len((char_u *)p + len, size - len);
if (len_next_char > size - len) {
break;
}
@@ -1046,20 +1010,16 @@ int utf_char2bytes(const int c, char *const buf)
}
}
-/*
- * Return true if "c" is a composing UTF-8 character. This means it will be
- * drawn on top of the preceding character.
- * Based on code from Markus Kuhn.
- */
+// Return true if "c" is a composing UTF-8 character. This means it will be
+// drawn on top of the preceding character.
+// Based on code from Markus Kuhn.
bool utf_iscomposing(int c)
{
return intable(combining, ARRAY_SIZE(combining), c);
}
-/*
- * Return true for characters that can be displayed in a normal way.
- * Only for characters of 0x100 and above!
- */
+// Return true for characters that can be displayed in a normal way.
+// Only for characters of 0x100 and above!
bool utf_printable(int c)
{
// Sorted list of non-overlapping intervals.
@@ -1074,12 +1034,10 @@ bool utf_printable(int c)
return !intable(nonprint, ARRAY_SIZE(nonprint), c);
}
-/*
- * Get class of a Unicode character.
- * 0: white space
- * 1: punctuation
- * 2 or bigger: some class of word character.
- */
+// Get class of a Unicode character.
+// 0: white space
+// 1: punctuation
+// 2 or bigger: some class of word character.
int utf_class(const int c)
{
return utf_class_tab(c, curbuf->b_chartab);
@@ -1208,11 +1166,9 @@ bool utf_ambiguous_width(int c)
|| intable(emoji_all, ARRAY_SIZE(emoji_all), c));
}
-/*
- * Generic conversion function for case operations.
- * Return the converted equivalent of "a", which is a UCS-4 character. Use
- * the given conversion "table". Uses binary search on "table".
- */
+// Generic conversion function for case operations.
+// Return the converted equivalent of "a", which is a UCS-4 character. Use
+// the given conversion "table". Uses binary search on "table".
static int utf_convert(int a, const convertStruct *const table, size_t n_items)
{
size_t start, mid, end; // indices into table
@@ -1238,10 +1194,8 @@ static int utf_convert(int a, const convertStruct *const table, size_t n_items)
}
}
-/*
- * Return the folded-case equivalent of "a", which is a UCS-4 character. Uses
- * simple case folding.
- */
+// Return the folded-case equivalent of "a", which is a UCS-4 character. Uses
+// simple case folding.
int utf_fold(int a)
{
if (a < 0x80) {
@@ -1570,10 +1524,8 @@ int mb_stricmp(const char *s1, const char *s2)
return mb_strnicmp(s1, s2, MAXCOL);
}
-/*
- * "g8": show bytes of the UTF-8 char under the cursor. Doesn't matter what
- * 'encoding' has been set to.
- */
+// "g8": show bytes of the UTF-8 char under the cursor. Doesn't matter what
+// 'encoding' has been set to.
void show_utf8(void)
{
int len;
@@ -1584,7 +1536,7 @@ void show_utf8(void)
// Get the byte length of the char under the cursor, including composing
// characters.
- line = get_cursor_pos_ptr();
+ line = (char_u *)get_cursor_pos_ptr();
len = utfc_ptr2len((char *)line);
if (len == 0) {
msg("NUL");
@@ -1920,9 +1872,7 @@ int utf_cp_head_off(const char_u *base, const char_u *p)
return i;
}
-/*
- * Find the next illegal byte sequence.
- */
+// Find the next illegal byte sequence.
void utf_find_illegal(void)
{
pos_T pos = curwin->w_cursor;
@@ -1941,7 +1891,7 @@ void utf_find_illegal(void)
curwin->w_cursor.coladd = 0;
for (;;) {
- p = get_cursor_pos_ptr();
+ p = (char_u *)get_cursor_pos_ptr();
if (vimconv.vc_type != CONV_NONE) {
xfree(tofree);
tofree = (char_u *)string_convert(&vimconv, (char *)p, NULL);
@@ -1958,12 +1908,12 @@ void utf_find_illegal(void)
if (*p >= 0x80 && (len == 1
|| utf_char2len(utf_ptr2char((char *)p)) != len)) {
if (vimconv.vc_type == CONV_NONE) {
- curwin->w_cursor.col += (colnr_T)(p - get_cursor_pos_ptr());
+ curwin->w_cursor.col += (colnr_T)(p - (char_u *)get_cursor_pos_ptr());
} else {
int l;
len = (int)(p - tofree);
- for (p = get_cursor_pos_ptr(); *p != NUL && len-- > 0; p += l) {
+ for (p = (char_u *)get_cursor_pos_ptr(); *p != NUL && len-- > 0; p += l) {
l = utf_ptr2len((char *)p);
curwin->w_cursor.col += l;
}
@@ -2012,10 +1962,8 @@ bool utf_valid_string(const char_u *s, const char_u *end)
return true;
}
-/*
- * If the cursor moves on an trail byte, set the cursor on the lead byte.
- * Thus it moves left if necessary.
- */
+// If the cursor moves on an trail byte, set the cursor on the lead byte.
+// Thus it moves left if necessary.
void mb_adjust_cursor(void)
{
mark_mb_adjustpos(curbuf, &curwin->w_cursor);
@@ -2032,7 +1980,7 @@ void mb_check_adjust_col(void *win_)
// Column 0 is always valid.
if (oldcol != 0) {
- char *p = (char *)ml_get_buf(win->w_buffer, win->w_cursor.lnum, false);
+ char *p = ml_get_buf(win->w_buffer, win->w_cursor.lnum, false);
colnr_T len = (colnr_T)STRLEN(p);
// Empty line or invalid column?
@@ -2166,27 +2114,27 @@ char *enc_skip(char *p)
char *enc_canonize(char *enc)
FUNC_ATTR_NONNULL_RET
{
- char_u *p, *s;
- if (STRCMP(enc, "default") == 0) {
+ char *p, *s;
+ if (strcmp(enc, "default") == 0) {
// Use the default encoding as found by set_init_1().
- return (char *)vim_strsave(fenc_default);
+ return xstrdup(fenc_default);
}
// copy "enc" to allocated memory, with room for two '-'
- char_u *r = xmalloc(STRLEN(enc) + 3);
+ char *r = xmalloc(STRLEN(enc) + 3);
// Make it all lower case and replace '_' with '-'.
p = r;
- for (s = (char_u *)enc; *s != NUL; s++) {
+ for (s = enc; *s != NUL; s++) {
if (*s == '_') {
*p++ = '-';
} else {
- *p++ = (char_u)TOLOWER_ASC(*s);
+ *p++ = (char)TOLOWER_ASC(*s);
}
}
*p = NUL;
// Skip "2byte-" and "8bit-".
- p = (char_u *)enc_skip((char *)r);
+ p = enc_skip(r);
// Change "microsoft-cp" to "cp". Used in some spell files.
if (STRNCMP(p, "microsoft-cp", 12) == 0) {
@@ -2219,19 +2167,19 @@ char *enc_canonize(char *enc)
} else if ((i = enc_alias_search(p)) >= 0) {
// alias recognized, get canonical name
xfree(r);
- r = vim_strsave((char_u *)enc_canon_table[i].name);
+ r = xstrdup(enc_canon_table[i].name);
}
- return (char *)r;
+ return r;
}
/// Search for an encoding alias of "name".
/// Returns -1 when not found.
-static int enc_alias_search(const char_u *name)
+static int enc_alias_search(const char *name)
{
int i;
for (i = 0; enc_alias_table[i].name != NULL; i++) {
- if (STRCMP(name, enc_alias_table[i].name) == 0) {
+ if (strcmp(name, enc_alias_table[i].name) == 0) {
return enc_alias_table[i].canon;
}
}
@@ -2242,10 +2190,8 @@ static int enc_alias_search(const char_u *name)
# include <langinfo.h>
#endif
-/*
- * Get the canonicalized encoding of the current locale.
- * Returns an allocated string when successful, NULL when not.
- */
+// Get the canonicalized encoding of the current locale.
+// Returns an allocated string when successful, NULL when not.
char_u *enc_locale(void)
{
int i;
@@ -2311,12 +2257,10 @@ enc_locale_copy_enc:
#if defined(HAVE_ICONV)
-/*
- * Call iconv_open() with a check if iconv() works properly (there are broken
- * versions).
- * Returns (void *)-1 if failed.
- * (should return iconv_t, but that causes problems with prototypes).
- */
+// Call iconv_open() with a check if iconv() works properly (there are broken
+// versions).
+// Returns (void *)-1 if failed.
+// (should return iconv_t, but that causes problems with prototypes).
void *my_iconv_open(char_u *to, char_u *from)
{
iconv_t fd;
@@ -2332,13 +2276,11 @@ void *my_iconv_open(char_u *to, char_u *from)
fd = iconv_open(enc_skip((char *)to), enc_skip((char *)from));
if (fd != (iconv_t)-1 && iconv_working == kUnknown) {
- /*
- * Do a dummy iconv() call to check if it actually works. There is a
- * version of iconv() on Linux that is broken. We can't ignore it,
- * because it's wide-spread. The symptoms are that after outputting
- * the initial shift state the "to" pointer is NULL and conversion
- * stops for no apparent reason after about 8160 characters.
- */
+ // Do a dummy iconv() call to check if it actually works. There is a
+ // version of iconv() on Linux that is broken. We can't ignore it,
+ // because it's wide-spread. The symptoms are that after outputting
+ // the initial shift state the "to" pointer is NULL and conversion
+ // stops for no apparent reason after about 8160 characters.
p = (char *)tobuf;
tolen = ICONV_TESTLEN;
(void)iconv(fd, NULL, NULL, &p, &tolen);
@@ -2354,13 +2296,11 @@ void *my_iconv_open(char_u *to, char_u *from)
return (void *)fd;
}
-/*
- * Convert the string "str[slen]" with iconv().
- * If "unconvlenp" is not NULL handle the string ending in an incomplete
- * sequence and set "*unconvlenp" to the length of it.
- * Returns the converted string in allocated memory. NULL for an error.
- * If resultlenp is not NULL, sets it to the result length in bytes.
- */
+// Convert the string "str[slen]" with iconv().
+// If "unconvlenp" is not NULL handle the string ending in an incomplete
+// sequence and set "*unconvlenp" to the length of it.
+// Returns the converted string in allocated memory. NULL for an error.
+// If resultlenp is not NULL, sets it to the result length in bytes.
static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen,
size_t *unconvlenp, size_t *resultlenp)
{
@@ -2420,7 +2360,7 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen
if (utf_ptr2cells(from) > 1) {
*to++ = '?';
}
- l = utfc_ptr2len_len((const char_u *)from, (int)fromlen);
+ l = utfc_ptr2len_len(from, (int)fromlen);
from += l;
fromlen -= (size_t)l;
} else if (ICONV_ERRNO != ICONV_E2BIG) {
@@ -2450,12 +2390,12 @@ static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen
/// @return FAIL when conversion is not supported, OK otherwise.
int convert_setup(vimconv_T *vcp, char *from, char *to)
{
- return convert_setup_ext(vcp, (char_u *)from, true, (char_u *)to, true);
+ return convert_setup_ext(vcp, from, true, to, true);
}
/// 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,
+int convert_setup_ext(vimconv_T *vcp, char *from, bool from_unicode_is_utf8, char *to,
bool to_unicode_is_utf8)
{
int from_prop;
@@ -2473,12 +2413,12 @@ int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, c
// 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);
+ from_prop = enc_canon_props((char_u *)from);
+ to_prop = enc_canon_props((char_u *)to);
if (from_unicode_is_utf8) {
from_is_utf8 = from_prop & ENC_UNICODE;
} else {
@@ -2508,8 +2448,8 @@ int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, c
#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" : (char_u *)to,
+ from_is_utf8 ? (char_u *)"utf-8" : (char_u *)from);
if (vcp->vc_fd != (iconv_t)-1) {
vcp->vc_type = CONV_ICONV;
vcp->vc_factor = 4; // could be longer too...
@@ -2533,11 +2473,9 @@ char *string_convert(const vimconv_T *const vcp, char *ptr, size_t *lenp)
return (char *)string_convert_ext(vcp, (char_u *)ptr, lenp, NULL);
}
-/*
- * Like string_convert(), but when "unconvlenp" is not NULL and there are is
- * an incomplete sequence at the end it is not converted and "*unconvlenp" is
- * set to the number of remaining bytes.
- */
+// Like string_convert(), but when "unconvlenp" is not NULL and there are is
+// an incomplete sequence at the end it is not converted and "*unconvlenp" is
+// set to the number of remaining bytes.
char_u *string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp,
size_t *unconvlenp)
{
@@ -2553,7 +2491,7 @@ char_u *string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp
len = *lenp;
}
if (len == 0) {
- return vim_strsave((char_u *)"");
+ return (char_u *)xstrdup("");
}
switch (vcp->vc_type) {
@@ -2855,7 +2793,7 @@ void f_setcellwidths(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
void f_charclass(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
{
- if (tv_check_for_string(&argvars[0]) == FAIL
+ if (tv_check_for_string_arg(argvars, 0) == FAIL
|| argvars[0].vval.v_string == NULL) {
return;
}
diff --git a/src/nvim/mbyte.h b/src/nvim/mbyte.h
index 2a9afcbd03..b499f33cc6 100644
--- a/src/nvim/mbyte.h
+++ b/src/nvim/mbyte.h
@@ -11,12 +11,10 @@
#include "nvim/os/os_defs.h" // For indirect
#include "nvim/types.h" // for char_u
-/*
- * Return byte length of character that starts with byte "b".
- * Returns 1 for a single-byte character.
- * MB_BYTE2LEN_CHECK() can be used to count a special key as one byte.
- * Don't call MB_BYTE2LEN(b) with b < 0 or b > 255!
- */
+// Return byte length of character that starts with byte "b".
+// Returns 1 for a single-byte character.
+// MB_BYTE2LEN_CHECK() can be used to count a special key as one byte.
+// Don't call MB_BYTE2LEN(b) with b < 0 or b > 255!
#define MB_BYTE2LEN(b) utf8len_tab[b]
#define MB_BYTE2LEN_CHECK(b) (((b) < 0 || (b) > 255) ? 1 : utf8len_tab[b])
diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c
index 9446aaee4f..bb9be0766e 100644
--- a/src/nvim/memfile.c
+++ b/src/nvim/memfile.c
@@ -170,7 +170,7 @@ void mf_close(memfile_T *mfp, bool del_file)
emsg(_(e_swapclose));
}
if (del_file && mfp->mf_fname != NULL) {
- os_remove((char *)mfp->mf_fname);
+ os_remove(mfp->mf_fname);
}
// free entries in used list
@@ -210,7 +210,7 @@ void mf_close_file(buf_T *buf, bool getlines)
mfp->mf_fd = -1;
if (mfp->mf_fname != NULL) {
- os_remove((char *)mfp->mf_fname); // delete the swap file
+ os_remove(mfp->mf_fname); // delete the swap file
mf_free_fnames(mfp);
}
}
@@ -751,8 +751,8 @@ void mf_free_fnames(memfile_T *mfp)
/// name so we must work out the full path name.
void mf_set_fnames(memfile_T *mfp, char *fname)
{
- mfp->mf_fname = (char_u *)fname;
- mfp->mf_ffname = (char_u *)FullName_save((char *)mfp->mf_fname, false);
+ mfp->mf_fname = fname;
+ mfp->mf_ffname = (char_u *)FullName_save(mfp->mf_fname, false);
}
/// Make name of memfile's swapfile a full path.
@@ -762,7 +762,7 @@ void mf_fullname(memfile_T *mfp)
{
if (mfp != NULL && mfp->mf_fname != NULL && mfp->mf_ffname != NULL) {
xfree(mfp->mf_fname);
- mfp->mf_fname = mfp->mf_ffname;
+ mfp->mf_fname = (char *)mfp->mf_ffname;
mfp->mf_ffname = NULL;
}
}
@@ -789,7 +789,7 @@ static bool mf_do_open(memfile_T *mfp, char *fname, int flags)
/// exist yet. If there is a symbolic link, this is most likely an attack.
FileInfo file_info;
if ((flags & O_CREAT)
- && os_fileinfo_link((char *)mfp->mf_fname, &file_info)) {
+ && os_fileinfo_link(mfp->mf_fname, &file_info)) {
mfp->mf_fd = -1;
emsg(_("E300: Swap file already exists (symlink attack?)"));
} else {
diff --git a/src/nvim/memfile_defs.h b/src/nvim/memfile_defs.h
index 537d3e5f65..d1e8fd0fb4 100644
--- a/src/nvim/memfile_defs.h
+++ b/src/nvim/memfile_defs.h
@@ -88,7 +88,7 @@ typedef struct mf_blocknr_trans_item {
/// A memory file.
typedef struct memfile {
- char_u *mf_fname; /// name of the file
+ char *mf_fname; /// name of the file
char_u *mf_ffname; /// idem, full path
int mf_fd; /// file descriptor
bhdr_T *mf_free_first; /// first block header in free list
diff --git a/src/nvim/memline.c b/src/nvim/memline.c
index a30a98d6e9..9d1ad5903d 100644
--- a/src/nvim/memline.c
+++ b/src/nvim/memline.c
@@ -5,36 +5,34 @@
// #define CHECK(c, s) do { if (c) emsg(s); } while (0)
#define CHECK(c, s) do {} while (0)
-/*
- * memline.c: Contains the functions for appending, deleting and changing the
- * text lines. The memfile functions are used to store the information in
- * blocks of memory, backed up by a file. The structure of the information is
- * a tree. The root of the tree is a pointer block. The leaves of the tree
- * are data blocks. In between may be several layers of pointer blocks,
- * forming branches.
- *
- * Three types of blocks are used:
- * - Block nr 0 contains information for recovery
- * - Pointer blocks contain list of pointers to other blocks.
- * - Data blocks contain the actual text.
- *
- * Block nr 0 contains the block0 structure (see below).
- *
- * Block nr 1 is the first pointer block. It is the root of the tree.
- * Other pointer blocks are branches.
- *
- * If a line is too big to fit in a single page, the block containing that
- * line is made big enough to hold the line. It may span several pages.
- * Otherwise all blocks are one page.
- *
- * A data block that was filled when starting to edit a file and was not
- * changed since then, can have a negative block number. This means that it
- * has not yet been assigned a place in the file. When recovering, the lines
- * in this data block can be read from the original file. When the block is
- * changed (lines appended/deleted/changed) or when it is flushed it gets a
- * positive number. Use mf_trans_del() to get the new number, before calling
- * mf_get().
- */
+// memline.c: Contains the functions for appending, deleting and changing the
+// text lines. The memfile functions are used to store the information in
+// blocks of memory, backed up by a file. The structure of the information is
+// a tree. The root of the tree is a pointer block. The leaves of the tree
+// are data blocks. In between may be several layers of pointer blocks,
+// forming branches.
+//
+// Three types of blocks are used:
+// - Block nr 0 contains information for recovery
+// - Pointer blocks contain list of pointers to other blocks.
+// - Data blocks contain the actual text.
+//
+// Block nr 0 contains the block0 structure (see below).
+//
+// Block nr 1 is the first pointer block. It is the root of the tree.
+// Other pointer blocks are branches.
+//
+// If a line is too big to fit in a single page, the block containing that
+// line is made big enough to hold the line. It may span several pages.
+// Otherwise all blocks are one page.
+//
+// A data block that was filled when starting to edit a file and was not
+// changed since then, can have a negative block number. This means that it
+// has not yet been assigned a place in the file. When recovering, the lines
+// in this data block can be read from the original file. When the block is
+// changed (lines appended/deleted/changed) or when it is flushed it gets a
+// positive number. Use mf_trans_del() to get the new number, before calling
+// mf_get().
#include <assert.h>
#include <errno.h>
@@ -90,9 +88,7 @@ typedef struct pointer_entry PTR_EN; // block/line-count pair
#define BLOCK0_ID0 'b' // block 0 id 0
#define BLOCK0_ID1 '0' // block 0 id 1
-/*
- * pointer to a block, used in a pointer block
- */
+// pointer to a block, used in a pointer block
struct pointer_entry {
blocknr_T pe_bnum; // block number
linenr_T pe_line_count; // number of lines in this branch
@@ -100,9 +96,7 @@ struct pointer_entry {
int pe_page_count; // number of pages in block pe_bnum
};
-/*
- * A pointer block contains a list of branches in the tree.
- */
+// A pointer block contains a list of branches in the tree.
struct pointer_block {
uint16_t pb_id; // ID for pointer block: PTR_ID
uint16_t pb_count; // number of pointers in this block
@@ -111,13 +105,11 @@ struct pointer_block {
// followed by empty space until end of page
};
-/*
- * A data block is a leaf in the tree.
- *
- * The text of the lines is at the end of the block. The text of the first line
- * in the block is put at the end, the text of the second line in front of it,
- * etc. Thus the order of the lines is the opposite of the line number.
- */
+// A data block is a leaf in the tree.
+//
+// The text of the lines is at the end of the block. The text of the first line
+// in the block is put at the end, the text of the second line in front of it,
+// etc. Thus the order of the lines is the opposite of the line number.
struct data_block {
uint16_t db_id; // ID for data block: DATA_ID
unsigned db_free; // free space available
@@ -130,14 +122,12 @@ struct data_block {
// end of page
};
-/*
- * The low bits of db_index hold the actual index. The topmost bit is
- * used for the global command to be able to mark a line.
- * This method is not clean, but otherwise there would be at least one extra
- * byte used for each line.
- * The mark has to be in this place to keep it with the correct line when other
- * lines are inserted or deleted.
- */
+// The low bits of db_index hold the actual index. The topmost bit is
+// used for the global command to be able to mark a line.
+// This method is not clean, but otherwise there would be at least one extra
+// byte used for each line.
+// The mark has to be in this place to keep it with the correct line when other
+// lines are inserted or deleted.
#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
#define DB_INDEX_MASK (~DB_MARKED)
@@ -149,28 +139,24 @@ struct data_block {
#define B0_FNAME_SIZE_CRYPT 890 // 10 bytes used for other things
#define B0_UNAME_SIZE 40
#define B0_HNAME_SIZE 40
-/*
- * Restrict the numbers to 32 bits, otherwise most compilers will complain.
- * This won't detect a 64 bit machine that only swaps a byte in the top 32
- * bits, but that is crazy anyway.
- */
+// Restrict the numbers to 32 bits, otherwise most compilers will complain.
+// This won't detect a 64 bit machine that only swaps a byte in the top 32
+// bits, but that is crazy anyway.
#define B0_MAGIC_LONG 0x30313233L
#define B0_MAGIC_INT 0x20212223L
#define B0_MAGIC_SHORT 0x10111213L
#define B0_MAGIC_CHAR 0x55
-/*
- * Block zero holds all info about the swap file.
- *
- * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
- * swap files unusable!
- *
- * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
- *
- * This block is built up of single bytes, to make it portable across
- * different machines. b0_magic_* is used to check the byte order and size of
- * variables, because the rest of the swap file is not portable.
- */
+// Block zero holds all info about the swap file.
+//
+// NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
+// swap files unusable!
+//
+// If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
+//
+// This block is built up of single bytes, to make it portable across
+// different machines. b0_magic_* is used to check the byte order and size of
+// variables, because the rest of the swap file is not portable.
struct block0 {
char_u b0_id[2]; ///< ID for block 0: BLOCK0_ID0 and BLOCK0_ID1.
char_u b0_version[10]; // Vim version string
@@ -187,18 +173,14 @@ struct block0 {
char_u b0_magic_char; // check for last char
};
-/*
- * Note: b0_dirty and b0_flags are put at the end of the file name. For very
- * long file names in older versions of Vim they are invalid.
- * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
- * when there is room, for very long file names it's omitted.
- */
+// Note: b0_dirty and b0_flags are put at the end of the file name. For very
+// long file names in older versions of Vim they are invalid.
+// The 'fileencoding' comes before b0_flags, with a NUL in front. But only
+// when there is room, for very long file names it's omitted.
#define B0_DIRTY 0x55
#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1]
-/*
- * The b0_flags field is new in Vim 7.0.
- */
+// The b0_flags field is new in Vim 7.0.
#define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2]
// The lowest two bits contain the fileformat. Zero means it's not set
@@ -216,17 +198,13 @@ struct block0 {
#define STACK_INCR 5 // nr of entries added to ml_stack at a time
-/*
- * The line number where the first mark may be is remembered.
- * If it is 0 there are no marks at all.
- * (always used for the current buffer only, no buffer change possible while
- * executing a global command).
- */
+// The line number where the first mark may be is remembered.
+// If it is 0 there are no marks at all.
+// (always used for the current buffer only, no buffer change possible while
+// executing a global command).
static linenr_T lowest_marked = 0;
-/*
- * arguments for ml_find_line()
- */
+// arguments for ml_find_line()
#define ML_DELETE 0x11 // delete line
#define ML_INSERT 0x12 // insert line
#define ML_FIND 0x13 // just find the line
@@ -253,9 +231,7 @@ int ml_open(buf_T *buf)
PTR_BL *pp;
DATA_BL *dp;
- /*
- * init fields in memline struct
- */
+ // init fields in memline struct
buf->b_ml.ml_stack_size = 0; // no stack yet
buf->b_ml.ml_stack = NULL; // no stack yet
buf->b_ml.ml_stack_top = 0; // nothing in the stack
@@ -269,9 +245,7 @@ int ml_open(buf_T *buf)
buf->b_p_swf = false;
}
- /*
- * When 'updatecount' is non-zero swap file may be opened later.
- */
+ // When 'updatecount' is non-zero swap file may be opened later.
if (!buf->terminal && p_uc && buf->b_p_swf) {
buf->b_may_swap = true;
} else {
@@ -289,9 +263,7 @@ int ml_open(buf_T *buf)
buf->b_ml.ml_line_count = 1;
curwin->w_nrwidth_line_count = 0;
- /*
- * fill block0 struct and write page 0
- */
+ // fill block0 struct and write page 0
hp = mf_new(mfp, false, 1);
if (hp->bh_bnum != 0) {
iemsg(_("E298: Didn't get block nr 0?"));
@@ -319,21 +291,17 @@ int ml_open(buf_T *buf)
long_to_char(os_get_pid(), b0p->b0_pid);
}
- /*
- * Always sync block number 0 to disk, so we can check the file name in
- * the swap file in findswapname(). Don't do this for a help files or
- * a spell buffer though.
- * Only works when there's a swapfile, otherwise it's done when the file
- * is created.
- */
+ // Always sync block number 0 to disk, so we can check the file name in
+ // the swap file in findswapname(). Don't do this for a help files or
+ // a spell buffer though.
+ // Only works when there's a swapfile, otherwise it's done when the file
+ // is created.
mf_put(mfp, hp, true, false);
if (!buf->b_help && !B_SPELL(buf)) {
(void)mf_sync(mfp, 0);
}
- /*
- * Fill in root pointer block and write page 1.
- */
+ // Fill in root pointer block and write page 1.
if ((hp = ml_new_ptr(mfp)) == NULL) {
goto error;
}
@@ -349,9 +317,7 @@ int ml_open(buf_T *buf)
pp->pb_pointer[0].pe_line_count = 1; // line count after insertion
mf_put(mfp, hp, true, false);
- /*
- * Allocate first data block and create an empty line 1.
- */
+ // Allocate first data block and create an empty line 1.
hp = ml_new_data(mfp, false, 1);
if (hp->bh_bnum != 2) {
iemsg(_("E298: Didn't get block nr 2?"));
@@ -383,15 +349,13 @@ void ml_setname(buf_T *buf)
{
bool success = false;
memfile_T *mfp;
- char_u *fname;
+ char *fname;
char *dirp;
mfp = buf->b_ml.ml_mfp;
if (mfp->mf_fd < 0) { // there is no swap file yet
- /*
- * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
- * For help files we will make a swap file now.
- */
+ // When 'updatecount' is 0 and 'noswapfile' there is no swap file.
+ // For help files we will make a swap file now.
if (p_uc != 0 && (cmdmod.cmod_flags & CMOD_NOSWAPFILE) == 0) {
ml_open_file(buf); // create a swap file
}
@@ -405,7 +369,7 @@ void ml_setname(buf_T *buf)
if (*dirp == NUL) { // tried all directories, fail
break;
}
- fname = (char_u *)findswapname(buf, &dirp, (char *)mfp->mf_fname, &found_existing_dir);
+ fname = findswapname(buf, &dirp, mfp->mf_fname, &found_existing_dir);
// alloc's fname
if (dirp == NULL) { // out of memory
break;
@@ -415,7 +379,7 @@ void ml_setname(buf_T *buf)
}
// if the file name is the same we don't have to do anything
- if (FNAMECMP(fname, mfp->mf_fname) == 0) {
+ if (path_fnamecmp(fname, mfp->mf_fname) == 0) {
xfree(fname);
success = true;
break;
@@ -430,7 +394,7 @@ void ml_setname(buf_T *buf)
if (vim_rename(mfp->mf_fname, fname) == 0) {
success = true;
mf_free_fnames(mfp);
- mf_set_fnames(mfp, (char *)fname);
+ mf_set_fnames(mfp, fname);
ml_upd_block0(buf, UB_SAME_DIR);
break;
}
@@ -438,7 +402,7 @@ void ml_setname(buf_T *buf)
}
if (mfp->mf_fd == -1) { // need to (re)open the swap file
- mfp->mf_fd = os_open((char *)mfp->mf_fname, O_RDWR, 0);
+ mfp->mf_fd = os_open(mfp->mf_fname, O_RDWR, 0);
if (mfp->mf_fd < 0) {
// could not (re)open the swap file, what can we do????
emsg(_("E301: Oops, lost the swap file!!!"));
@@ -481,7 +445,7 @@ void ml_open_file(buf_T *buf)
// For a spell buffer use a temp file name.
if (buf->b_spell) {
- fname = vim_tempname();
+ fname = (char_u *)vim_tempname();
if (fname != NULL) {
(void)mf_open_file(mfp, (char *)fname); // consumes fname!
}
@@ -653,13 +617,11 @@ static void set_b0_fname(ZERO_BL *b0p, buf_T *buf)
} else {
char uname[B0_UNAME_SIZE];
- /*
- * For a file under the home directory of the current user, we try to
- * replace the home directory path with "~user". This helps when
- * editing the same file on different machines over a network.
- * First replace home dir path with "~/" with home_replace().
- * Then insert the user name to get "~user/".
- */
+ // For a file under the home directory of the current user, we try to
+ // replace the home directory path with "~user". This helps when
+ // editing the same file on different machines over a network.
+ // First replace home dir path with "~/" with home_replace().
+ // Then insert the user name to get "~user/".
home_replace(NULL, buf->b_ffname, (char *)b0p->b0_fname,
B0_FNAME_SIZE_CRYPT, true);
if (b0p->b0_fname[0] == '~') {
@@ -703,7 +665,7 @@ static void set_b0_fname(ZERO_BL *b0p, buf_T *buf)
/// not set.
static void set_b0_dir_flag(ZERO_BL *b0p, buf_T *buf)
{
- if (same_directory(buf->b_ml.ml_mfp->mf_fname, (char_u *)buf->b_ffname)) {
+ if (same_directory((char_u *)buf->b_ml.ml_mfp->mf_fname, (char_u *)buf->b_ffname)) {
b0p->b0_flags |= B0_SAME_DIR;
} else {
b0p->b0_flags &= (uint8_t) ~B0_SAME_DIR;
@@ -735,12 +697,12 @@ void ml_recover(bool checkext)
{
buf_T *buf = NULL;
memfile_T *mfp = NULL;
- char_u *fname;
- char_u *fname_used = NULL;
+ char *fname;
+ char *fname_used = NULL;
bhdr_T *hp = NULL;
ZERO_BL *b0p;
int b0_ff;
- char_u *b0_fenc = NULL;
+ char *b0_fenc = NULL;
PTR_BL *pp;
DATA_BL *dp;
infoptr_T *ip;
@@ -748,7 +710,7 @@ void ml_recover(bool checkext)
int len;
bool directly;
linenr_T lnum;
- char_u *p;
+ char *p;
int i;
long error;
bool cannot_open;
@@ -770,9 +732,9 @@ void ml_recover(bool checkext)
// If the file name ends in ".s[a-w][a-z]" we assume this is the swap file.
// Otherwise a search is done to find the swap file(s).
- fname = (char_u *)curbuf->b_fname;
+ fname = curbuf->b_fname;
if (fname == NULL) { // When there is no file name
- fname = (char_u *)"";
+ fname = "";
}
len = (int)STRLEN(fname);
if (checkext && len >= 4
@@ -780,12 +742,12 @@ void ml_recover(bool checkext)
&& vim_strchr("abcdefghijklmnopqrstuvw", TOLOWER_ASC(fname[len - 2])) != NULL
&& ASCII_ISALPHA(fname[len - 1])) {
directly = true;
- fname_used = vim_strsave(fname); // make a copy for mf_open()
+ fname_used = xstrdup(fname); // make a copy for mf_open()
} else {
directly = false;
// count the number of matching swap files
- len = recover_names(fname, false, 0, NULL);
+ len = recover_names((char_u *)fname, false, 0, NULL);
if (len == 0) { // no swap files found
semsg(_("E305: No swap file found for %s"), fname);
goto theend;
@@ -794,7 +756,7 @@ void ml_recover(bool checkext)
i = 1;
} else { // several swap files found, choose
// list the names of the swap files
- (void)recover_names(fname, true, 0, NULL);
+ (void)recover_names((char_u *)fname, true, 0, NULL);
msg_putchar('\n');
msg_puts(_("Enter number of swap file to use (0 to quit): "));
i = get_number(false, NULL);
@@ -803,7 +765,7 @@ void ml_recover(bool checkext)
}
}
// get the swap file name that will be used
- (void)recover_names(fname, false, i, &fname_used);
+ (void)recover_names((char_u *)fname, false, i, &fname_used);
}
if (fname_used == NULL) {
goto theend; // user chose invalid number.
@@ -813,15 +775,11 @@ void ml_recover(bool checkext)
getout(1);
}
- /*
- * Allocate a buffer structure for the swap file that is used for recovery.
- * Only the memline in it is really used.
- */
+ // Allocate a buffer structure for the swap file that is used for recovery.
+ // Only the memline in it is really used.
buf = xmalloc(sizeof(buf_T));
- /*
- * init fields in memline struct
- */
+ // init fields in memline struct
buf->b_ml.ml_stack_size = 0; // no stack yet
buf->b_ml.ml_stack = NULL; // no stack yet
buf->b_ml.ml_stack_top = 0; // nothing in the stack
@@ -830,12 +788,10 @@ void ml_recover(bool checkext)
buf->b_ml.ml_locked = NULL; // no locked block
buf->b_ml.ml_flags = 0;
- /*
- * open the memfile from the old swap file
- */
- p = vim_strsave(fname_used); // save "fname_used" for the message:
- // mf_open() will consume "fname_used"!
- mfp = mf_open((char *)fname_used, O_RDONLY);
+ // open the memfile from the old swap file
+ p = xstrdup(fname_used); // save "fname_used" for the message:
+ // mf_open() will consume "fname_used"!
+ mfp = mf_open(fname_used, O_RDONLY);
fname_used = p;
if (mfp == NULL || mfp->mf_fd < 0) {
semsg(_("E306: Cannot open %s"), fname_used);
@@ -843,21 +799,17 @@ void ml_recover(bool checkext)
}
buf->b_ml.ml_mfp = mfp;
- /*
- * The page size set in mf_open() might be different from the page size
- * used in the swap file, we must get it from block 0. But to read block
- * 0 we need a page size. Use the minimal size for block 0 here, it will
- * be set to the real value below.
- */
+ // The page size set in mf_open() might be different from the page size
+ // used in the swap file, we must get it from block 0. But to read block
+ // 0 we need a page size. Use the minimal size for block 0 here, it will
+ // be set to the real value below.
mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
- /*
- * try to read block 0
- */
+ // try to read block 0
if ((hp = mf_get(mfp, 0, 1)) == NULL) {
msg_start();
msg_puts_attr(_("Unable to read block 0 from "), attr | MSG_HIST);
- msg_outtrans_attr((char *)mfp->mf_fname, attr | MSG_HIST);
+ msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
msg_puts_attr(_("\nMaybe no changes were made or Vim did not update the swap file."),
attr | MSG_HIST);
msg_end();
@@ -866,7 +818,7 @@ void ml_recover(bool checkext)
b0p = hp->bh_data;
if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0) {
msg_start();
- msg_outtrans_attr((char *)mfp->mf_fname, MSG_HIST);
+ msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
msg_puts_attr(_(" cannot be used with this version of Vim.\n"),
MSG_HIST);
msg_puts_attr(_("Use Vim version 3.0.\n"), MSG_HIST);
@@ -879,7 +831,7 @@ void ml_recover(bool checkext)
}
if (b0_magic_wrong(b0p)) {
msg_start();
- msg_outtrans_attr((char *)mfp->mf_fname, attr | MSG_HIST);
+ msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
msg_puts_attr(_(" cannot be used on this computer.\n"),
attr | MSG_HIST);
msg_puts_attr(_("The file was created on "), attr | MSG_HIST);
@@ -891,17 +843,15 @@ void ml_recover(bool checkext)
goto theend;
}
- /*
- * If we guessed the wrong page size, we have to recalculate the
- * highest block number in the file.
- */
+ // If we guessed the wrong page size, we have to recalculate the
+ // highest block number in the file.
if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size)) {
unsigned previous_page_size = mfp->mf_page_size;
mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
if (mfp->mf_page_size < previous_page_size) {
msg_start();
- msg_outtrans_attr((char *)mfp->mf_fname, attr | MSG_HIST);
+ msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
msg_puts_attr(_(" has been damaged (page size is smaller than minimum value).\n"),
attr | MSG_HIST);
msg_end();
@@ -930,7 +880,7 @@ void ml_recover(bool checkext)
}
}
- home_replace(NULL, (char *)mfp->mf_fname, (char *)NameBuff, MAXPATHL, true);
+ home_replace(NULL, mfp->mf_fname, (char *)NameBuff, MAXPATHL, true);
smsg(_("Using swap file \"%s\""), NameBuff);
if (buf_spname(curbuf) != NULL) {
@@ -941,15 +891,13 @@ void ml_recover(bool checkext)
smsg(_("Original file \"%s\""), NameBuff);
msg_putchar('\n');
- /*
- * check date of swap file and original file
- */
+ // check date of swap file and original file
FileInfo org_file_info;
FileInfo swp_file_info;
mtime = char_to_long(b0p->b0_mtime);
if (curbuf->b_ffname != NULL
&& os_fileinfo(curbuf->b_ffname, &org_file_info)
- && ((os_fileinfo((char *)mfp->mf_fname, &swp_file_info)
+ && ((os_fileinfo(mfp->mf_fname, &swp_file_info)
&& org_file_info.stat.st_mtim.tv_sec
> swp_file_info.stat.st_mtim.tv_sec)
|| org_file_info.stat.st_mtim.tv_sec != mtime)) {
@@ -962,25 +910,21 @@ void ml_recover(bool checkext)
if (b0p->b0_flags & B0_HAS_FENC) {
int fnsize = B0_FNAME_SIZE_NOCRYPT;
- for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; p--) {}
- b0_fenc = vim_strnsave(p, (size_t)(b0p->b0_fname + fnsize - p));
+ for (p = (char *)b0p->b0_fname + fnsize; (char_u *)p > b0p->b0_fname && p[-1] != NUL; p--) {}
+ b0_fenc = xstrnsave(p, (size_t)(b0p->b0_fname + fnsize - (char_u *)p));
}
mf_put(mfp, hp, false, false); // release block 0
hp = NULL;
- /*
- * Now that we are sure that the file is going to be recovered, clear the
- * contents of the current buffer.
- */
+ // Now that we are sure that the file is going to be recovered, clear the
+ // contents of the current buffer.
while (!(curbuf->b_ml.ml_flags & ML_EMPTY)) {
ml_delete((linenr_T)1, false);
}
- /*
- * Try reading the original file to obtain the values of 'fileformat',
- * 'fileencoding', etc. Ignore errors. The text itself is not used.
- */
+ // Try reading the original file to obtain the values of 'fileformat',
+ // 'fileencoding', etc. Ignore errors. The text itself is not used.
if (curbuf->b_ffname != NULL) {
orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
(linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW, false);
@@ -991,7 +935,7 @@ void ml_recover(bool checkext)
set_fileformat(b0_ff - 1, OPT_LOCAL);
}
if (b0_fenc != NULL) {
- set_option_value_give_err("fenc", 0L, (char *)b0_fenc, OPT_LOCAL);
+ set_option_value_give_err("fenc", 0L, b0_fenc, OPT_LOCAL);
xfree(b0_fenc);
}
unchanged(curbuf, true, true);
@@ -1017,9 +961,7 @@ void ml_recover(bool checkext)
if (hp != NULL) {
mf_put(mfp, hp, false, false); // release previous block
}
- /*
- * get block
- */
+ // get block
if ((hp = mf_get(mfp, bnum, page_count)) == NULL) {
if (bnum == 1) {
semsg(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
@@ -1049,11 +991,9 @@ void ml_recover(bool checkext)
error++;
} else if (idx < (int)pp->pb_count) { // go a block deeper
if (pp->pb_pointer[idx].pe_bnum < 0) {
- /*
- * Data block with negative block number.
- * Try to read lines from the original file.
- * This is slow, but it works.
- */
+ // Data block with negative block number.
+ // Try to read lines from the original file.
+ // This is slow, but it works.
if (!cannot_open) {
line_count = pp->pb_pointer[idx].pe_line_count;
if (readfile(curbuf->b_ffname, NULL, lnum,
@@ -1073,9 +1013,7 @@ void ml_recover(bool checkext)
continue;
}
- /*
- * going one block deeper in the tree
- */
+ // going one block deeper in the tree
top = ml_add_stack(buf); // new entry in stack
ip = &(buf->b_ml.ml_stack[top]);
ip->ip_bnum = bnum;
@@ -1116,10 +1054,8 @@ void ml_recover(bool checkext)
// make sure there is a NUL at the end of the block
*((char_u *)dp + dp->db_txt_end - 1) = NUL;
- /*
- * check number of lines in block
- * if wrong, use count in data block
- */
+ // check number of lines in block
+ // if wrong, use count in data block
if (line_count != dp->db_line_count) {
ml_append(lnum++,
_("??? from here until ???END lines"
@@ -1133,12 +1069,12 @@ void ml_recover(bool checkext)
txt_start = (dp->db_index[i] & DB_INDEX_MASK);
if (txt_start <= (int)HEADER_SIZE
|| txt_start >= (int)dp->db_txt_end) {
- p = (char_u *)"???";
+ p = "???";
error++;
} else {
- p = (char_u *)dp + txt_start;
+ p = (char *)dp + txt_start;
}
- ml_append(lnum++, (char *)p, (colnr_T)0, true);
+ ml_append(lnum++, p, (colnr_T)0, true);
}
if (has_error) {
ml_append(lnum++, _("???END"), (colnr_T)0, true);
@@ -1151,22 +1087,18 @@ void ml_recover(bool checkext)
break;
}
- /*
- * go one block up in the tree
- */
+ // go one block up in the tree
ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
bnum = ip->ip_bnum;
idx = ip->ip_index + 1; // go to next index
page_count = 1;
}
- /*
- * Compare the buffer contents with the original file. When they differ
- * set the 'modified' flag.
- * Lines 1 - lnum are the new contents.
- * Lines lnum + 1 to ml_line_count are the original contents.
- * Line ml_line_count + 1 in the dummy empty line.
- */
+ // Compare the buffer contents with the original file. When they differ
+ // set the 'modified' flag.
+ // Lines 1 - lnum are the new contents.
+ // Lines lnum + 1 to ml_line_count are the original contents.
+ // Line ml_line_count + 1 in the dummy empty line.
if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1) {
// Recovering an empty file results in two lines and the first line is
// empty. Don't set the modified flag then.
@@ -1177,8 +1109,8 @@ void ml_recover(bool checkext)
} else {
for (idx = 1; idx <= lnum; idx++) {
// Need to copy one line, fetching the other one may flush it.
- p = vim_strsave((char_u *)ml_get(idx));
- i = STRCMP(p, ml_get(idx + lnum));
+ p = xstrdup(ml_get(idx));
+ i = strcmp(p, ml_get(idx + lnum));
xfree(p);
if (i != 0) {
changed_internal();
@@ -1188,10 +1120,8 @@ void ml_recover(bool checkext)
}
}
- /*
- * Delete the lines from the original file and the dummy line from the
- * empty buffer. These will now be after the last line in the buffer.
- */
+ // Delete the lines from the original file and the dummy line from the
+ // empty buffer. These will now be after the last line in the buffer.
while (curbuf->b_ml.ml_line_count > lnum
&& !(curbuf->b_ml.ml_flags & ML_EMPTY)) {
ml_delete(curbuf->b_ml.ml_line_count, false);
@@ -1231,7 +1161,7 @@ theend:
}
mf_close(mfp, false); // will also xfree(mfp->mf_fname)
}
- if (buf != NULL) { //may be NULL if swap file not found.
+ if (buf != NULL) { // may be NULL if swap file not found.
xfree(buf->b_ml.ml_stack);
xfree(buf);
}
@@ -1256,7 +1186,7 @@ theend:
/// @param list when true, list the swap file names
/// @param nr when non-zero, return nr'th swap file name
/// @param fname_out result when "nr" > 0
-int recover_names(char_u *fname, int list, int nr, char_u **fname_out)
+int recover_names(char_u *fname, int list, int nr, char **fname_out)
{
int num_names;
char *(names[6]);
@@ -1308,7 +1238,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out)
names[2] = xstrdup(".sw?");
num_names = 3;
} else {
- num_names = recov_file_names(names, fname_res, true);
+ num_names = recov_file_names(names, (char *)fname_res, true);
}
} else { // check directory dir_name
if (fname == NULL) {
@@ -1331,7 +1261,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out)
tail = (char_u *)path_tail((char *)fname_res);
tail = (char_u *)concat_fnames((char *)dir_name, (char *)tail, true);
}
- num_names = recov_file_names(names, tail, false);
+ num_names = recov_file_names(names, (char *)tail, false);
xfree(tail);
}
}
@@ -1343,11 +1273,9 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out)
num_files = 0;
}
- /*
- * When no swap file found, wildcard expansion might have failed (e.g.
- * not able to execute the shell).
- * Try finding a swap file by simply adding ".swp" to the file name.
- */
+ // When no swap file found, wildcard expansion might have failed (e.g.
+ // not able to execute the shell).
+ // Try finding a swap file by simply adding ".swp" to the file name.
if (*dirp == NUL && file_count + num_files == 0 && fname != NULL) {
char_u *swapname = (char_u *)modname((char *)fname_res, ".swp", true);
if (swapname != NULL) {
@@ -1361,11 +1289,9 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out)
}
}
- /*
- * remove swapfile name of the current buffer, it must be ignored
- */
+ // remove swapfile name of the current buffer, it must be ignored
if (curbuf->b_ml.ml_mfp != NULL
- && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL) {
+ && (p = (char_u *)curbuf->b_ml.ml_mfp->mf_fname) != NULL) {
for (int i = 0; i < num_files; i++) {
// Do not expand wildcards, on Windows would try to expand
// "%tmp%" in "%tmp%file"
@@ -1387,7 +1313,7 @@ int recover_names(char_u *fname, int list, int nr, char_u **fname_out)
if (nr > 0) {
file_count += num_files;
if (nr <= file_count) {
- *fname_out = vim_strsave((char_u *)files[nr - 1 + num_files - file_count]);
+ *fname_out = xstrdup(files[nr - 1 + num_files - file_count]);
dirp = ""; // stop searching
}
} else if (list) {
@@ -1522,9 +1448,7 @@ static time_t swapfile_info(char_u *fname)
msg_puts(os_ctime_r(&x, ctime_buf, sizeof(ctime_buf)));
}
- /*
- * print the original file name
- */
+ // print the original file name
fd = os_open((char *)fname, O_RDONLY, 0);
if (fd >= 0) {
if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) {
@@ -1629,7 +1553,7 @@ static bool swapfile_unchanged(char *fname)
return ret;
}
-static int recov_file_names(char **names, char_u *path, int prepend_dot)
+static int recov_file_names(char **names, char *path, int prepend_dot)
FUNC_ATTR_NONNULL_ALL
{
int num_names = 0;
@@ -1637,7 +1561,7 @@ static int recov_file_names(char **names, char_u *path, int prepend_dot)
// May also add the file name with a dot prepended, for swap file in same
// dir as original file.
if (prepend_dot) {
- names[num_names] = modname((char *)path, ".sw?", true);
+ names[num_names] = modname(path, ".sw?", true);
if (names[num_names] == NULL) {
return num_names;
}
@@ -1645,14 +1569,14 @@ static int recov_file_names(char **names, char_u *path, int prepend_dot)
}
// Form the normal swap file name pattern by appending ".sw?".
- names[num_names] = concat_fnames((char *)path, ".sw?", false);
+ names[num_names] = concat_fnames(path, ".sw?", false);
if (num_names >= 1) { // check if we have the same name twice
- char_u *p = (char_u *)names[num_names - 1];
+ char *p = names[num_names - 1];
int i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
if (i > 0) {
p += i; // file name has been expanded to full path
}
- if (STRCMP(p, names[num_names]) != 0) {
+ if (strcmp(p, names[num_names]) != 0) {
num_names++;
} else {
xfree(names[num_names]);
@@ -1681,10 +1605,8 @@ void ml_sync_all(int check_file, int check_char, bool do_fsync)
(void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
&& buf->b_ffname != NULL) {
- /*
- * If the original file does not exist anymore or has been changed
- * call ml_preserve() to get rid of all negative numbered blocks.
- */
+ // If the original file does not exist anymore or has been changed
+ // call ml_preserve() to get rid of all negative numbered blocks.
FileInfo file_info;
if (!os_fileinfo(buf->b_ffname, &file_info)
|| file_info.stat.st_mtim.tv_sec != buf->b_mtime_read
@@ -1739,18 +1661,16 @@ void ml_preserve(buf_T *buf, int message, bool do_fsync)
// stack is invalid after mf_sync(.., MFS_ALL)
buf->b_ml.ml_stack_top = 0;
- /*
- * Some of the data blocks may have been changed from negative to
- * positive block number. In that case the pointer blocks need to be
- * updated.
- *
- * We don't know in which pointer block the references are, so we visit
- * all data blocks until there are no more translations to be done (or
- * we hit the end of the file, which can only happen in case a write fails,
- * e.g. when file system if full).
- * ml_find_line() does the work by translating the negative block numbers
- * when getting the first line of each data block.
- */
+ // Some of the data blocks may have been changed from negative to
+ // positive block number. In that case the pointer blocks need to be
+ // updated.
+ //
+ // We don't know in which pointer block the references are, so we visit
+ // all data blocks until there are no more translations to be done (or
+ // we hit the end of the file, which can only happen in case a write fails,
+ // e.g. when file system if full).
+ // ml_find_line() does the work by translating the negative block numbers
+ // when getting the first line of each data block.
if (mf_need_trans(mfp) && !got_int) {
lnum = 1;
while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count) {
@@ -1781,13 +1701,11 @@ theend:
}
}
-/*
- * NOTE: The pointer returned by the ml_get_*() functions only remains valid
- * until the next call!
- * line1 = ml_get(1);
- * line2 = ml_get(2); // line1 is now invalid!
- * Make a copy of the line if necessary.
- */
+// NOTE: The pointer returned by the ml_get_*() functions only remains valid
+// until the next call!
+// line1 = ml_get(1);
+// line2 = ml_get(2); // line1 is now invalid!
+// Make a copy of the line if necessary.
/// @return a pointer to a (read-only copy of a) line.
///
@@ -1795,14 +1713,14 @@ theend:
/// having to check for error everywhere).
char *ml_get(linenr_T lnum)
{
- return (char *)ml_get_buf(curbuf, lnum, false);
+ return ml_get_buf(curbuf, lnum, false);
}
/// @return pointer to position "pos".
char_u *ml_get_pos(const pos_T *pos)
FUNC_ATTR_NONNULL_ALL
{
- return ml_get_buf(curbuf, pos->lnum, false) + pos->col;
+ return (char_u *)ml_get_buf(curbuf, pos->lnum, false) + pos->col;
}
/// @return codepoint at pos. pos must be either valid or have col set to MAXCOL!
@@ -1819,14 +1737,14 @@ int gchar_pos(pos_T *pos)
/// @param will_change true mark the buffer dirty (chars in the line will be changed)
///
/// @return a pointer to a line in a specific buffer
-char_u *ml_get_buf(buf_T *buf, linenr_T lnum, bool will_change)
+char *ml_get_buf(buf_T *buf, linenr_T lnum, bool will_change)
FUNC_ATTR_NONNULL_ALL
{
bhdr_T *hp;
DATA_BL *dp;
- char_u *ptr;
+ char *ptr;
static int recursive = 0;
- static char_u questions[4];
+ static char questions[4];
if (lnum > buf->b_ml.ml_line_count) { // invalid line number
if (recursive == 0) {
@@ -1848,23 +1766,19 @@ errorret:
}
if (buf->b_ml.ml_mfp == NULL) { // there are no lines
- return (char_u *)"";
+ return "";
}
- /*
- * See if it is the same line as requested last time.
- * Otherwise may need to flush last used line.
- * Don't use the last used line when 'swapfile' is reset, need to load all
- * blocks.
- */
+ // See if it is the same line as requested last time.
+ // Otherwise may need to flush last used line.
+ // Don't use the last used line when 'swapfile' is reset, need to load all
+ // blocks.
if (buf->b_ml.ml_line_lnum != lnum) {
ml_flush_line(buf);
- /*
- * Find the data block containing the line.
- * This also fills the stack with the blocks from the root to the data
- * block and releases any locked block.
- */
+ // Find the data block containing the line.
+ // This also fills the stack with the blocks from the root to the data
+ // block and releases any locked block.
if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL) {
if (recursive == 0) {
// Avoid giving this message for a recursive call, may happen
@@ -1881,9 +1795,9 @@ errorret:
dp = hp->bh_data;
- ptr = (char_u *)dp +
+ ptr = (char *)dp +
((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
- buf->b_ml.ml_line_ptr = ptr;
+ buf->b_ml.ml_line_ptr = (char_u *)ptr;
buf->b_ml.ml_line_lnum = lnum;
buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
}
@@ -1892,7 +1806,7 @@ errorret:
ml_add_deleted_len_buf(buf, buf->b_ml.ml_line_ptr, -1);
}
- return buf->b_ml.ml_line_ptr;
+ return (char *)buf->b_ml.ml_line_ptr;
}
/// Check if a line that was just obtained by a call to ml_get
@@ -1986,11 +1900,9 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
memfile_T *mfp = buf->b_ml.ml_mfp;
int page_size = (int)mfp->mf_page_size;
- /*
- * find the data block containing the previous line
- * This also fills the stack with the blocks from the root to the data block
- * This also releases any locked block.
- */
+ // find the data block containing the previous line
+ // This also fills the stack with the blocks from the root to the data block
+ // This also releases any locked block.
if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
ML_INSERT)) == NULL) {
return FAIL;
@@ -2008,22 +1920,18 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
dp = hp->bh_data;
- /*
- * If
- * - there is not enough room in the current block
- * - appending to the last line in the block
- * - not appending to the last line in the file
- * insert in front of the next block.
- */
+ // If
+ // - there is not enough room in the current block
+ // - appending to the last line in the block
+ // - not appending to the last line in the file
+ // insert in front of the next block.
if ((int)dp->db_free < space_needed && db_idx == line_count - 1
&& lnum < buf->b_ml.ml_line_count) {
- /*
- * Now that the line is not going to be inserted in the block that we
- * expected, the line count has to be adjusted in the pointer blocks
- * by using ml_locked_lineadd.
- */
- --(buf->b_ml.ml_locked_lineadd);
- --(buf->b_ml.ml_locked_high);
+ // Now that the line is not going to be inserted in the block that we
+ // expected, the line count has to be adjusted in the pointer blocks
+ // by using ml_locked_lineadd.
+ (buf->b_ml.ml_locked_lineadd)--;
+ (buf->b_ml.ml_locked_high)--;
if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL) {
return FAIL;
}
@@ -2039,22 +1947,16 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
buf->b_ml.ml_line_count++;
if ((int)dp->db_free >= space_needed) { // enough room in data block
- /*
- * Insert new line in existing data block, or in data block allocated above.
- */
+ // Insert new line in existing data block, or in data block allocated above.
dp->db_txt_start -= (unsigned)len;
dp->db_free -= (unsigned)space_needed;
dp->db_line_count++;
- /*
- * move the text of the lines that follow to the front
- * adjust the indexes of the lines that follow
- */
+ // move the text of the lines that follow to the front
+ // adjust the indexes of the lines that follow
if (line_count > db_idx + 1) { // if there are following lines
- /*
- * Offset is the start of the previous line.
- * This will become the character just after the new line.
- */
+ // Offset is the start of the previous line.
+ // This will become the character just after the new line.
if (db_idx < 0) {
offset = (int)dp->db_txt_end;
} else {
@@ -2071,31 +1973,25 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
dp->db_index[db_idx + 1] = dp->db_txt_start;
}
- /*
- * copy the text into the block
- */
+ // copy the text into the block
memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
if (mark) {
dp->db_index[db_idx + 1] |= DB_MARKED;
}
- /*
- * Mark the block dirty.
- */
+ // Mark the block dirty.
buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
if (!newfile) {
buf->b_ml.ml_flags |= ML_LOCKED_POS;
}
} else { // not enough space in data block
- /*
- * If there is not enough room we have to create a new data block and copy some
- * lines into it.
- * Then we have to insert an entry in the pointer block.
- * If this pointer block also is full, we go up another block, and so on, up
- * to the root if necessary.
- * The line counts in the pointer blocks have already been adjusted by
- * ml_find_line().
- */
+ // If there is not enough room we have to create a new data block and copy some
+ // lines into it.
+ // Then we have to insert an entry in the pointer block.
+ // If this pointer block also is full, we go up another block, and so on, up
+ // to the root if necessary.
+ // The line counts in the pointer blocks have already been adjusted by
+ // ml_find_line().
int line_count_left, line_count_right;
int page_count_left, page_count_right;
bhdr_T *hp_left;
@@ -2113,14 +2009,12 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
int pb_idx;
PTR_BL *pp_new;
- /*
- * We are going to allocate a new data block. Depending on the
- * situation it will be put to the left or right of the existing
- * block. If possible we put the new line in the left block and move
- * the lines after it to the right block. Otherwise the new line is
- * also put in the right block. This method is more efficient when
- * inserting a lot of lines at one place.
- */
+ // We are going to allocate a new data block. Depending on the
+ // situation it will be put to the left or right of the existing
+ // block. If possible we put the new line in the left block and move
+ // the lines after it to the right block. Otherwise the new line is
+ // also put in the right block. This method is more efficient when
+ // inserting a lot of lines at one place.
if (db_idx < 0) { // left block is new, right block is existing
lines_moved = 0;
in_left = true;
@@ -2164,9 +2058,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
page_count_left = (int)hp_left->bh_page_count;
page_count_right = (int)hp_right->bh_page_count;
- /*
- * May move the new line into the right/new block.
- */
+ // May move the new line into the right/new block.
if (!in_left) {
dp_right->db_txt_start -= (unsigned)len;
dp_right->db_free -= (unsigned)len + (unsigned)INDEX_SIZE;
@@ -2179,12 +2071,8 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
line, (size_t)len);
line_count_right++;
}
- /*
- * may move lines from the left/old block to the right/new one.
- */
+ // may move lines from the left/old block to the right/new one.
if (lines_moved) {
- /*
- */
dp_right->db_txt_start -= (unsigned)data_moved;
dp_right->db_free -= (unsigned)total_moved;
memmove((char *)dp_right + dp_right->db_txt_start,
@@ -2194,9 +2082,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
dp_left->db_txt_start += (unsigned)data_moved;
dp_left->db_free += (unsigned)total_moved;
- /*
- * update indexes in the new block
- */
+ // update indexes in the new block
for (to = line_count_right, from = db_idx + 1;
from < line_count_left; from++, to++) {
dp_right->db_index[to] = dp->db_index[from] + (unsigned)offset;
@@ -2205,9 +2091,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
line_count_left -= lines_moved;
}
- /*
- * May move the new line into the left (old or new) block.
- */
+ // May move the new line into the left (old or new) block.
if (in_left) {
dp_left->db_txt_start -= (unsigned)len;
dp_left->db_free -= (unsigned)len + (unsigned)INDEX_SIZE;
@@ -2234,12 +2118,10 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
dp_left->db_line_count = line_count_left;
dp_right->db_line_count = line_count_right;
- /*
- * release the two data blocks
- * The new one (hp_new) already has a correct blocknumber.
- * The old one (hp, in ml_locked) gets a positive blocknumber if
- * we changed it and we are not editing a new file.
- */
+ // release the two data blocks
+ // The new one (hp_new) already has a correct blocknumber.
+ // The old one (hp, in ml_locked) gets a positive blocknumber if
+ // we changed it and we are not editing a new file.
if (lines_moved || in_left) {
buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
}
@@ -2248,18 +2130,14 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
}
mf_put(mfp, hp_new, true, false);
- /*
- * flush the old data block
- * set ml_locked_lineadd to 0, because the updating of the
- * pointer blocks is done below
- */
+ // flush the old data block
+ // set ml_locked_lineadd to 0, because the updating of the
+ // pointer blocks is done below
lineadd = buf->b_ml.ml_locked_lineadd;
buf->b_ml.ml_locked_lineadd = 0;
(void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); // flush data block
- /*
- * update pointer blocks for the new data block
- */
+ // update pointer blocks for the new data block
for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
--stack_idx) {
ip = &(buf->b_ml.ml_stack[stack_idx]);
@@ -2273,10 +2151,8 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
mf_put(mfp, hp, false, false);
return FAIL;
}
- /*
- * TODO: If the pointer block is full and we are adding at the end
- * try to insert in front of the next block
- */
+ // TODO(vim): If the pointer block is full and we are adding at the end
+ // try to insert in front of the next block
// block not full, add one entry
if (pp->pb_count < pp->pb_count_max) {
if (pb_idx + 1 < (int)pp->pb_count) {
@@ -2312,9 +2188,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
++(buf->b_ml.ml_stack_top);
}
- /*
- * We are finished, break the loop here.
- */
+ // We are finished, break the loop here.
break;
}
// pointer block full
@@ -2400,9 +2274,7 @@ static int ml_append_int(buf_T *buf, linenr_T lnum, char_u *line, colnr_T len, b
mf_put(mfp, hp_new, true, false);
}
- /*
- * Safety check: fallen out of for loop?
- */
+ // Safety check: fallen out of for loop?
if (stack_idx < 0) {
iemsg(_("E318: Updated too many blocks?"));
buf->b_ml.ml_stack_top = 0; // invalidate stack
@@ -2480,7 +2352,7 @@ int ml_replace_buf(buf_T *buf, linenr_T lnum, char *line, bool copy)
}
if (readlen && kv_size(buf->update_callbacks)) {
- ml_add_deleted_len_buf(buf, ml_get_buf(buf, lnum, false), -1);
+ ml_add_deleted_len_buf(buf, (char_u *)ml_get_buf(buf, lnum, false), -1);
}
buf->b_ml.ml_line_ptr = (char_u *)line;
@@ -2526,9 +2398,7 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message)
lowest_marked--;
}
- /*
- * If the file becomes empty the last line is replaced by an empty line.
- */
+ // If the file becomes empty the last line is replaced by an empty line.
if (buf->b_ml.ml_line_count == 1) { // file becomes empty
if (message) {
set_keep_msg(_(no_lines_msg), 0);
@@ -2540,11 +2410,9 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message)
return i;
}
- /*
- * find the data block containing the line
- * This also fills the stack with the blocks from the root to the data block
- * This also releases any locked block.
- */
+ // find the data block containing the line
+ // This also fills the stack with the blocks from the root to the data block
+ // This also releases any locked block.
mfp = buf->b_ml.ml_mfp;
if (mfp == NULL) {
return FAIL;
@@ -2573,14 +2441,12 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message)
assert(line_size >= 1);
ml_add_deleted_len_buf(buf, (char_u *)dp + line_start, line_size - 1);
- /*
- * special case: If there is only one line in the data block it becomes empty.
- * Then we have to remove the entry, pointing to this data block, from the
- * pointer block. If this pointer block also becomes empty, we go up another
- * block, and so on, up to the root if necessary.
- * The line counts in the pointer blocks have already been adjusted by
- * ml_find_line().
- */
+ // special case: If there is only one line in the data block it becomes empty.
+ // Then we have to remove the entry, pointing to this data block, from the
+ // pointer block. If this pointer block also becomes empty, we go up another
+ // block, and so on, up to the root if necessary.
+ // The line counts in the pointer blocks have already been adjusted by
+ // ml_find_line().
if (count == 1) {
mf_free(mfp, hp); // free the data block
buf->b_ml.ml_locked = NULL;
@@ -2638,9 +2504,7 @@ static int ml_delete_int(buf_T *buf, linenr_T lnum, bool message)
dp->db_txt_start += (unsigned)line_size;
dp->db_line_count--;
- /*
- * mark the block dirty and make sure it is in the file (for recovery)
- */
+ // mark the block dirty and make sure it is in the file (for recovery)
buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
}
@@ -2662,11 +2526,9 @@ void ml_setmarked(linenr_T lnum)
lowest_marked = lnum;
}
- /*
- * find the data block containing the line
- * This also fills the stack with the blocks from the root to the data block
- * This also releases any locked block.
- */
+ // find the data block containing the line
+ // This also fills the stack with the blocks from the root to the data block
+ // This also releases any locked block.
if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) {
return; // give error message?
}
@@ -2687,16 +2549,12 @@ linenr_T ml_firstmarked(void)
return (linenr_T)0;
}
- /*
- * The search starts with lowest_marked line. This is the last line where
- * a mark was found, adjusted by inserting/deleting lines.
- */
+ // The search starts with lowest_marked line. This is the last line where
+ // a mark was found, adjusted by inserting/deleting lines.
for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count;) {
- /*
- * Find the data block containing the line.
- * This also fills the stack with the blocks from the root to the data
- * block This also releases any locked block.
- */
+ // Find the data block containing the line.
+ // This also fills the stack with the blocks from the root to the data
+ // block This also releases any locked block.
if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) {
return (linenr_T)0; // give error message?
}
@@ -2728,15 +2586,11 @@ void ml_clearmarked(void)
return;
}
- /*
- * The search starts with line lowest_marked.
- */
+ // The search starts with line lowest_marked.
for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count;) {
- /*
- * Find the data block containing the line.
- * This also fills the stack with the blocks from the root to the data
- * block and releases any locked block.
- */
+ // Find the data block containing the line.
+ // This also fills the stack with the blocks from the root to the data
+ // block and releases any locked block.
if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) {
return; // give error message?
}
@@ -2813,9 +2667,7 @@ static void ml_flush_line(buf_T *buf)
new_len = (colnr_T)STRLEN(new_line) + 1;
extra = new_len - old_len; // negative if lines gets smaller
- /*
- * if new line fits in data block, replace directly
- */
+ // if new line fits in data block, replace directly
if ((int)dp->db_free >= extra) {
// if the length changes and there are following lines
count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
@@ -2918,13 +2770,11 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action)
mfp = buf->b_ml.ml_mfp;
- /*
- * If there is a locked block check if the wanted line is in it.
- * If not, flush and release the locked block.
- * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
- * Don't do this for ML_FLUSH, because we want to flush the locked block.
- * Don't do this when 'swapfile' is reset, we want to load all the blocks.
- */
+ // If there is a locked block check if the wanted line is in it.
+ // If not, flush and release the locked block.
+ // Don't do this for ML_INSERT_SAME, because the stack need to be updated.
+ // Don't do this for ML_FLUSH, because we want to flush the locked block.
+ // Don't do this when 'swapfile' is reset, we want to load all the blocks.
if (buf->b_ml.ml_locked) {
if (ML_SIMPLE(action)
&& buf->b_ml.ml_locked_low <= lnum
@@ -2944,10 +2794,8 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action)
buf->b_ml.ml_flags & ML_LOCKED_POS);
buf->b_ml.ml_locked = NULL;
- /*
- * If lines have been added or deleted in the locked block, need to
- * update the line count in pointer blocks.
- */
+ // If lines have been added or deleted in the locked block, need to
+ // update the line count in pointer blocks.
if (buf->b_ml.ml_locked_lineadd != 0) {
ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
}
@@ -2979,17 +2827,13 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action)
} else { // ML_DELETE or ML_INSERT
buf->b_ml.ml_stack_top = 0; // start at the root
}
- /*
- * search downwards in the tree until a data block is found
- */
+ // search downwards in the tree until a data block is found
for (;;) {
if ((hp = mf_get(mfp, bnum, (unsigned)page_count)) == NULL) {
goto error_noblock;
}
- /*
- * update high for insert/delete
- */
+ // update high for insert/delete
if (action == ML_INSERT) {
high++;
} else if (action == ML_DELETE) {
@@ -3030,9 +2874,7 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action)
high = low - 1;
low -= t;
- /*
- * a negative block number may have been changed
- */
+ // a negative block number may have been changed
if (bnum < 0) {
bnum2 = mf_trans_del(mfp, bnum);
if (bnum != bnum2) {
@@ -3067,11 +2909,9 @@ static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action)
error_block:
mf_put(mfp, hp, false, false);
error_noblock:
- /*
- * If action is ML_DELETE or ML_INSERT we have to correct the tree for
- * the incremented/decremented line counts, because there won't be a line
- * inserted/deleted after all.
- */
+ // If action is ML_DELETE or ML_INSERT we have to correct the tree for
+ // the incremented/decremented line counts, because there won't be a line
+ // inserted/deleted after all.
if (action == ML_DELETE) {
ml_lineadd(buf, 1);
} else if (action == ML_INSERT) {
@@ -3196,11 +3036,9 @@ int resolve_symlink(const char *fname, char *buf)
}
}
- /*
- * Try to resolve the full name of the file so that the swapfile name will
- * be consistent even when opening a relative symlink from different
- * working directories.
- */
+ // Try to resolve the full name of the file so that the swapfile name will
+ // be consistent even when opening a relative symlink from different
+ // working directories.
return vim_FullName(tmp, buf, MAXPATHL, true);
}
#endif
@@ -3243,7 +3081,7 @@ char_u *makeswapname(char_u *fname, char_u *ffname, buf_T *buf, char_u *dir_name
return NULL;
}
- s = get_file_in_dir(r, dir_name);
+ s = (char_u *)get_file_in_dir((char *)r, (char *)dir_name);
xfree(r);
return s;
}
@@ -3260,30 +3098,30 @@ char_u *makeswapname(char_u *fname, char_u *ffname, buf_T *buf, char_u *dir_name
/// The return value is an allocated string and can be NULL.
///
/// @param dname don't use "dirname", it is a global for Alpha
-char_u *get_file_in_dir(char_u *fname, char_u *dname)
+char *get_file_in_dir(char *fname, char *dname)
{
- char_u *t;
- char_u *tail;
- char_u *retval;
+ char *t;
+ char *tail;
+ char *retval;
int save_char;
- tail = (char_u *)path_tail((char *)fname);
+ tail = path_tail(fname);
if (dname[0] == '.' && dname[1] == NUL) {
- retval = vim_strsave(fname);
+ retval = xstrdup(fname);
} else if (dname[0] == '.' && vim_ispathsep(dname[1])) {
if (tail == fname) { // no path before file name
- retval = (char_u *)concat_fnames((char *)dname + 2, (char *)tail, true);
+ retval = concat_fnames(dname + 2, tail, true);
} else {
- save_char = *tail;
+ save_char = (uint8_t)(*tail);
*tail = NUL;
- t = (char_u *)concat_fnames((char *)fname, (char *)dname + 2, true);
- *tail = (uint8_t)save_char;
- retval = (char_u *)concat_fnames((char *)t, (char *)tail, true);
+ t = concat_fnames(fname, dname + 2, true);
+ *tail = (char)save_char;
+ retval = concat_fnames(t, tail, true);
xfree(t);
}
} else {
- retval = (char_u *)concat_fnames((char *)dname, (char *)tail, true);
+ retval = concat_fnames(dname, tail, true);
}
return retval;
@@ -3407,17 +3245,13 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_
char *dir_name;
char *buf_fname = buf->b_fname;
- /*
- * Isolate a directory name from *dirp and put it in dir_name.
- * First allocate some memory to put the directory name in.
- */
+ // Isolate a directory name from *dirp and put it in dir_name.
+ // First allocate some memory to put the directory name in.
const size_t dir_len = strlen(*dirp) + 1;
dir_name = xmalloc(dir_len);
(void)copy_option_part(dirp, dir_name, dir_len, ",");
- /*
- * we try different names until we find one that does not exist yet
- */
+ // we try different names until we find one that does not exist yet
fname = (char *)makeswapname((char_u *)buf_fname, (char_u *)buf->b_ffname, buf,
(char_u *)dir_name);
@@ -3439,7 +3273,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_
}
// A file name equal to old_fname is OK to use.
- if (old_fname != NULL && FNAMECMP(fname, old_fname) == 0) {
+ if (old_fname != NULL && path_fnamecmp(fname, old_fname) == 0) {
break;
}
@@ -3464,14 +3298,14 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_
// buffer don't compare the directory names, they can
// have a different mountpoint.
if (b0.b0_flags & B0_SAME_DIR) {
- if (FNAMECMP(path_tail((char *)buf->b_ffname),
- path_tail((char *)b0.b0_fname)) != 0
+ if (path_fnamecmp(path_tail(buf->b_ffname),
+ path_tail((char *)b0.b0_fname)) != 0
|| !same_directory((char_u *)fname, (char_u *)buf->b_ffname)) {
// Symlinks may point to the same file even
// when the name differs, need to check the
// inode too.
expand_env((char *)b0.b0_fname, NameBuff, MAXPATHL);
- if (fnamecmp_ino((char_u *)buf->b_ffname, (char_u *)NameBuff,
+ if (fnamecmp_ino(buf->b_ffname, NameBuff,
char_to_long(b0.b0_ino))) {
differ = true;
}
@@ -3480,7 +3314,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_
// The name in the swap file may be
// "~user/path/file". Expand it first.
expand_env((char *)b0.b0_fname, NameBuff, MAXPATHL);
- if (fnamecmp_ino((char_u *)buf->b_ffname, (char_u *)NameBuff,
+ if (fnamecmp_ino(buf->b_ffname, NameBuff,
char_to_long(b0.b0_ino))) {
differ = true;
}
@@ -3596,12 +3430,10 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_
}
}
- /*
- * Change the ".swp" extension to find another file that can be used.
- * First decrement the last char: ".swo", ".swn", etc.
- * If that still isn't enough decrement the last but one char: ".svz"
- * Can happen when editing many "No Name" buffers.
- */
+ // Change the ".swp" extension to find another file that can be used.
+ // First decrement the last char: ".swo", ".swn", etc.
+ // If that still isn't enough decrement the last but one char: ".svz"
+ // Can happen when editing many "No Name" buffers.
if (fname[n - 1] == 'a') { // ".s?a"
if (fname[n - 2] == 'a') { // ".saa": tried enough, give up
emsg(_("E326: Too many swap files found"));
@@ -3687,26 +3519,24 @@ static int b0_magic_wrong(ZERO_BL *b0p)
///
/// @param fname_c current file name
/// @param fname_s file name from swap file
-static bool fnamecmp_ino(char_u *fname_c, char_u *fname_s, long ino_block0)
+static bool fnamecmp_ino(char *fname_c, char *fname_s, long ino_block0)
{
uint64_t ino_c = 0; // ino of current file
uint64_t ino_s; // ino of file from swap file
- char_u buf_c[MAXPATHL]; // full path of fname_c
- char_u buf_s[MAXPATHL]; // full path of fname_s
+ char buf_c[MAXPATHL]; // full path of fname_c
+ char buf_s[MAXPATHL]; // full path of fname_s
int retval_c; // flag: buf_c valid
int retval_s; // flag: buf_s valid
FileInfo file_info;
- if (os_fileinfo((char *)fname_c, &file_info)) {
+ if (os_fileinfo(fname_c, &file_info)) {
ino_c = os_fileinfo_inode(&file_info);
}
- /*
- * First we try to get the inode from the file name, because the inode in
- * the swap file may be outdated. If that fails (e.g. this path is not
- * valid on this machine), use the inode from block 0.
- */
- if (os_fileinfo((char *)fname_s, &file_info)) {
+ // First we try to get the inode from the file name, because the inode in
+ // the swap file may be outdated. If that fails (e.g. this path is not
+ // valid on this machine), use the inode from block 0.
+ if (os_fileinfo(fname_s, &file_info)) {
ino_s = os_fileinfo_inode(&file_info);
} else {
ino_s = (uint64_t)ino_block0;
@@ -3716,23 +3546,19 @@ static bool fnamecmp_ino(char_u *fname_c, char_u *fname_s, long ino_block0)
return ino_c != ino_s;
}
- /*
- * One of the inode numbers is unknown, try a forced vim_FullName() and
- * compare the file names.
- */
- retval_c = vim_FullName((char *)fname_c, (char *)buf_c, MAXPATHL, true);
- retval_s = vim_FullName((char *)fname_s, (char *)buf_s, MAXPATHL, true);
+ // One of the inode numbers is unknown, try a forced vim_FullName() and
+ // compare the file names.
+ retval_c = vim_FullName(fname_c, (char *)buf_c, MAXPATHL, true);
+ retval_s = vim_FullName(fname_s, (char *)buf_s, MAXPATHL, true);
if (retval_c == OK && retval_s == OK) {
- return STRCMP(buf_c, buf_s) != 0;
+ return strcmp(buf_c, buf_s) != 0;
}
- /*
- * Can't compare inodes or file names, guess that the files are different,
- * unless both appear not to exist at all, then compare with the file name
- * in the swap file.
- */
+ // Can't compare inodes or file names, guess that the files are different,
+ // unless both appear not to exist at all, then compare with the file name
+ // in the swap file.
if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL) {
- return STRCMP(fname_c, fname_s) != 0;
+ return strcmp(fname_c, fname_s) != 0;
}
return true;
}
@@ -3827,9 +3653,7 @@ static void ml_updatechunk(buf_T *buf, linenr_T line, long len, int updtype)
}
if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1) {
- /*
- * First line in empty buffer from ml_flush_line() -- reset
- */
+ // First line in empty buffer from ml_flush_line() -- reset
buf->b_ml.ml_usedchunks = 1;
buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
buf->b_ml.ml_chunksize[0].mlcs_totalsize =
@@ -3837,10 +3661,8 @@ static void ml_updatechunk(buf_T *buf, linenr_T line, long len, int updtype)
return;
}
- /*
- * Find chunk that our line belongs to, curline will be at start of the
- * chunk.
- */
+ // Find chunk that our line belongs to, curline will be at start of the
+ // chunk.
if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
|| updtype != ML_CHNK_ADDLINE) {
for (curline = 1, curix = 0;
@@ -3928,10 +3750,8 @@ static void ml_updatechunk(buf_T *buf, linenr_T line, long len, int updtype)
curchnk->mlcs_numlines = 0;
curchnk->mlcs_totalsize = 0;
} else {
- /*
- * Line is just prior to last, move count for last
- * This is the common case when loading a new file
- */
+ // Line is just prior to last, move count for last
+ // This is the common case when loading a new file
hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
if (hp == NULL) {
buf->b_ml.ml_usedchunks = -1;
@@ -4044,10 +3864,8 @@ long ml_find_line_or_offset(buf_T *buf, linenr_T lnum, long *offp, bool no_ff)
if (lnum == 0 && offset <= 0) {
return 1; // Not a "find offset" and offset 0 _must_ be in line 1
}
- /*
- * Find the last chunk before the one containing our line. Last chunk is
- * special because it will never qualify
- */
+ // Find the last chunk before the one containing our line. Last chunk is
+ // special because it will never qualify
curline = 1;
curix = 0;
size = 0;
diff --git a/src/nvim/memline_defs.h b/src/nvim/memline_defs.h
index 922a2c98d1..552ec1e3a9 100644
--- a/src/nvim/memline_defs.h
+++ b/src/nvim/memline_defs.h
@@ -69,4 +69,4 @@ typedef struct memline {
int ml_usedchunks;
} memline_T;
-#endif // NVIM_MEMLINE_DEFS_H
+#endif // NVIM_MEMLINE_DEFS_H
diff --git a/src/nvim/memory.c b/src/nvim/memory.c
index acd2478c81..03cfde6160 100644
--- a/src/nvim/memory.c
+++ b/src/nvim/memory.c
@@ -502,22 +502,22 @@ bool striequal(const char *a, const char *b)
return (a == NULL && b == NULL) || (a && b && STRICMP(a, b) == 0);
}
-/*
- * Avoid repeating the error message many times (they take 1 second each).
- * Did_outofmem_msg is reset when a character is read.
- */
+// Avoid repeating the error message many times (they take 1 second each).
+// Did_outofmem_msg is reset when a character is read.
void do_outofmem_msg(size_t size)
{
- if (!did_outofmem_msg) {
- // Don't hide this message
- emsg_silent = 0;
+ if (did_outofmem_msg) {
+ return;
+ }
- /* Must come first to avoid coming back here when printing the error
- * message fails, e.g. when setting v:errmsg. */
- did_outofmem_msg = true;
+ // Don't hide this message
+ emsg_silent = 0;
- semsg(_("E342: Out of memory! (allocating %" PRIu64 " bytes)"), (uint64_t)size);
- }
+ // Must come first to avoid coming back here when printing the error
+ // message fails, e.g. when setting v:errmsg.
+ did_outofmem_msg = true;
+
+ semsg(_("E342: Out of memory! (allocating %" PRIu64 " bytes)"), (uint64_t)size);
}
/// Writes time_t to "buf[8]".
@@ -675,13 +675,11 @@ char *arena_memdupz(Arena *arena, const char *buf, size_t size)
# include "nvim/tag.h"
# include "nvim/window.h"
-/*
- * Free everything that we allocated.
- * Can be used to detect memory leaks, e.g., with ccmalloc.
- * NOTE: This is tricky! Things are freed that functions depend on. Don't be
- * surprised if Vim crashes...
- * Some things can't be freed, esp. things local to a library function.
- */
+// Free everything that we allocated.
+// Can be used to detect memory leaks, e.g., with ccmalloc.
+// NOTE: This is tricky! Things are freed that functions depend on. Don't be
+// surprised if Vim crashes...
+// Some things can't be freed, esp. things local to a library function.
void free_all_mem(void)
{
buf_T *buf, *nextbuf;
diff --git a/src/nvim/menu.c b/src/nvim/menu.c
index 84a1defbe0..d8b7e872d9 100644
--- a/src/nvim/menu.c
+++ b/src/nvim/menu.c
@@ -1,10 +1,8 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * Code for menus. Used for the GUI and 'wildmenu'.
- * GUI/Motif support by Robert Webb
- */
+// Code for menus. Used for the GUI and 'wildmenu'.
+// GUI/Motif support by Robert Webb
#include <assert.h>
#include <inttypes.h>
@@ -141,9 +139,7 @@ void ex_menu(exarg_T *eap)
}
pri_tab[MENUDEPTH] = -1; // mark end of the table
- /*
- * Check for "disable" or "enable" argument.
- */
+ // Check for "disable" or "enable" argument.
if (STRNCMP(arg, "enable", 6) == 0 && ascii_iswhite(arg[6])) {
enable = kTrue;
arg = skipwhite(arg + 6);
@@ -152,9 +148,7 @@ void ex_menu(exarg_T *eap)
arg = skipwhite(arg + 7);
}
- /*
- * If there is no argument, display all menus.
- */
+ // If there is no argument, display all menus.
if (*arg == NUL) {
show_menus(arg, modes);
return;
@@ -168,9 +162,7 @@ void ex_menu(exarg_T *eap)
map_to = menu_translate_tab_and_shift(arg);
- /*
- * If there is only a menu name, display menus with that name.
- */
+ // If there is only a menu name, display menus with that name.
if (*map_to == NUL && !unmenu && enable == kNone) {
show_menus(menu_path, modes);
goto theend;
@@ -185,7 +177,7 @@ void ex_menu(exarg_T *eap)
// Change sensitivity of the menu.
// For the PopUp menu, remove a menu for each mode separately.
// Careful: menu_enable_recurse() changes menu_path.
- if (STRCMP(menu_path, "*") == 0) { // meaning: do all menus
+ if (strcmp(menu_path, "*") == 0) { // meaning: do all menus
menu_path = "";
}
@@ -200,16 +192,12 @@ void ex_menu(exarg_T *eap)
}
menu_enable_recurse(*root_menu_ptr, menu_path, modes, enable);
} else if (unmenu) {
- /*
- * Delete menu(s).
- */
- if (STRCMP(menu_path, "*") == 0) { // meaning: remove all menus
+ // Delete menu(s).
+ if (strcmp(menu_path, "*") == 0) { // meaning: remove all menus
menu_path = "";
}
- /*
- * For the PopUp menu, remove a menu for each mode separately.
- */
+ // For the PopUp menu, remove a menu for each mode separately.
if (menu_is_popup(menu_path)) {
for (i = 0; i < MENU_INDEX_TIP; i++) {
if (modes & (1 << i)) {
@@ -223,10 +211,8 @@ void ex_menu(exarg_T *eap)
// Careful: remove_menu() changes menu_path
remove_menu(root_menu_ptr, menu_path, modes, false);
} else {
- /*
- * Add menu(s).
- * Replace special key codes.
- */
+ // Add menu(s).
+ // Replace special key codes.
if (STRICMP(map_to, "<nop>") == 0) { // "<Nop>" means nothing
map_to = "";
map_buf = NULL;
@@ -242,9 +228,7 @@ void ex_menu(exarg_T *eap)
menuarg.silent[0] = silent;
add_menu_path(menu_path, &menuarg, pri_tab, map_to);
- /*
- * For the PopUp menu, add a menu for each mode separately.
- */
+ // For the PopUp menu, add a menu for each mode separately.
if (menu_is_popup(menu_path)) {
for (i = 0; i < MENU_INDEX_TIP; i++) {
if (modes & (1 << i)) {
@@ -384,11 +368,9 @@ static int add_menu_path(const char *const menu_path, vimmenu_T *menuarg, const
} else {
old_modes = menu->modes;
- /*
- * If this menu option was previously only available in other
- * modes, then make sure it's available for this one now
- * Also enable a menu when it's created or changed.
- */
+ // If this menu option was previously only available in other
+ // modes, then make sure it's available for this one now
+ // Also enable a menu when it's created or changed.
{
menu->modes |= modes;
menu->enabled |= modes;
@@ -405,10 +387,8 @@ static int add_menu_path(const char *const menu_path, vimmenu_T *menuarg, const
}
xfree(path_name);
- /*
- * Only add system menu items which have not been defined yet.
- * First check if this was an ":amenu".
- */
+ // Only add system menu items which have not been defined yet.
+ // First check if this was an ":amenu".
amenu = ((modes & (MENU_NORMAL_MODE | MENU_INSERT_MODE)) ==
(MENU_NORMAL_MODE | MENU_INSERT_MODE));
if (sys_menu) {
@@ -491,10 +471,8 @@ erret:
return FAIL;
}
-/*
- * Set the (sub)menu with the given name to enabled or disabled.
- * Called recursively.
- */
+// Set the (sub)menu with the given name to enabled or disabled.
+// Called recursively.
static int menu_enable_recurse(vimmenu_T *menu, char *name, int modes, int enable)
{
char *p;
@@ -522,11 +500,9 @@ static int menu_enable_recurse(vimmenu_T *menu, char *name, int modes, int enabl
menu->enabled &= ~modes;
}
- /*
- * When name is empty, we are doing all menu items for the given
- * modes, so keep looping, otherwise we are just doing the named
- * menu item (which has been found) so break here.
- */
+ // When name is empty, we are doing all menu items for the given
+ // modes, so keep looping, otherwise we are just doing the named
+ // menu item (which has been found) so break here.
if (*name != NUL && *name != '*') {
break;
}
@@ -577,11 +553,9 @@ static int remove_menu(vimmenu_T **menup, char *name, int modes, bool silent)
return FAIL;
}
- /*
- * When name is empty, we are removing all menu items for the given
- * modes, so keep looping, otherwise we are just removing the named
- * menu item (which has been found) so break here.
- */
+ // When name is empty, we are removing all menu items for the given
+ // modes, so keep looping, otherwise we are just removing the named
+ // menu item (which has been found) so break here.
if (*name != NUL) {
break;
}
@@ -628,9 +602,7 @@ static int remove_menu(vimmenu_T **menup, char *name, int modes, bool silent)
return OK;
}
-/*
- * Free the given menu structure and remove it from the linked list.
- */
+// Free the given menu structure and remove it from the linked list.
static void free_menu(vimmenu_T **menup)
{
int i;
@@ -652,9 +624,7 @@ static void free_menu(vimmenu_T **menup)
xfree(menu);
}
-/*
- * Free the menu->string with the given index.
- */
+// Free the menu->string with the given index.
static void free_menu_string(vimmenu_T *menu, int idx)
{
int count = 0;
@@ -909,16 +879,12 @@ static void show_menus_recursive(vimmenu_T *menu, int modes, int depth)
}
}
-/*
- * Used when expanding menu names.
- */
+// Used when expanding menu names.
static vimmenu_T *expand_menu = NULL;
static int expand_modes = 0x0;
static int expand_emenu; // true for ":emenu" command
-/*
- * Work out what to complete when doing command line completion of menu names.
- */
+// Work out what to complete when doing command line completion of menu names.
char *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char *arg, bool forceit)
FUNC_ATTR_NONNULL_ALL
{
@@ -994,10 +960,8 @@ char *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char *arg, bool for
// Found menu
if ((*p != NUL && menu->children == NULL)
|| ((menu->modes & expand_modes) == 0x0)) {
- /*
- * Menu path continues, but we have reached a leaf.
- * Or menu exists only in another mode.
- */
+ // Menu path continues, but we have reached a leaf.
+ // Or menu exists only in another mode.
xfree(path_name);
return NULL;
}
@@ -1024,10 +988,8 @@ char *set_context_in_menu_cmd(expand_T *xp, const char *cmd, char *arg, bool for
return NULL;
}
-/*
- * Function given to ExpandGeneric() to obtain the list of (sub)menus (not
- * entries).
- */
+// Function given to ExpandGeneric() to obtain the list of (sub)menus (not
+// entries).
char *get_menu_name(expand_T *xp, int idx)
{
static vimmenu_T *menu = NULL;
@@ -1073,10 +1035,8 @@ char *get_menu_name(expand_T *xp, int idx)
return str;
}
-/*
- * Function given to ExpandGeneric() to obtain the list of menus and menu
- * entries.
- */
+// Function given to ExpandGeneric() to obtain the list of menus and menu
+// entries.
char *get_menu_names(expand_T *xp, int idx)
{
static vimmenu_T *menu = NULL;
@@ -1312,10 +1272,8 @@ static char *get_menu_mode_str(int modes)
return "";
}
-/*
- * Modify a menu name starting with "PopUp" to include the mode character.
- * Returns the name in allocated memory.
- */
+// Modify a menu name starting with "PopUp" to include the mode character.
+// Returns the name in allocated memory.
static char *popup_mode_name(char *name, int idx)
{
size_t len = STRLEN(name);
@@ -1730,9 +1688,7 @@ theend:
return menu;
}
-/*
- * Translation of menu names. Just a simple lookup table.
- */
+// Translation of menu names. Just a simple lookup table.
typedef struct {
char *from; // English name
@@ -1748,11 +1704,9 @@ static garray_T menutrans_ga = GA_EMPTY_INIT_VALUE;
xfree(_mt->from_noamp); \
xfree(_mt->to)
-/*
- * ":menutrans".
- * This function is also defined without the +multi_lang feature, in which
- * case the commands are ignored.
- */
+// ":menutrans".
+// This function is also defined without the +multi_lang feature, in which
+// case the commands are ignored.
void ex_menutranslate(exarg_T *eap)
{
char *arg = eap->arg;
@@ -1762,9 +1716,7 @@ void ex_menutranslate(exarg_T *eap)
ga_init(&menutrans_ga, (int)sizeof(menutrans_T), 5);
}
- /*
- * ":menutrans clear": clear all translations.
- */
+ // ":menutrans clear": clear all translations.
if (STRNCMP(arg, "clear", 5) == 0 && ends_excmd(*skipwhite(arg + 5))) {
GA_DEEP_CLEAR(&menutrans_ga, menutrans_T, FREE_MENUTRANS);
@@ -1796,9 +1748,7 @@ void ex_menutranslate(exarg_T *eap)
}
}
-/*
- * Find the character just after one part of a menu name.
- */
+// Find the character just after one part of a menu name.
static char *menu_skip_part(char *p)
{
while (*p != NUL && *p != '.' && !ascii_iswhite(*p)) {
@@ -1810,10 +1760,8 @@ static char *menu_skip_part(char *p)
return p;
}
-/*
- * Lookup part of a menu name in the translations.
- * Return a pointer to the translation or NULL if not found.
- */
+// Lookup part of a menu name in the translations.
+// Return a pointer to the translation or NULL if not found.
static char *menutrans_lookup(char *name, int len)
{
menutrans_T *tp = (menutrans_T *)menutrans_ga.ga_data;
@@ -1841,9 +1789,7 @@ static char *menutrans_lookup(char *name, int len)
return NULL;
}
-/*
- * Unescape the name in the translate dictionary table.
- */
+// Unescape the name in the translate dictionary table.
static void menu_unescape_name(char *name)
{
char *p;
@@ -1855,10 +1801,8 @@ static void menu_unescape_name(char *name)
}
}
-/*
- * Isolate the menu name.
- * Skip the menu name, and translate <Tab> into a real TAB.
- */
+// Isolate the menu name.
+// Skip the menu name, and translate <Tab> into a real TAB.
static char *menu_translate_tab_and_shift(char *arg_start)
{
char *arg = arg_start;
diff --git a/src/nvim/message.c b/src/nvim/message.c
index e7959c73c6..2d23797bc8 100644
--- a/src/nvim/message.c
+++ b/src/nvim/message.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * message.c: functions for displaying messages on the command line
- */
+// message.c: functions for displaying messages on the command line
#include <assert.h>
#include <inttypes.h>
@@ -48,10 +46,8 @@
#include "nvim/ui_compositor.h"
#include "nvim/vim.h"
-/*
- * To be able to scroll back at the "more" and "hit-enter" prompts we need to
- * store the displayed text and remember where screen lines start.
- */
+// To be able to scroll back at the "more" and "hit-enter" prompts we need to
+// store the displayed text and remember where screen lines start.
typedef struct msgchunk_S msgchunk_T;
struct msgchunk_S {
msgchunk_T *sb_next;
@@ -82,41 +78,39 @@ static int verbose_did_open = false;
bool keep_msg_more = false; // keep_msg was set by msgmore()
-/*
- * When writing messages to the screen, there are many different situations.
- * A number of variables is used to remember the current state:
- * msg_didany true when messages were written since the last time the
- * user reacted to a prompt.
- * Reset: After hitting a key for the hit-return prompt,
- * hitting <CR> for the command line or input().
- * Set: When any message is written to the screen.
- * msg_didout true when something was written to the current line.
- * Reset: When advancing to the next line, when the current
- * text can be overwritten.
- * Set: When any message is written to the screen.
- * msg_nowait No extra delay for the last drawn message.
- * Used in normal_cmd() before the mode message is drawn.
- * emsg_on_display There was an error message recently. Indicates that there
- * should be a delay before redrawing.
- * msg_scroll The next message should not overwrite the current one.
- * msg_scrolled How many lines the screen has been scrolled (because of
- * messages). Used in update_screen() to scroll the screen
- * back. Incremented each time the screen scrolls a line.
- * msg_scrolled_ign true when msg_scrolled is non-zero and msg_puts_attr()
- * writes something without scrolling should not make
- * need_wait_return to be set. This is a hack to make ":ts"
- * work without an extra prompt.
- * lines_left Number of lines available for messages before the
- * more-prompt is to be given. -1 when not set.
- * need_wait_return true when the hit-return prompt is needed.
- * Reset: After giving the hit-return prompt, when the user
- * has answered some other prompt.
- * Set: When the ruler or typeahead display is overwritten,
- * scrolling the screen for some message.
- * keep_msg Message to be displayed after redrawing the screen, in
- * main_loop().
- * This is an allocated string or NULL when not used.
- */
+// When writing messages to the screen, there are many different situations.
+// A number of variables is used to remember the current state:
+// msg_didany true when messages were written since the last time the
+// user reacted to a prompt.
+// Reset: After hitting a key for the hit-return prompt,
+// hitting <CR> for the command line or input().
+// Set: When any message is written to the screen.
+// msg_didout true when something was written to the current line.
+// Reset: When advancing to the next line, when the current
+// text can be overwritten.
+// Set: When any message is written to the screen.
+// msg_nowait No extra delay for the last drawn message.
+// Used in normal_cmd() before the mode message is drawn.
+// emsg_on_display There was an error message recently. Indicates that there
+// should be a delay before redrawing.
+// msg_scroll The next message should not overwrite the current one.
+// msg_scrolled How many lines the screen has been scrolled (because of
+// messages). Used in update_screen() to scroll the screen
+// back. Incremented each time the screen scrolls a line.
+// msg_scrolled_ign true when msg_scrolled is non-zero and msg_puts_attr()
+// writes something without scrolling should not make
+// need_wait_return to be set. This is a hack to make ":ts"
+// work without an extra prompt.
+// lines_left Number of lines available for messages before the
+// more-prompt is to be given. -1 when not set.
+// need_wait_return true when the hit-return prompt is needed.
+// Reset: After giving the hit-return prompt, when the user
+// has answered some other prompt.
+// Set: When the ruler or typeahead display is overwritten,
+// scrolling the screen for some message.
+// keep_msg Message to be displayed after redrawing the screen, in
+// main_loop().
+// This is an allocated string or NULL when not used.
// Extended msg state, currently used for external UIs with ext_messages
static const char *msg_ext_kind = NULL;
@@ -313,11 +307,9 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline)
set_vim_var_string(VV_STATUSMSG, s, -1);
}
- /*
- * It is possible that displaying a messages causes a problem (e.g.,
- * when redrawing the window), which causes another message, etc.. To
- * break this loop, limit the recursiveness to 3 levels.
- */
+ // It is possible that displaying a messages causes a problem (e.g.,
+ // when redrawing the window), which causes another message, etc.. To
+ // break this loop, limit the recursiveness to 3 levels.
if (entered >= 3) {
return true;
}
@@ -329,7 +321,7 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline)
|| (*s != '<'
&& last_msg_hist != NULL
&& last_msg_hist->msg != NULL
- && STRCMP(s, last_msg_hist->msg))) {
+ && strcmp(s, last_msg_hist->msg))) {
add_msg_hist(s, -1, attr, multiline);
}
@@ -483,10 +475,8 @@ void trunc_string(char *s, char *buf, int room_in, int buflen)
}
}
-/*
- * Note: Caller of smsg() and smsg_attr() must check the resulting string is
- * shorter than IOSIZE!!!
- */
+// Note: Caller of smsg() and smsg_attr() must check the resulting string is
+// shorter than IOSIZE!!!
int smsg(const char *s, ...)
FUNC_ATTR_PRINTF(1, 2)
@@ -522,10 +512,8 @@ int smsg_attr_keep(int attr, const char *s, ...)
return msg_attr_keep((const char *)IObuff, attr, true, false);
}
-/*
- * Remember the last sourcing name/lnum used in an error message, so that it
- * isn't printed each time when it didn't change.
- */
+// Remember the last sourcing name/lnum used in an error message, so that it
+// isn't printed each time when it didn't change.
static int last_sourcing_lnum = 0;
static char *last_sourcing_name = NULL;
@@ -681,10 +669,8 @@ static bool emsg_multiline(const char *s, bool multiline)
// set "v:errmsg", also when using ":silent! cmd"
set_vim_var_string(VV_ERRMSG, s, -1);
- /*
- * When using ":silent! cmd" ignore error messages.
- * But do write it to the redirection file.
- */
+ // When using ":silent! cmd" ignore error messages.
+ // But do write it to the redirection file.
if (emsg_silent != 0) {
if (!emsg_noredir) {
msg_start();
@@ -992,7 +978,7 @@ static void add_msg_hist_multiattr(const char *s, int len, int attr, bool multil
while (len > 0 && s[len - 1] == '\n') {
len--;
}
- p->msg = (char_u *)xmemdupz(s, (size_t)len);
+ p->msg = xmemdupz(s, (size_t)len);
} else {
p->msg = NULL;
}
@@ -1042,7 +1028,7 @@ void ex_messages(void *const eap_p)
struct msg_hist *p;
int c = 0;
- if (STRCMP(eap->arg, "clear") == 0) {
+ if (strcmp(eap->arg, "clear") == 0) {
int keep = eap->addr_count == 0 ? 0 : eap->line2;
while (msg_hist_len > keep) {
@@ -1109,7 +1095,7 @@ void ex_messages(void *const eap_p)
if (kv_size(p->multiattr)) {
msg_multiattr(p->multiattr, p->kind, false);
} else if (p->msg != NULL) {
- msg_attr_keep((char *)p->msg, p->attr, false, p->multiline);
+ msg_attr_keep(p->msg, p->attr, false, p->multiline);
}
}
msg_hist_off = false;
@@ -1156,12 +1142,10 @@ void wait_return(int redraw)
return;
}
- /*
- * When inside vgetc(), we can't wait for a typed character at all.
- * With the global command (and some others) we only need one return at
- * the end. Adjust cmdline_row to avoid the next message overwriting the
- * last one.
- */
+ // When inside vgetc(), we can't wait for a typed character at all.
+ // With the global command (and some others) we only need one return at
+ // the end. Adjust cmdline_row to avoid the next message overwriting the
+ // last one.
if (vgetc_busy > 0) {
return;
}
@@ -1226,12 +1210,10 @@ void wait_return(int redraw)
reg_recording = save_reg_recording;
scriptout = save_scriptout;
- /*
- * Allow scrolling back in the messages.
- * Also accept scroll-down commands when messages fill the screen,
- * to avoid that typing one 'j' too many makes the messages
- * disappear.
- */
+ // Allow scrolling back in the messages.
+ // Also accept scroll-down commands when messages fill the screen,
+ // to avoid that typing one 'j' too many makes the messages
+ // disappear.
if (p_more) {
if (c == 'b' || c == 'k' || c == 'u' || c == 'g'
|| c == K_UP || c == K_PAGEUP) {
@@ -1268,9 +1250,7 @@ void wait_return(int redraw)
|| c == K_MOUSEDOWN || c == K_MOUSEUP
|| c == K_MOUSEMOVE);
os_breakcheck();
- /*
- * Avoid that the mouse-up event causes visual mode to start.
- */
+ // Avoid that the mouse-up event causes visual mode to start.
if (c == K_LEFTMOUSE || c == K_MIDDLEMOUSE || c == K_RIGHTMOUSE
|| c == K_X1MOUSE || c == K_X2MOUSE) {
(void)jump_to_mouse(MOUSE_SETPOS, NULL, 0);
@@ -1575,13 +1555,11 @@ int msg_outtrans_len_attr(const char *msgstr, int len, int attr)
msg_puts_attr(" ", attr);
}
- /*
- * Go over the string. Special characters are translated and printed.
- * Normal characters are printed several at a time.
- */
+ // Go over the string. Special characters are translated and printed.
+ // Normal characters are printed several at a time.
while (--len >= 0 && !got_int) {
// Don't include composing chars after the end.
- mb_l = utfc_ptr2len_len((char_u *)str, len + 1);
+ mb_l = utfc_ptr2len_len(str, len + 1);
if (mb_l > 1) {
c = utf_ptr2char(str);
if (vim_isprintc(c)) {
@@ -2219,7 +2197,7 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse)
if (has_last_char) {
if (maxlen >= 0) {
// Avoid including composing chars after the end.
- l = utfc_ptr2len_len((char_u *)s, (int)((str + maxlen) - s));
+ l = utfc_ptr2len_len(s, (int)((str + maxlen) - s));
} else {
l = utfc_ptr2len(s);
}
@@ -2250,10 +2228,8 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse)
cmdline_row--;
}
- /*
- * If screen is completely filled and 'more' is set then wait
- * for a character.
- */
+ // If screen is completely filled and 'more' is set then wait
+ // for a character.
if (lines_left > 0) {
lines_left--;
}
@@ -2316,7 +2292,7 @@ static void msg_puts_display(const char *str, int maxlen, int attr, int recurse)
cw = utf_ptr2cells(s);
if (maxlen >= 0) {
// avoid including composing chars after the end
- l = utfc_ptr2len_len((char_u *)s, (int)((str + maxlen) - s));
+ l = utfc_ptr2len_len(s, (int)((str + maxlen) - s));
} else {
l = utfc_ptr2len(s);
}
@@ -2374,7 +2350,7 @@ bool msg_use_msgsep(void)
{
// the full-screen scroll behavior doesn't really make sense with
// 'ext_multigrid'
- return ((dy_flags & DY_MSGSEP) || ui_has(kUIMultigrid));
+ return (dy_flags & DY_MSGSEP) || ui_has(kUIMultigrid);
}
bool msg_do_throttle(void)
@@ -2828,9 +2804,7 @@ static int do_more_prompt(int typed_char)
msg_moremsg(false);
}
for (;;) {
- /*
- * Get a typed character directly from the user.
- */
+ // Get a typed character directly from the user.
if (used_typed_char != NUL) {
c = used_typed_char; // was typed at hit-enter prompt
used_typed_char = NUL;
@@ -3170,12 +3144,10 @@ void msg_clr_cmdline(void)
/// @return true if wait_return() not called.
int msg_end(void)
{
- /*
- * If the string is larger than the window,
- * or the ruler option is set and we run into it,
- * we have to redraw the window.
- * Do not do this if we are abandoning the file or editing the command line.
- */
+ // If the string is larger than the window,
+ // or the ruler option is set and we run into it,
+ // we have to redraw the window.
+ // Do not do this if we are abandoning the file or editing the command line.
if (!exiting && need_wait_return && !(State & MODE_CMDLINE)) {
wait_return(false);
return false;
@@ -3545,10 +3517,8 @@ int do_dialog(int type, char *title, char *message, char *buttons, int dfltbutto
State = MODE_CONFIRM;
setmouse();
- /*
- * Since we wait for a keypress, don't make the
- * user press RETURN as well afterwards.
- */
+ // Since we wait for a keypress, don't make the
+ // user press RETURN as well afterwards.
no_wait_return++;
hotkeys = msg_show_console_dialog(message, buttons, dfltbutton);
diff --git a/src/nvim/message.h b/src/nvim/message.h
index 2de2890213..811e621c11 100644
--- a/src/nvim/message.h
+++ b/src/nvim/message.h
@@ -11,9 +11,7 @@
#include "nvim/macros.h"
#include "nvim/types.h"
-/*
- * Types of dialogs passed to do_dialog().
- */
+// Types of dialogs passed to do_dialog().
#define VIM_GENERIC 0
#define VIM_ERROR 1
#define VIM_WARNING 2
@@ -21,9 +19,7 @@
#define VIM_QUESTION 4
#define VIM_LAST_TYPE 4 // sentinel value
-/*
- * Return values for functions like vim_dialogyesno()
- */
+// Return values for functions like vim_dialogyesno()
#define VIM_YES 2
#define VIM_NO 3
#define VIM_CANCEL 4
@@ -40,7 +36,7 @@ typedef kvec_t(HlMessageChunk) HlMessage;
/// Message history for `:messages`
typedef struct msg_hist {
struct msg_hist *next; ///< Next message.
- char_u *msg; ///< Message text.
+ char *msg; ///< Message text.
const char *kind; ///< Message kind (for msg_ext)
int attr; ///< Message highlighting.
bool multiline; ///< Multiline message.
diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c
index 90084bde17..7b267d6ce4 100644
--- a/src/nvim/mouse.c
+++ b/src/nvim/mouse.c
@@ -631,7 +631,7 @@ colnr_T vcol2col(win_T *const wp, const linenr_T lnum, const colnr_T vcol)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
// try to advance to the specified column
- char_u *line = ml_get_buf(wp->w_buffer, lnum, false);
+ char_u *line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
chartabsize_T cts;
init_chartabsize_arg(&cts, wp, lnum, 0, (char *)line, (char *)line);
while (cts.cts_vcol < vcol && *cts.cts_ptr != NUL) {
diff --git a/src/nvim/move.c b/src/nvim/move.c
index b3ec3a8e7a..481746881b 100644
--- a/src/nvim/move.c
+++ b/src/nvim/move.c
@@ -1,16 +1,14 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * move.c: Functions for moving the cursor and scrolling text.
- *
- * There are two ways to move the cursor:
- * 1. Move the cursor directly, the text is scrolled to keep the cursor in the
- * window.
- * 2. Scroll the text, the cursor is moved into the text visible in the
- * window.
- * The 'scrolloff' option makes this a bit complicated.
- */
+// move.c: Functions for moving the cursor and scrolling text.
+//
+// There are two ways to move the cursor:
+// 1. Move the cursor directly, the text is scrolled to keep the cursor in the
+// window.
+// 2. Scroll the text, the cursor is moved into the text visible in the
+// window.
+// The 'scrolloff' option makes this a bit complicated.
#include <assert.h>
#include <inttypes.h>
@@ -23,12 +21,15 @@
#include "nvim/diff.h"
#include "nvim/drawscreen.h"
#include "nvim/edit.h"
+#include "nvim/eval.h"
+#include "nvim/eval/typval.h"
#include "nvim/fold.h"
#include "nvim/getchar.h"
#include "nvim/grid.h"
#include "nvim/highlight.h"
#include "nvim/mbyte.h"
#include "nvim/memline.h"
+#include "nvim/mouse.h"
#include "nvim/move.h"
#include "nvim/option.h"
#include "nvim/plines.h"
@@ -47,19 +48,15 @@ typedef struct {
# include "move.c.generated.h"
#endif
-/*
- * Compute wp->w_botline for the current wp->w_topline. Can be called after
- * wp->w_topline changed.
- */
+// Compute wp->w_botline for the current wp->w_topline. Can be called after
+// wp->w_topline changed.
static void comp_botline(win_T *wp)
{
linenr_T lnum;
int done;
- /*
- * If w_cline_row is valid, start there.
- * Otherwise have to start at w_topline.
- */
+ // If w_cline_row is valid, start there.
+ // Otherwise have to start at w_topline.
check_cursor_moved(wp);
if (wp->w_valid & VALID_CROW) {
lnum = wp->w_cursor.lnum;
@@ -133,10 +130,8 @@ static void redraw_for_cursorcolumn(win_T *wp)
}
}
-/*
- * Update curwin->w_topline and redraw if necessary.
- * Used to update the screen before printing a message.
- */
+// Update curwin->w_topline and redraw if necessary.
+// Used to update the screen before printing a message.
void update_topline_redraw(void)
{
update_topline(curwin);
@@ -145,9 +140,7 @@ void update_topline_redraw(void)
}
}
-/*
- * Update curwin->w_topline to move the cursor onto the screen.
- */
+// Update curwin->w_topline to move the cursor onto the screen.
void update_topline(win_T *wp)
{
linenr_T old_topline;
@@ -250,14 +243,12 @@ void update_topline(win_T *wp)
}
}
- /*
- * If the cursor is below the bottom of the window, scroll the window
- * to put the cursor on the window.
- * When w_botline is invalid, recompute it first, to avoid a redraw later.
- * If w_botline was approximated, we might need a redraw later in a few
- * cases, but we don't want to spend (a lot of) time recomputing w_botline
- * for every small change.
- */
+ // If the cursor is below the bottom of the window, scroll the window
+ // to put the cursor on the window.
+ // When w_botline is invalid, recompute it first, to avoid a redraw later.
+ // If w_botline was approximated, we might need a redraw later in a few
+ // cases, but we don't want to spend (a lot of) time recomputing w_botline
+ // for every small change.
if (check_botline) {
if (!(wp->w_valid & VALID_BOTLINE_AP)) {
validate_botline(wp);
@@ -328,9 +319,7 @@ void update_topline(win_T *wp)
wp->w_viewport_invalid = true;
win_check_anchored_floats(wp);
- /*
- * Need to redraw when topline changed.
- */
+ // Need to redraw when topline changed.
if (wp->w_topline != old_topline
|| wp->w_topfill != old_topfill) {
dollar_vcol = -1;
@@ -349,9 +338,7 @@ void update_topline(win_T *wp)
*so_ptr = save_so;
}
-/*
- * Update win->w_topline to move the cursor onto the screen.
- */
+// Update win->w_topline to move the cursor onto the screen.
void update_topline_win(win_T *win)
{
switchwin_T switchwin;
@@ -360,11 +347,9 @@ void update_topline_win(win_T *win)
restore_win(&switchwin, true);
}
-/*
- * Return the scrolljump value to use for the current window.
- * When 'scrolljump' is positive use it as-is.
- * When 'scrolljump' is negative use it as a percentage of the window height.
- */
+// Return the scrolljump value to use for the current window.
+// When 'scrolljump' is positive use it as-is.
+// When 'scrolljump' is negative use it as a percentage of the window height.
static int scrolljump_value(void)
{
long result = p_sj >= 0 ? p_sj : (curwin->w_height_inner * -p_sj) / 100;
@@ -372,10 +357,8 @@ static int scrolljump_value(void)
return (int)result;
}
-/*
- * Return true when there are not 'scrolloff' lines above the cursor for the
- * current window.
- */
+// Return true when there are not 'scrolloff' lines above the cursor for the
+// current window.
static bool check_top_offset(void)
{
long so = get_scrolloff_value(curwin);
@@ -412,9 +395,7 @@ void update_curswant(void)
}
}
-/*
- * Check if the cursor has moved. Set the w_valid flag accordingly.
- */
+// Check if the cursor has moved. Set the w_valid flag accordingly.
void check_cursor_moved(win_T *wp)
{
if (wp->w_cursor.lnum != wp->w_valid_cursor.lnum) {
@@ -435,11 +416,9 @@ void check_cursor_moved(win_T *wp)
}
}
-/*
- * Call this function when some window settings have changed, which require
- * the cursor position, botline and topline to be recomputed and the window to
- * be redrawn. E.g, when changing the 'wrap' option or folding.
- */
+// Call this function when some window settings have changed, which require
+// the cursor position, botline and topline to be recomputed and the window to
+// be redrawn. E.g, when changing the 'wrap' option or folding.
void changed_window_setting(void)
{
changed_window_setting_win(curwin);
@@ -453,9 +432,7 @@ void changed_window_setting_win(win_T *wp)
redraw_later(wp, UPD_NOT_VALID);
}
-/*
- * Set wp->w_topline to a certain number.
- */
+// Set wp->w_topline to a certain number.
void set_topline(win_T *wp, linenr_T lnum)
{
linenr_T prev_topline = wp->w_topline;
@@ -475,11 +452,9 @@ void set_topline(win_T *wp, linenr_T lnum)
redraw_later(wp, UPD_VALID);
}
-/*
- * Call this function when the length of the cursor line (in screen
- * characters) has changed, and the change is before the cursor.
- * Need to take care of w_botline separately!
- */
+// Call this function when the length of the cursor line (in screen
+// characters) has changed, and the change is before the cursor.
+// Need to take care of w_botline separately!
void changed_cline_bef_curs(void)
{
curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL
@@ -492,11 +467,9 @@ void changed_cline_bef_curs_win(win_T *wp)
|VALID_CHEIGHT|VALID_TOPLINE);
}
-/*
- * Call this function when the length of a line (in screen characters) above
- * the cursor have changed.
- * Need to take care of w_botline separately!
- */
+// Call this function when the length of a line (in screen characters) above
+// the cursor have changed.
+// Need to take care of w_botline separately!
void changed_line_abv_curs(void)
{
curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL|VALID_CROW
@@ -509,9 +482,7 @@ void changed_line_abv_curs_win(win_T *wp)
|VALID_CHEIGHT|VALID_TOPLINE);
}
-/*
- * Make sure the value of curwin->w_botline is valid.
- */
+// Make sure the value of curwin->w_botline is valid.
void validate_botline(win_T *wp)
{
if (!(wp->w_valid & VALID_BOTLINE)) {
@@ -519,9 +490,7 @@ void validate_botline(win_T *wp)
}
}
-/*
- * Mark curwin->w_botline as invalid (because of some change in the buffer).
- */
+// Mark curwin->w_botline as invalid (because of some change in the buffer).
void invalidate_botline(void)
{
curwin->w_valid &= ~(VALID_BOTLINE|VALID_BOTLINE_AP);
@@ -537,9 +506,7 @@ void approximate_botline_win(win_T *wp)
wp->w_valid &= ~VALID_BOTLINE;
}
-/*
- * Return true if curwin->w_wrow and curwin->w_wcol are valid.
- */
+// Return true if curwin->w_wrow and curwin->w_wcol are valid.
int cursor_valid(void)
{
check_cursor_moved(curwin);
@@ -547,10 +514,8 @@ int cursor_valid(void)
(VALID_WROW|VALID_WCOL);
}
-/*
- * Validate cursor position. Makes sure w_wrow and w_wcol are valid.
- * w_topline must be valid, you may need to call update_topline() first!
- */
+// Validate cursor position. Makes sure w_wrow and w_wcol are valid.
+// w_topline must be valid, you may need to call update_topline() first!
void validate_cursor(void)
{
check_cursor_moved(curwin);
@@ -559,10 +524,8 @@ void validate_cursor(void)
}
}
-/*
- * Compute wp->w_cline_row and wp->w_cline_height, based on the current value
- * of wp->w_topline.
- */
+// Compute wp->w_cline_row and wp->w_cline_height, based on the current value
+// of wp->w_topline.
static void curs_rows(win_T *wp)
{
// Check if wp->w_lines[].wl_size is invalid
@@ -633,17 +596,13 @@ static void curs_rows(win_T *wp)
wp->w_valid |= VALID_CROW|VALID_CHEIGHT;
}
-/*
- * Validate curwin->w_virtcol only.
- */
+// Validate curwin->w_virtcol only.
void validate_virtcol(void)
{
validate_virtcol_win(curwin);
}
-/*
- * Validate wp->w_virtcol only.
- */
+// Validate wp->w_virtcol only.
void validate_virtcol_win(win_T *wp)
{
check_cursor_moved(wp);
@@ -654,9 +613,7 @@ void validate_virtcol_win(win_T *wp)
}
}
-/*
- * Validate curwin->w_cline_height only.
- */
+// Validate curwin->w_cline_height only.
void validate_cheight(void)
{
check_cursor_moved(curwin);
@@ -668,9 +625,7 @@ void validate_cheight(void)
}
}
-/*
- * Validate w_wcol and w_virtcol only.
- */
+// Validate w_wcol and w_virtcol only.
void validate_cursor_col(void)
{
validate_virtcol();
@@ -697,10 +652,8 @@ void validate_cursor_col(void)
}
}
-/*
- * Compute offset of a window, occupied by absolute or relative line number,
- * fold column and sign column (these don't move when scrolling horizontally).
- */
+// Compute offset of a window, occupied by absolute or relative line number,
+// fold column and sign column (these don't move when scrolling horizontally).
int win_col_off(win_T *wp)
{
return ((wp->w_p_nu || wp->w_p_rnu) ? number_width(wp) + 1 : 0)
@@ -714,11 +667,9 @@ int curwin_col_off(void)
return win_col_off(curwin);
}
-/*
- * Return the difference in column offset for the second screen line of a
- * wrapped line. It's 8 if 'number' or 'relativenumber' is on and 'n' is in
- * 'cpoptions'.
- */
+// Return the difference in column offset for the second screen line of a
+// wrapped line. It's 8 if 'number' or 'relativenumber' is on and 'n' is in
+// 'cpoptions'.
int win_col_off2(win_T *wp)
{
if ((wp->w_p_nu || wp->w_p_rnu) && vim_strchr(p_cpo, CPO_NUMCOL) != NULL) {
@@ -746,9 +697,7 @@ void curs_columns(win_T *wp, int may_scroll)
long so = get_scrolloff_value(wp);
long siso = get_sidescrolloff_value(wp);
- /*
- * First make sure that w_topline is valid (after moving the cursor).
- */
+ // First make sure that w_topline is valid (after moving the cursor).
update_topline(wp);
// Next make sure that w_cline_row is valid.
@@ -756,9 +705,7 @@ void curs_columns(win_T *wp, int may_scroll)
curs_rows(wp);
}
- /*
- * Compute the number of virtual columns.
- */
+ // Compute the number of virtual columns.
if (wp->w_cline_folded) {
// In a folded line the cursor is always in the first column
startcol = wp->w_virtcol = endcol = wp->w_leftcol;
@@ -1033,6 +980,62 @@ void textpos2screenpos(win_T *wp, pos_T *pos, int *rowp, int *scolp, int *ccolp,
*ecolp = ecol + coloff;
}
+/// "screenpos({winid}, {lnum}, {col})" function
+void f_screenpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
+{
+ tv_dict_alloc_ret(rettv);
+ dict_T *dict = rettv->vval.v_dict;
+
+ win_T *wp = find_win_by_nr_or_id(&argvars[0]);
+ if (wp == NULL) {
+ return;
+ }
+
+ pos_T pos = {
+ .lnum = (linenr_T)tv_get_number(&argvars[1]),
+ .col = (colnr_T)tv_get_number(&argvars[2]) - 1,
+ .coladd = 0
+ };
+ int row = 0;
+ int scol = 0, ccol = 0, ecol = 0;
+ textpos2screenpos(wp, &pos, &row, &scol, &ccol, &ecol, false);
+
+ tv_dict_add_nr(dict, S_LEN("row"), row);
+ tv_dict_add_nr(dict, S_LEN("col"), scol);
+ tv_dict_add_nr(dict, S_LEN("curscol"), ccol);
+ tv_dict_add_nr(dict, S_LEN("endcol"), ecol);
+}
+
+/// "virtcol2col({winid}, {lnum}, {col})" function
+void f_virtcol2col(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
+{
+ rettv->vval.v_number = -1;
+
+ if (tv_check_for_number_arg(argvars, 0) == FAIL
+ || tv_check_for_number_arg(argvars, 1) == FAIL
+ || tv_check_for_number_arg(argvars, 2) == FAIL) {
+ return;
+ }
+
+ win_T *wp = find_win_by_nr_or_id(&argvars[0]);
+ if (wp == NULL) {
+ return;
+ }
+
+ bool error = false;
+ linenr_T lnum = (linenr_T)tv_get_number_chk(&argvars[1], &error);
+ if (error || lnum < 0 || lnum > wp->w_buffer->b_ml.ml_line_count) {
+ return;
+ }
+
+ int screencol = (int)tv_get_number_chk(&argvars[2], &error);
+ if (error || screencol < 0) {
+ return;
+ }
+
+ rettv->vval.v_number = vcol2col(wp, lnum, screencol);
+}
+
/// Scroll the current window down by "line_count" logical lines. "CTRL-Y"
///
/// @param line_count number of lines to scroll
@@ -1079,10 +1082,8 @@ bool scrolldown(long line_count, int byfold)
}
check_topfill(curwin, true);
- /*
- * Compute the row number of the last row of the cursor line
- * and move the cursor onto the displayed part of the window.
- */
+ // Compute the row number of the last row of the cursor line
+ // and move the cursor onto the displayed part of the window.
int wrow = curwin->w_wrow;
if (curwin->w_p_wrap && curwin->w_width_inner != 0) {
validate_virtcol();
@@ -1200,10 +1201,8 @@ void check_topfill(win_T *wp, bool down)
win_check_anchored_floats(curwin);
}
-/*
- * Use as many filler lines as possible for w_topline. Make sure w_topline
- * is still visible.
- */
+// Use as many filler lines as possible for w_topline. Make sure w_topline
+// is still visible.
static void max_topfill(void)
{
int n = plines_win_nofill(curwin, curwin->w_topline, true);
@@ -1217,10 +1216,8 @@ static void max_topfill(void)
}
}
-/*
- * Scroll the screen one line down, but don't do it if it would move the
- * cursor off the screen.
- */
+// Scroll the screen one line down, but don't do it if it would move the
+// cursor off the screen.
void scrolldown_clamp(void)
{
int can_fill = (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline));
@@ -1261,10 +1258,8 @@ void scrolldown_clamp(void)
}
}
-/*
- * Scroll the screen one line up, but don't do it if it would move the cursor
- * off the screen.
- */
+// Scroll the screen one line up, but don't do it if it would move the cursor
+// off the screen.
void scrollup_clamp(void)
{
if (curwin->w_topline == curbuf->b_ml.ml_line_count
@@ -1296,12 +1291,10 @@ void scrollup_clamp(void)
}
}
-/*
- * Add one line above "lp->lnum". This can be a filler line, a closed fold or
- * a (wrapped) text line. Uses and sets "lp->fill".
- * Returns the height of the added line in "lp->height".
- * Lines above the first one are incredibly high: MAXCOL.
- */
+// Add one line above "lp->lnum". This can be a filler line, a closed fold or
+// a (wrapped) text line. Uses and sets "lp->fill".
+// Returns the height of the added line in "lp->height".
+// Lines above the first one are incredibly high: MAXCOL.
static void topline_back(win_T *wp, lineoff_T *lp)
{
if (lp->fill < win_get_fill(wp, lp->lnum)) {
@@ -1322,12 +1315,10 @@ static void topline_back(win_T *wp, lineoff_T *lp)
}
}
-/*
- * Add one line below "lp->lnum". This can be a filler line, a closed fold or
- * a (wrapped) text line. Uses and sets "lp->fill".
- * Returns the height of the added line in "lp->height".
- * Lines below the last one are incredibly high.
- */
+// Add one line below "lp->lnum". This can be a filler line, a closed fold or
+// a (wrapped) text line. Uses and sets "lp->fill".
+// Returns the height of the added line in "lp->height".
+// Lines below the last one are incredibly high.
static void botline_forw(win_T *wp, lineoff_T *lp)
{
if (lp->fill < win_get_fill(wp, lp->lnum + 1)) {
@@ -1349,11 +1340,9 @@ static void botline_forw(win_T *wp, lineoff_T *lp)
}
}
-/*
- * Switch from including filler lines below lp->lnum to including filler
- * lines above loff.lnum + 1. This keeps pointing to the same line.
- * When there are no filler lines nothing changes.
- */
+// Switch from including filler lines below lp->lnum to including filler
+// lines above loff.lnum + 1. This keeps pointing to the same line.
+// When there are no filler lines nothing changes.
static void botline_topline(lineoff_T *lp)
{
if (lp->fill > 0) {
@@ -1362,11 +1351,9 @@ static void botline_topline(lineoff_T *lp)
}
}
-/*
- * Switch from including filler lines above lp->lnum to including filler
- * lines below loff.lnum - 1. This keeps pointing to the same line.
- * When there are no filler lines nothing changes.
- */
+// Switch from including filler lines above lp->lnum to including filler
+// lines below loff.lnum - 1. This keeps pointing to the same line.
+// When there are no filler lines nothing changes.
static void topline_botline(lineoff_T *lp)
{
if (lp->fill > 0) {
@@ -1375,11 +1362,9 @@ static void topline_botline(lineoff_T *lp)
}
}
-/*
- * Recompute topline to put the cursor at the top of the window.
- * Scroll at least "min_scroll" lines.
- * If "always" is true, always set topline (for "zt").
- */
+// Recompute topline to put the cursor at the top of the window.
+// Scroll at least "min_scroll" lines.
+// If "always" is true, always set topline (for "zt").
void scroll_cursor_top(int min_scroll, int always)
{
int scrolled = 0;
@@ -1394,13 +1379,11 @@ void scroll_cursor_top(int min_scroll, int always)
off = mouse_dragging - 1;
}
- /*
- * Decrease topline until:
- * - it has become 1
- * - (part of) the cursor line is moved off the screen or
- * - moved at least 'scrolljump' lines and
- * - at least 'scrolloff' lines above and below the cursor
- */
+ // Decrease topline until:
+ // - it has become 1
+ // - (part of) the cursor line is moved off the screen or
+ // - moved at least 'scrolljump' lines and
+ // - at least 'scrolloff' lines above and below the cursor
validate_cheight();
int used = curwin->w_cline_height; // includes filler lines above
if (curwin->w_cursor.lnum < curwin->w_topline) {
@@ -1421,10 +1404,8 @@ void scroll_cursor_top(int min_scroll, int always)
// Hide filler lines above cursor line by adding them to "extra".
int extra = win_get_fill(curwin, curwin->w_cursor.lnum);
- /*
- * Check if the lines from "top" to "bot" fit in the window. If they do,
- * set new_topline and advance "top" and "bot" to include more lines.
- */
+ // Check if the lines from "top" to "bot" fit in the window. If they do,
+ // set new_topline and advance "top" and "bot" to include more lines.
while (top > 0) {
int i = hasFolding(top, &top, NULL)
? 1 // count one logical line for a sequence of folded lines
@@ -1445,9 +1426,7 @@ void scroll_cursor_top(int min_scroll, int always)
scrolled += i;
}
- /*
- * If scrolling is needed, scroll at least 'sj' lines.
- */
+ // If scrolling is needed, scroll at least 'sj' lines.
if ((new_topline >= curwin->w_topline || scrolled > min_scroll)
&& extra >= off) {
break;
@@ -1459,18 +1438,14 @@ void scroll_cursor_top(int min_scroll, int always)
bot++;
}
- /*
- * If we don't have enough space, put cursor in the middle.
- * This makes sure we get the same position when using "k" and "j"
- * in a small window.
- */
+ // If we don't have enough space, put cursor in the middle.
+ // This makes sure we get the same position when using "k" and "j"
+ // in a small window.
if (used > curwin->w_height_inner) {
scroll_cursor_halfway(false);
} else {
- /*
- * If "always" is false, only adjust topline to a lower value, higher
- * value may happen with wrapping lines
- */
+ // If "always" is false, only adjust topline to a lower value, higher
+ // value may happen with wrapping lines
if (new_topline < curwin->w_topline || always) {
curwin->w_topline = new_topline;
}
@@ -1495,10 +1470,8 @@ void scroll_cursor_top(int min_scroll, int always)
}
}
-/*
- * Set w_empty_rows and w_filler_rows for window "wp", having used up "used"
- * screen lines for text lines.
- */
+// Set w_empty_rows and w_filler_rows for window "wp", having used up "used"
+// screen lines for text lines.
void set_empty_rows(win_T *wp, int used)
{
wp->w_filler_rows = 0;
@@ -1577,13 +1550,11 @@ void scroll_cursor_bot(int min_scroll, int set_topbot)
}
}
- /*
- * Stop counting lines to scroll when
- * - hitting start of the file
- * - scrolled nothing or at least 'sj' lines
- * - at least 'so' lines below the cursor
- * - lines between botline and cursor have been counted
- */
+ // Stop counting lines to scroll when
+ // - hitting start of the file
+ // - scrolled nothing or at least 'sj' lines
+ // - at least 'so' lines below the cursor
+ // - lines between botline and cursor have been counted
if (!hasFolding(curwin->w_cursor.lnum, &loff.lnum, &boff.lnum)) {
loff.lnum = cln;
boff.lnum = cln;
@@ -1673,21 +1644,17 @@ void scroll_cursor_bot(int min_scroll, int set_topbot)
}
}
- /*
- * Scroll up if the cursor is off the bottom of the screen a bit.
- * Otherwise put it at 1/2 of the screen.
- */
+ // Scroll up if the cursor is off the bottom of the screen a bit.
+ // Otherwise put it at 1/2 of the screen.
if (line_count >= curwin->w_height_inner && line_count > min_scroll) {
scroll_cursor_halfway(false);
} else {
scrollup(line_count, true);
}
- /*
- * If topline didn't change we need to restore w_botline and w_empty_rows
- * (we changed them).
- * If topline did change, update_screen() will set botline.
- */
+ // If topline didn't change we need to restore w_botline and w_empty_rows
+ // (we changed them).
+ // If topline did change, update_screen() will set botline.
if (curwin->w_topline == old_topline && set_topbot) {
curwin->w_botline = old_botline;
curwin->w_empty_rows = old_empty_rows;
@@ -1760,18 +1727,14 @@ void scroll_cursor_halfway(int atend)
curwin->w_valid |= VALID_TOPLINE;
}
-/*
- * Correct the cursor position so that it is in a part of the screen at least
- * 'so' lines from the top and bottom, if possible.
- * If not possible, put it at the same position as scroll_cursor_halfway().
- * When called topline must be valid!
- */
+// Correct the cursor position so that it is in a part of the screen at least
+// 'so' lines from the top and bottom, if possible.
+// If not possible, put it at the same position as scroll_cursor_halfway().
+// When called topline must be valid!
void cursor_correct(void)
{
- /*
- * How many lines we would like to have above/below the cursor depends on
- * whether the first/last line of the file is on screen.
- */
+ // How many lines we would like to have above/below the cursor depends on
+ // whether the first/last line of the file is on screen.
int above_wanted = (int)get_scrolloff_value(curwin);
int below_wanted = (int)get_scrolloff_value(curwin);
if (mouse_dragging > 0) {
@@ -1795,10 +1758,8 @@ void cursor_correct(void)
}
}
- /*
- * If there are sufficient file-lines above and below the cursor, we can
- * return now.
- */
+ // If there are sufficient file-lines above and below the cursor, we can
+ // return now.
linenr_T cln = curwin->w_cursor.lnum; // Cursor Line Number
if (cln >= curwin->w_topline + above_wanted
&& cln < curwin->w_botline - below_wanted
@@ -1806,12 +1767,10 @@ void cursor_correct(void)
return;
}
- /*
- * Narrow down the area where the cursor can be put by taking lines from
- * the top and the bottom until:
- * - the desired context lines are found
- * - the lines from the top is past the lines from the bottom
- */
+ // Narrow down the area where the cursor can be put by taking lines from
+ // the top and the bottom until:
+ // - the desired context lines are found
+ // - the lines from the top is past the lines from the bottom
linenr_T topline = curwin->w_topline;
linenr_T botline = curwin->w_botline - 1;
// count filler lines as context
@@ -1860,11 +1819,9 @@ void cursor_correct(void)
curwin->w_viewport_invalid = true;
}
-/*
- * move screen 'count' pages up or down and update screen
- *
- * return FAIL for failure, OK otherwise
- */
+// move screen 'count' pages up or down and update screen
+//
+// return FAIL for failure, OK otherwise
int onepage(Direction dir, long count)
{
long n;
@@ -2044,18 +2001,16 @@ int onepage(Direction dir, long count)
return retval;
}
-/*
- * Decide how much overlap to use for page-up or page-down scrolling.
- * This is symmetric, so that doing both keeps the same lines displayed.
- * Three lines are examined:
- *
- * before CTRL-F after CTRL-F / before CTRL-B
- * etc. l1
- * l1 last but one line ------------
- * l2 last text line l2 top text line
- * ------------- l3 second text line
- * l3 etc.
- */
+// Decide how much overlap to use for page-up or page-down scrolling.
+// This is symmetric, so that doing both keeps the same lines displayed.
+// Three lines are examined:
+//
+// before CTRL-F after CTRL-F / before CTRL-B
+// etc. l1
+// l1 last but one line ------------
+// l2 last text line l2 top text line
+// ------------- l3 second text line
+// l3 etc.
static void get_scroll_overlap(lineoff_T *lp, int dir)
{
int min_height = curwin->w_height_inner - 2;
@@ -2125,9 +2080,7 @@ void halfpage(bool flag, linenr_T Prenum)
validate_botline(curwin);
int room = curwin->w_empty_rows + curwin->w_filler_rows;
if (flag) {
- /*
- * scroll the text up
- */
+ // scroll the text up
while (n > 0 && curwin->w_botline <= curbuf->b_ml.ml_line_count) {
if (curwin->w_topfill > 0) {
i = 1;
@@ -2185,9 +2138,7 @@ void halfpage(bool flag, linenr_T Prenum)
check_cursor_lnum();
}
} else {
- /*
- * scroll the text down
- */
+ // scroll the text down
while (n > 0 && curwin->w_topline > 1) {
if (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline)) {
i = 1;
@@ -2247,9 +2198,7 @@ void do_check_cursorbind(void)
int old_VIsual_select = VIsual_select;
int old_VIsual_active = VIsual_active;
- /*
- * loop through the cursorbound windows
- */
+ // loop through the cursorbound windows
VIsual_select = VIsual_active = 0;
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
curwin = wp;
@@ -2294,9 +2243,7 @@ void do_check_cursorbind(void)
}
}
- /*
- * reset current-window
- */
+ // reset current-window
VIsual_select = old_VIsual_select;
VIsual_active = old_VIsual_active;
curwin = old_curwin;
diff --git a/src/nvim/normal.c b/src/nvim/normal.c
index 17b79e27c1..326469bd38 100644
--- a/src/nvim/normal.c
+++ b/src/nvim/normal.c
@@ -629,18 +629,18 @@ 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 *kmsg;
- kmsg = (char_u *)keep_msg;
+ kmsg = keep_msg;
keep_msg = NULL;
// Showmode() will clear keep_msg, but we want to use it anyway.
// First update w_topline.
setcursor();
update_screen(0);
// now reset it, otherwise it's put in the history again
- keep_msg = (char *)kmsg;
+ keep_msg = kmsg;
- kmsg = vim_strsave((char_u *)keep_msg);
+ kmsg = xstrdup(keep_msg);
msg_attr((const char *)kmsg, keep_msg_attr);
xfree(kmsg);
}
@@ -1807,7 +1807,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent)
return false;
}
jump_flags = 0;
- if (STRCMP(p_mousem, "popup_setpos") == 0) {
+ if (strcmp(p_mousem, "popup_setpos") == 0) {
// First set the cursor position before showing the popup
// menu.
if (VIsual_active) {
@@ -2180,7 +2180,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent)
find_start_of_word(&VIsual);
if (*p_sel == 'e' && *get_cursor_pos_ptr() != NUL) {
curwin->w_cursor.col +=
- utfc_ptr2len((char *)get_cursor_pos_ptr());
+ utfc_ptr2len(get_cursor_pos_ptr());
}
find_end_of_word(&curwin->w_cursor);
}
@@ -2416,7 +2416,7 @@ size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text
// if i == 0: try to find an identifier
// if i == 1: try to find any non-white text
- char_u *ptr = ml_get_buf(wp->w_buffer, lnum, false);
+ char_u *ptr = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
for (i = (find_type & FIND_IDENT) ? 0 : 1; i < 2; i++) {
// 1. skip to start of identifier/text
col = startcol;
@@ -2675,9 +2675,9 @@ void clear_showcmd(void)
if (cursor_bot) {
s = ml_get_pos(&VIsual);
- e = get_cursor_pos_ptr();
+ e = (char_u *)get_cursor_pos_ptr();
} else {
- s = get_cursor_pos_ptr();
+ s = (char_u *)get_cursor_pos_ptr();
e = ml_get_pos(&VIsual);
}
while ((*p_sel != 'e') ? s <= e : s < e) {
@@ -3134,7 +3134,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_
} else {
par_pos = curwin->w_cursor;
while (curwin->w_cursor.lnum > 1
- && *skipwhite((char *)get_cursor_line_ptr()) != NUL) {
+ && *skipwhite(get_cursor_line_ptr()) != NUL) {
curwin->w_cursor.lnum--;
}
}
@@ -3171,13 +3171,13 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_
}
break;
}
- if (get_leader_len((char *)get_cursor_line_ptr(), NULL, false, true) > 0) {
+ if (get_leader_len(get_cursor_line_ptr(), NULL, false, true) > 0) {
// Ignore this line, continue at start of next line.
curwin->w_cursor.lnum++;
curwin->w_cursor.col = 0;
continue;
}
- bool valid = is_ident(get_cursor_line_ptr(), curwin->w_cursor.col);
+ bool valid = is_ident((char_u *)get_cursor_line_ptr(), curwin->w_cursor.col);
// If the current position is not a valid identifier and a previous match is
// present, favor that one instead.
@@ -3232,7 +3232,7 @@ bool find_decl(char_u *ptr, size_t len, bool locally, bool thisblock, int flags_
/// @return true if able to move cursor, false otherwise.
static bool nv_screengo(oparg_T *oap, int dir, long dist)
{
- int linelen = linetabsize(get_cursor_line_ptr());
+ int linelen = linetabsize((char_u *)get_cursor_line_ptr());
bool retval = true;
bool atend = false;
int n;
@@ -3303,7 +3303,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist)
}
curwin->w_cursor.lnum--;
- linelen = linetabsize(get_cursor_line_ptr());
+ linelen = linetabsize((char_u *)get_cursor_line_ptr());
if (linelen > width1) {
int w = (((linelen - width1 - 1) / width2) + 1) * width2;
assert(curwin->w_curswant <= INT_MAX - w);
@@ -3339,7 +3339,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist)
if (curwin->w_curswant >= width1) {
curwin->w_curswant -= width2;
}
- linelen = linetabsize(get_cursor_line_ptr());
+ linelen = linetabsize((char_u *)get_cursor_line_ptr());
}
}
}
@@ -3361,7 +3361,7 @@ static bool nv_screengo(oparg_T *oap, int dir, long dist)
virtcol -= vim_strsize((char *)get_showbreak_value(curwin));
}
- int c = utf_ptr2char((char *)get_cursor_pos_ptr());
+ int c = utf_ptr2char(get_cursor_pos_ptr());
if (dir == FORWARD && virtcol < curwin->w_curswant
&& (curwin->w_curswant <= (colnr_T)width1)
&& !vim_isprintc(c) && c > 255) {
@@ -4164,7 +4164,7 @@ void do_nv_ident(int c1, int c2)
/// 'K' normal-mode command. Get the command to lookup the keyword under the
/// cursor.
-static size_t nv_K_getcmd(cmdarg_T *cap, char_u *kp, bool kp_help, bool kp_ex, char **ptr_arg,
+static size_t nv_K_getcmd(cmdarg_T *cap, char *kp, bool kp_help, bool kp_ex, char **ptr_arg,
size_t n, char *buf, size_t buf_size)
{
if (kp_help) {
@@ -4201,8 +4201,8 @@ static size_t nv_K_getcmd(cmdarg_T *cap, char_u *kp, bool kp_help, bool kp_ex, c
// When a count is given, turn it into a range. Is this
// really what we want?
- bool isman = (STRCMP(kp, "man") == 0);
- bool isman_s = (STRCMP(kp, "man -s") == 0);
+ bool isman = (strcmp(kp, "man") == 0);
+ bool isman_s = (strcmp(kp, "man -s") == 0);
if (cap->count0 != 0 && !(isman || isman_s)) {
snprintf(buf, buf_size, ".,.+%" PRId64, (int64_t)(cap->count0 - 1));
}
@@ -4234,12 +4234,12 @@ static size_t nv_K_getcmd(cmdarg_T *cap, char_u *kp, bool kp_help, bool kp_ex, c
static void nv_ident(cmdarg_T *cap)
{
char *ptr = NULL;
- char_u *p;
+ char *p;
size_t n = 0; // init for GCC
int cmdchar;
bool g_cmd; // "g" command
bool tag_cmd = false;
- char_u *aux_ptr;
+ char *aux_ptr;
if (cap->cmdchar == 'g') { // "g*", "g#", "g]" and "gCTRL-]"
cmdchar = cap->nchar;
@@ -4275,8 +4275,8 @@ static void nv_ident(cmdarg_T *cap)
// Allocate buffer to put the command in. Inserting backslashes can
// double the length of the word. p_kp / curbuf->b_p_kp could be added
// and some numbers.
- char_u *kp = *curbuf->b_p_kp == NUL ? p_kp : (char_u *)curbuf->b_p_kp; // 'keywordprg'
- bool kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0 || STRCMP(kp, ":help") == 0);
+ char *kp = *curbuf->b_p_kp == NUL ? (char *)p_kp : curbuf->b_p_kp; // 'keywordprg'
+ bool kp_help = (*kp == NUL || strcmp(kp, ":he") == 0 || strcmp(kp, ":help") == 0);
if (kp_help && *skipwhite(ptr) == NUL) {
emsg(_(e_noident)); // found white space only
return;
@@ -4294,7 +4294,7 @@ static void nv_ident(cmdarg_T *cap)
// Call setpcmark() first, so "*``" puts the cursor back where
// it was.
setpcmark();
- curwin->w_cursor.col = (colnr_T)(ptr - (char *)get_cursor_line_ptr());
+ curwin->w_cursor.col = (colnr_T)(ptr - get_cursor_line_ptr());
if (!g_cmd && vim_iswordp((char_u *)ptr)) {
STRCPY(buf, "\\<");
@@ -4336,10 +4336,10 @@ static void nv_ident(cmdarg_T *cap)
ptr = xstrnsave(ptr, n);
if (kp_ex) {
// Escape the argument properly for an Ex command
- p = (char_u *)vim_strsave_fnameescape((const char *)ptr, VSE_NONE);
+ p = vim_strsave_fnameescape((const char *)ptr, VSE_NONE);
} else {
// Escape the argument properly for a shell command
- p = vim_strsave_shellescape((char_u *)ptr, true, true);
+ p = (char *)vim_strsave_shellescape((char_u *)ptr, true, true);
}
xfree(ptr);
char *newbuf = xrealloc(buf, STRLEN(buf) + STRLEN(p) + 1);
@@ -4348,33 +4348,33 @@ static void nv_ident(cmdarg_T *cap)
xfree(p);
} else {
if (cmdchar == '*') {
- aux_ptr = (char_u *)(p_magic ? "/.*~[^$\\" : "/^$\\");
+ aux_ptr = (p_magic ? "/.*~[^$\\" : "/^$\\");
} else if (cmdchar == '#') {
- aux_ptr = (char_u *)(p_magic ? "/?.*~[^$\\" : "/?^$\\");
+ aux_ptr = (p_magic ? "/?.*~[^$\\" : "/?^$\\");
} else if (tag_cmd) {
if (curbuf->b_help) {
// ":help" handles unescaped argument
- aux_ptr = (char_u *)"";
+ aux_ptr = "";
} else {
- aux_ptr = (char_u *)"\\|\"\n[";
+ aux_ptr = "\\|\"\n[";
}
} else {
- aux_ptr = (char_u *)"\\|\"\n*?[";
+ aux_ptr = "\\|\"\n*?[";
}
- p = (char_u *)buf + STRLEN(buf);
+ p = buf + STRLEN(buf);
while (n-- > 0) {
// put a backslash before \ and some others
- if (vim_strchr((char *)aux_ptr, *ptr) != NULL) {
+ 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);
for (size_t i = 0; i < len && n > 0; i++, n--) {
- *p++ = (char_u)(*ptr++);
+ *p++ = *ptr++;
}
- *p++ = (char_u)(*ptr++);
+ *p++ = *ptr++;
}
*p = NUL;
}
@@ -4382,13 +4382,13 @@ static void nv_ident(cmdarg_T *cap)
// Execute the command.
if (cmdchar == '*' || cmdchar == '#') {
if (!g_cmd
- && vim_iswordp(mb_prevptr(get_cursor_line_ptr(), (char_u *)ptr))) {
+ && vim_iswordp(mb_prevptr((char_u *)get_cursor_line_ptr(), (char_u *)ptr))) {
STRCAT(buf, "\\>");
}
// put pattern in search history
init_history();
- add_to_history(HIST_SEARCH, (char_u *)buf, true, NUL);
+ add_to_history(HIST_SEARCH, buf, true, NUL);
(void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0, NULL);
} else {
@@ -4425,7 +4425,7 @@ bool get_visual_text(cmdarg_T *cap, char **pp, size_t *lenp)
return false;
}
if (VIsual_mode == 'V') {
- *pp = (char *)get_cursor_line_ptr();
+ *pp = get_cursor_line_ptr();
*lenp = STRLEN(*pp);
} else {
if (lt(curwin->w_cursor, VIsual)) {
@@ -4451,7 +4451,7 @@ bool get_visual_text(cmdarg_T *cap, char **pp, size_t *lenp)
static void nv_tagpop(cmdarg_T *cap)
{
if (!checkclearopq(cap->oap)) {
- do_tag((char_u *)"", DT_POP, (int)cap->count1, false, true);
+ do_tag("", DT_POP, (int)cap->count1, false, true);
}
}
@@ -4600,7 +4600,7 @@ static void nv_right(cmdarg_T *cap)
if (virtual_active()) {
oneright();
} else {
- curwin->w_cursor.col += utfc_ptr2len((char *)get_cursor_pos_ptr());
+ curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr());
}
}
}
@@ -4648,7 +4648,7 @@ static void nv_left(cmdarg_T *cap)
// Don't adjust op_end now, otherwise it won't work.
if ((cap->oap->op_type == OP_DELETE || cap->oap->op_type == OP_CHANGE)
&& !LINEEMPTY(curwin->w_cursor.lnum)) {
- char_u *cp = get_cursor_pos_ptr();
+ char_u *cp = (char_u *)get_cursor_pos_ptr();
if (*cp != NUL) {
curwin->w_cursor.col += utfc_ptr2len((char *)cp);
@@ -5360,7 +5360,7 @@ static void nv_replace(cmdarg_T *cap)
}
// Abort if not enough characters to replace.
- ptr = get_cursor_pos_ptr();
+ ptr = (char_u *)get_cursor_pos_ptr();
if (STRLEN(ptr) < (unsigned)cap->count1
|| (mb_charlen(ptr) < cap->count1)) {
clearopbeep(cap->oap);
@@ -6068,7 +6068,7 @@ static void nv_g_underscore_cmd(cmdarg_T *cap)
return;
}
- char_u *ptr = get_cursor_line_ptr();
+ char_u *ptr = (char_u *)get_cursor_line_ptr();
// In Visual mode we may end up after the line.
if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) {
@@ -6279,7 +6279,7 @@ static void nv_g_cmd(cmdarg_T *cap)
case 'M':
oap->motion_type = kMTCharWise;
oap->inclusive = false;
- i = linetabsize(get_cursor_line_ptr());
+ i = linetabsize((char_u *)get_cursor_line_ptr());
if (cap->count0 > 0 && cap->count0 <= 100) {
coladvance((colnr_T)(i * cap->count0 / 100));
} else {
diff --git a/src/nvim/normal.h b/src/nvim/normal.h
index 13ea233658..0317080f4f 100644
--- a/src/nvim/normal.h
+++ b/src/nvim/normal.h
@@ -22,9 +22,7 @@ typedef enum {
kMTUnknown = -1, ///< Unknown or invalid motion type
} MotionType;
-/*
- * Arguments for operators.
- */
+// Arguments for operators.
typedef struct oparg_S {
int op_type; // current pending operator type
int regname; // register to use for the operator
@@ -53,9 +51,7 @@ typedef struct oparg_S {
// block
} oparg_T;
-/*
- * Arguments for Normal mode commands.
- */
+// Arguments for Normal mode commands.
typedef struct cmdarg_S {
oparg_T *oap; // Operator arguments
int prechar; // prefix character (optional, always 'g')
diff --git a/src/nvim/ops.c b/src/nvim/ops.c
index d2321be4a4..10e957287e 100644
--- a/src/nvim/ops.c
+++ b/src/nvim/ops.c
@@ -1,10 +1,8 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * ops.c: implementation of various operators: op_shift, op_delete, op_tilde,
- * op_change, op_yank, do_put, do_join
- */
+// ops.c: implementation of various operators: op_shift, op_delete, op_tilde,
+// op_change, op_yank, do_put, do_join
#include <assert.h>
#include <inttypes.h>
@@ -67,10 +65,8 @@ static bool clipboard_delay_update = false; // delay clipboard update
static bool clipboard_needs_update = false; // clipboard was updated
static bool clipboard_didwarn = false;
-/*
- * structure used by block_prep, op_delete and op_yank for blockwise operators
- * also op_change, op_shift, op_insert, op_replace - AKelly
- */
+// structure used by block_prep, op_delete and op_yank for blockwise operators
+// also op_change, op_shift, op_insert, op_replace - AKelly
struct block_def {
int startspaces; // 'extra' cols before first char
int endspaces; // 'extra' cols after last char
@@ -96,11 +92,9 @@ struct block_def {
#define OPF_LINES 1 // operator always works on lines
#define OPF_CHANGE 2 // operator changes text
-/*
- * The names of operators.
- * IMPORTANT: Index must correspond with defines in vim.h!!!
- * The third field indicates whether the operator always works on lines.
- */
+// The names of operators.
+// IMPORTANT: Index must correspond with defines in vim.h!!!
+// The third field indicates whether the operator always works on lines.
static char opchars[][3] =
{
{ NUL, NUL, 0 }, // OP_NOP
@@ -225,7 +219,7 @@ void op_shift(oparg_T *oap, int curs_top, int amount)
}
for (i = oap->line_count - 1; i >= 0; i--) {
- first_char = *get_cursor_line_ptr();
+ first_char = (uint8_t)(*get_cursor_line_ptr());
if (first_char == NUL) { // empty line
curwin->w_cursor.col = 0;
} else if (oap->motion_type == kMTBlockWise) {
@@ -356,17 +350,15 @@ static void shift_block(oparg_T *oap, int amount)
return; // multiplication overflow
}
- char_u *const oldp = get_cursor_line_ptr();
+ char_u *const oldp = (char_u *)get_cursor_line_ptr();
int startcol, oldlen, newlen;
if (!left) {
- /*
- * 1. Get start vcol
- * 2. Total ws vcols
- * 3. Divvy into TABs & spp
- * 4. Construct new string
- */
+ // 1. Get start vcol
+ // 2. Total ws vcols
+ // 3. Divvy into TABs & spp
+ // 4. Construct new string
total += bd.pre_whitesp; // all virtual WS up to & incl a split TAB
colnr_T ws_vcol = bd.start_vcol - bd.pre_whitesp;
char_u *old_textstart = bd.textstart;
@@ -428,13 +420,11 @@ static void shift_block(oparg_T *oap, int amount)
// block shift
char_u *non_white = bd.textstart;
- /*
- * Firstly, let's find the first non-whitespace character that is
- * displayed after the block's start column and the character's column
- * number. Also, let's calculate the width of all the whitespace
- * characters that are displayed in the block and precede the searched
- * non-whitespace character.
- */
+ // Firstly, let's find the first non-whitespace character that is
+ // displayed after the block's start column and the character's column
+ // number. Also, let's calculate the width of all the whitespace
+ // characters that are displayed in the block and precede the searched
+ // non-whitespace character.
// If "bd.startspaces" is set, "bd.textstart" points to the character,
// the part of which is displayed at the block's beginning. Let's start
@@ -668,7 +658,7 @@ void op_reindent(oparg_T *oap, Indenter how)
// indented, unless there is only one line.
if (i != oap->line_count - 1 || oap->line_count == 1
|| how != get_lisp_indent) {
- l = (char_u *)skipwhite((char *)get_cursor_line_ptr());
+ l = (char_u *)skipwhite(get_cursor_line_ptr());
if (*l == NUL) { // empty or blank line
amount = 0;
} else {
@@ -691,9 +681,9 @@ void op_reindent(oparg_T *oap, Indenter how)
curwin->w_cursor.lnum = start_lnum;
beginline(BL_SOL | BL_FIX);
- /* Mark changed lines so that they will be redrawn. When Visual
- * highlighting was present, need to continue until the last line. When
- * there is no change still need to remove the Visual highlighting. */
+ // Mark changed lines so that they will be redrawn. When Visual
+ // highlighting was present, need to continue until the last line. When
+ // there is no change still need to remove the Visual highlighting.
if (last_changed != 0) {
changed_lines(first_changed, 0,
oap->is_VIsual ? start_lnum + (linenr_T)oap->line_count :
@@ -715,9 +705,7 @@ void op_reindent(oparg_T *oap, Indenter how)
}
}
-/*
- * Keep the last expression line here, for repeating.
- */
+// Keep the last expression line here, for repeating.
static char_u *expr_line = NULL;
/// Get an expression for the "\"=expr1" or "CTRL-R =expr1"
@@ -734,56 +722,56 @@ int get_expr_register(void)
if (*new_line == NUL) { // use previous line
xfree(new_line);
} else {
- set_expr_line(new_line);
+ set_expr_line((char *)new_line);
}
return '=';
}
/// Set the expression for the '=' register.
/// Argument must be an allocated string.
-void set_expr_line(char_u *new_line)
+void set_expr_line(char *new_line)
{
xfree(expr_line);
- expr_line = new_line;
+ expr_line = (char_u *)new_line;
}
/// Get the result of the '=' register expression.
///
/// @return a pointer to allocated memory, or NULL for failure.
-char_u *get_expr_line(void)
+char *get_expr_line(void)
{
- char_u *expr_copy;
- char_u *rv;
+ char *expr_copy;
+ char *rv;
static int nested = 0;
if (expr_line == NULL) {
return NULL;
}
- /* Make a copy of the expression, because evaluating it may cause it to be
- * changed. */
- expr_copy = vim_strsave(expr_line);
+ // Make a copy of the expression, because evaluating it may cause it to be
+ // changed.
+ expr_copy = xstrdup((char *)expr_line);
- /* When we are invoked recursively limit the evaluation to 10 levels.
- * Then return the string as-is. */
+ // When we are invoked recursively limit the evaluation to 10 levels.
+ // Then return the string as-is.
if (nested >= 10) {
return expr_copy;
}
nested++;
- rv = (char_u *)eval_to_string((char *)expr_copy, NULL, true);
+ rv = eval_to_string(expr_copy, NULL, true);
nested--;
xfree(expr_copy);
return rv;
}
/// Get the '=' register expression itself, without evaluating it.
-char_u *get_expr_line_src(void)
+char *get_expr_line_src(void)
{
if (expr_line == NULL) {
return NULL;
}
- return vim_strsave(expr_line);
+ return xstrdup((char *)expr_line);
}
/// @return whether `regname` is a valid name of a yank register.
@@ -1082,11 +1070,11 @@ static char_u *execreg_line_continuation(char **lines, size_t *idx)
}
}
ga_append(&ga, NUL);
- char_u *str = vim_strsave(ga.ga_data);
+ char *str = xstrdup(ga.ga_data);
ga_clear(&ga);
*idx = i;
- return str;
+ return (char_u *)str;
}
/// Execute a yank register: copy it into the stuff buffer
@@ -1142,7 +1130,7 @@ int do_execreg(int regname, int colon, int addcr, int silent)
}
xfree(p);
} else if (regname == '=') {
- p = get_expr_line();
+ p = (char_u *)get_expr_line();
if (p == NULL) {
return FAIL;
}
@@ -1165,9 +1153,7 @@ int do_execreg(int regname, int colon, int addcr, int silent)
// Disallow remapping for ":@r".
int remap = colon ? REMAP_NONE : REMAP_YES;
- /*
- * Insert lines into typeahead buffer, from last one to first one.
- */
+ // Insert lines into typeahead buffer, from last one to first one.
put_reedit_in_typebuf(silent);
char *escaped;
for (size_t i = reg->y_size; i-- > 0;) { // from y_size - 1 to 0 included
@@ -1277,11 +1263,9 @@ int insert_reg(int regname, bool literally_arg)
bool allocated;
const bool literally = literally_arg || is_literal_register(regname);
- /*
- * It is possible to get into an endless loop by having CTRL-R a in
- * register a and then, in insert mode, doing CTRL-R a.
- * If you hit CTRL-C, the loop will be broken here.
- */
+ // It is possible to get into an endless loop by having CTRL-R a in
+ // register a and then, in insert mode, doing CTRL-R a.
+ // If you hit CTRL-C, the loop will be broken here.
os_breakcheck();
if (got_int) {
return FAIL;
@@ -1354,7 +1338,7 @@ bool get_spec_reg(int regname, char **argp, bool *allocated, bool errmsg)
return true;
case '=': // result of expression
- *argp = (char *)get_expr_line();
+ *argp = get_expr_line();
*allocated = true;
return true;
@@ -1408,7 +1392,7 @@ bool get_spec_reg(int regname, char **argp, bool *allocated, bool errmsg)
return false;
}
- *argp = (char *)ml_get_buf(curwin->w_buffer, curwin->w_cursor.lnum, false);
+ *argp = ml_get_buf(curwin->w_buffer, curwin->w_cursor.lnum, false);
return true;
case '_': // black hole: always empty
@@ -1447,8 +1431,8 @@ bool cmdline_paste_reg(int regname, bool literally_arg, bool remcr)
cmdline_paste_str((char_u *)"\r", literally);
}
- /* Check for CTRL-C, in case someone tries to paste a few thousand
- * lines and gets bored. */
+ // Check for CTRL-C, in case someone tries to paste a few thousand
+ // lines and gets bored.
os_breakcheck();
if (got_int) {
return FAIL;
@@ -1503,11 +1487,9 @@ int op_delete(oparg_T *oap)
mb_adjust_opend(oap);
- /*
- * Imitate the strange Vi behaviour: If the delete spans more than one
- * line and motion_type == kMTCharWise and the result is a blank line, make the
- * delete linewise. Don't do this for the change command or Visual mode.
- */
+ // Imitate the strange Vi behaviour: If the delete spans more than one
+ // line and motion_type == kMTCharWise and the result is a blank line, make the
+ // delete linewise. Don't do this for the change command or Visual mode.
if (oap->motion_type == kMTCharWise
&& !oap->is_VIsual
&& oap->line_count > 1
@@ -1523,10 +1505,8 @@ int op_delete(oparg_T *oap)
}
}
- /*
- * Check for trying to delete (e.g. "D") in an empty line.
- * Note: For the change operator it is ok.
- */
+ // Check for trying to delete (e.g. "D") in an empty line.
+ // Note: For the change operator it is ok.
if (oap->motion_type != kMTLineWise
&& oap->line_count == 1
&& oap->op_type == OP_DELETE
@@ -1544,11 +1524,9 @@ int op_delete(oparg_T *oap)
return OK;
}
- /*
- * Do a yank of whatever we're about to delete.
- * If a yank register was specified, put the deleted text into that
- * register. For the black hole register '_' don't yank anything.
- */
+ // Do a yank of whatever we're about to delete.
+ // If a yank register was specified, put the deleted text into that
+ // register. For the black hole register '_' don't yank anything.
if (oap->regname != '_') {
yankreg_T *reg = NULL;
int did_yank = false;
@@ -1592,9 +1570,7 @@ int op_delete(oparg_T *oap)
}
}
- /*
- * block mode delete
- */
+ // block mode delete
if (oap->motion_type == kMTBlockWise) {
if (u_save((linenr_T)(oap->start.lnum - 1),
(linenr_T)(oap->end.lnum + 1)) == FAIL) {
@@ -1735,7 +1711,7 @@ int op_delete(oparg_T *oap)
if (virtual_op) {
// fix up things for virtualedit-delete:
// break the tabs which are going to get in our way
- char_u *curline = get_cursor_line_ptr();
+ char_u *curline = (char_u *)get_cursor_line_ptr();
int len = (int)STRLEN(curline);
if (oap->end.coladd != 0
@@ -1825,7 +1801,7 @@ static void mb_adjust_opend(oparg_T *oap)
static inline void pbyte(pos_T lp, int c)
{
assert(c <= UCHAR_MAX);
- *(ml_get_buf(curbuf, lp.lnum, true) + lp.col) = (char_u)c;
+ *(ml_get_buf(curbuf, lp.lnum, true) + lp.col) = (char)c;
if (!curbuf_splice_pending) {
extmark_splice_cols(curbuf, (int)lp.lnum - 1, lp.col, 1, 1, kExtmarkUndo);
}
@@ -1873,9 +1849,7 @@ static int op_replace(oparg_T *oap, int c)
return FAIL;
}
- /*
- * block mode replace
- */
+ // block mode replace
if (oap->motion_type == kMTBlockWise) {
bd.is_MAX = (curwin->w_curswant == MAXCOL);
for (; curwin->w_cursor.lnum <= oap->end.lnum; curwin->w_cursor.lnum++) {
@@ -1926,7 +1900,7 @@ static int op_replace(oparg_T *oap, int c)
num_chars = numc;
numc *= utf_char2len(c);
- oldp = get_cursor_line_ptr();
+ oldp = (char_u *)get_cursor_line_ptr();
oldlen = (int)STRLEN(oldp);
size_t newp_size = (size_t)bd.textcol + (size_t)bd.startspaces;
@@ -2004,7 +1978,7 @@ static int op_replace(oparg_T *oap, int c)
n = gchar_cursor();
if (n != NUL) {
int new_byte_len = utf_char2len(c);
- int old_byte_len = utfc_ptr2len((char *)get_cursor_pos_ptr());
+ int old_byte_len = utfc_ptr2len(get_cursor_pos_ptr());
if (new_byte_len > 1 || old_byte_len > 1) {
// This is slow, but it handles replacing a single-byte
@@ -2225,7 +2199,7 @@ bool swapchar(int op_type, pos_T *pos)
curwin->w_cursor = *pos;
// don't use del_char(), it also removes composing chars
- del_bytes(utf_ptr2len((char *)get_cursor_pos_ptr()), false, false);
+ del_bytes(utf_ptr2len(get_cursor_pos_ptr()), false, false);
ins_char(nc);
curwin->w_cursor = sp;
} else {
@@ -2240,7 +2214,7 @@ bool swapchar(int op_type, pos_T *pos)
void op_insert(oparg_T *oap, long count1)
{
long ins_len, pre_textlen = 0;
- char_u *firstline, *ins_text;
+ char *firstline, *ins_text;
colnr_T ind_pre_col = 0, ind_post_col;
int ind_pre_vcol = 0, ind_post_vcol = 0;
struct block_def bd;
@@ -2281,7 +2255,7 @@ void op_insert(oparg_T *oap, long count1)
// Get indent information
ind_pre_col = (colnr_T)getwhitecols_curline();
ind_pre_vcol = get_indent();
- firstline = (char_u *)ml_get(oap->start.lnum) + bd.textcol;
+ firstline = ml_get(oap->start.lnum) + bd.textcol;
if (oap->op_type == OP_APPEND) {
firstline += bd.textlen;
@@ -2409,11 +2383,9 @@ void op_insert(oparg_T *oap, long count1)
bd.textlen = bd2.textlen;
}
- /*
- * Subsequent calls to ml_get() flush the firstline data - take a
- * copy of the required string.
- */
- firstline = (char_u *)ml_get(oap->start.lnum);
+ // Subsequent calls to ml_get() flush the firstline data - take a
+ // copy of the required string.
+ firstline = ml_get(oap->start.lnum);
const size_t len = STRLEN(firstline);
colnr_T add = bd.textcol;
colnr_T offset = 0; // offset when cursor was moved in insert mode
@@ -2438,10 +2410,10 @@ void op_insert(oparg_T *oap, long count1)
}
ins_len = (long)STRLEN(firstline) - pre_textlen - offset;
if (pre_textlen >= 0 && ins_len > 0) {
- ins_text = vim_strnsave(firstline, (size_t)ins_len);
+ ins_text = xstrnsave(firstline, (size_t)ins_len);
// block handled here
if (u_save(oap->start.lnum, (linenr_T)(oap->end.lnum + 1)) == OK) {
- block_insert(oap, ins_text, (oap->op_type == OP_INSERT), &bd);
+ block_insert(oap, (char_u *)ins_text, (oap->op_type == OP_INSERT), &bd);
}
curwin->w_cursor.col = oap->start.col;
@@ -2510,11 +2482,9 @@ int op_change(oparg_T *oap)
retval = edit(NUL, false, (linenr_T)1);
- /*
- * In Visual block mode, handle copying the new text to all lines of the
- * block.
- * Don't repeat the insert when Insert mode ended with CTRL-C.
- */
+ // In Visual block mode, handle copying the new text to all lines of the
+ // block.
+ // Don't repeat the insert when Insert mode ended with CTRL-C.
if (oap->motion_type == kMTBlockWise
&& oap->start.lnum != oap->end.lnum && !got_int) {
// Auto-indenting may have changed the indent. If the cursor was past
@@ -2707,8 +2677,7 @@ static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append)
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. */
+ // Part of a tab selected -- but don't double-count it.
bd.startspaces = (ce - cs + 1)
- oap->start.coladd;
startcol++;
@@ -2934,9 +2903,9 @@ static void do_autocmd_textyankpost(oparg_T *oap, yankreg_T *reg)
/// @param dir BACKWARD for 'P', FORWARD for 'p'
void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
{
- char_u *ptr;
- char_u *newp;
- char_u *oldp;
+ char *ptr;
+ char *newp;
+ char *oldp;
int yanklen;
size_t totlen = 0; // init for gcc
linenr_T lnum = 0;
@@ -2973,10 +2942,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
curbuf->b_op_start = curwin->w_cursor; // default for '[ mark
curbuf->b_op_end = curwin->w_cursor; // default for '] mark
- /*
- * Using inserted text works differently, because the register includes
- * special characters (newlines, etc.).
- */
+ // Using inserted text works differently, because the register includes
+ // special characters (newlines, etc.).
if (regname == '.' && !reg) {
bool non_linewise_vis = (VIsual_active && VIsual_mode != 'V');
@@ -3028,7 +2995,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
// STRLEN(ml_get(curwin->w_cursor.lnum)). With 'virtualedit' and the
// cursor past the end of the line, curwin->w_cursor.coladd is
// incremented instead of curwin->w_cursor.col.
- char_u *cursor_pos = get_cursor_pos_ptr();
+ char_u *cursor_pos = (char_u *)get_cursor_pos_ptr();
bool one_past_line = (*cursor_pos == NUL);
bool eol = false;
if (!one_past_line) {
@@ -3056,10 +3023,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
return;
}
- /*
- * For special registers '%' (file name), '#' (alternate file name) and
- * ':' (last command line), etc. we have to create a fake yank register.
- */
+ // For special registers '%' (file name), '#' (alternate file name) and
+ // ':' (last command line), etc. we have to create a fake yank register.
if (!reg && get_spec_reg(regname, &insert_string, &allocated, true)) {
if (insert_string == NULL) {
return;
@@ -3077,18 +3042,18 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
if (insert_string != NULL) {
y_type = kMTCharWise;
if (regname == '=') {
- /* For the = register we need to split the string at NL
- * characters.
- * Loop twice: count the number of lines and save them. */
+ // For the = register we need to split the string at NL
+ // characters.
+ // Loop twice: count the number of lines and save them.
for (;;) {
y_size = 0;
- ptr = (char_u *)insert_string;
+ ptr = insert_string;
while (ptr != NULL) {
if (y_array != NULL) {
- y_array[y_size] = (char *)ptr;
+ y_array[y_size] = ptr;
}
y_size++;
- ptr = (char_u *)vim_strchr((char *)ptr, '\n');
+ ptr = vim_strchr(ptr, '\n');
if (ptr != NULL) {
if (y_array != NULL) {
*ptr = NUL;
@@ -3136,12 +3101,12 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
if (u_save_cursor() == FAIL) {
goto end;
}
- char_u *p = get_cursor_pos_ptr();
+ char *p = get_cursor_pos_ptr();
if (dir == FORWARD && *p != NUL) {
MB_PTR_ADV(p);
}
- ptr = vim_strsave(p);
- ml_append(curwin->w_cursor.lnum, (char *)ptr, (colnr_T)0, false);
+ ptr = xstrdup(p);
+ ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, false);
xfree(ptr);
oldp = get_cursor_line_ptr();
@@ -3149,8 +3114,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
if (dir == FORWARD && *p != NUL) {
MB_PTR_ADV(p);
}
- ptr = vim_strnsave(oldp, (size_t)(p - oldp));
- ml_replace(curwin->w_cursor.lnum, (char *)ptr, false);
+ ptr = xstrnsave(oldp, (size_t)(p - oldp));
+ ml_replace(curwin->w_cursor.lnum, ptr, false);
nr_lines++;
dir = FORWARD;
}
@@ -3232,9 +3197,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
lnum = curwin->w_cursor.lnum;
col = curwin->w_cursor.col;
- /*
- * Block mode
- */
+ // Block mode
if (y_type == kMTBlockWise) {
int c = gchar_cursor();
colnr_T endcol2 = 0;
@@ -3247,7 +3210,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
}
// move to start of next multi-byte character
- curwin->w_cursor.col += utfc_ptr2len((char *)get_cursor_pos_ptr());
+ curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr());
col++;
} else {
getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
@@ -3298,8 +3261,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
oldp = get_cursor_line_ptr();
oldlen = STRLEN(oldp);
chartabsize_T cts;
- init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0,
- (char *)oldp, (char *)oldp);
+ init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, 0, oldp, oldp);
while (cts.cts_vcol < col && *cts.cts_ptr != NUL) {
// Count a tab for what it's worth (if list mode not on)
@@ -3307,7 +3269,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
cts.cts_vcol += incr;
}
vcol = cts.cts_vcol;
- ptr = (char_u *)cts.cts_ptr;
+ ptr = cts.cts_ptr;
bd.textcol = (colnr_T)(ptr - oldp);
clear_chartabsize_arg(&cts);
@@ -3320,11 +3282,11 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
bd.startspaces = incr - bd.endspaces;
bd.textcol--;
delcount = 1;
- bd.textcol -= utf_head_off((char *)oldp, (char *)oldp + bd.textcol);
+ bd.textcol -= utf_head_off(oldp, oldp + bd.textcol);
if (oldp[bd.textcol] != TAB) {
- /* Only a Tab can be split into spaces. Other
- * characters will have to be moved to after the
- * block, causing misalignment. */
+ // Only a Tab can be split into spaces. Other
+ // characters will have to be moved to after the
+ // block, causing misalignment.
delcount = 0;
bd.endspaces = 0;
}
@@ -3356,9 +3318,8 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
break;
}
- totlen = (size_t)(count * (yanklen + spaces)
- + bd.startspaces + bd.endspaces);
- newp = (char_u *)xmalloc(totlen + oldlen + 1);
+ totlen = (size_t)(count * (yanklen + spaces) + bd.startspaces + bd.endspaces);
+ newp = xmalloc(totlen + oldlen + 1);
// copy part up to cursor to new line
ptr = newp;
@@ -3391,7 +3352,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
int columns = (int)oldlen - bd.textcol - delcount + 1;
assert(columns >= 0);
memmove(ptr, oldp + bd.textcol + delcount, (size_t)columns);
- ml_replace(curwin->w_cursor.lnum, (char *)newp, false);
+ ml_replace(curwin->w_cursor.lnum, newp, false);
extmark_splice_cols(curbuf, (int)curwin->w_cursor.lnum - 1, bd.textcol,
delcount, (int)totlen + lines_appended, kExtmarkUndo);
@@ -3432,7 +3393,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
// if type is kMTCharWise, FORWARD is the same as BACKWARD on the next
// char
if (dir == FORWARD && gchar_cursor() != NUL) {
- int bytelen = utfc_ptr2len((char *)get_cursor_pos_ptr());
+ int bytelen = utfc_ptr2len(get_cursor_pos_ptr());
// put it on the next of the multi-byte character.
col += bytelen;
@@ -3482,7 +3443,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
} else {
totlen = (size_t)(count * yanklen);
do {
- oldp = (char_u *)ml_get(lnum);
+ oldp = ml_get(lnum);
oldlen = STRLEN(oldp);
if (lnum > start_lnum) {
pos_T pos = {
@@ -3498,7 +3459,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
lnum++;
continue;
}
- newp = (char_u *)xmalloc(totlen + oldlen + 1);
+ newp = xmalloc(totlen + oldlen + 1);
memmove(newp, oldp, (size_t)col);
ptr = newp + col;
for (i = 0; i < (size_t)count; i++) {
@@ -3506,10 +3467,10 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
ptr += yanklen;
}
STRMOVE(ptr, oldp + col);
- ml_replace(lnum, (char *)newp, false);
+ ml_replace(lnum, newp, false);
// compute the byte offset for the last character
- first_byte_off = utf_head_off((char *)newp, (char *)ptr - 1);
+ first_byte_off = utf_head_off(newp, ptr - 1);
// Place cursor on last putted char.
if (lnum == curwin->w_cursor.lnum) {
@@ -3553,23 +3514,23 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
// First insert y_array[size - 1] in front of second line.
// Then append y_array[0] to first line.
lnum = new_cursor.lnum;
- ptr = (char_u *)ml_get(lnum) + col;
+ ptr = ml_get(lnum) + col;
totlen = STRLEN(y_array[y_size - 1]);
- newp = (char_u *)xmalloc((size_t)(STRLEN(ptr) + totlen + 1));
+ newp = xmalloc((size_t)(STRLEN(ptr) + totlen + 1));
STRCPY(newp, y_array[y_size - 1]);
STRCAT(newp, ptr);
// insert second line
- ml_append(lnum, (char *)newp, (colnr_T)0, false);
+ ml_append(lnum, newp, (colnr_T)0, false);
new_lnum++;
xfree(newp);
- oldp = (char_u *)ml_get(lnum);
- newp = (char_u *)xmalloc((size_t)col + (size_t)yanklen + 1);
+ oldp = ml_get(lnum);
+ newp = xmalloc((size_t)col + (size_t)yanklen + 1);
// copy first part of line
memmove(newp, oldp, (size_t)col);
// append to first line
memmove(newp + col, y_array[0], (size_t)yanklen + 1);
- ml_replace(lnum, (char *)newp, false);
+ ml_replace(lnum, newp, false);
curwin->w_cursor.lnum = lnum;
i = 1;
@@ -3587,7 +3548,7 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
if (flags & PUT_FIXINDENT) {
old_pos = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
- ptr = (char_u *)ml_get(lnum);
+ ptr = ml_get(lnum);
if (cnt == count && i == y_size - 1) {
lendiff = (int)STRLEN(ptr);
}
@@ -4131,13 +4092,11 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions
cend = newp + sumsize;
*cend = 0;
- /*
- * Move affected lines to the new long one.
- *
- * Move marks from each deleted line to the joined line, adjusting the
- * column. This is not Vi compatible, but Vi deletes the marks, thus that
- * should not really be a problem.
- */
+ // Move affected lines to the new long one.
+ //
+ // Move marks from each deleted line to the joined line, adjusting the
+ // column. This is not Vi compatible, but Vi deletes the marks, thus that
+ // should not really be a problem.
curbuf_splice_pending++;
@@ -4187,11 +4146,9 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions
changed_lines(curwin->w_cursor.lnum, currsize,
curwin->w_cursor.lnum + 1, 0L, true);
- /*
- * Delete following lines. To do this we move the cursor there
- * briefly, and then move it back. After del_lines() the cursor may
- * have moved up (last line deleted), so the current lnum is kept in t.
- */
+ // Delete following lines. To do this we move the cursor there
+ // briefly, and then move it back. After del_lines() the cursor may
+ // have moved up (last line deleted), so the current lnum is kept in t.
t = curwin->w_cursor.lnum;
curwin->w_cursor.lnum++;
del_lines((long)count - 1, false);
@@ -4199,11 +4156,9 @@ int do_join(size_t count, int insert_space, int save_undo, int use_formatoptions
curbuf_splice_pending--;
curbuf->deleted_bytes2 = 0;
- /*
- * Set the cursor column:
- * Vi compatible: use the column of the first join
- * vim: use the column of the last join
- */
+ // Set the cursor column:
+ // Vi compatible: use the column of the first join
+ // vim: use the column of the last join
curwin->w_cursor.col =
(vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col);
check_cursor_col();
@@ -4656,7 +4611,7 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1)
: length);
}
- vim_str2nr(ptr + col, &pre, &length,
+ vim_str2nr((char *)ptr + col, &pre, &length,
0 + (do_bin ? STR2NR_BIN : 0)
+ (do_oct ? STR2NR_OCT : 0)
+ (do_hex ? STR2NR_HEX : 0),
@@ -4898,13 +4853,13 @@ void format_reg_type(MotionType reg_type, colnr_T reg_width, char *buf, size_t b
/// Otherwise just return `s`.
///
/// @return a void * for use in get_reg_contents().
-static void *get_reg_wrap_one_line(char_u *s, int flags)
+static void *get_reg_wrap_one_line(char *s, int flags)
{
if (!(flags & kGRegList)) {
return s;
}
list_T *const list = tv_list_alloc(1);
- tv_list_append_allocated_string(list, (char *)s);
+ tv_list_append_allocated_string(list, s);
return list;
}
@@ -4946,9 +4901,9 @@ void *get_reg_contents(int regname, int flags)
return NULL;
}
if (allocated) {
- return get_reg_wrap_one_line((char_u *)retval, flags);
+ return get_reg_wrap_one_line(retval, flags);
}
- return get_reg_wrap_one_line(vim_strsave((char_u *)retval), flags);
+ return get_reg_wrap_one_line(xstrdup(retval), flags);
}
yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
@@ -4965,16 +4920,12 @@ void *get_reg_contents(int regname, int flags)
return list;
}
- /*
- * Compute length of resulting string.
- */
+ // Compute length of resulting string.
size_t len = 0;
for (size_t i = 0; i < reg->y_size; i++) {
len += STRLEN(reg->y_array[i]);
- /*
- * Insert a newline between lines and after last line if
- * y_type is kMTLineWise.
- */
+ // Insert a newline between lines and after last line if
+ // y_type is kMTLineWise.
if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
len++;
}
@@ -4982,18 +4933,14 @@ void *get_reg_contents(int regname, int flags)
retval = xmalloc(len + 1);
- /*
- * Copy the lines of the yank register into the string.
- */
+ // Copy the lines of the yank register into the string.
len = 0;
for (size_t i = 0; i < reg->y_size; i++) {
STRCPY(retval + len, reg->y_array[i]);
len += STRLEN(retval + len);
- /*
- * Insert a NL between lines and after the last line if y_type is
- * kMTLineWise.
- */
+ // Insert a NL between lines and after the last line if y_type is
+ // kMTLineWise.
if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
retval[len++] = '\n';
}
@@ -5504,7 +5451,7 @@ void cursor_pos_info(dict_T *dict)
(int64_t)byte_count_cursor, (int64_t)byte_count);
}
} else {
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
validate_virtcol();
col_print((char *)buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1,
(int)curwin->w_virtcol + 1);
@@ -5627,7 +5574,7 @@ static Callback opfunc_cb;
/// @return OK or FAIL
int set_operatorfunc_option(void)
{
- return option_set_callback_func((char_u *)p_opfunc, &opfunc_cb);
+ return option_set_callback_func(p_opfunc, &opfunc_cb);
}
#if defined(EXITFREE)
diff --git a/src/nvim/ops.h b/src/nvim/ops.h
index 05893c9940..840e33a48c 100644
--- a/src/nvim/ops.h
+++ b/src/nvim/ops.h
@@ -23,15 +23,13 @@ typedef int (*Indenter)(void);
#define PUT_LINE_FORWARD 32 // put linewise register below Visual sel.
#define PUT_BLOCK_INNER 64 // in block mode, do not add trailing spaces
-/*
- * Registers:
- * 0 = register for latest (unnamed) yank
- * 1..9 = registers '1' to '9', for deletes
- * 10..35 = registers 'a' to 'z'
- * 36 = delete register '-'
- * 37 = selection register '*'
- * 38 = clipboard register '+'
- */
+// Registers:
+// 0 = register for latest (unnamed) yank
+// 1..9 = registers '1' to '9', for deletes
+// 10..35 = registers 'a' to 'z'
+// 36 = delete register '-'
+// 37 = selection register '*'
+// 38 = clipboard register '+'
#define DELETION_REGISTER 36
#define NUM_SAVED_REGISTERS 37
// The following registers should not be saved in ShaDa file:
diff --git a/src/nvim/option.c b/src/nvim/option.c
index 269a21b512..ab4db30aaf 100644
--- a/src/nvim/option.c
+++ b/src/nvim/option.c
@@ -106,14 +106,12 @@ static char e_number_required_after_equal[]
static char e_preview_window_already_exists[]
= N_("E590: A preview window already exists");
-/*
- * The options that are local to a window or buffer have "indir" set to one of
- * these values. Special values:
- * PV_NONE: global option.
- * PV_WIN is added: window-local option
- * PV_BUF is added: buffer-local option
- * PV_BOTH is added: global option which also has a local value.
- */
+// The options that are local to a window or buffer have "indir" set to one of
+// these values. Special values:
+// PV_NONE: global option.
+// PV_WIN is added: window-local option
+// PV_BUF is added: buffer-local option
+// PV_BOTH is added: global option which also has a local value.
#define PV_BOTH 0x1000
#define PV_WIN 0x2000
#define PV_BUF 0x4000
@@ -128,10 +126,8 @@ typedef enum {
PV_MAXVAL = 0xffff, // to avoid warnings for value out of range
} idopt_T;
-/*
- * Options local to a window have a value local to a buffer and global to all
- * buffers. Indicate this by setting "var" to VAR_WIN.
- */
+// Options local to a window have a value local to a buffer and global to all
+// buffers. Indicate this by setting "var" to VAR_WIN.
#define VAR_WIN ((char_u *)-1)
static char *p_term = NULL;
@@ -160,18 +156,16 @@ typedef struct vimoption {
// buffer-local option: global value
idopt_T indir; // global option: PV_NONE;
// local option: indirect option index
- char_u *def_val; // default values for variable (neovim!!)
+ char *def_val; // default values for variable (neovim!!)
LastSet last_set; // script in which the option was last set
} vimoption_T;
-/*
- * options[] is initialized here.
- * The order of the options MUST be alphabetic for ":set all" and findoption().
- * All option names MUST start with a lowercase letter (for findoption()).
- * Exception: "t_" options are at the end.
- * The options with a NULL variable are 'hidden': a set command for them is
- * ignored and they are not printed.
- */
+// options[] is initialized here.
+// The order of the options MUST be alphabetic for ":set all" and findoption().
+// All option names MUST start with a lowercase letter (for findoption()).
+// Exception: "t_" options are at the end.
+// The options with a NULL variable are 'hidden': a set command for them is
+// ignored and they are not printed.
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "options.generated.h"
@@ -197,10 +191,8 @@ void set_init_1(bool clean_arg)
langmap_init();
- /*
- * Find default value for 'shell' option.
- * Don't use it if it is empty.
- */
+ // Find default value for 'shell' option.
+ // Don't use it if it is empty.
{
const char *shell = os_getenv("SHELL");
if (shell != NULL) {
@@ -215,10 +207,8 @@ void set_init_1(bool clean_arg)
}
}
- /*
- * Set the default for 'backupskip' to include environment variables for
- * temp files.
- */
+ // Set the default for 'backupskip' to include environment variables for
+ // temp files.
{
#ifdef UNIX
static char *(names[4]) = { "", "TMPDIR", "TEMP", "TMP" };
@@ -300,7 +290,7 @@ void set_init_1(bool clean_arg)
buf[j] = NUL;
opt_idx = findoption("cdpath");
if (opt_idx >= 0) {
- options[opt_idx].def_val = buf;
+ options[opt_idx].def_val = (char *)buf;
options[opt_idx].flags |= P_DEF_ALLOCED;
} else {
xfree(buf); // cannot happen
@@ -354,10 +344,8 @@ void set_init_1(bool clean_arg)
rtp = NULL; // ownership taken
}
- /*
- * Set all the options (except the terminal options) to their default
- * value. Also set the global value for local options.
- */
+ // Set all the options (except the terminal options) to their default
+ // value. Also set the global value for local options.
set_options_default(0);
curbuf->b_p_initialized = true;
@@ -380,15 +368,13 @@ void set_init_1(bool clean_arg)
// didset_options() because it only depends on 'encoding'.
init_spell_chartab();
- /*
- * Expand environment variables and things like "~" for the defaults.
- * If option_expand() returns non-NULL the variable is expanded. This can
- * only happen for non-indirect options.
- * Also set the default to the expanded value, so ":set" does not list
- * them.
- * Don't set the P_ALLOCED flag, because we don't want to free the
- * default.
- */
+ // Expand environment variables and things like "~" for the defaults.
+ // If option_expand() returns non-NULL the variable is expanded. This can
+ // only happen for non-indirect options.
+ // Also set the default to the expanded value, so ":set" does not list
+ // them.
+ // Don't set the P_ALLOCED flag, because we don't want to free the
+ // default.
for (opt_idx = 0; options[opt_idx].fullname; opt_idx++) {
if (options[opt_idx].flags & P_NO_DEF_EXP) {
continue;
@@ -398,7 +384,7 @@ void set_init_1(bool clean_arg)
&& options[opt_idx].var != NULL) {
p = _(*(char **)options[opt_idx].var);
} else {
- p = (char *)option_expand(opt_idx, NULL);
+ p = option_expand(opt_idx, NULL);
}
if (p != NULL) {
p = xstrdup(p);
@@ -406,7 +392,7 @@ void set_init_1(bool clean_arg)
if (options[opt_idx].flags & P_DEF_ALLOCED) {
xfree(options[opt_idx].def_val);
}
- options[opt_idx].def_val = (char_u *)p;
+ options[opt_idx].def_val = p;
options[opt_idx].flags |= P_DEF_ALLOCED;
}
}
@@ -434,7 +420,7 @@ void set_init_1(bool clean_arg)
// use utf-8 as 'default' if locale encoding can't be detected.
p = (char_u *)xmemdupz(S_LEN("utf-8"));
}
- fenc_default = p;
+ fenc_default = (char *)p;
#ifdef HAVE_WORKING_LIBINTL
// GNU gettext 0.10.37 supports this feature: set the codeset used for
@@ -463,12 +449,12 @@ static void set_option_default(int opt_idx, int opt_flags)
// freeing and allocating the value.
if (options[opt_idx].indir != PV_NONE) {
set_string_option_direct(NULL, opt_idx,
- (char *)options[opt_idx].def_val, opt_flags, 0);
+ options[opt_idx].def_val, opt_flags, 0);
} else {
if ((opt_flags & OPT_FREE) && (flags & P_ALLOCED)) {
free_string_option(*(char **)(varp));
}
- *(char_u **)varp = options[opt_idx].def_val;
+ *(char **)varp = options[opt_idx].def_val;
options[opt_idx].flags &= ~P_ALLOCED;
}
} else if (flags & P_NUM) {
@@ -547,9 +533,7 @@ static void set_string_default(const char *name, char *val, bool allocated)
xfree(options[opt_idx].def_val);
}
- options[opt_idx].def_val = allocated
- ? (char_u *)val
- : (char_u *)xstrdup(val);
+ options[opt_idx].def_val = allocated ? val : xstrdup(val);
options[opt_idx].flags |= P_DEF_ALLOCED;
}
}
@@ -593,7 +577,7 @@ void set_number_default(char *name, long val)
opt_idx = findoption(name);
if (opt_idx >= 0) {
- options[opt_idx].def_val = (char_u *)(intptr_t)val;
+ options[opt_idx].def_val = (char *)(intptr_t)val;
}
}
@@ -608,7 +592,7 @@ void free_all_options(void)
free_string_option(*(char **)options[i].var);
}
if (options[i].flags & P_DEF_ALLOCED) {
- free_string_option((char *)options[i].def_val);
+ free_string_option(options[i].def_val);
}
} else if (options[i].var != VAR_WIN && (options[i].flags & P_STRING)) {
// buffer-local option: free global value
@@ -635,10 +619,8 @@ void set_init_2(bool headless)
}
comp_col();
- /*
- * 'window' is only for backwards compatibility with Vi.
- * Default is Rows - 1.
- */
+ // 'window' is only for backwards compatibility with Vi.
+ // Default is Rows - 1.
if (!option_was_set("window")) {
p_window = Rows - 1;
}
@@ -664,42 +646,42 @@ void set_init_3(void)
: !(options[idx_sp].flags & P_WAS_SET);
size_t len = 0;
- char_u *p = (char_u *)invocation_path_tail(p_sh, &len);
- p = vim_strnsave(p, len);
+ char *p = (char *)invocation_path_tail((char_u *)p_sh, &len);
+ p = xstrnsave(p, len);
{
//
// Default for p_sp is "| tee", for p_srr is ">".
// For known shells it is changed here to include stderr.
//
- if (FNAMECMP(p, "csh") == 0
- || FNAMECMP(p, "tcsh") == 0) {
+ if (path_fnamecmp(p, "csh") == 0
+ || path_fnamecmp(p, "tcsh") == 0) {
if (do_sp) {
p_sp = "|& tee";
- options[idx_sp].def_val = (char_u *)p_sp;
+ options[idx_sp].def_val = p_sp;
}
if (do_srr) {
p_srr = ">&";
- options[idx_srr].def_val = (char_u *)p_srr;
+ options[idx_srr].def_val = p_srr;
}
- } else if (FNAMECMP(p, "sh") == 0
- || FNAMECMP(p, "ksh") == 0
- || FNAMECMP(p, "mksh") == 0
- || FNAMECMP(p, "pdksh") == 0
- || FNAMECMP(p, "zsh") == 0
- || FNAMECMP(p, "zsh-beta") == 0
- || FNAMECMP(p, "bash") == 0
- || FNAMECMP(p, "fish") == 0
- || FNAMECMP(p, "ash") == 0
- || FNAMECMP(p, "dash") == 0) {
+ } else if (path_fnamecmp(p, "sh") == 0
+ || path_fnamecmp(p, "ksh") == 0
+ || path_fnamecmp(p, "mksh") == 0
+ || path_fnamecmp(p, "pdksh") == 0
+ || path_fnamecmp(p, "zsh") == 0
+ || path_fnamecmp(p, "zsh-beta") == 0
+ || path_fnamecmp(p, "bash") == 0
+ || path_fnamecmp(p, "fish") == 0
+ || path_fnamecmp(p, "ash") == 0
+ || path_fnamecmp(p, "dash") == 0) {
// Always use POSIX shell style redirection if we reach this
if (do_sp) {
p_sp = "2>&1| tee";
- options[idx_sp].def_val = (char_u *)p_sp;
+ options[idx_sp].def_val = p_sp;
}
if (do_srr) {
p_srr = ">%s 2>&1";
- options[idx_srr].def_val = (char_u *)p_srr;
+ options[idx_srr].def_val = p_srr;
}
}
xfree(p);
@@ -758,19 +740,17 @@ void set_title_defaults(void)
{
int idx1;
- /*
- * If GUI is (going to be) used, we can always set the window title and
- * icon name. Saves a bit of time, because the X11 display server does
- * not need to be contacted.
- */
+ // If GUI is (going to be) used, we can always set the window title and
+ // icon name. Saves a bit of time, because the X11 display server does
+ // not need to be contacted.
idx1 = findoption("title");
if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) {
- options[idx1].def_val = (char_u *)(intptr_t)0;
+ options[idx1].def_val = 0;
p_title = 0;
}
idx1 = findoption("icon");
if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) {
- options[idx1].def_val = (char_u *)(intptr_t)0;
+ options[idx1].def_val = 0;
p_icon = 0;
}
}
@@ -837,10 +817,8 @@ int do_set(char *arg, int opt_flags)
if (STRNCMP(arg, "all", 3) == 0 && !isalpha(arg[3])
&& !(opt_flags & OPT_MODELINE)) {
- /*
- * ":set all" show all options.
- * ":set all&" set all options to their default value.
- */
+ // ":set all" show all options.
+ // ":set all&" set all options to their default value.
arg += 3;
if (*arg == '&') {
arg++;
@@ -1016,9 +994,7 @@ int do_set(char *arg, int opt_flags)
|| (prefix == 1
&& vim_strchr("=:&<", nextchar) == NULL
&& !(flags & P_BOOL))) {
- /*
- * print value
- */
+ // print value
if (did_show) {
msg_putchar('\n'); // cursor below last one
} else {
@@ -1057,11 +1033,9 @@ int do_set(char *arg, int opt_flags)
goto skip;
}
- /*
- * ":set opt!": invert
- * ":set opt&": reset to default value
- * ":set opt<": reset to global value
- */
+ // ":set opt!": invert
+ // ":set opt&": reset to default value
+ // ":set opt<": reset to global value
if (nextchar == '!') {
value = *(int *)(varp) ^ 1;
} else if (nextchar == '&') {
@@ -1076,10 +1050,8 @@ int do_set(char *arg, int opt_flags)
OPT_GLOBAL);
}
} else {
- /*
- * ":set invopt": invert
- * ":set opt" or ":set noopt": set or reset
- */
+ // ":set invopt": invert
+ // ":set opt" or ":set noopt": set or reset
if (nextchar != NUL && !ascii_iswhite(afterchar)) {
errmsg = e_trailing;
goto skip;
@@ -1131,7 +1103,7 @@ int do_set(char *arg, int opt_flags)
}
} else if (*arg == '-' || ascii_isdigit(*arg)) {
// Allow negative, octal and hex numbers.
- vim_str2nr((char_u *)arg, NULL, &i, STR2NR_ALL, &value, NULL, 0, true);
+ vim_str2nr(arg, NULL, &i, STR2NR_ALL, &value, NULL, 0, true);
if (i == 0 || (arg[i] != NUL && !ascii_iswhite(arg[i]))) {
errmsg = e_number_required_after_equal;
goto skip;
@@ -1155,9 +1127,9 @@ int do_set(char *arg, int opt_flags)
opt_flags);
} else if (opt_idx >= 0) { // String.
char_u *save_arg = NULL;
- char_u *s = NULL;
+ char *s = NULL;
char_u *oldval = NULL; // previous value if *varp
- char_u *newval;
+ char *newval;
char_u *origval = NULL;
char_u *origval_l = NULL;
char_u *origval_g = NULL;
@@ -1207,18 +1179,18 @@ int do_set(char *arg, int opt_flags)
// required when an environment variable was set
// later
if (newval == NULL) {
- newval = (char_u *)empty_option;
+ newval = empty_option;
} else if (!(options[opt_idx].flags & P_NO_DEF_EXP)) {
s = option_expand(opt_idx, newval);
if (s == NULL) {
s = newval;
}
- newval = vim_strsave(s);
+ newval = xstrdup(s);
} else {
- newval = (char_u *)xstrdup((char *)newval);
+ newval = xstrdup(newval);
}
} else if (nextchar == '<') { // set to global val
- newval = vim_strsave(*(char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL));
+ newval = xstrdup(*(char **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL));
} else {
arg++; // jump to after the '=' or ':'
@@ -1238,13 +1210,13 @@ int do_set(char *arg, int opt_flags)
*(char **)varp = empty_option;
break;
case 1:
- *(char_u **)varp = vim_strsave((char_u *)"indent,eol");
+ *(char_u **)varp = (char_u *)xstrdup("indent,eol");
break;
case 2:
- *(char_u **)varp = vim_strsave((char_u *)"indent,eol,start");
+ *(char_u **)varp = (char_u *)xstrdup("indent,eol,start");
break;
case 3:
- *(char_u **)varp = vim_strsave((char_u *)"indent,eol,nostop");
+ *(char_u **)varp = (char_u *)xstrdup("indent,eol,nostop");
break;
}
xfree(oldval);
@@ -1265,19 +1237,19 @@ int do_set(char *arg, int opt_flags)
*errbuf = NUL;
i = getdigits_int(&arg, true, 0);
if (i & 1) {
- STRLCAT(errbuf, "b,", sizeof(errbuf));
+ xstrlcat(errbuf, "b,", sizeof(errbuf));
}
if (i & 2) {
- STRLCAT(errbuf, "s,", sizeof(errbuf));
+ xstrlcat(errbuf, "s,", sizeof(errbuf));
}
if (i & 4) {
- STRLCAT(errbuf, "h,l,", sizeof(errbuf));
+ xstrlcat(errbuf, "h,l,", sizeof(errbuf));
}
if (i & 8) {
- STRLCAT(errbuf, "<,>,", sizeof(errbuf));
+ xstrlcat(errbuf, "<,>,", sizeof(errbuf));
}
if (i & 16) {
- STRLCAT(errbuf, "[,],", sizeof(errbuf));
+ xstrlcat(errbuf, "[,],", sizeof(errbuf));
}
save_arg = (char_u *)arg;
arg = errbuf;
@@ -1289,11 +1261,10 @@ int do_set(char *arg, int opt_flags)
arg++;
}
- /*
- * Copy the new string into allocated memory.
- * Can't use set_string_option_direct(), because
- * we need to remove the backslashes.
- */
+ // Copy the new string into allocated memory.
+ // Can't use set_string_option_direct(), because
+ // we need to remove the backslashes.
+
// get a bit too much
newlen = (unsigned)STRLEN(arg) + 1;
if (adding || prepending || removing) {
@@ -1302,14 +1273,12 @@ int do_set(char *arg, int opt_flags)
newval = xmalloc(newlen);
s = newval;
- /*
- * Copy the string, skip over escaped chars.
- * For WIN32 backslashes before normal
- * file name characters are not removed, and keep
- * backslash at start, for "\\machine\path", but
- * do remove it for "\\\\machine\\path".
- * The reverse is found in ExpandOldSetting().
- */
+ // Copy the string, skip over escaped chars.
+ // For WIN32 backslashes before normal
+ // file name characters are not removed, and keep
+ // backslash at start, for "\\machine\path", but
+ // do remove it for "\\\\machine\\path".
+ // The reverse is found in ExpandOldSetting().
while (*arg && !ascii_iswhite(*arg)) {
if (*arg == '\\' && arg[1] != NUL
#ifdef BACKSLASH_IN_FILENAME
@@ -1330,16 +1299,14 @@ int do_set(char *arg, int opt_flags)
arg += i;
s += i;
} else {
- *s++ = (uint8_t)(*arg++);
+ *s++ = *arg++;
}
}
*s = NUL;
- /*
- * Expand environment variables and ~.
- * Don't do it when adding without inserting a
- * comma.
- */
+ // Expand environment variables and ~.
+ // Don't do it when adding without inserting a
+ // comma.
if (!(adding || prepending || removing)
|| (flags & P_COMMA)) {
s = option_expand(opt_idx, newval);
@@ -1359,7 +1326,7 @@ int do_set(char *arg, int opt_flags)
i = 0; // init for GCC
if (removing || (flags & P_NODUP)) {
i = (int)STRLEN(newval);
- s = find_dup_item(origval, newval, flags);
+ s = (char *)find_dup_item(origval, (char_u *)newval, flags);
// do not add if already there
if ((adding || prepending) && s != NULL) {
@@ -1371,7 +1338,7 @@ int do_set(char *arg, int opt_flags)
// if no duplicate, move pointer to end of
// original value
if (s == NULL) {
- s = origval + (int)STRLEN(origval);
+ s = (char *)origval + (int)STRLEN(origval);
}
}
@@ -1408,7 +1375,7 @@ int do_set(char *arg, int opt_flags)
if (*s) {
// may need to remove a comma
if (flags & P_COMMA) {
- if (s == origval) {
+ if (s == (char *)origval) {
// include comma after string
if (s[i] == ',') {
i++;
@@ -1419,7 +1386,7 @@ int do_set(char *arg, int opt_flags)
i++;
}
}
- STRMOVE(newval + (s - origval), s + i);
+ STRMOVE(newval + (s - (char *)origval), s + i);
}
}
@@ -1430,14 +1397,14 @@ int do_set(char *arg, int opt_flags)
// 'whichwrap'
if (flags & P_ONECOMMA) {
if (*s != ',' && *(s + 1) == ','
- && vim_strchr((char *)s + 2, *s) != NULL) {
+ && vim_strchr(s + 2, *s) != NULL) {
// Remove the duplicated value and the next comma.
STRMOVE(s, s + 2);
continue;
}
} else {
if ((!(flags & P_COMMA) || *s != ',')
- && vim_strchr((char *)s + 1, *s) != NULL) {
+ && vim_strchr(s + 1, *s) != NULL) {
STRMOVE(s, s + 1);
continue;
}
@@ -1452,7 +1419,7 @@ int do_set(char *arg, int opt_flags)
}
// Set the new value.
- *(char_u **)(varp) = newval;
+ *(char_u **)(varp) = (char_u *)newval;
// origval may be freed by
// did_set_string_option(), make a copy.
@@ -1462,7 +1429,7 @@ int do_set(char *arg, int opt_flags)
// newval (and varp) may become invalid if the
// buffer is closed by autocommands.
- saved_newval = (newval != NULL) ? xstrdup((char *)newval) : 0;
+ saved_newval = (newval != NULL) ? xstrdup(newval) : 0;
{
uint32_t *p = insecure_flag(curwin, opt_idx, opt_flags);
@@ -1521,12 +1488,10 @@ int do_set(char *arg, int opt_flags)
}
skip:
- /*
- * Advance to next argument.
- * - skip until a blank found, taking care of backslashes
- * - skip blanks
- * - skip one "=val" argument (for hidden options ":set gfn =xx")
- */
+ // Advance to next argument.
+ // - skip until a blank found, taking care of backslashes
+ // - skip blanks
+ // - skip one "=val" argument (for hidden options ":set gfn =xx")
for (i = 0; i < 2; i++) {
while (*arg != NUL && !ascii_iswhite(*arg)) {
if (*arg++ == '\\' && *arg != NUL) {
@@ -1629,10 +1594,8 @@ void did_set_title(void)
/// @param opt_flags OPT_LOCAL and/or OPT_GLOBAL
void set_options_bin(int oldval, int newval, int opt_flags)
{
- /*
- * The option values that are changed when 'bin' changes are
- * copied when 'bin is set and restored when 'bin' is reset.
- */
+ // The option values that are changed when 'bin' changes are
+ // copied when 'bin is set and restored when 'bin' is reset.
if (newval) {
if (!oldval) { // switched on
if (!(opt_flags & OPT_GLOBAL)) {
@@ -1718,7 +1681,7 @@ char_u *find_shada_parameter(int type)
/// These string options cannot be indirect!
/// If "val" is NULL expand the current value of the option.
/// Return pointer to NameBuff, or NULL when not expanded.
-static char_u *option_expand(int opt_idx, char_u *val)
+static char *option_expand(int opt_idx, char *val)
{
// if option doesn't need expansion nothing to do
if (!(options[opt_idx].flags & P_EXPAND) || options[opt_idx].var == NULL) {
@@ -1726,7 +1689,7 @@ static char_u *option_expand(int opt_idx, char_u *val)
}
if (val == NULL) {
- val = *(char_u **)options[opt_idx].var;
+ val = *(char **)options[opt_idx].var;
}
// If val is longer than MAXPATHL no meaningful expansion can be done,
@@ -1735,21 +1698,19 @@ static char_u *option_expand(int opt_idx, char_u *val)
return NULL;
}
- /*
- * Expanding this with NameBuff, expand_env() must not be passed IObuff.
- * Escape spaces when expanding 'tags', they are used to separate file
- * names.
- * For 'spellsuggest' expand after "file:".
- */
- expand_env_esc(val, (char_u *)NameBuff, MAXPATHL,
+ // Expanding this with NameBuff, expand_env() must not be passed IObuff.
+ // Escape spaces when expanding 'tags', they are used to separate file
+ // names.
+ // For 'spellsuggest' expand after "file:".
+ expand_env_esc((char_u *)val, (char_u *)NameBuff, MAXPATHL,
(char_u **)options[opt_idx].var == &p_tags, false,
(char_u **)options[opt_idx].var == (char_u **)&p_sps ? (char_u *)"file:" :
NULL);
- if (STRCMP(NameBuff, val) == 0) { // they are the same
+ if (strcmp(NameBuff, val) == 0) { // they are the same
return NULL;
}
- return (char_u *)NameBuff;
+ return NameBuff;
}
/// After setting various option values: recompute variables that depend on
@@ -2153,9 +2114,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va
if ((int *)varp == &curwin->w_p_arab) {
if (curwin->w_p_arab) {
- /*
- * 'arabic' is set, handle various sub-settings.
- */
+ // 'arabic' is set, handle various sub-settings.
if (!p_tbidi) {
// set rightleft mode
if (!curwin->w_p_rl) {
@@ -2172,7 +2131,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va
// Arabic requires a utf-8 encoding, inform the user if it's not
// set.
- if (STRCMP(p_enc, "utf-8") != 0) {
+ if (strcmp(p_enc, "utf-8") != 0) {
static char *w_arabic = N_("W17: Arabic requires UTF-8, do ':set encoding=utf-8'");
msg_source(HL_ATTR(HLF_W));
@@ -2186,9 +2145,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va
// Force-set the necessary keymap for arabic.
errmsg = set_option_value("keymap", 0L, "arabic", OPT_LOCAL);
} else {
- /*
- * 'arabic' is reset, handle various sub-settings.
- */
+ // 'arabic' is reset, handle various sub-settings.
if (!p_tbidi) {
// reset rightleft mode
if (curwin->w_p_rl) {
@@ -2209,9 +2166,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va
}
}
- /*
- * End of handling side effects for bool options.
- */
+ // End of handling side effects for bool options.
// after handling side effects, call autocommand
@@ -2801,7 +2756,7 @@ int findoption_len(const char *const arg, const size_t len)
if (STRLEN(options[opt_idx].fullname) == 7) {
return findoption_len("shada", 5);
}
- assert(STRCMP(options[opt_idx].fullname, "viminfofile") == 0);
+ assert(strcmp(options[opt_idx].fullname, "viminfofile") == 0);
return findoption_len("shadafile", 9);
}
}
@@ -3328,9 +3283,7 @@ static void showoptions(int all, int opt_flags)
}
}
- /*
- * display the items
- */
+ // display the items
if (run == 1) {
assert(Columns <= INT_MAX - GAP
&& Columns + GAP >= INT_MIN + 3
@@ -3374,7 +3327,7 @@ static int optval_default(vimoption_T *p, char_u *varp)
return *(int *)varp == (int)(intptr_t)p->def_val;
}
// P_STRING
- return STRCMP(*(char_u **)varp, p->def_val) == 0;
+ return strcmp(*(char **)varp, p->def_val) == 0;
}
/// Send update to UIs with values of UI relevant options
@@ -3467,15 +3420,13 @@ int makeset(FILE *fd, int opt_flags, int local_only)
int round;
int pri;
- /*
- * Some options are never written:
- * - Options that don't have a default (terminal name, columns, lines).
- * - Terminal options.
- * - Hidden options.
- *
- * Do the loop over "options[]" twice: once for options with the
- * P_PRI_MKRC flag and once without.
- */
+ // Some options are never written:
+ // - Options that don't have a default (terminal name, columns, lines).
+ // - Terminal options.
+ // - Hidden options.
+ //
+ // Do the loop over "options[]" twice: once for options with the
+ // P_PRI_MKRC flag and once without.
for (pri = 1; pri >= 0; pri--) {
for (p = &options[0]; p->fullname; p++) {
if (!(p->flags & P_NO_MKRC)
@@ -4400,10 +4351,8 @@ void buf_copy_options(buf_T *buf, int flags)
int dont_do_help;
int did_isk = false;
- /*
- * Skip this when the option defaults have not been set yet. Happens when
- * main() allocates the first buffer.
- */
+ // Skip this when the option defaults have not been set yet. Happens when
+ // main() allocates the first buffer.
if (p_cpo != NULL) {
//
// Always copy when entering and 'cpo' contains 'S'.
@@ -4500,7 +4449,7 @@ void buf_copy_options(buf_T *buf, int flags)
buf->b_p_cpt = xstrdup(p_cpt);
COPY_OPT_SCTX(buf, BV_CPT);
#ifdef BACKSLASH_IN_FILENAME
- buf->b_p_csl = vim_strsave(p_csl);
+ buf->b_p_csl = xstrdup(p_csl);
COPY_OPT_SCTX(buf, BV_CSL);
#endif
buf->b_p_cfu = xstrdup(p_cfu);
@@ -4617,12 +4566,10 @@ void buf_copy_options(buf_T *buf, int flags)
buf->b_p_lw = empty_option;
buf->b_p_menc = empty_option;
- /*
- * Don't copy the options set by ex_help(), use the saved values,
- * when going from a help buffer to a non-help buffer.
- * Don't touch these at all when BCO_NOHELP is used and going from
- * or to a help buffer.
- */
+ // Don't copy the options set by ex_help(), use the saved values,
+ // when going from a help buffer to a non-help buffer.
+ // Don't touch these at all when BCO_NOHELP is used and going from
+ // or to a help buffer.
if (dont_do_help) {
buf->b_p_isk = (char *)save_p_isk;
if (p_vts && p_vts != empty_option && !buf->b_p_vts_array) {
@@ -4652,10 +4599,8 @@ void buf_copy_options(buf_T *buf, int flags)
}
}
- /*
- * When the options should be copied (ignoring BCO_ALWAYS), set the
- * flag that indicates that the options have been initialized.
- */
+ // When the options should be copied (ignoring BCO_ALWAYS), set the
+ // flag that indicates that the options have been initialized.
if (should_copy) {
buf->b_p_initialized = true;
}
@@ -4879,7 +4824,7 @@ int ExpandSettings(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***fi
int num_normal = 0; // Nr of matching non-term-code settings
int match;
int count = 0;
- char_u *str;
+ char *str;
int loop;
static char *(names[]) = { "all" };
int ic = regmatch->rm_ic; // remember the ignore-case flag
@@ -4901,7 +4846,7 @@ int ExpandSettings(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***fi
}
}
}
- for (size_t opt_idx = 0; (str = (char_u *)options[opt_idx].fullname) != NULL;
+ for (size_t opt_idx = 0; (str = options[opt_idx].fullname) != NULL;
opt_idx++) {
if (options[opt_idx].var == NULL) {
continue;
@@ -4911,7 +4856,7 @@ int ExpandSettings(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***fi
continue;
}
match = false;
- if (vim_regexec(regmatch, (char *)str, (colnr_T)0)
+ if (vim_regexec(regmatch, str, (colnr_T)0)
|| (options[opt_idx].shortname != NULL
&& vim_regexec(regmatch,
options[opt_idx].shortname,
@@ -4923,7 +4868,7 @@ int ExpandSettings(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***fi
if (loop == 0) {
num_normal++;
} else {
- (*file)[count++] = (char *)vim_strsave(str);
+ (*file)[count++] = xstrdup(str);
}
}
}
@@ -4934,7 +4879,7 @@ int ExpandSettings(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***fi
} else {
return OK;
}
- *file = xmalloc((size_t)(*num_file) * sizeof(char_u *));
+ *file = xmalloc((size_t)(*num_file) * sizeof(char *));
}
}
return OK;
@@ -4947,9 +4892,7 @@ void ExpandOldSetting(int *num_file, char ***file)
*num_file = 0;
*file = xmalloc(sizeof(char_u *));
- /*
- * For a terminal key code expand_option_idx is < 0.
- */
+ // For a terminal key code expand_option_idx is < 0.
if (expand_option_idx < 0) {
expand_option_idx = findoption((const char *)expand_option_name);
}
@@ -5055,10 +4998,8 @@ static void paste_option_changed(void)
static int save_hkmap = 0;
if (p_paste) {
- /*
- * Paste switched from off to on.
- * Save the current values, so they can be restored later.
- */
+ // Paste switched from off to on.
+ // Save the current values, so they can be restored later.
if (!old_p_paste) {
// save options for each buffer
FOR_ALL_BUFFERS(buf) {
@@ -5287,7 +5228,7 @@ int fill_culopt_flags(char *val, win_T *wp)
/// Set the callback function value for an option that accepts a function name,
/// lambda, et al. (e.g. 'operatorfunc', 'tagfunc', etc.)
/// @return OK if the option is successfully set to a function, otherwise FAIL
-int option_set_callback_func(char_u *optval, Callback *optcb)
+int option_set_callback_func(char *optval, Callback *optcb)
{
if (optval == NULL || *optval == NUL) {
callback_free(optcb);
@@ -5299,7 +5240,7 @@ int option_set_callback_func(char_u *optval, Callback *optcb)
|| (STRNCMP(optval, "function(", 9) == 0)
|| (STRNCMP(optval, "funcref(", 8) == 0)) {
// Lambda expression or a funcref
- tv = eval_expr((char *)optval);
+ tv = eval_expr(optval);
if (tv == NULL) {
return FAIL;
}
@@ -5307,7 +5248,7 @@ int option_set_callback_func(char_u *optval, Callback *optcb)
// treat everything else as a function name string
tv = xcalloc(1, sizeof(*tv));
tv->v_type = VAR_STRING;
- tv->vval.v_string = (char *)vim_strsave(optval);
+ tv->vval.v_string = xstrdup(optval);
}
Callback cb;
@@ -5366,7 +5307,7 @@ char_u *get_showbreak_value(win_T *const win)
if (win->w_p_sbr == NULL || *win->w_p_sbr == NUL) {
return (char_u *)p_sbr;
}
- if (STRCMP(win->w_p_sbr, "NONE") == 0) {
+ if (strcmp(win->w_p_sbr, "NONE") == 0) {
return (char_u *)empty_option;
}
return (char_u *)win->w_p_sbr;
@@ -5512,13 +5453,13 @@ size_t copy_option_part(char **option, char *buf, size_t maxlen, char *sep_chars
/// Return true when 'shell' has "csh" in the tail.
int csh_like_shell(void)
{
- return strstr(path_tail((char *)p_sh), "csh") != NULL;
+ return strstr(path_tail(p_sh), "csh") != NULL;
}
/// Return true when 'shell' has "fish" in the tail.
bool fish_like_shell(void)
{
- return strstr(path_tail((char *)p_sh), "fish") != NULL;
+ return strstr(path_tail(p_sh), "fish") != NULL;
}
/// Return the number of requested sign columns, based on current
@@ -5676,7 +5617,7 @@ static Dictionary vimoption2dict(vimoption_T *opt)
const char *type;
Object def;
// TODO(bfredl): do you even nocp?
- char_u *def_val = opt->def_val;
+ char_u *def_val = (char_u *)opt->def_val;
if (opt->flags & P_STRING) {
type = "string";
def = CSTR_TO_OBJ(def_val ? (char *)def_val : "");
diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h
index 6af6b16e86..5dabc92bfc 100644
--- a/src/nvim/option_defs.h
+++ b/src/nvim/option_defs.h
@@ -379,9 +379,7 @@ enum {
#define LISPWORD_VALUE \
"defun,define,defmacro,set!,lambda,if,case,let,flet,let*,letrec,do,do*,define-syntax,let-syntax,letrec-syntax,destructuring-bind,defpackage,defparameter,defstruct,deftype,defvar,do-all-symbols,do-external-symbols,do-symbols,dolist,dotimes,ecase,etypecase,eval-when,labels,macrolet,multiple-value-bind,multiple-value-call,multiple-value-prog1,multiple-value-setq,prog1,progv,typecase,unless,unwind-protect,when,with-input-from-string,with-open-file,with-open-stream,with-output-to-string,with-package-iterator,define-condition,handler-bind,handler-case,restart-bind,restart-case,with-simple-restart,store-value,use-value,muffle-warning,abort,continue,with-slots,with-slots*,with-accessors,with-accessors*,defclass,defmethod,print-unreadable-object"
-/*
- * The following are actual variables for the options
- */
+// The following are actual variables for the options
EXTERN long p_aleph; // 'aleph'
EXTERN char *p_ambw; ///< 'ambiwidth'
@@ -505,7 +503,7 @@ EXTERN int p_eb; // 'errorbells'
EXTERN char_u *p_ef; // 'errorfile'
EXTERN char *p_efm; // 'errorformat'
EXTERN char *p_gefm; // 'grepformat'
-EXTERN char_u *p_gp; // 'grepprg'
+EXTERN char *p_gp; // 'grepprg'
EXTERN int p_eol; ///< 'endofline'
EXTERN char *p_ei; // 'eventignore'
EXTERN int p_et; ///< 'expandtab'
@@ -618,6 +616,7 @@ EXTERN int p_ma; ///< 'modifiable'
EXTERN int p_mod; ///< 'modified'
EXTERN char *p_mouse; // 'mouse'
EXTERN char *p_mousem; // 'mousemodel'
+EXTERN int p_mousemev; ///< 'mousemoveevent'
EXTERN int p_mousef; // 'mousefocus'
EXTERN char *p_mousescroll; // 'mousescroll'
EXTERN long p_mousescroll_vert INIT(= MOUSESCROLL_VERT_DFLT);
@@ -685,11 +684,11 @@ EXTERN unsigned ssop_flags;
#define SSOP_TERMINAL 0x10000
#define SSOP_SKIP_RTP 0x20000
-EXTERN char_u *p_sh; // 'shell'
+EXTERN char *p_sh; // 'shell'
EXTERN char_u *p_shcf; // 'shellcmdflag'
EXTERN char *p_sp; // 'shellpipe'
EXTERN char_u *p_shq; // 'shellquote'
-EXTERN char_u *p_sxq; // 'shellxquote'
+EXTERN char *p_sxq; // 'shellxquote'
EXTERN char_u *p_sxe; // 'shellxescape'
EXTERN char *p_srr; // 'shellredir'
EXTERN int p_stmp; // 'shelltemp'
@@ -732,6 +731,7 @@ EXTERN char *p_spc; ///< 'spellcapcheck'
EXTERN char *p_spf; ///< 'spellfile'
EXTERN char *p_spl; ///< 'spelllang'
EXTERN char *p_spo; // 'spelloptions'
+EXTERN unsigned int spo_flags;
EXTERN char *p_sps; // 'spellsuggest'
EXTERN int p_spr; // 'splitright'
EXTERN int p_sol; // 'startofline'
@@ -924,11 +924,9 @@ enum {
BV_COUNT, // must be the last one
};
-/*
- * "indir" values for window-local options.
- * These need to be defined globally, so that the WV_COUNT can be used in the
- * window structure.
- */
+// "indir" values for window-local options.
+// These need to be defined globally, so that the WV_COUNT can be used in the
+// window structure.
enum {
WV_LIST = 0,
WV_ARAB,
@@ -992,4 +990,4 @@ typedef struct {
uint64_t channel_id; /// Only used when script_id is SID_API_CLIENT.
} LastSet;
-#endif // NVIM_OPTION_DEFS_H
+#endif // NVIM_OPTION_DEFS_H
diff --git a/src/nvim/options.lua b/src/nvim/options.lua
index 2f941f5d0c..1d9a821e20 100644
--- a/src/nvim/options.lua
+++ b/src/nvim/options.lua
@@ -1622,6 +1622,14 @@ return {
defaults={if_true="popup_setpos"}
},
{
+ full_name='mousemoveevent', abbreviation='mousemev',
+ short_desc=N_("deliver mouse move events to input queue"),
+ type='bool', scope={'global'},
+ redraw={'ui_option'},
+ varname='p_mousemev',
+ defaults={if_true=false}
+ },
+ {
full_name='mousescroll',
short_desc=N_("amount to scroll by when scrolling with a mouse"),
type='string', list='comma', scope={'global'},
@@ -2347,6 +2355,7 @@ return {
secure=true,
expand=true,
varname='p_spo',
+ redraw={'current_buffer'},
defaults={if_true=""}
},
{
@@ -2859,7 +2868,8 @@ return {
{
full_name='winhighlight', abbreviation='winhl',
short_desc=N_("Setup window-local highlights");
- type='string', scope={'window'},
+ type='string', list='onecomma', scope={'window'},
+ deny_duplicates=true,
alloced=true,
redraw={'current_window'},
defaults={if_true=""}
diff --git a/src/nvim/optionstr.c b/src/nvim/optionstr.c
index 1bdfcbecb9..9d21603754 100644
--- a/src/nvim/optionstr.c
+++ b/src/nvim/optionstr.c
@@ -107,6 +107,7 @@ static char *(p_fdc_values[]) = { "auto", "auto:1", "auto:2", "auto:3", "auto:4"
"auto:6", "auto:7", "auto:8", "auto:9", "0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", NULL };
static char *(p_cb_values[]) = { "unnamed", "unnamedplus", NULL };
+static char *(p_spo_values[]) = { "camel", "noplainbuffer", NULL };
static char *(p_icm_values[]) = { "nosplit", "split", NULL };
static char *(p_jop_values[]) = { "stack", "view", NULL };
static char *(p_tpf_values[]) = { "BS", "HT", "FF", "ESC", "DEL", "C0", "C1", NULL };
@@ -252,7 +253,7 @@ void check_buf_options(buf_T *buf)
/// Free the string allocated for an option.
/// Checks for the string being empty_option. This may happen if we're out of
-/// memory, vim_strsave() returned NULL, which was replaced by empty_option by
+/// memory, xstrdup() returned NULL, which was replaced by empty_option by
/// check_options().
/// Does NOT check for P_ALLOCED flag!
void free_string_option(char *p)
@@ -682,7 +683,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
}
}
} else if (varp == &p_bex || varp == &p_pm) { // 'backupext' and 'patchmode'
- if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex,
+ if (strcmp(*p_bex == '.' ? p_bex + 1 : p_bex,
*p_pm == '.' ? p_pm + 1 : p_pm) == 0) {
errmsg = e_backupext_and_patchmode_are_equal;
}
@@ -730,7 +731,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
}
}
} else if (varp == &p_hl) { // 'highlight'
- if (STRCMP(*varp, HIGHLIGHT_INIT) != 0) {
+ if (strcmp(*varp, HIGHLIGHT_INIT) != 0) {
errmsg = e_unsupportedoption;
}
} else if (varp == &p_jop) { // 'jumpoptions'
@@ -822,13 +823,13 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
}
if (errmsg == NULL) {
- // canonize the value, so that STRCMP() can be used on it
+ // canonize the value, so that strcmp() can be used on it
p = enc_canonize(*varp);
xfree(*varp);
*varp = p;
if (varp == &p_enc) {
// only encoding=utf-8 allowed
- if (STRCMP(p_enc, "utf-8") != 0) {
+ if (strcmp(p_enc, "utf-8") != 0) {
errmsg = e_unsupportedoption;
} else {
spell_reload();
@@ -1125,7 +1126,8 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
// When 'spellcapcheck' is set compile the regexp program.
errmsg = compile_cap_prog(curwin->w_s);
} else if (varp == &(curwin->w_s->b_p_spo)) { // 'spelloptions'
- if (**varp != NUL && STRCMP("camel", *varp) != 0) {
+ if (opt_strings_flags(curwin->w_s->b_p_spo, p_spo_values, &(curwin->w_s->b_p_spo_flags),
+ true) != OK) {
errmsg = e_invarg;
}
} else if (varp == &p_sps) { // 'spellsuggest'
@@ -1356,7 +1358,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
} else {
if (opt_strings_flags(ve, p_ve_values, flags, true) != OK) {
errmsg = e_invarg;
- } else if (STRCMP(p_ve, oldval) != 0) {
+ } else if (strcmp(p_ve, oldval) != 0) {
// Recompute cursor position in case the new 've' setting
// changes something.
validate_virtcol();
@@ -1391,7 +1393,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
if (!valid_filetype(*varp)) {
errmsg = e_invarg;
} else {
- value_changed = STRCMP(oldval, *varp) != 0;
+ value_changed = strcmp(oldval, *varp) != 0;
// Since we check the value, there is no need to set P_INSECURE,
// even when the value comes from a modeline.
@@ -1401,7 +1403,7 @@ char *did_set_string_option(int opt_idx, char **varp, char *oldval, char *errbuf
if (!valid_filetype(*varp)) {
errmsg = e_invarg;
} else {
- value_changed = STRCMP(oldval, *varp) != 0;
+ value_changed = strcmp(oldval, *varp) != 0;
// Since we check the value, there is no need to set P_INSECURE,
// even when the value comes from a modeline.
diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c
index c940c86675..34ed3aaf6e 100644
--- a/src/nvim/os/env.c
+++ b/src/nvim/os/env.c
@@ -476,7 +476,7 @@ void init_homedir(void)
// Change to the directory and get the actual path. This resolves
// links. Don't do it when we can't return.
if (os_dirname((char_u *)os_buf, MAXPATHL) == OK && os_chdir(os_buf) == 0) {
- if (!os_chdir(var) && os_dirname(IObuff, IOSIZE) == OK) {
+ if (!os_chdir(var) && os_dirname((char_u *)IObuff, IOSIZE) == OK) {
var = (char *)IObuff;
}
if (os_chdir(os_buf) != 0) {
@@ -669,8 +669,8 @@ void expand_env_esc(char_u *restrict srcp, char_u *restrict dst, int dstlen, boo
ExpandInit(&xpc);
xpc.xp_context = EXPAND_FILES;
- var = ExpandOne(&xpc, dst, NULL,
- WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
+ var = (char_u *)ExpandOne(&xpc, (char *)dst, NULL,
+ WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
mustfree = true;
}
#else
@@ -684,7 +684,7 @@ void expand_env_esc(char_u *restrict srcp, char_u *restrict dst, int dstlen, boo
// If 'shellslash' is set change backslashes to forward slashes.
// Can't use slash_adjust(), p_ssl may be set temporarily.
if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL) {
- char_u *p = vim_strsave(var);
+ char_u *p = xstrdup(var);
if (mustfree) {
xfree(var);
@@ -804,7 +804,7 @@ static char *remove_tail(char *path, char *pend, char *dirname)
char *new_tail = pend - len - 1;
if (new_tail >= path
- && FNAMENCMP((char_u *)new_tail, (char_u *)dirname, len) == 0
+ && path_fnamencmp(new_tail, dirname, len) == 0
&& (new_tail == path || after_pathsep(path, new_tail))) {
return new_tail;
}
@@ -1098,7 +1098,7 @@ size_t home_replace(const buf_T *const buf, const char *src, char *const dst, si
size_t len = dirlen;
for (;;) {
if (len
- && FNAMENCMP(src, (char_u *)p, len) == 0
+ && path_fnamencmp(src, p, len) == 0
&& (vim_ispathsep(src[len])
|| (!one && (src[len] == ',' || src[len] == ' '))
|| src[len] == NUL)) {
diff --git a/src/nvim/os/input.c b/src/nvim/os/input.c
index bfe6d59dc6..ea9f31d776 100644
--- a/src/nvim/os/input.c
+++ b/src/nvim/os/input.c
@@ -293,7 +293,8 @@ static uint8_t check_multiclick(int code, int grid, int row, int col)
|| code == KE_MOUSEDOWN
|| code == KE_MOUSEUP
|| code == KE_MOUSELEFT
- || code == KE_MOUSERIGHT) {
+ || code == KE_MOUSERIGHT
+ || code == KE_MOUSEMOVE) {
return 0;
}
uint64_t mouse_time = os_hrtime(); // time of current mouse click (ns)
@@ -347,7 +348,8 @@ static unsigned int handle_mouse_event(char **ptr, uint8_t *buf, unsigned int bu
if (type != KS_EXTRA
|| !((mouse_code >= KE_LEFTMOUSE && mouse_code <= KE_RIGHTRELEASE)
- || (mouse_code >= KE_MOUSEDOWN && mouse_code <= KE_MOUSERIGHT))) {
+ || (mouse_code >= KE_MOUSEDOWN && mouse_code <= KE_MOUSERIGHT)
+ || mouse_code == KE_MOUSEMOVE)) {
return bufsize;
}
diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c
index 35390e3dc1..cf66899493 100644
--- a/src/nvim/os/shell.c
+++ b/src/nvim/os/shell.c
@@ -52,11 +52,11 @@ static void save_patterns(int num_pat, char **pat, int *num_file, char ***file)
{
*file = xmalloc((size_t)num_pat * sizeof(char_u *));
for (int i = 0; i < num_pat; i++) {
- char_u *s = vim_strsave((char_u *)pat[i]);
+ char *s = xstrdup(pat[i]);
// Be compatible with expand_filename(): halve the number of
// backslashes.
- backslash_halve((char *)s);
- (*file)[i] = (char *)s;
+ backslash_halve(s);
+ (*file)[i] = s;
}
*num_file = num_pat;
}
@@ -64,7 +64,7 @@ static void save_patterns(int num_pat, char **pat, int *num_file, char ***file)
static bool have_wildcard(int num, char **file)
{
for (int i = 0; i < num; i++) {
- if (path_has_wildcard((char_u *)file[i])) {
+ if (path_has_wildcard(file[i])) {
return true;
}
}
@@ -129,7 +129,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in
bool is_fish_shell =
#if defined(UNIX)
- STRNCMP(invocation_path_tail(p_sh, NULL), "fish", 4) == 0;
+ STRNCMP(invocation_path_tail((char_u *)p_sh, NULL), "fish", 4) == 0;
#else
false;
#endif
@@ -160,7 +160,7 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in
}
// get a name for the temp file
- if ((tempname = vim_tempname()) == NULL) {
+ if ((tempname = (char_u *)vim_tempname()) == NULL) {
emsg(_(e_notmp));
return FAIL;
}
@@ -182,14 +182,14 @@ int os_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, in
&& *(pat[0] + len - 1) == '`') {
shell_style = STYLE_BT;
} else if ((len = STRLEN(p_sh)) >= 3) {
- if (STRCMP(p_sh + len - 3, "csh") == 0) {
+ if (strcmp(p_sh + len - 3, "csh") == 0) {
shell_style = STYLE_GLOB;
- } else if (STRCMP(p_sh + len - 3, "zsh") == 0) {
+ } else if (strcmp(p_sh + len - 3, "zsh") == 0) {
shell_style = STYLE_PRINT;
}
}
if (shell_style == STYLE_ECHO
- && strstr(path_tail((char *)p_sh), "sh") != NULL) {
+ && strstr(path_tail(p_sh), "sh") != NULL) {
shell_style = STYLE_VIMGLOB;
}
@@ -555,11 +555,11 @@ notfound:
char **shell_build_argv(const char *cmd, const char *extra_args)
FUNC_ATTR_NONNULL_RET
{
- size_t argc = tokenize(p_sh, NULL) + (cmd ? tokenize(p_shcf, NULL) : 0);
+ size_t argc = tokenize((char_u *)p_sh, NULL) + (cmd ? tokenize(p_shcf, NULL) : 0);
char **rv = xmalloc((argc + 4) * sizeof(*rv));
// Split 'shell'
- size_t i = tokenize(p_sh, rv);
+ size_t i = tokenize((char_u *)p_sh, rv);
if (extra_args) {
rv[i++] = xstrdup(extra_args); // Push a copy of `extra_args`
@@ -700,7 +700,7 @@ int call_shell(char_u *cmd, ShellOpts opts, char_u *extra_shell_arg)
if (p_verbose > 3) {
verbose_enter();
- smsg(_("Executing command: \"%s\""), cmd == NULL ? p_sh : cmd);
+ smsg(_("Executing command: \"%s\""), cmd == NULL ? p_sh : (char *)cmd);
msg_putchar('\n');
verbose_leave();
}
@@ -746,7 +746,7 @@ char_u *get_cmd_output(char_u *cmd, char_u *infile, ShellOpts flags, size_t *ret
}
// get a name for the temp file
- char_u *tempname = vim_tempname();
+ char_u *tempname = (char_u *)vim_tempname();
if (tempname == NULL) {
emsg(_(e_notmp));
return NULL;
@@ -1106,7 +1106,7 @@ static void out_data_append_to_screen(char *output, size_t *count, bool eof)
// incomplete UTF-8 sequence that could be composing with the last
// complete sequence.
// This will be corrected when we switch to vterm based implementation
- int i = *p ? utfc_ptr2len_len((char_u *)p, (int)(end - p)) : 1;
+ int i = *p ? utfc_ptr2len_len(p, (int)(end - p)) : 1;
if (!eof && i == 1 && utf8len_tab_zero[*(uint8_t *)p] > (end - p)) {
*count = (size_t)(p - output);
goto end;
@@ -1316,7 +1316,7 @@ static char *shell_xescape_xquote(const char *cmd)
}
const char *ecmd = cmd;
- if (*p_sxe != NUL && STRCMP(p_sxq, "(") == 0) {
+ if (*p_sxe != NUL && strcmp(p_sxq, "(") == 0) {
ecmd = (char *)vim_strsave_escaped_ext((char_u *)cmd, p_sxe, '^', false);
}
size_t ncmd_size = strlen(ecmd) + STRLEN(p_sxq) * 2 + 1;
@@ -1324,9 +1324,9 @@ static char *shell_xescape_xquote(const char *cmd)
// When 'shellxquote' is ( append ).
// When 'shellxquote' is "( append )".
- if (STRCMP(p_sxq, "(") == 0) {
+ if (strcmp(p_sxq, "(") == 0) {
vim_snprintf(ncmd, ncmd_size, "(%s)", ecmd);
- } else if (STRCMP(p_sxq, "\"(") == 0) {
+ } else if (strcmp(p_sxq, "\"(") == 0) {
vim_snprintf(ncmd, ncmd_size, "\"(%s)\"", ecmd);
} else {
vim_snprintf(ncmd, ncmd_size, "%s%s%s", p_sxq, ecmd, p_sxq);
diff --git a/src/nvim/os/users.c b/src/nvim/os/users.c
index bd34e917b2..0c662e8843 100644
--- a/src/nvim/os/users.c
+++ b/src/nvim/os/users.c
@@ -93,7 +93,7 @@ int os_get_usernames(garray_T *users)
for (i = 0; i < users->ga_len; i++) {
char *local_user = ((char **)users->ga_data)[i];
- if (STRCMP(local_user, user_env) == 0) {
+ if (strcmp(local_user, user_env) == 0) {
break;
}
}
@@ -208,14 +208,14 @@ char *get_users(expand_T *xp, int idx)
/// @return 0 if name does not match any user name.
/// 1 if name partially matches the beginning of a user name.
/// 2 is name fully matches a user name.
-int match_user(char_u *name)
+int match_user(char *name)
{
int n = (int)STRLEN(name);
int result = 0;
init_users();
for (int i = 0; i < ga_users.ga_len; i++) {
- if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0) {
+ if (strcmp(((char **)ga_users.ga_data)[i], name) == 0) {
return 2; // full match
}
if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0) {
diff --git a/src/nvim/path.c b/src/nvim/path.c
index 8973d4dfdb..ac07fbee87 100644
--- a/src/nvim/path.c
+++ b/src/nvim/path.c
@@ -73,7 +73,7 @@ FileComparison path_full_compare(char *const s1, char *const s2, const bool chec
if (checkname) {
vim_FullName(exp1, full1, MAXPATHL, false);
vim_FullName(s2, full2, MAXPATHL, false);
- if (FNAMECMP(full1, full2) == 0) {
+ if (path_fnamecmp(full1, full2) == 0) {
return kEqualFileNames;
}
}
@@ -248,9 +248,7 @@ int vim_ispathsep(int c)
#endif
}
-/*
- * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
- */
+// Like vim_ispathsep(c), but exclude the colon for MS-Windows.
int vim_ispathsep_nocolon(int c)
{
return vim_ispathsep(c)
@@ -333,6 +331,12 @@ bool dir_of_file_exists(char_u *fname)
/// Compare two file names
///
+/// On some systems case in a file name does not matter, on others it does.
+///
+/// @note Does not account for maximum name lengths and things like "../dir",
+/// thus it is not 100% accurate. OS may also use different algorithm for
+/// case-insensitive comparison.
+///
/// Handles '/' and '\\' correctly and deals with &fileignorecase option.
///
/// @param[in] fname1 First file name.
@@ -509,7 +513,7 @@ char *save_abs_path(const char *name)
/// @param p The path to expand.
/// @returns Unix: True if it contains one of "?[{`'$".
/// @returns Windows: True if it contains one of "*?$[".
-bool path_has_wildcard(const char_u *p)
+bool path_has_wildcard(const char *p)
FUNC_ATTR_NONNULL_ALL
{
for (; *p; MB_PTR_ADV(p)) {
@@ -532,9 +536,7 @@ bool path_has_wildcard(const char_u *p)
return false;
}
-/*
- * Unix style wildcard expansion code.
- */
+// Unix style wildcard expansion code.
static int pstrcmp(const void *a, const void *b)
{
return pathcmp(*(char **)a, *(char **)b, -1);
@@ -579,7 +581,7 @@ bool path_has_exp_wildcard(const char_u *p)
static size_t path_expand(garray_T *gap, const char_u *path, int flags)
FUNC_ATTR_NONNULL_ALL
{
- return do_path_expand(gap, path, 0, flags, false);
+ return do_path_expand(gap, (char *)path, 0, flags, false);
}
static const char *scandir_next_with_dots(Directory *dir)
@@ -600,7 +602,7 @@ static const char *scandir_next_with_dots(Directory *dir)
/// Implementation of path_expand().
///
/// Chars before `path + wildoff` do not get expanded.
-static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, int flags,
+static size_t do_path_expand(garray_T *gap, const char *path, size_t wildoff, int flags,
bool didstar)
FUNC_ATTR_NONNULL_ALL
{
@@ -627,18 +629,18 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
char_u *p = buf;
char_u *s = buf;
char_u *e = NULL;
- const char_u *path_end = path;
+ const char_u *path_end = (char_u *)path;
while (*path_end != NUL) {
- /* May ignore a wildcard that has a backslash before it; it will
- * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
- if (path_end >= path + wildoff && rem_backslash((char *)path_end)) {
+ // May ignore a wildcard that has a backslash before it; it will
+ // be removed by rem_backslash() or file_pat_to_reg_pat() below.
+ if (path_end >= (char_u *)path + wildoff && rem_backslash((char *)path_end)) {
*p++ = *path_end++;
} else if (vim_ispathsep_nocolon(*path_end)) {
if (e != NULL) {
break;
}
s = p + 1;
- } else if (path_end >= path + wildoff
+ } else if (path_end >= (char_u *)path + wildoff
&& (vim_strchr("*?[{~$", *path_end) != NULL
#ifndef WIN32
|| (!p_fic && (flags & EW_ICASE) && mb_isalpha(utf_ptr2char((char *)path_end)))
@@ -655,8 +657,8 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
*e = NUL;
// Now we have one wildcard component between "s" and "e".
- /* Remove backslashes between "wildoff" and the start of the wildcard
- * component. */
+ // Remove backslashes between "wildoff" and the start of the wildcard
+ // component.
for (p = buf + wildoff; p < s; p++) {
if (rem_backslash((char *)p)) {
STRMOVE(p, p + 1);
@@ -702,13 +704,13 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
return 0;
}
- /* If "**" is by itself, this is the first time we encounter it and more
- * is following then find matches without any directory. */
+ // If "**" is by itself, this is the first time we encounter it and more
+ // is following then find matches without any directory.
if (!didstar && stardepth < 100 && starstar && e - s == 2
&& *path_end == '/') {
STRCPY(s, path_end + 1);
stardepth++;
- (void)do_path_expand(gap, buf, (size_t)(s - buf), flags, true);
+ (void)do_path_expand(gap, (char *)buf, (size_t)(s - buf), flags, true);
stardepth--;
}
*s = NUL;
@@ -717,27 +719,27 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
char *dirpath = (*buf == NUL ? "." : (char *)buf);
if (os_file_is_readable(dirpath) && os_scandir(&dir, dirpath)) {
// Find all matching entries.
- char_u *name;
+ char *name;
scandir_next_with_dots(NULL); // initialize
- while (!got_int && (name = (char_u *)scandir_next_with_dots(&dir)) != NULL) {
+ while (!got_int && (name = (char *)scandir_next_with_dots(&dir)) != NULL) {
if ((name[0] != '.'
|| starts_with_dot
|| ((flags & EW_DODOT)
&& name[1] != NUL
&& (name[1] != '.' || name[2] != NUL))) // -V557
- && ((regmatch.regprog != NULL && vim_regexec(&regmatch, (char *)name, 0))
+ && ((regmatch.regprog != NULL && vim_regexec(&regmatch, name, 0))
|| ((flags & EW_NOTWILD)
- && FNAMENCMP(path + (s - buf), name, e - s) == 0))) {
+ && path_fnamencmp(path + (s - buf), name, (size_t)(e - s)) == 0))) {
STRCPY(s, name);
len = STRLEN(buf);
if (starstar && stardepth < 100) {
- /* For "**" in the pattern first go deeper in the tree to
- * find matches. */
- STRCPY(buf + len, "/**");
+ // For "**" in the pattern first go deeper in the tree to
+ // find matches.
+ STRCPY(buf + len, "/**"); // NOLINT
STRCPY(buf + len + 3, path_end);
stardepth++;
- (void)do_path_expand(gap, buf, len + 1, flags, true);
+ (void)do_path_expand(gap, (char *)buf, len + 1, flags, true);
stardepth--;
}
@@ -745,7 +747,7 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
if (path_has_exp_wildcard(path_end)) { // handle more wildcards
// need to expand another component of the path
// remove backslashes for the remaining components only
- (void)do_path_expand(gap, buf, len + 1, flags, false);
+ (void)do_path_expand(gap, (char *)buf, len + 1, flags, false);
} else {
FileInfo file_info;
@@ -779,10 +781,8 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
return matches;
}
-/*
- * Moves "*psep" back to the previous path separator in "path".
- * Returns FAIL is "*psep" ends up at the beginning of "path".
- */
+// Moves "*psep" back to the previous path separator in "path".
+// Returns FAIL is "*psep" ends up at the beginning of "path".
static int find_previous_pathsep(char_u *path, char_u **psep)
{
// skip the current separator
@@ -803,9 +803,9 @@ static int find_previous_pathsep(char_u *path, char_u **psep)
/// Returns true if "maybe_unique" is unique wrt other_paths in "gap".
/// "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
-static bool is_unique(char_u *maybe_unique, garray_T *gap, int i)
+static bool is_unique(char *maybe_unique, garray_T *gap, int i)
{
- char_u **other_paths = (char_u **)gap->ga_data;
+ char **other_paths = gap->ga_data;
for (int j = 0; j < gap->ga_len; j++) {
if (j == i) {
@@ -816,8 +816,8 @@ static bool is_unique(char_u *maybe_unique, garray_T *gap, int i)
if (other_path_len < candidate_len) {
continue; // it's different when it's shorter
}
- char_u *rival = other_paths[j] + other_path_len - candidate_len;
- if (FNAMECMP(maybe_unique, rival) == 0
+ char *rival = other_paths[j] + other_path_len - candidate_len;
+ if (path_fnamecmp(maybe_unique, rival) == 0
&& (rival == other_paths[j] || vim_ispathsep(*(rival - 1)))) {
return false; // match
}
@@ -825,27 +825,25 @@ static bool is_unique(char_u *maybe_unique, garray_T *gap, int i)
return true; // no match found
}
-/*
- * Split the 'path' option into an array of strings in garray_T. Relative
- * paths are expanded to their equivalent fullpath. This includes the "."
- * (relative to current buffer directory) and empty path (relative to current
- * directory) notations.
- *
- * TODO: handle upward search (;) and path limiter (**N) notations by
- * expanding each into their equivalent path(s).
- */
+// Split the 'path' option into an array of strings in garray_T. Relative
+// paths are expanded to their equivalent fullpath. This includes the "."
+// (relative to current buffer directory) and empty path (relative to current
+// directory) notations.
+//
+// TODO(vim): handle upward search (;) and path limiter (**N) notations by
+// expanding each into their equivalent path(s).
static void expand_path_option(char_u *curdir, garray_T *gap)
{
char_u *path_option = *curbuf->b_p_path == NUL ? p_path : (char_u *)curbuf->b_p_path;
- char_u *buf = xmalloc(MAXPATHL);
+ char *buf = xmalloc(MAXPATHL);
while (*path_option != NUL) {
- copy_option_part((char **)&path_option, (char *)buf, MAXPATHL, " ,");
+ copy_option_part((char **)&path_option, buf, MAXPATHL, " ,");
if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1]))) {
- /* Relative to current buffer:
- * "/path/file" + "." -> "/path/"
- * "/path/file" + "./subdir" -> "/path/subdir" */
+ // Relative to current buffer:
+ // "/path/file" + "." -> "/path/"
+ // "/path/file" + "./subdir" -> "/path/subdir"
if (curbuf->b_ffname == NULL) {
continue;
}
@@ -860,12 +858,12 @@ static void expand_path_option(char_u *curdir, garray_T *gap)
STRMOVE(buf + len, buf + 2);
}
memmove(buf, curbuf->b_ffname, len);
- simplify_filename(buf);
+ simplify_filename((char_u *)buf);
} else if (buf[0] == NUL) {
STRCPY(buf, curdir); // relative to current directory
- } else if (path_with_url((char *)buf)) {
+ } else if (path_with_url(buf)) {
continue; // URL can't be used here
- } else if (!path_is_absolute(buf)) {
+ } else if (!path_is_absolute((char_u *)buf)) {
// Expand relative path to their full path equivalent
size_t len = STRLEN(curdir);
if (len + STRLEN(buf) + 3 > MAXPATHL) {
@@ -874,23 +872,21 @@ static void expand_path_option(char_u *curdir, garray_T *gap)
STRMOVE(buf + len + 1, buf);
STRCPY(buf, curdir);
buf[len] = (char_u)PATHSEP;
- simplify_filename(buf);
+ simplify_filename((char_u *)buf);
}
- GA_APPEND(char_u *, gap, vim_strsave(buf));
+ GA_APPEND(char *, gap, xstrdup(buf));
}
xfree(buf);
}
-/*
- * Returns a pointer to the file or directory name in "fname" that matches the
- * longest path in "ga"p, or NULL if there is no match. For example:
- *
- * path: /foo/bar/baz
- * fname: /foo/bar/baz/quux.txt
- * returns: ^this
- */
+// Returns a pointer to the file or directory name in "fname" that matches the
+// longest path in "ga"p, or NULL if there is no match. For example:
+//
+// path: /foo/bar/baz
+// fname: /foo/bar/baz/quux.txt
+// returns: ^this
static char_u *get_path_cutoff(char_u *fname, garray_T *gap)
{
int maxlen = 0;
@@ -924,19 +920,17 @@ static char_u *get_path_cutoff(char_u *fname, garray_T *gap)
return cutoff;
}
-/*
- * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
- * that they are unique with respect to each other while conserving the part
- * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
- */
+// Sorts, removes duplicates and modifies all the fullpath names in "gap" so
+// that they are unique with respect to each other while conserving the part
+// that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
static void uniquefy_paths(garray_T *gap, char_u *pattern)
{
- char_u **fnames = (char_u **)gap->ga_data;
+ char **fnames = gap->ga_data;
bool sort_again = false;
regmatch_T regmatch;
garray_T path_ga;
- char_u **in_curdir = NULL;
- char_u *short_name;
+ char **in_curdir = NULL;
+ char *short_name;
ga_remove_duplicate_strings(gap);
ga_init(&path_ga, (int)sizeof(char_u *), 1);
@@ -945,11 +939,11 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
// regex matches anywhere in the path. FIXME: is this valid for all
// possible patterns?
size_t len = STRLEN(pattern);
- char_u *file_pattern = xmalloc(len + 2);
+ char *file_pattern = xmalloc(len + 2);
file_pattern[0] = '*';
file_pattern[1] = NUL;
STRCAT(file_pattern, pattern);
- char *pat = file_pat_to_reg_pat((char *)file_pattern, NULL, NULL, true);
+ char *pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, true);
xfree(file_pattern);
if (pat == NULL) {
return;
@@ -962,28 +956,28 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
return;
}
- char_u *curdir = xmalloc(MAXPATHL);
- os_dirname(curdir, MAXPATHL);
- expand_path_option(curdir, &path_ga);
+ char *curdir = xmalloc(MAXPATHL);
+ os_dirname((char_u *)curdir, MAXPATHL);
+ expand_path_option((char_u *)curdir, &path_ga);
in_curdir = xcalloc((size_t)gap->ga_len, sizeof(char_u *));
for (int i = 0; i < gap->ga_len && !got_int; i++) {
- char_u *path = fnames[i];
+ char *path = fnames[i];
int is_in_curdir;
- char_u *dir_end = (char_u *)gettail_dir((const char *)path);
- char_u *pathsep_p;
- char_u *path_cutoff;
+ char *dir_end = (char *)gettail_dir((const char *)path);
+ char *pathsep_p;
+ char *path_cutoff;
len = STRLEN(path);
- is_in_curdir = FNAMENCMP(curdir, path, dir_end - path) == 0
+ is_in_curdir = path_fnamencmp(curdir, path, (size_t)(dir_end - path)) == 0
&& curdir[dir_end - path] == NUL;
if (is_in_curdir) {
- in_curdir[i] = vim_strsave(path);
+ in_curdir[i] = xstrdup(path);
}
// Shorten the filename while maintaining its uniqueness
- path_cutoff = get_path_cutoff(path, &path_ga);
+ path_cutoff = (char *)get_path_cutoff((char_u *)path, &path_ga);
// Don't assume all files can be reached without path when search
// pattern starts with **/, so only remove path_cutoff
@@ -991,7 +985,7 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
if (pattern[0] == '*' && pattern[1] == '*'
&& vim_ispathsep_nocolon(pattern[2])
&& path_cutoff != NULL
- && vim_regexec(&regmatch, (char *)path_cutoff, (colnr_T)0)
+ && vim_regexec(&regmatch, path_cutoff, (colnr_T)0)
&& is_unique(path_cutoff, gap, i)) {
sort_again = true;
memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
@@ -999,8 +993,8 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
// Here all files can be reached without path, so get shortest
// unique path. We start at the end of the path. */
pathsep_p = path + len - 1;
- while (find_previous_pathsep(path, &pathsep_p)) {
- if (vim_regexec(&regmatch, (char *)pathsep_p + 1, (colnr_T)0)
+ while (find_previous_pathsep((char_u *)path, (char_u **)&pathsep_p)) {
+ if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
&& is_unique(pathsep_p + 1, gap, i)
&& path_cutoff != NULL && pathsep_p + 1 >= path_cutoff) {
sort_again = true;
@@ -1010,7 +1004,7 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
}
}
- if (path_is_absolute(path)) {
+ if (path_is_absolute((char_u *)path)) {
// Last resort: shorten relative to curdir if possible.
// 'possible' means:
// 1. It is under the current directory.
@@ -1024,7 +1018,7 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
short_name = path_shorten_fname(path, curdir);
if (short_name != NULL && short_name > path + 1) {
STRCPY(path, ".");
- add_pathsep((char *)path);
+ add_pathsep(path);
STRMOVE(path + STRLEN(path), short_name);
}
}
@@ -1033,15 +1027,15 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
// Shorten filenames in /in/current/directory/{filename}
for (int i = 0; i < gap->ga_len && !got_int; i++) {
- char_u *rel_path;
- char_u *path = in_curdir[i];
+ char *rel_path;
+ char *path = in_curdir[i];
if (path == NULL) {
continue;
}
- /* If the {filename} is not unique, change it to ./{filename}.
- * Else reduce it to {filename} */
+ // If the {filename} is not unique, change it to ./{filename}.
+ // Else reduce it to {filename}
short_name = path_shorten_fname(path, curdir);
if (short_name == NULL) {
short_name = path;
@@ -1053,7 +1047,7 @@ static void uniquefy_paths(garray_T *gap, char_u *pattern)
rel_path = xmalloc(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2);
STRCPY(rel_path, ".");
- add_pathsep((char *)rel_path);
+ add_pathsep(rel_path);
STRCAT(rel_path, short_name);
xfree(fnames[i]);
@@ -1212,26 +1206,23 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i
int add_pat;
bool did_expand_in_path = false;
- /*
- * expand_env() is called to expand things like "~user". If this fails,
- * it calls ExpandOne(), which brings us back here. In this case, always
- * call the machine specific expansion function, if possible. Otherwise,
- * return FAIL.
- */
- if (recursive)
+ // expand_env() is called to expand things like "~user". If this fails,
+ // it calls ExpandOne(), which brings us back here. In this case, always
+ // call the machine specific expansion function, if possible. Otherwise,
+ // return FAIL.
+ if (recursive) {
#ifdef SPECIAL_WILDCHAR
- { return os_expand_wildcards(num_pat, pat, num_file, file, flags); }
+ return os_expand_wildcards(num_pat, pat, num_file, file, flags);
#else
- { return FAIL; }
+ return FAIL;
#endif
+ }
#ifdef SPECIAL_WILDCHAR
- /*
- * If there are any special wildcard characters which we cannot handle
- * here, call machine specific function for all the expansion. This
- * avoids starting the shell for each argument separately.
- * For `=expr` do use the internal function.
- */
+ // If there are any special wildcard characters which we cannot handle
+ // here, call machine specific function for all the expansion. This
+ // avoids starting the shell for each argument separately.
+ // For `=expr` do use the internal function.
for (int i = 0; i < num_pat; i++) {
if (has_special_wildchar((char_u *)pat[i])
&& !(vim_backtick((char_u *)pat[i]) && pat[i][1] == '=')) {
@@ -1242,9 +1233,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i
recursive = true;
- /*
- * The matching file names are stored in a growarray. Init it empty.
- */
+ // The matching file names are stored in a growarray. Init it empty.
ga_init(&ga, (int)sizeof(char_u *), 30);
for (int i = 0; i < num_pat && !got_int; i++) {
@@ -1252,7 +1241,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i
p = (char_u *)pat[i];
if (vim_backtick(p)) {
- add_pat = expand_backtick(&ga, p, flags);
+ add_pat = expand_backtick(&ga, (char *)p, flags);
if (add_pat == -1) {
recursive = false;
FreeWild(ga.ga_len, ga.ga_data);
@@ -1266,40 +1255,37 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i
p = expand_env_save_opt(p, true);
if (p == NULL) {
p = (char_u *)pat[i];
- }
+ } else {
#ifdef UNIX
- /*
- * On Unix, if expand_env() can't expand an environment
- * variable, use the shell to do that. Discard previously
- * found file names and start all over again.
- */
- else if (has_env_var(p) || *p == '~') {
- xfree(p);
- ga_clear_strings(&ga);
- i = os_expand_wildcards(num_pat, pat, num_file, file,
- flags | EW_KEEPDOLLAR);
- recursive = false;
- return i;
- }
+ // On Unix, if expand_env() can't expand an environment
+ // variable, use the shell to do that. Discard previously
+ // found file names and start all over again.
+ if (has_env_var(p) || *p == '~') {
+ xfree(p);
+ ga_clear_strings(&ga);
+ i = os_expand_wildcards(num_pat, pat, num_file, file,
+ flags | EW_KEEPDOLLAR);
+ recursive = false;
+ return i;
+ }
#endif
+ }
}
- /*
- * If there are wildcards: Expand file names and add each match to
- * the list. If there is no match, and EW_NOTFOUND is given, add
- * the pattern.
- * If there are no wildcards: Add the file name if it exists or
- * when EW_NOTFOUND is given.
- */
- if (path_has_exp_wildcard(p)) {
+ // If there are wildcards or case-insensitive expansion is
+ // required: Expand file names and add each match to the list. If
+ // there is no match, and EW_NOTFOUND is given, add the pattern.
+ // Otherwise: Add the file name if it exists or when EW_NOTFOUND is
+ // given.
+ if (path_has_exp_wildcard(p) || (flags & EW_ICASE)) {
if ((flags & EW_PATH)
&& !path_is_absolute(p)
&& !(p[0] == '.'
&& (vim_ispathsep(p[1])
|| (p[1] == '.'
&& vim_ispathsep(p[2]))))) {
- /* :find completion where 'path' is used.
- * Recursiveness is OK here. */
+ // :find completion where 'path' is used.
+ // Recursiveness is OK here.
recursive = false;
add_pat = expand_in_path(&ga, p, flags);
recursive = true;
@@ -1315,8 +1301,8 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i
if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND))) {
char_u *t = (char_u *)backslash_halve_save((char *)p);
- /* When EW_NOTFOUND is used, always add files and dirs. Makes
- * "vim c:/" work. */
+ // When EW_NOTFOUND is used, always add files and dirs. Makes
+ // "vim c:/" work.
if (flags & EW_NOTFOUND) {
addfile(&ga, t, flags | EW_DIR | EW_FILE);
} else {
@@ -1367,14 +1353,14 @@ static int vim_backtick(char_u *p)
/// Returns number of file names found, -1 if an error is encountered.
///
/// @param flags EW_* flags
-static int expand_backtick(garray_T *gap, char_u *pat, int flags)
+static int expand_backtick(garray_T *gap, char *pat, int flags)
{
char *p;
char *buffer;
int cnt = 0;
// Create the command: lop off the backticks.
- char *cmd = (char *)vim_strnsave(pat + 1, STRLEN(pat) - 2);
+ char *cmd = xstrnsave(pat + 1, STRLEN(pat) - 2);
if (*cmd == '=') { // `={expr}`: Expand expression
buffer = eval_to_string(cmd + 1, &p, true);
@@ -1491,21 +1477,17 @@ void addfile(garray_T *gap, char_u *f, int flags)
#ifdef BACKSLASH_IN_FILENAME
slash_adjust(p);
#endif
- /*
- * Append a slash or backslash after directory names if none is present.
- */
+ // Append a slash or backslash after directory names if none is present.
if (isdir && (flags & EW_ADDSLASH)) {
add_pathsep((char *)p);
}
GA_APPEND(char_u *, gap, p);
}
-/*
- * Converts a file name into a canonical form. It simplifies a file name into
- * its simplest form by stripping out unneeded components, if any. The
- * resulting file name is simplified in place and will either be the same
- * length as that supplied, or shorter.
- */
+// Converts a file name into a canonical form. It simplifies a file name into
+// its simplest form by stripping out unneeded components, if any. The
+// resulting file name is simplified in place and will either be the same
+// length as that supplied, or shorter.
void simplify_filename(char_u *filename)
{
int components = 0;
@@ -1529,8 +1511,8 @@ void simplify_filename(char_u *filename)
start = p; // remember start after "c:/" or "/" or "///"
do {
- /* At this point "p" is pointing to the char following a single "/"
- * or "p" is at the "start" of the (absolute or relative) path name. */
+ // At this point "p" is pointing to the char following a single "/"
+ // or "p" is at the "start" of the (absolute or relative) path name.
if (vim_ispathsep(*p)) {
STRMOVE(p, p + 1); // remove duplicate "/"
} else if (p[0] == '.'
@@ -1538,10 +1520,10 @@ void simplify_filename(char_u *filename)
if (p == start && relative) {
p += 1 + (p[1] != NUL); // keep single "." or leading "./"
} else {
- /* Strip "./" or ".///". If we are at the end of the file name
- * and there is no trailing path separator, either strip "/." if
- * we are after "start", or strip "." if we are at the beginning
- * of an absolute path name . */
+ // Strip "./" or ".///". If we are at the end of the file name
+ // and there is no trailing path separator, either strip "/." if
+ // we are after "start", or strip "." if we are at the beginning
+ // of an absolute path name.
tail = p + 1;
if (p[1] != NUL) {
while (vim_ispathsep(*tail)) {
@@ -1566,9 +1548,9 @@ void simplify_filename(char_u *filename)
// Don't strip for an erroneous file name.
if (!stripping_disabled) {
- /* If the preceding component does not exist in the file
- * system, we strip it. On Unix, we don't accept a symbolic
- * link that refers to a non-existent file. */
+ // If the preceding component does not exist in the file
+ // system, we strip it. On Unix, we don't accept a symbolic
+ // link that refers to a non-existent file.
saved_char = p[-1];
p[-1] = NUL;
FileInfo file_info;
@@ -1584,16 +1566,16 @@ void simplify_filename(char_u *filename)
}
if (!do_strip) {
- /* If the component exists in the file system, check
- * that stripping it won't change the meaning of the
- * file name. First get information about the
- * unstripped file name. This may fail if the component
- * to strip is not a searchable directory (but a regular
- * file, for instance), since the trailing "/.." cannot
- * be applied then. We don't strip it then since we
- * don't want to replace an erroneous file name by
- * a valid one, and we disable stripping of later
- * components. */
+ // If the component exists in the file system, check
+ // that stripping it won't change the meaning of the
+ // file name. First get information about the
+ // unstripped file name. This may fail if the component
+ // to strip is not a searchable directory (but a regular
+ // file, for instance), since the trailing "/.." cannot
+ // be applied then. We don't strip it then since we
+ // don't want to replace an erroneous file name by
+ // a valid one, and we disable stripping of later
+ // components.
saved_char = *tail;
*tail = NUL;
if (os_fileinfo((char *)filename, &file_info)) {
@@ -1603,13 +1585,13 @@ void simplify_filename(char_u *filename)
}
*tail = saved_char;
if (do_strip) {
- /* The check for the unstripped file name
- * above works also for a symbolic link pointing to
- * a searchable directory. But then the parent of
- * the directory pointed to by the link must be the
- * same as the stripped file name. (The latter
- * exists in the file system since it is the
- * component's parent directory.) */
+ // The check for the unstripped file name
+ // above works also for a symbolic link pointing to
+ // a searchable directory. But then the parent of
+ // the directory pointed to by the link must be the
+ // same as the stripped file name. (The latter
+ // exists in the file system since it is the
+ // component's parent directory.)
FileInfo new_file_info;
if (p == start && relative) {
os_fileinfo(".", &new_file_info);
@@ -1622,26 +1604,26 @@ void simplify_filename(char_u *filename)
if (!os_fileinfo_id_equal(&file_info, &new_file_info)) {
do_strip = false;
- /* We don't disable stripping of later
- * components since the unstripped path name is
- * still valid. */
+ // We don't disable stripping of later
+ // components since the unstripped path name is
+ // still valid.
}
}
}
}
if (!do_strip) {
- /* Skip the ".." or "../" and reset the counter for the
- * components that might be stripped later on. */
+ // Skip the ".." or "../" and reset the counter for the
+ // components that might be stripped later on.
p = tail;
components = 0;
} else {
- /* Strip previous component. If the result would get empty
- * and there is no trailing path separator, leave a single
- * "." instead. If we are at the end of the file name and
- * there is no trailing path separator and a preceding
- * component is left after stripping, strip its trailing
- * path separator as well. */
+ // Strip previous component. If the result would get empty
+ // and there is no trailing path separator, leave a single
+ // "." instead. If we are at the end of the file name and
+ // there is no trailing path separator and a preceding
+ // component is left after stripping, strip its trailing
+ // path separator as well.
if (p == start && relative && tail[-1] == '.') {
*p++ = '.';
*p = NUL;
@@ -1683,17 +1665,17 @@ static char *eval_includeexpr(const char *const ptr, const size_t len)
/// Otherwise like file_name_at_cursor().
///
/// @param rel_fname file we are searching relative to
-char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count, char_u *rel_fname)
+char *find_file_name_in_path(char *ptr, size_t len, int options, long count, char *rel_fname)
{
- char_u *file_name;
- char_u *tofree = NULL;
+ char *file_name;
+ char *tofree = NULL;
if (len == 0) {
return NULL;
}
if ((options & FNAME_INCL) && *curbuf->b_p_inex != NUL) {
- tofree = (char_u *)eval_includeexpr((char *)ptr, len);
+ tofree = eval_includeexpr(ptr, len);
if (tofree != NULL) {
ptr = tofree;
len = STRLEN(ptr);
@@ -1701,38 +1683,37 @@ char_u *find_file_name_in_path(char_u *ptr, size_t len, int options, long count,
}
if (options & FNAME_EXP) {
- file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS, true,
- rel_fname);
+ file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS, true,
+ (char_u *)rel_fname);
- /*
- * If the file could not be found in a normal way, try applying
- * 'includeexpr' (unless done already).
- */
+ // If the file could not be found in a normal way, try applying
+ // 'includeexpr' (unless done already).
if (file_name == NULL
&& !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL) {
- tofree = (char_u *)eval_includeexpr((char *)ptr, len);
+ tofree = eval_includeexpr(ptr, len);
if (tofree != NULL) {
ptr = tofree;
len = STRLEN(ptr);
- file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
- true, rel_fname);
+ file_name = (char *)find_file_in_path((char_u *)ptr, len, options & ~FNAME_MESS,
+ true, (char_u *)rel_fname);
}
}
if (file_name == NULL && (options & FNAME_MESS)) {
- char_u c = ptr[len];
+ char c = ptr[len];
ptr[len] = NUL;
semsg(_("E447: Can't find file \"%s\" in path"), ptr);
ptr[len] = c;
}
- /* Repeat finding the file "count" times. This matters when it
- * appears several times in the path. */
+ // Repeat finding the file "count" times. This matters when it
+ // appears several times in the path.
while (file_name != NULL && --count > 0) {
xfree(file_name);
- file_name = find_file_in_path(ptr, len, options, false, rel_fname);
+ file_name =
+ (char *)find_file_in_path((char_u *)ptr, len, options, false, (char_u *)rel_fname);
}
} else {
- file_name = vim_strnsave(ptr, len);
+ file_name = xstrnsave(ptr, len);
}
xfree(tofree);
@@ -1975,11 +1956,9 @@ bool same_directory(char_u *f1, char_u *f2)
&& pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0;
}
-/*
- * Compare path "p[]" to "q[]".
- * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
- * Return value like strcmp(p, q), but consider path separators.
- */
+// Compare path "p[]" to "q[]".
+// If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
+// Return value like strcmp(p, q), but consider path separators.
int pathcmp(const char *p, const char *q, int maxlen)
{
int i, j;
@@ -2064,7 +2043,7 @@ char_u *path_try_shorten_fname(char_u *full_path)
char_u *p = full_path;
if (os_dirname(dirname, MAXPATHL) == OK) {
- p = path_shorten_fname(full_path, dirname);
+ p = (char_u *)path_shorten_fname((char *)full_path, (char *)dirname);
if (p == NULL || *p == NUL) {
p = full_path;
}
@@ -2080,7 +2059,7 @@ char_u *path_try_shorten_fname(char_u *full_path)
/// @return
/// - Pointer into `full_path` if shortened.
/// - NULL if no shorter name is possible.
-char_u *path_shorten_fname(char_u *full_path, char_u *dir_name)
+char *path_shorten_fname(char *full_path, char *dir_name)
{
if (full_path == NULL) {
return NULL;
@@ -2090,17 +2069,17 @@ char_u *path_shorten_fname(char_u *full_path, char_u *dir_name)
size_t len = STRLEN(dir_name);
// If dir_name is a path head, full_path can always be made relative.
- if (len == (size_t)path_head_length() && is_path_head(dir_name)) {
+ if (len == (size_t)path_head_length() && is_path_head((char_u *)dir_name)) {
return full_path + len;
}
// If full_path and dir_name do not match, it's impossible to make one
// relative to the other.
- if (FNAMENCMP(dir_name, full_path, len) != 0) {
+ if (path_fnamencmp(dir_name, full_path, len) != 0) {
return NULL;
}
- char_u *p = full_path + len;
+ char_u *p = (char_u *)full_path + len;
// If *p is not pointing to a path separator, this means that full_path's
// last directory name is longer than *dir_name's last directory, so they
@@ -2109,7 +2088,7 @@ char_u *path_shorten_fname(char_u *full_path, char_u *dir_name)
return NULL;
}
- return p + 1;
+ return (char *)p + 1;
}
/// Invoke expand_wildcards() for one pattern
@@ -2126,21 +2105,25 @@ char_u *path_shorten_fname(char_u *full_path, char_u *dir_name)
/// If FAIL is returned, *num_file and *file are either
/// unchanged or *num_file is set to 0 and *file is set
/// to NULL or points to "".
-int expand_wildcards_eval(char_u **pat, int *num_file, char ***file, int flags)
+int expand_wildcards_eval(char **pat, int *num_file, char ***file, int flags)
{
int ret = FAIL;
- char_u *eval_pat = NULL;
- char *exp_pat = (char *)(*pat);
+ char *eval_pat = NULL;
+ char *exp_pat = *pat;
char *ignored_msg;
size_t usedlen;
+ const bool is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
+ bool star_follows = false;
- if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<') {
+ if (is_cur_alt_file || *exp_pat == '<') {
emsg_off++;
- eval_pat = eval_vars((char_u *)exp_pat, (char_u *)exp_pat, &usedlen, NULL, &ignored_msg, NULL,
- true);
+ eval_pat = (char *)eval_vars((char_u *)exp_pat, (char_u *)exp_pat, &usedlen, NULL, &ignored_msg,
+ NULL,
+ true);
emsg_off--;
if (eval_pat != NULL) {
- exp_pat = concat_str((char *)eval_pat, exp_pat + usedlen);
+ star_follows = strcmp(exp_pat + usedlen, "*") == 0;
+ exp_pat = concat_str(eval_pat, exp_pat + usedlen);
}
}
@@ -2149,6 +2132,16 @@ int expand_wildcards_eval(char_u **pat, int *num_file, char ***file, int flags)
}
if (eval_pat != NULL) {
+ if (*num_file == 0 && is_cur_alt_file && star_follows) {
+ // Expanding "%" or "#" and the file does not exist: Add the
+ // pattern anyway (without the star) so that this works for remote
+ // files and non-file buffer names.
+ *file = xmalloc(sizeof(char *));
+ **file = eval_pat;
+ eval_pat = NULL;
+ *num_file = 1;
+ ret = OK;
+ }
xfree(exp_pat);
xfree(eval_pat);
}
@@ -2184,9 +2177,7 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int
return retval;
}
- /*
- * Remove names that match 'wildignore'.
- */
+ // Remove names that match 'wildignore'.
if (*p_wig) {
char_u *ffname;
@@ -2215,7 +2206,7 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int
if (*num_files > 1 && !got_int) {
non_suf_match = 0;
for (i = 0; i < *num_files; i++) {
- if (!match_suffix((char_u *)(*files)[i])) {
+ if (!match_suffix((*files)[i])) {
// Move the name without matching suffix to the front of the list.
p = (char_u *)(*files)[i];
for (j = i; j > non_suf_match; j--) {
@@ -2235,27 +2226,27 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int
return retval;
}
-/// Return true if "fname" matches with an entry in 'suffixes'.
-int match_suffix(char_u *fname)
+/// @return true if "fname" matches with an entry in 'suffixes'.
+int match_suffix(char *fname)
{
#define MAXSUFLEN 30 // maximum length of a file suffix
- char_u suf_buf[MAXSUFLEN];
+ char suf_buf[MAXSUFLEN];
size_t fnamelen = STRLEN(fname);
size_t setsuflen = 0;
for (char_u *setsuf = p_su; *setsuf;) {
setsuflen = copy_option_part((char **)&setsuf, (char *)suf_buf, MAXSUFLEN, ".,");
if (setsuflen == 0) {
- char_u *tail = (char_u *)path_tail((char *)fname);
+ char *tail = path_tail(fname);
// empty entry: match name without a '.'
- if (vim_strchr((char *)tail, '.') == NULL) {
+ if (vim_strchr(tail, '.') == NULL) {
setsuflen = 1;
break;
}
} else {
if (fnamelen >= setsuflen
- && FNAMENCMP(suf_buf, fname + fnamelen - setsuflen, setsuflen) == 0) {
+ && path_fnamencmp(suf_buf, fname + fnamelen - setsuflen, setsuflen) == 0) {
break;
}
setsuflen = 0;
@@ -2449,8 +2440,8 @@ void path_guess_exepath(const char *argv0, char *buf, size_t bufsize)
continue;
}
STRLCPY(NameBuff, dir, dir_len + 1);
- STRLCAT(NameBuff, PATHSEPSTR, sizeof(NameBuff));
- STRLCAT(NameBuff, argv0, sizeof(NameBuff));
+ xstrlcat(NameBuff, PATHSEPSTR, sizeof(NameBuff));
+ xstrlcat(NameBuff, argv0, sizeof(NameBuff));
if (os_can_exe((char *)NameBuff, NULL, false)) {
xstrlcpy(buf, (char *)NameBuff, bufsize);
return;
diff --git a/src/nvim/path.h b/src/nvim/path.h
index 1006ef9ffb..37a0883c7f 100644
--- a/src/nvim/path.h
+++ b/src/nvim/path.h
@@ -18,8 +18,8 @@
#define EW_NOERROR 0x200 // no error for bad regexp
#define EW_NOTWILD 0x400 // add match with literal name if exists
#define EW_KEEPDOLLAR 0x800 // do not escape $, $var is expanded
-/* Note: mostly EW_NOTFOUND and EW_SILENT are mutually exclusive: EW_NOTFOUND
-* is used when executing commands and EW_SILENT for interactive expanding. */
+// Note: mostly EW_NOTFOUND and EW_SILENT are mutually exclusive: EW_NOTFOUND
+// is used when executing commands and EW_SILENT for interactive expanding.
#define EW_ALLLINKS 0x1000 // also links not pointing to existing file
#define EW_SHELLCMD 0x2000 // called from expand_shellcmd(), don't check
// if executable is in $PATH
diff --git a/src/nvim/plines.c b/src/nvim/plines.c
index 3ba09b45a1..cbde0cfff9 100644
--- a/src/nvim/plines.c
+++ b/src/nvim/plines.c
@@ -102,7 +102,7 @@ int plines_win_nofold(win_T *wp, linenr_T lnum)
unsigned int col;
int width;
- s = (char *)ml_get_buf(wp->w_buffer, lnum, false);
+ s = ml_get_buf(wp->w_buffer, lnum, false);
if (*s == NUL) { // empty line
return 1;
}
@@ -144,7 +144,7 @@ int plines_win_col(win_T *wp, linenr_T lnum, long column)
return lines + 1;
}
- char_u *line = ml_get_buf(wp->w_buffer, lnum, false);
+ char_u *line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
colnr_T col = 0;
chartabsize_T cts;
@@ -288,11 +288,10 @@ unsigned int win_linetabsize(win_T *wp, linenr_T lnum, char_u *line, colnr_T len
///
/// "line" is the start of the line, "ptr" is the first relevant character.
/// When "lnum" is zero do not use text properties that insert text.
-void init_chartabsize_arg(chartabsize_T *cts, win_T *wp, linenr_T lnum, colnr_T col, char *line,
- char *ptr)
+void init_chartabsize_arg(chartabsize_T *cts, win_T *wp, linenr_T lnum FUNC_ATTR_UNUSED,
+ colnr_T col, char *line, char *ptr)
{
cts->cts_win = wp;
- cts->cts_lnum = lnum;
cts->cts_vcol = col;
cts->cts_line = line;
cts->cts_ptr = ptr;
diff --git a/src/nvim/plines.h b/src/nvim/plines.h
index 7b228f3e91..f463d82f10 100644
--- a/src/nvim/plines.h
+++ b/src/nvim/plines.h
@@ -6,7 +6,6 @@
// Argument for lbr_chartabsize().
typedef struct {
win_T *cts_win;
- linenr_T cts_lnum; // zero when not using text properties
char *cts_line; // start of the line
char *cts_ptr; // current position in line
diff --git a/src/nvim/popupmenu.c b/src/nvim/popupmenu.c
index 0d9080ceb7..4de3713f4f 100644
--- a/src/nvim/popupmenu.c
+++ b/src/nvim/popupmenu.c
@@ -1045,6 +1045,10 @@ void pum_show_popupmenu(vimmenu_T *menu)
pum_selected = -1;
pum_first = 0;
+ if (!p_mousemev) {
+ // Pretend 'mousemoveevent' is set.
+ ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(true));
+ }
for (;;) {
pum_is_visible = true;
@@ -1102,6 +1106,9 @@ void pum_show_popupmenu(vimmenu_T *menu)
xfree(array);
pum_undisplay(true);
+ if (!p_mousemev) {
+ ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(false));
+ }
}
void pum_make_popup(const char *path_name, int use_mouse_pos)
diff --git a/src/nvim/profile.c b/src/nvim/profile.c
index cded231c85..50a8a371f5 100644
--- a/src/nvim/profile.c
+++ b/src/nvim/profile.c
@@ -291,23 +291,23 @@ void ex_profile(exarg_T *eap)
set_vim_var_nr(VV_PROFILING, 1L);
} else if (do_profiling == PROF_NONE) {
emsg(_("E750: First use \":profile start {fname}\""));
- } else if (STRCMP(eap->arg, "stop") == 0) {
+ } else if (strcmp(eap->arg, "stop") == 0) {
profile_dump();
do_profiling = PROF_NONE;
set_vim_var_nr(VV_PROFILING, 0L);
profile_reset();
- } else if (STRCMP(eap->arg, "pause") == 0) {
+ } else if (strcmp(eap->arg, "pause") == 0) {
if (do_profiling == PROF_YES) {
pause_time = profile_start();
}
do_profiling = PROF_PAUSED;
- } else if (STRCMP(eap->arg, "continue") == 0) {
+ } else if (strcmp(eap->arg, "continue") == 0) {
if (do_profiling == PROF_PAUSED) {
pause_time = profile_end(pause_time);
profile_set_wait(profile_add(profile_get_wait(), pause_time));
}
do_profiling = PROF_YES;
- } else if (STRCMP(eap->arg, "dump") == 0) {
+ } else if (strcmp(eap->arg, "dump") == 0) {
profile_dump();
} else {
// The rest is similar to ":breakadd".
@@ -728,7 +728,7 @@ static void script_dump_profile(FILE *fd)
// Keep going till the end of file, so that trailing
// continuation lines are listed.
for (int i = 0;; i++) {
- if (vim_fgets(IObuff, IOSIZE, sfd)) {
+ if (vim_fgets((char_u *)IObuff, IOSIZE, sfd)) {
break;
}
// When a line has been truncated, append NL, taking care
diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c
index 86f60cb57e..9494308ef0 100644
--- a/src/nvim/quickfix.c
+++ b/src/nvim/quickfix.c
@@ -710,7 +710,7 @@ static int qf_get_next_buf_line(qfstate_T *state)
if (state->buflnum > state->lnumlast) {
return QF_END_OF_INPUT;
}
- char *p_buf = (char *)ml_get_buf(state->buf, state->buflnum, false);
+ char *p_buf = ml_get_buf(state->buf, state->buflnum, false);
state->buflnum += 1;
size_t len = STRLEN(p_buf);
@@ -1098,7 +1098,7 @@ static int qf_init_ext(qf_info_T *qi, int qf_idx, const char *restrict efile, bu
// If the errorformat didn't change between calls, then reuse the previously
// parsed values.
- if (last_efm == NULL || (STRCMP(last_efm, efm) != 0)) {
+ if (last_efm == NULL || (strcmp(last_efm, efm) != 0)) {
// free the previously parsed data
XFREE_CLEAR(last_efm);
free_efm_list(&fmt_first);
@@ -1242,10 +1242,10 @@ static int qf_parse_fmt_f(regmatch_T *rmp, int midx, qffields_T *fields, int pre
}
// Expand ~/file and $HOME/file to full path.
- char c = (char)(*rmp->endp[midx]);
+ char c = *rmp->endp[midx];
*rmp->endp[midx] = NUL;
- expand_env((char *)rmp->startp[midx], fields->namebuf, CMDBUFFSIZE);
- *rmp->endp[midx] = (char_u)c;
+ expand_env(rmp->startp[midx], fields->namebuf, CMDBUFFSIZE);
+ *rmp->endp[midx] = c;
// For separate filename patterns (%O, %P and %Q), the specified file
// should exist.
@@ -1264,7 +1264,7 @@ static int qf_parse_fmt_n(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->enr = (int)atol((char *)rmp->startp[midx]);
+ fields->enr = (int)atol(rmp->startp[midx]);
return QF_OK;
}
@@ -1275,7 +1275,7 @@ static int qf_parse_fmt_l(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->lnum = (linenr_T)atol((char *)rmp->startp[midx]);
+ fields->lnum = (linenr_T)atol(rmp->startp[midx]);
return QF_OK;
}
@@ -1286,7 +1286,7 @@ static int qf_parse_fmt_e(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->end_lnum = (linenr_T)atol((char *)rmp->startp[midx]);
+ fields->end_lnum = (linenr_T)atol(rmp->startp[midx]);
return QF_OK;
}
@@ -1297,7 +1297,7 @@ static int qf_parse_fmt_c(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->col = (int)atol((char *)rmp->startp[midx]);
+ fields->col = (int)atol(rmp->startp[midx]);
return QF_OK;
}
@@ -1308,7 +1308,7 @@ static int qf_parse_fmt_k(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->end_col = (int)atol((char *)rmp->startp[midx]);
+ fields->end_col = (int)atol(rmp->startp[midx]);
return QF_OK;
}
@@ -1319,7 +1319,7 @@ static int qf_parse_fmt_t(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->type = (char)(*rmp->startp[midx]);
+ fields->type = *rmp->startp[midx];
return QF_OK;
}
@@ -1360,7 +1360,7 @@ static int qf_parse_fmt_r(regmatch_T *rmp, int midx, char **tail)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- *tail = (char *)rmp->startp[midx];
+ *tail = rmp->startp[midx];
return QF_OK;
}
@@ -1372,7 +1372,7 @@ static int qf_parse_fmt_p(regmatch_T *rmp, int midx, qffields_T *fields)
return QF_FAIL;
}
fields->col = 0;
- for (char *match_ptr = (char *)rmp->startp[midx]; (char_u *)match_ptr != rmp->endp[midx];
+ for (char *match_ptr = rmp->startp[midx]; match_ptr != rmp->endp[midx];
match_ptr++) {
fields->col++;
if (*match_ptr == TAB) {
@@ -1392,7 +1392,7 @@ static int qf_parse_fmt_v(regmatch_T *rmp, int midx, qffields_T *fields)
if (rmp->startp[midx] == NULL) {
return QF_FAIL;
}
- fields->col = (int)atol((char *)rmp->startp[midx]);
+ fields->col = (int)atol(rmp->startp[midx]);
fields->use_viscol = true;
return QF_OK;
}
@@ -1409,7 +1409,7 @@ static int qf_parse_fmt_s(regmatch_T *rmp, int midx, qffields_T *fields)
len = CMDBUFFSIZE - 5;
}
STRCPY(fields->pattern, "^\\V");
- STRLCAT(fields->pattern, rmp->startp[midx], len + 4);
+ xstrlcat(fields->pattern, rmp->startp[midx], len + 4);
fields->pattern[len + 3] = '\\';
fields->pattern[len + 4] = '$';
fields->pattern[len + 5] = NUL;
@@ -1428,7 +1428,7 @@ static int qf_parse_fmt_o(regmatch_T *rmp, int midx, qffields_T *fields)
if (dsize > CMDBUFFSIZE) {
dsize = CMDBUFFSIZE;
}
- STRLCAT(fields->module, rmp->startp[midx], dsize);
+ xstrlcat(fields->module, rmp->startp[midx], dsize);
return QF_OK;
}
@@ -2085,7 +2085,7 @@ static int qf_get_fnum(qf_list_T *qfl, char *directory, char *fname)
}
if (qf_last_bufname != NULL
- && STRCMP(bufname, qf_last_bufname) == 0
+ && strcmp(bufname, qf_last_bufname) == 0
&& bufref_valid(&qf_last_bufref)) {
buf = qf_last_bufref.br_buf;
xfree(ptr);
@@ -3074,7 +3074,7 @@ static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel)
}
msg_puts(" ");
- char_u *tbuf = IObuff;
+ char *tbuf = IObuff;
size_t tbuflen = IOSIZE;
size_t len = STRLEN(qfp->qf_text) + 3;
@@ -3088,8 +3088,8 @@ static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel)
// with ^^^^.
qf_fmt_text((fname != NULL || qfp->qf_lnum != 0)
? skipwhite(qfp->qf_text) : qfp->qf_text,
- (char *)tbuf, (int)tbuflen);
- msg_prt_line((char *)tbuf, false);
+ tbuf, (int)tbuflen);
+ msg_prt_line(tbuf, false);
if (tbuf != IObuff) {
xfree(tbuf);
@@ -3236,7 +3236,7 @@ static void qf_msg(qf_info_T *qi, int which, char *lead)
memset(buf + len, ' ', 34 - len);
buf[34] = NUL;
}
- STRLCAT(buf, title, IOSIZE);
+ xstrlcat(buf, title, IOSIZE);
}
trunc_string(buf, buf, Columns - 1, IOSIZE);
msg(buf);
@@ -3832,7 +3832,7 @@ static buf_T *qf_find_buf(qf_info_T *qi)
/// @return OK or FAIL
int qf_process_qftf_option(void)
{
- return option_set_callback_func((char_u *)p_qftf, &qftf_cb);
+ return option_set_callback_func(p_qftf, &qftf_cb);
}
/// Update the w:quickfix_title variable in the quickfix/location list window in
@@ -3965,7 +3965,7 @@ static int qf_buf_add_line(qf_list_T *qfl, buf_T *buf, linenr_T lnum, const qfli
(char *)IObuff + len, IOSIZE - len);
}
- if (ml_append_buf(buf, lnum, IObuff,
+ if (ml_append_buf(buf, lnum, (char_u *)IObuff,
(colnr_T)STRLEN(IObuff) + 1, false) == FAIL) {
return FAIL;
}
@@ -4180,8 +4180,7 @@ int grep_internal(cmdidx_T cmdidx)
|| cmdidx == CMD_lgrep
|| cmdidx == CMD_grepadd
|| cmdidx == CMD_lgrepadd)
- && STRCMP("internal",
- *curbuf->b_p_gp == NUL ? p_gp : (char_u *)curbuf->b_p_gp) == 0;
+ && strcmp("internal", *curbuf->b_p_gp == NUL ? p_gp : curbuf->b_p_gp) == 0;
}
// Return the make/grep autocmd name.
@@ -4317,7 +4316,7 @@ static char *get_mef_name(void)
static int off = 0;
if (*p_mef == NUL) {
- name = (char *)vim_tempname();
+ name = vim_tempname();
if (name == NULL) {
emsg(_(e_notmp));
}
@@ -5153,7 +5152,7 @@ static bool vgr_match_buflines(qf_list_T *qfl, char *fname, buf_T *buf, char *sp
fname,
NULL,
duplicate_name ? 0 : buf->b_fnum,
- (char *)ml_get_buf(buf, regmatch->startpos[0].lnum + lnum, false),
+ ml_get_buf(buf, regmatch->startpos[0].lnum + lnum, false),
regmatch->startpos[0].lnum + lnum,
regmatch->endpos[0].lnum + lnum,
regmatch->startpos[0].col + 1,
@@ -5180,7 +5179,7 @@ static bool vgr_match_buflines(qf_list_T *qfl, char *fname, buf_T *buf, char *sp
}
}
} else {
- char *const str = (char *)ml_get_buf(buf, lnum, false);
+ char *const str = ml_get_buf(buf, lnum, false);
int score;
uint32_t matches[MAX_FUZZY_MATCHES];
const size_t sz = sizeof(matches) / sizeof(matches[0]);
@@ -5260,7 +5259,7 @@ static bool existing_swapfile(const buf_T *buf)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL) {
- const char *const fname = (char *)buf->b_ml.ml_mfp->mf_fname;
+ const char *const fname = buf->b_ml.ml_mfp->mf_fname;
const size_t len = STRLEN(fname);
return fname[len - 1] != 'p' || fname[len - 2] != 'w';
@@ -5417,7 +5416,7 @@ static int vgr_process_files(win_T *wp, qf_info_T *qi, vgr_args_T *cmd_args, boo
// directory we jumped to below.
if (buf == *first_match_buf
&& *target_dir == NULL
- && STRCMP(dirname_start, dirname_now) != 0) {
+ && strcmp(dirname_start, dirname_now) != 0) {
*target_dir = xstrdup(dirname_now);
}
@@ -5540,7 +5539,7 @@ static void restore_start_dir(char *dirname_start)
char *dirname_now = xmalloc(MAXPATHL);
os_dirname((char_u *)dirname_now, MAXPATHL);
- if (STRCMP(dirname_start, dirname_now) != 0) {
+ if (strcmp(dirname_start, dirname_now) != 0) {
// If the directory has changed, change it back by building up an
// appropriate ex command and executing it.
exarg_T ea = {
@@ -6498,7 +6497,7 @@ static int qf_setprop_curidx(qf_info_T *qi, qf_list_T *qfl, const dictitem_T *di
// If the specified index is '$', then use the last entry
if (di->di_tv.v_type == VAR_STRING
&& di->di_tv.vval.v_string != NULL
- && STRCMP(di->di_tv.vval.v_string, "$") == 0) {
+ && strcmp(di->di_tv.vval.v_string, "$") == 0) {
newidx = qfl->qf_count;
} else {
// Otherwise use the specified index
@@ -6949,7 +6948,7 @@ static void hgr_search_file(qf_list_T *qfl, char *fname, regmatch_T *p_regmatch)
}
linenr_T lnum = 1;
- while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int) {
+ while (!vim_fgets((char_u *)IObuff, IOSIZE, fd) && !got_int) {
char *line = (char *)IObuff;
if (vim_regexec(p_regmatch, line, (colnr_T)0)) {
@@ -6968,8 +6967,8 @@ static void hgr_search_file(qf_list_T *qfl, char *fname, regmatch_T *p_regmatch)
line,
lnum,
0,
- (int)(p_regmatch->startp[0] - (char_u *)line) + 1, // col
- (int)(p_regmatch->endp[0] - (char_u *)line)
+ (int)(p_regmatch->startp[0] - line) + 1, // col
+ (int)(p_regmatch->endp[0] - line)
+ 1, // end_col
false, // vis_col
NULL, // search pattern
@@ -6978,13 +6977,13 @@ static void hgr_search_file(qf_list_T *qfl, char *fname, regmatch_T *p_regmatch)
true) // valid
== QF_FAIL) {
got_int = true;
- if ((char_u *)line != IObuff) {
+ if (line != IObuff) {
xfree(line);
}
break;
}
}
- if ((char_u *)line != IObuff) {
+ if (line != IObuff) {
xfree(line);
}
lnum++;
diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c
index 563d85964c..9a8890a28a 100644
--- a/src/nvim/regexp.c
+++ b/src/nvim/regexp.c
@@ -137,7 +137,7 @@ static int re_multi_type(int c)
return NOT_MULTI;
}
-static char_u *reg_prev_sub = NULL;
+static char *reg_prev_sub = NULL;
/*
* REGEXP_INRANGE contains all characters which are always special in a []
@@ -1040,7 +1040,7 @@ static char_u *reg_getline(linenr_T lnum)
// Must have matched the "\n" in the last line.
return (char_u *)"";
}
- return ml_get_buf(rex.reg_buf, rex.reg_firstlnum + lnum, false);
+ return (char_u *)ml_get_buf(rex.reg_buf, rex.reg_firstlnum + lnum, false);
}
static char_u *reg_startzp[NSUBEXP]; // Workspace to mark beginning
@@ -1523,23 +1523,21 @@ static fptr_T do_Lower(int *d, int c)
return (fptr_T)do_Lower;
}
-/*
- * regtilde(): Replace tildes in the pattern by the old pattern.
- *
- * Short explanation of the tilde: It stands for the previous replacement
- * pattern. If that previous pattern also contains a ~ we should go back a
- * step further... But we insert the previous pattern into the current one
- * and remember that.
- * This still does not handle the case where "magic" changes. So require the
- * user to keep his hands off of "magic".
- *
- * The tildes are parsed once before the first call to vim_regsub().
- */
-char_u *regtilde(char_u *source, int magic, bool preview)
+/// regtilde(): Replace tildes in the pattern by the old pattern.
+///
+/// Short explanation of the tilde: It stands for the previous replacement
+/// pattern. If that previous pattern also contains a ~ we should go back a
+/// step further... But we insert the previous pattern into the current one
+/// and remember that.
+/// This still does not handle the case where "magic" changes. So require the
+/// user to keep his hands off of "magic".
+///
+/// The tildes are parsed once before the first call to vim_regsub().
+char *regtilde(char *source, int magic, bool preview)
{
- char_u *newsub = source;
- char_u *tmpsub;
- char_u *p;
+ char *newsub = source;
+ char *tmpsub;
+ char *p;
int len;
int prevlen;
@@ -1575,7 +1573,7 @@ char_u *regtilde(char_u *source, int magic, bool preview)
if (*p == '\\' && p[1]) { // skip escaped characters
p++;
}
- p += utfc_ptr2len((char *)p) - 1;
+ p += utfc_ptr2len(p) - 1;
}
}
@@ -1584,7 +1582,7 @@ char_u *regtilde(char_u *source, int magic, bool preview)
// Store a copy of newsub in reg_prev_sub. It is always allocated,
// because recursive calls may make the returned string invalid.
xfree(reg_prev_sub);
- reg_prev_sub = vim_strsave(newsub);
+ reg_prev_sub = xstrdup(newsub);
}
return newsub;
@@ -1623,14 +1621,14 @@ static int fill_submatch_list(int argc FUNC_ATTR_UNUSED, typval_T *argv, int arg
// There are always 10 list items in staticList10_T.
listitem_T *li = tv_list_first(listarg->vval.v_list);
for (int i = 0; i < 10; i++) {
- char_u *s = rsm.sm_match->startp[i];
+ char *s = rsm.sm_match->startp[i];
if (s == NULL || rsm.sm_match->endp[i] == NULL) {
s = NULL;
} else {
- s = vim_strnsave(s, (size_t)(rsm.sm_match->endp[i] - s));
+ s = xstrnsave(s, (size_t)(rsm.sm_match->endp[i] - s));
}
TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(li)->vval.v_string = (char *)s;
+ TV_LIST_ITEM_TV(li)->vval.v_string = s;
li = TV_LIST_ITEM_NEXT(argv->vval.v_list, li);
}
return argskip + 1;
@@ -1717,7 +1715,7 @@ int vim_regsub_multi(regmmatch_T *rmp, linenr_T lnum, char_u *source, char_u *de
// When nesting more than a couple levels it's probably a mistake.
#define MAX_REGSUB_NESTING 4
-static char_u *eval_result[MAX_REGSUB_NESTING] = { NULL, NULL, NULL, NULL };
+static char *eval_result[MAX_REGSUB_NESTING] = { NULL, NULL, NULL, NULL };
#if defined(EXITFREE)
void free_resub_eval_result(void)
@@ -1826,21 +1824,21 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest, int des
eval_result[nested] = NULL;
} else {
char buf[NUMBUFLEN];
- eval_result[nested] = (char_u *)tv_get_string_buf_chk(&rettv, buf);
+ eval_result[nested] = (char *)tv_get_string_buf_chk(&rettv, buf);
if (eval_result[nested] != NULL) {
- eval_result[nested] = vim_strsave(eval_result[nested]);
+ eval_result[nested] = xstrdup(eval_result[nested]);
}
}
tv_clear(&rettv);
} else {
- eval_result[nested] = (char_u *)eval_to_string((char *)source + 2, NULL, true);
+ eval_result[nested] = eval_to_string((char *)source + 2, NULL, true);
}
nesting--;
if (eval_result[nested] != NULL) {
int had_backslash = false;
- for (s = eval_result[nested]; *s != NUL; MB_PTR_ADV(s)) {
+ for (s = (char_u *)eval_result[nested]; *s != NUL; MB_PTR_ADV(s)) {
// Change NL to CR, so that it becomes a line break,
// unless called from vim_regexec_nl().
// Skip over a backslashed character.
@@ -1862,9 +1860,9 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest, int des
}
if (had_backslash && (flags & REGSUB_BACKSLASH)) {
// Backslashes will be consumed, need to double them.
- s = vim_strsave_escaped(eval_result[nested], (char_u *)"\\");
+ s = vim_strsave_escaped((char_u *)eval_result[nested], (char_u *)"\\");
xfree(eval_result[nested]);
- eval_result[nested] = s;
+ eval_result[nested] = (char *)s;
}
dst += STRLEN(eval_result[nested]);
@@ -2008,11 +2006,11 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest, int des
}
}
} else {
- s = rex.reg_match->startp[no];
+ s = (char_u *)rex.reg_match->startp[no];
if (rex.reg_match->endp[no] == NULL) {
s = NULL;
} else {
- len = (int)(rex.reg_match->endp[no] - s);
+ len = (int)(rex.reg_match->endp[no] - (char *)s);
}
}
if (s != NULL) {
@@ -2208,11 +2206,11 @@ char *reg_submatch(int no)
}
}
} else {
- s = (char *)rsm.sm_match->startp[no];
+ s = rsm.sm_match->startp[no];
if (s == NULL || rsm.sm_match->endp[no] == NULL) {
retval = NULL;
} else {
- retval = xstrnsave(s, (size_t)(rsm.sm_match->endp[no] - (char_u *)s));
+ retval = xstrnsave(s, (size_t)(rsm.sm_match->endp[no] - s));
}
}
@@ -2466,12 +2464,12 @@ static bool vim_regexec_string(regmatch_T *rmp, char_u *line, colnr_T col, bool
&& result == NFA_TOO_EXPENSIVE) {
int save_p_re = (int)p_re;
int re_flags = (int)rmp->regprog->re_flags;
- char_u *pat = vim_strsave(((nfa_regprog_T *)rmp->regprog)->pattern);
+ char *pat = xstrdup(((nfa_regprog_T *)rmp->regprog)->pattern);
p_re = BACKTRACKING_ENGINE;
vim_regfree(rmp->regprog);
- report_re_switch(pat);
- rmp->regprog = vim_regcomp((char *)pat, re_flags);
+ report_re_switch((char_u *)pat);
+ rmp->regprog = vim_regcomp(pat, re_flags);
if (rmp->regprog != NULL) {
rmp->regprog->re_in_use = true;
result = rmp->regprog->engine->regexec_nl(rmp, line, col, nl);
@@ -2557,16 +2555,16 @@ long vim_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum,
&& result == NFA_TOO_EXPENSIVE) {
int save_p_re = (int)p_re;
int re_flags = (int)rmp->regprog->re_flags;
- char_u *pat = vim_strsave(((nfa_regprog_T *)rmp->regprog)->pattern);
+ char *pat = xstrdup(((nfa_regprog_T *)rmp->regprog)->pattern);
p_re = BACKTRACKING_ENGINE;
regprog_T *prev_prog = rmp->regprog;
- report_re_switch(pat);
+ report_re_switch((char_u *)pat);
// checking for \z misuse was already done when compiling for NFA,
// allow all here
reg_do_extmatch = REX_ALL;
- rmp->regprog = vim_regcomp((char *)pat, re_flags);
+ rmp->regprog = vim_regcomp(pat, re_flags);
reg_do_extmatch = 0;
if (rmp->regprog == NULL) {
diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c
index 9b9b33b09f..59a6ed28af 100644
--- a/src/nvim/regexp_bt.c
+++ b/src/nvim/regexp_bt.c
@@ -1857,14 +1857,14 @@ static char_u *regatom(int *flagp)
char_u *lp;
ret = regnode(EXACTLY);
- lp = reg_prev_sub;
+ lp = (char_u *)reg_prev_sub;
while (*lp != NUL) {
regc(*lp++);
}
regc(NUL);
if (*reg_prev_sub != NUL) {
*flagp |= HASWIDTH;
- if ((lp - reg_prev_sub) == 1) {
+ if ((lp - (char_u *)reg_prev_sub) == 1) {
*flagp |= SIMPLE;
}
}
@@ -2469,7 +2469,7 @@ do_multibyte:
// Need to get composing character too.
for (;;) {
l = utf_ptr2len((char *)regparse);
- if (!utf_composinglike((char_u *)regparse, (char_u *)regparse + l)) {
+ if (!utf_composinglike(regparse, regparse + l)) {
break;
}
regmbc(utf_ptr2char((char *)regparse));
@@ -3192,7 +3192,7 @@ static int regrepeat(char_u *p, long maxcount)
case SKWORD:
case SKWORD + ADD_NL:
while (count < maxcount) {
- if (vim_iswordp_buf(scan, rex.reg_buf)
+ if (vim_iswordp_buf((char *)scan, rex.reg_buf)
&& (testval || !ascii_isdigit(*scan))) {
MB_PTR_ADV(scan);
} else if (*scan == NUL) {
@@ -3829,7 +3829,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out)
break;
case KWORD:
- if (!vim_iswordp_buf(rex.input, rex.reg_buf)) {
+ if (!vim_iswordp_buf((char *)rex.input, rex.reg_buf)) {
status = RA_NOMATCH;
} else {
ADVANCE_REGINPUT();
@@ -3838,7 +3838,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out)
case SKWORD:
if (ascii_isdigit(*rex.input)
- || !vim_iswordp_buf(rex.input, rex.reg_buf)) {
+ || !vim_iswordp_buf((char *)rex.input, rex.reg_buf)) {
status = RA_NOMATCH;
} else {
ADVANCE_REGINPUT();
@@ -4046,7 +4046,7 @@ static bool regmatch(char_u *scan, proftime_T *tm, int *timed_out)
// Check for following composing character, unless %C
// follows (skips over all composing chars).
if (status != RA_NOMATCH
- && utf_composinglike(rex.input, rex.input + len)
+ && utf_composinglike((char *)rex.input, (char *)rex.input + len)
&& !rex.reg_icombine
&& OP(next) != RE_COMPOSING) {
// raaron: This code makes a composing character get
@@ -4975,13 +4975,13 @@ static long regtry(bt_regprog_T *prog, colnr_T col, proftime_T *tm, int *timed_o
&& reg_endzpos[i].lnum == reg_startzpos[i].lnum
&& reg_endzpos[i].col >= reg_startzpos[i].col) {
re_extmatch_out->matches[i] =
- vim_strnsave(reg_getline(reg_startzpos[i].lnum) + reg_startzpos[i].col,
- (size_t)(reg_endzpos[i].col - reg_startzpos[i].col));
+ (char_u *)xstrnsave((char *)reg_getline(reg_startzpos[i].lnum) + reg_startzpos[i].col,
+ (size_t)(reg_endzpos[i].col - reg_startzpos[i].col));
}
} else {
if (reg_startzp[i] != NULL && reg_endzp[i] != NULL) {
re_extmatch_out->matches[i] =
- vim_strnsave(reg_startzp[i], (size_t)(reg_endzp[i] - reg_startzp[i]));
+ (char_u *)xstrnsave((char *)reg_startzp[i], (size_t)(reg_endzp[i] - reg_startzp[i]));
}
}
}
@@ -5028,8 +5028,8 @@ static long bt_regexec_both(char_u *line, colnr_T col, proftime_T *tm, int *time
rex.reg_endpos = rex.reg_mmatch->endpos;
} else {
prog = (bt_regprog_T *)rex.reg_match->regprog;
- rex.reg_startp = rex.reg_match->startp;
- rex.reg_endp = rex.reg_match->endp;
+ rex.reg_startp = (char_u **)rex.reg_match->startp;
+ rex.reg_endp = (char_u **)rex.reg_match->endp;
}
// Be paranoid...
diff --git a/src/nvim/regexp_defs.h b/src/nvim/regexp_defs.h
index b313dfe877..b24ed350e8 100644
--- a/src/nvim/regexp_defs.h
+++ b/src/nvim/regexp_defs.h
@@ -127,7 +127,7 @@ typedef struct {
int has_zend; // pattern contains \ze
int has_backref; // pattern contains \1 .. \9
int reghasz;
- char_u *pattern;
+ char *pattern;
int nsubexp; // number of ()
int nstate;
nfa_state_T state[1]; // actually longer..
@@ -140,8 +140,8 @@ typedef struct {
*/
typedef struct {
regprog_T *regprog;
- char_u *startp[NSUBEXP];
- char_u *endp[NSUBEXP];
+ char *startp[NSUBEXP];
+ char *endp[NSUBEXP];
bool rm_ic;
} regmatch_T;
diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c
index d01404b5c2..fbd4e26c75 100644
--- a/src/nvim/regexp_nfa.c
+++ b/src/nvim/regexp_nfa.c
@@ -1959,9 +1959,9 @@ static int nfa_regatom(void)
emsg(_(e_nopresub));
return FAIL;
}
- for (lp = reg_prev_sub; *lp != NUL; MB_CPTR_ADV(lp)) {
+ for (lp = (char_u *)reg_prev_sub; *lp != NUL; MB_CPTR_ADV(lp)) {
EMIT(utf_ptr2char((char *)lp));
- if (lp != reg_prev_sub) {
+ if (lp != (char_u *)reg_prev_sub) {
EMIT(NFA_CONCAT);
}
}
@@ -6643,13 +6643,13 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, regsubs_T *subm
break;
case NFA_KWORD: // \k
- result = vim_iswordp_buf(rex.input, rex.reg_buf);
+ result = vim_iswordp_buf((char *)rex.input, rex.reg_buf);
ADD_STATE_IF_MATCH(t->state);
break;
case NFA_SKWORD: // \K
result = !ascii_isdigit(curc)
- && vim_iswordp_buf(rex.input, rex.reg_buf);
+ && vim_iswordp_buf((char *)rex.input, rex.reg_buf);
ADD_STATE_IF_MATCH(t->state);
break;
@@ -7362,15 +7362,15 @@ static long nfa_regtry(nfa_regprog_T *prog, colnr_T col, proftime_T *tm, int *ti
&& mpos->start_lnum == mpos->end_lnum
&& mpos->end_col >= mpos->start_col) {
re_extmatch_out->matches[i] =
- vim_strnsave(reg_getline(mpos->start_lnum) + mpos->start_col,
- (size_t)(mpos->end_col - mpos->start_col));
+ (char_u *)xstrnsave((char *)reg_getline(mpos->start_lnum) + mpos->start_col,
+ (size_t)(mpos->end_col - mpos->start_col));
}
} else {
struct linepos *lpos = &subs.synt.list.line[i];
if (lpos->start != NULL && lpos->end != NULL) {
re_extmatch_out->matches[i] =
- vim_strnsave(lpos->start, (size_t)(lpos->end - lpos->start));
+ (char_u *)xstrnsave((char *)lpos->start, (size_t)(lpos->end - lpos->start));
}
}
}
@@ -7402,8 +7402,8 @@ static long nfa_regexec_both(char_u *line, colnr_T startcol, proftime_T *tm, int
rex.reg_endpos = rex.reg_mmatch->endpos;
} else {
prog = (nfa_regprog_T *)rex.reg_match->regprog;
- rex.reg_startp = rex.reg_match->startp;
- rex.reg_endp = rex.reg_match->endp;
+ rex.reg_startp = (char_u **)rex.reg_match->startp;
+ rex.reg_endp = (char_u **)rex.reg_match->endp;
}
// Be paranoid...
@@ -7593,7 +7593,7 @@ static regprog_T *nfa_regcomp(char_u *expr, int re_flags)
#endif
// Remember whether this pattern has any \z specials in it.
prog->reghasz = re_has_z;
- prog->pattern = vim_strsave(expr);
+ prog->pattern = xstrdup((char *)expr);
#ifdef REGEXP_DEBUG
nfa_regengine.expr = NULL;
#endif
diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c
index a38f743081..78a157f9fb 100644
--- a/src/nvim/runtime.c
+++ b/src/nvim/runtime.c
@@ -651,7 +651,7 @@ static bool path_is_after(char *buf, size_t buflen)
// "after" dir in SOME codepaths not not in ALL codepaths.
return buflen >= 5
&& (!(buflen >= 6) || vim_ispathsep(buf[buflen - 6]))
- && STRCMP(buf + buflen - 5, "after") == 0;
+ && strcmp(buf + buflen - 5, "after") == 0;
}
RuntimeSearchPath runtime_search_path_build(void)
@@ -1065,7 +1065,7 @@ static void add_pack_start_dir(char *fname, void *cookie)
continue;
}
STRLCPY(buf, fname, MAXPATHL);
- STRLCAT(buf, start_pat[i], sizeof buf);
+ xstrlcat(buf, start_pat[i], sizeof buf);
if (pack_has_entries(buf)) {
add_pack_dir_to_rtp(buf, true);
}
@@ -2121,7 +2121,7 @@ scriptitem_T *get_current_script_id(char **fnamep, sctx_T *ret_sctx)
// - If a script is deleted and another script is written, with a
// different name, the inode may be re-used.
si = &SCRIPT_ITEM(script_sctx.sc_sid);
- if (si->sn_name != NULL && FNAMECMP(si->sn_name, *fnamep) == 0) {
+ if (si->sn_name != NULL && path_fnamecmp(si->sn_name, *fnamep) == 0) {
// Found it!
break;
}
diff --git a/src/nvim/screen.c b/src/nvim/screen.c
index d268dde845..8e10f2d62d 100644
--- a/src/nvim/screen.c
+++ b/src/nvim/screen.c
@@ -620,7 +620,7 @@ void setcursor_mayforce(bool force)
// With 'rightleft' set and the cursor on a double-wide character,
// position it on the leftmost column.
col = curwin->w_width_inner - curwin->w_wcol
- - ((utf_ptr2cells((char *)get_cursor_pos_ptr()) == 2
+ - ((utf_ptr2cells(get_cursor_pos_ptr()) == 2
&& vim_isprintc(gchar_cursor())) ? 2 : 1);
}
diff --git a/src/nvim/search.c b/src/nvim/search.c
index db1c766eb2..8477efed92 100644
--- a/src/nvim/search.c
+++ b/src/nvim/search.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * search.c: code for normal mode searching commands
- */
+// search.c: code for normal mode searching commands
#include <assert.h>
#include <inttypes.h>
@@ -106,10 +104,8 @@ static bool saved_spats_no_hlsearch = false;
static char_u *mr_pattern = NULL; // pattern used by search_regcomp()
static bool mr_pattern_alloced = false; // mr_pattern was allocated
-/*
- * Type used by find_pattern_in_path() to remember which included files have
- * been searched already.
- */
+// Type used by find_pattern_in_path() to remember which included files have
+// been searched already.
typedef struct SearchedFile {
FILE *fp; // File pointer
char_u *name; // Full name of file
@@ -139,9 +135,7 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc
rc_did_emsg = false;
magic = p_magic;
- /*
- * If no pattern given, use a previously defined pattern.
- */
+ // If no pattern given, use a previously defined pattern.
if (pat == NULL || *pat == NUL) {
if (pat_use == RE_LAST) {
i = last_idx;
@@ -161,7 +155,7 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc
magic = spats[i].magic;
no_smartcase = spats[i].no_scs;
} else if (options & SEARCH_HIS) { // put new pattern in history
- add_to_history(HIST_SEARCH, pat, true, NUL);
+ add_to_history(HIST_SEARCH, (char *)pat, true, NUL);
}
if (mr_pattern_alloced) {
@@ -176,18 +170,16 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc
mr_pattern = pat;
}
- /*
- * Save the currently used pattern in the appropriate place,
- * unless the pattern should not be remembered.
- */
+ // Save the currently used pattern in the appropriate place,
+ // unless the pattern should not be remembered.
if (!(options & SEARCH_KEEP) && (cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) {
// search or global command
if (pat_save == RE_SEARCH || pat_save == RE_BOTH) {
- save_re_pat(RE_SEARCH, pat, magic);
+ save_re_pat(RE_SEARCH, (char *)pat, magic);
}
// substitute or global command
if (pat_save == RE_SUBST || pat_save == RE_BOTH) {
- save_re_pat(RE_SUBST, pat, magic);
+ save_re_pat(RE_SUBST, (char *)pat, magic);
}
}
@@ -200,19 +192,17 @@ int search_regcomp(char_u *pat, int pat_save, int pat_use, int options, regmmatc
return OK;
}
-/*
- * Get search pattern used by search_regcomp().
- */
+// Get search pattern used by search_regcomp().
char_u *get_search_pat(void)
{
return mr_pattern;
}
-void save_re_pat(int idx, char_u *pat, int magic)
+void save_re_pat(int idx, char *pat, int magic)
{
- if (spats[idx].pat != pat) {
+ if (spats[idx].pat != (char_u *)pat) {
free_spat(&spats[idx]);
- spats[idx].pat = vim_strsave(pat);
+ spats[idx].pat = (char_u *)xstrdup(pat);
spats[idx].magic = magic;
spats[idx].no_scs = no_smartcase;
spats[idx].timestamp = os_time();
@@ -226,10 +216,8 @@ void save_re_pat(int idx, char_u *pat, int magic)
}
}
-/*
- * Save the search patterns, so they can be restored later.
- * Used before/after executing autocommands and user functions.
- */
+// Save the search patterns, so they can be restored later.
+// Used before/after executing autocommands and user functions.
static int save_level = 0;
void save_search_patterns(void)
@@ -237,11 +225,11 @@ void save_search_patterns(void)
if (save_level++ == 0) {
saved_spats[0] = spats[0];
if (spats[0].pat != NULL) {
- saved_spats[0].pat = vim_strsave(spats[0].pat);
+ saved_spats[0].pat = (char_u *)xstrdup((char *)spats[0].pat);
}
saved_spats[1] = spats[1];
if (spats[1].pat != NULL) {
- saved_spats[1].pat = vim_strsave(spats[1].pat);
+ saved_spats[1].pat = (char_u *)xstrdup((char *)spats[1].pat);
}
saved_spats_last_idx = last_idx;
saved_spats_no_hlsearch = no_hlsearch;
@@ -308,7 +296,7 @@ void save_last_search_pattern(void)
saved_last_search_spat = spats[RE_SEARCH];
if (spats[RE_SEARCH].pat != NULL) {
- saved_last_search_spat.pat = vim_strsave(spats[RE_SEARCH].pat);
+ saved_last_search_spat.pat = (char_u *)xstrdup((char *)spats[RE_SEARCH].pat);
}
saved_last_idx = last_idx;
saved_no_hlsearch = no_hlsearch;
@@ -450,19 +438,15 @@ char_u *last_search_pat(void)
return spats[last_idx].pat;
}
-/*
- * Reset search direction to forward. For "gd" and "gD" commands.
- */
+// Reset search direction to forward. For "gd" and "gD" commands.
void reset_search_dir(void)
{
spats[0].off.dir = '/';
set_vv_searchforward();
}
-/*
- * Set the last search pattern. For ":let @/ =" and ShaDa file.
- * Also set the saved search pattern, so that this works in an autocommand.
- */
+// Set the last search pattern. For ":let @/ =" and ShaDa file.
+// Also set the saved search pattern, so that this works in an autocommand.
void set_last_search_pat(const char_u *s, int idx, int magic, int setlast)
{
free_spat(&spats[idx]);
@@ -490,7 +474,7 @@ void set_last_search_pat(const char_u *s, int idx, int magic, int setlast)
if (spats[idx].pat == NULL) {
saved_spats[idx].pat = NULL;
} else {
- saved_spats[idx].pat = vim_strsave(spats[idx].pat);
+ saved_spats[idx].pat = (char_u *)xstrdup((char *)spats[idx].pat);
}
saved_spats_last_idx = last_idx;
}
@@ -500,11 +484,9 @@ void set_last_search_pat(const char_u *s, int idx, int magic, int setlast)
}
}
-/*
- * Get a regexp program for the last used search pattern.
- * This is used for highlighting all matches in a window.
- * Values returned in regmatch->regprog and regmatch->rmm_ic.
- */
+// Get a regexp program for the last used search pattern.
+// This is used for highlighting all matches in a window.
+// Values returned in regmatch->regprog and regmatch->rmm_ic.
void last_pat_prog(regmmatch_T *regmatch)
{
if (spats[last_idx].pat == NULL) {
@@ -578,9 +560,7 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
return FAIL;
}
- /*
- * find the string
- */
+ // find the string
do { // loop for count
// When not accepting a match at the start position set "extra_col" to a
// non-zero value. Don't do that when starting at MAXCOL, since MAXCOL + 1
@@ -591,7 +571,7 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
&& pos->lnum <= buf->b_ml.ml_line_count
&& pos->col < MAXCOL - 2) {
// Watch out for the "col" being MAXCOL - 2, used in a closed fold.
- ptr = ml_get_buf(buf, pos->lnum, false);
+ ptr = (char_u *)ml_get_buf(buf, pos->lnum, false);
if ((int)STRLEN(ptr) <= pos->col) {
start_char_len = 1;
} else {
@@ -615,13 +595,11 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
at_first_line = false; // not in first line now
}
- /*
- * Start searching in current line, unless searching backwards and
- * we're in column 0.
- * If we are searching backwards, in column 0, and not including the
- * current position, gain some efficiency by skipping back a line.
- * Otherwise begin the search in the current line.
- */
+ // Start searching in current line, unless searching backwards and
+ // we're in column 0.
+ // If we are searching backwards, in column 0, and not including the
+ // current position, gain some efficiency by skipping back a line.
+ // Otherwise begin the search in the current line.
if (dir == BACKWARD && start_pos.col == 0
&& (options & SEARCH_START) == 0) {
lnum = pos->lnum - 1;
@@ -664,14 +642,12 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
if (lnum + matchpos.lnum > buf->b_ml.ml_line_count) {
ptr = (char_u *)"";
} else {
- ptr = ml_get_buf(buf, lnum + matchpos.lnum, false);
+ ptr = (char_u *)ml_get_buf(buf, lnum + matchpos.lnum, false);
}
- /*
- * Forward search in the first line: match should be after
- * the start position. If not, continue at the end of the
- * match (this is vi compatible) or on the next char.
- */
+ // Forward search in the first line: match should be after
+ // the start position. If not, continue at the end of the
+ // match (this is vi compatible) or on the next char.
if (dir == FORWARD && at_first_line) {
match_ok = true;
// When the match starts in a next line it's certainly
@@ -687,11 +663,9 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
: ((int)matchpos.col
- (ptr[matchpos.col] == NUL)
< (int)start_pos.col + extra_col))) {
- /*
- * If vi-compatible searching, continue at the end
- * of the match, otherwise continue one position
- * forward.
- */
+ // If vi-compatible searching, continue at the end
+ // of the match, otherwise continue one position
+ // forward.
if (vim_strchr(p_cpo, CPO_SEARCH) != NULL) {
if (nmatched > 1) {
// end is in next line, thus no match in
@@ -737,20 +711,18 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
}
// Need to get the line pointer again, a multi-line search may
// have made it invalid.
- ptr = ml_get_buf(buf, lnum, false);
+ ptr = (char_u *)ml_get_buf(buf, lnum, false);
}
if (!match_ok) {
continue;
}
}
if (dir == BACKWARD) {
- /*
- * Now, if there are multiple matches on this line,
- * we have to get the last one. Or the last one before
- * the cursor, if we're on that line.
- * When putting the new cursor at the end, compare
- * relative to the end of the match.
- */
+ // Now, if there are multiple matches on this line,
+ // we have to get the last one. Or the last one before
+ // the cursor, if we're on that line.
+ // When putting the new cursor at the end, compare
+ // relative to the end of the match.
match_ok = false;
for (;;) {
// Remember a position that is before the start
@@ -822,13 +794,11 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
}
// Need to get the line pointer again, a
// multi-line search may have made it invalid.
- ptr = ml_get_buf(buf, lnum + matchpos.lnum, false);
+ ptr = (char_u *)ml_get_buf(buf, lnum + matchpos.lnum, false);
}
- /*
- * If there is only a match after the cursor, skip
- * this match.
- */
+ // If there is only a match after the cursor, skip
+ // this match.
if (!match_ok) {
continue;
}
@@ -852,7 +822,7 @@ int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir,
} else {
pos->col--;
if (pos->lnum <= buf->b_ml.ml_line_count) {
- ptr = ml_get_buf(buf, pos->lnum, false);
+ ptr = (char_u *)ml_get_buf(buf, pos->lnum, false);
pos->col -= utf_head_off((char *)ptr, (char *)ptr + pos->col);
}
}
@@ -1042,25 +1012,19 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count,
size_t len;
bool has_offset = false;
- /*
- * A line offset is not remembered, this is vi compatible.
- */
+ // A line offset is not remembered, this is vi compatible.
if (spats[0].off.line && vim_strchr(p_cpo, CPO_LINEOFF) != NULL) {
spats[0].off.line = false;
spats[0].off.off = 0;
}
- /*
- * Save the values for when (options & SEARCH_KEEP) is used.
- * (there is no "if ()" around this because gcc wants them initialized)
- */
+ // Save the values for when (options & SEARCH_KEEP) is used.
+ // (there is no "if ()" around this because gcc wants them initialized)
old_off = spats[0].off;
pos = curwin->w_cursor; // start searching at the cursor position
- /*
- * Find out the direction of the search.
- */
+ // Find out the direction of the search.
if (dirc == 0) {
dirc = (char_u)spats[0].off.dir;
} else {
@@ -1087,17 +1051,13 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count,
}
}
- /*
- * Turn 'hlsearch' highlighting back on.
- */
+ // Turn 'hlsearch' highlighting back on.
if (no_hlsearch && !(options & SEARCH_KEEP)) {
redraw_all_later(UPD_SOME_VALID);
set_no_hlsearch(false);
}
- /*
- * Repeat the search when pattern followed by ';', e.g. "/foo/;?bar".
- */
+ // Repeat the search when pattern followed by ';', e.g. "/foo/;?bar".
for (;;) {
bool show_top_bot_msg = false;
@@ -1119,10 +1079,8 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count,
}
if (pat != NULL && *pat != NUL) { // look for (new) offset
- /*
- * Find end of regular expression.
- * If there is a matching '/' or '?', toss it.
- */
+ // Find end of regular expression.
+ // If there is a matching '/' or '?', toss it.
ps = (char_u *)strcopy;
p = (char_u *)skip_regexp((char *)pat, search_delim, p_magic, &strcopy);
if (strcopy != (char *)ps) {
@@ -1287,13 +1245,11 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count,
}
}
- /*
- * If there is a character offset, subtract it from the current
- * position, so we don't get stuck at "?pat?e+2" or "/pat/s-2".
- * Skip this if pos.col is near MAXCOL (closed fold).
- * This is not done for a line offset, because then we would not be vi
- * compatible.
- */
+ // If there is a character offset, subtract it from the current
+ // position, so we don't get stuck at "?pat?e+2" or "/pat/s-2".
+ // Skip this if pos.col is near MAXCOL (closed fold).
+ // This is not done for a line offset, because then we would not be vi
+ // compatible.
if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2) {
if (spats[0].off.off > 0) {
for (c = spats[0].off.off; c; c--) {
@@ -1350,9 +1306,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count,
apply_autocmds(EVENT_SEARCHWRAPPED, NULL, NULL, false, NULL);
}
- /*
- * Add character and/or line offset
- */
+ // Add character and/or line offset
if (!(options & SEARCH_NOOF) || (pat != NULL && *pat == ';')) {
pos_T org_pos = pos;
@@ -1444,15 +1398,13 @@ end_do_search:
return retval;
}
-/*
- * search_for_exact_line(buf, pos, dir, pat)
- *
- * Search for a line starting with the given pattern (ignoring leading
- * white-space), starting from pos and going in direction "dir". "pos" will
- * contain the position of the match found. Blank lines match only if
- * ADDING is set. If p_ic is set then the pattern must be in lowercase.
- * Return OK for success, or FAIL if no line found.
- */
+// search_for_exact_line(buf, pos, dir, pat)
+//
+// Search for a line starting with the given pattern (ignoring leading
+// white-space), starting from pos and going in direction "dir". "pos" will
+// contain the position of the match found. Blank lines match only if
+// ADDING is set. If p_ic is set then the pattern must be in lowercase.
+// Return OK for success, or FAIL if no line found.
int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat)
{
linenr_T start = 0;
@@ -1491,7 +1443,7 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat)
if (start == 0) {
start = pos->lnum;
}
- ptr = ml_get_buf(buf, pos->lnum, false);
+ ptr = (char_u *)ml_get_buf(buf, pos->lnum, false);
p = (char_u *)skipwhite((char *)ptr);
pos->col = (colnr_T)(p - ptr);
@@ -1513,9 +1465,7 @@ int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char_u *pat)
return FAIL;
}
-/*
- * Character Searches
- */
+// Character Searches
/// Search for a character in a line. If "t_cmd" is false, move to the
/// position of the character, otherwise move to just before the char.
@@ -1574,7 +1524,7 @@ int searchc(cmdarg_T *cap, int t_cmd)
cap->oap->inclusive = true;
}
- p = get_cursor_line_ptr();
+ p = (char_u *)get_cursor_line_ptr();
col = curwin->w_cursor.col;
len = (int)STRLEN(p);
@@ -1618,15 +1568,11 @@ int searchc(cmdarg_T *cap, int t_cmd)
return OK;
}
-/*
- * "Other" Searches
- */
+// "Other" Searches
-/*
- * findmatch - find the matching paren or brace
- *
- * Improvement over vi: Braces inside quotes are ignored.
- */
+// findmatch - find the matching paren or brace
+//
+// Improvement over vi: Braces inside quotes are ignored.
pos_T *findmatch(oparg_T *oap, int initc)
{
return findmatchlimit(oap, initc, 0, 0);
@@ -1649,22 +1595,21 @@ static bool check_prevcol(char_u *linep, int col, int ch, int *prevcol)
return col >= 0 && linep[col] == ch;
}
-/*
- * Raw string start is found at linep[startpos.col - 1].
- * Return true if the matching end can be found between startpos and endpos.
- */
-static bool find_rawstring_end(char_u *linep, pos_T *startpos, pos_T *endpos)
+/// Raw string start is found at linep[startpos.col - 1].
+///
+/// @return true if the matching end can be found between startpos and endpos.
+static bool find_rawstring_end(char *linep, pos_T *startpos, pos_T *endpos)
{
- char_u *p;
+ char *p;
linenr_T lnum;
for (p = linep + startpos->col + 1; *p && *p != '('; p++) {}
size_t delim_len = (size_t)((p - linep) - startpos->col - 1);
- char_u *delim_copy = vim_strnsave(linep + startpos->col + 1, delim_len);
+ char *delim_copy = xstrnsave(linep + startpos->col + 1, delim_len);
bool found = false;
for (lnum = startpos->lnum; lnum <= endpos->lnum; lnum++) {
- char_u *line = (char_u *)ml_get(lnum);
+ char *line = ml_get(lnum);
for (p = line + (lnum == startpos->lnum ? startpos->col + 1 : 0); *p; p++) {
if (lnum == endpos->lnum && (colnr_T)(p - line) >= endpos->col) {
@@ -1726,27 +1671,24 @@ static void find_mps_values(int *initc, int *findc, bool *backwards, bool switch
}
}
-/*
- * findmatchlimit -- find the matching paren or brace, if it exists within
- * maxtravel lines of the cursor. A maxtravel of 0 means search until falling
- * off the edge of the file.
- *
- * "initc" is the character to find a match for. NUL means to find the
- * character at or after the cursor. Special values:
- * '*' look for C-style comment / *
- * '/' look for C-style comment / *, ignoring comment-end
- * '#' look for preprocessor directives
- * 'R' look for raw string start: R"delim(text)delim" (only backwards)
- *
- * flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#')
- * FM_FORWARD search forwards (when initc is '/', '*' or '#')
- * FM_BLOCKSTOP stop at start/end of block ({ or } in column 0)
- * FM_SKIPCOMM skip comments (not implemented yet!)
- *
- * "oap" is only used to set oap->motion_type for a linewise motion, it can be
- * NULL
- */
-
+// findmatchlimit -- find the matching paren or brace, if it exists within
+// maxtravel lines of the cursor. A maxtravel of 0 means search until falling
+// off the edge of the file.
+//
+// "initc" is the character to find a match for. NUL means to find the
+// character at or after the cursor. Special values:
+// '*' look for C-style comment / *
+// '/' look for C-style comment / *, ignoring comment-end
+// '#' look for preprocessor directives
+// 'R' look for raw string start: R"delim(text)delim" (only backwards)
+//
+// flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#')
+// FM_FORWARD search forwards (when initc is '/', '*' or '#')
+// FM_BLOCKSTOP stop at start/end of block ({ or } in column 0)
+// FM_SKIPCOMM skip comments (not implemented yet!)
+//
+// "oap" is only used to set oap->motion_type for a linewise motion, it can be
+// NULL
pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
{
static pos_T pos; // current search position
@@ -1784,12 +1726,10 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
dir = 0;
}
- /*
- * if initc given, look in the table for the matching character
- * '/' and '*' are special cases: look for start or end of comment.
- * When '/' is used, we ignore running backwards into a star-slash, for
- * "[*" command, we just want to find any comment.
- */
+ // if initc given, look in the table for the matching character
+ // '/' and '*' are special cases: look for start or end of comment.
+ // When '/' is used, we ignore running backwards into a star-slash, for
+ // "[*" command, we just want to find any comment.
if (initc == '/' || initc == '*' || initc == 'R') {
comment_dir = dir;
if (initc == '/') {
@@ -1807,18 +1747,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
return NULL;
}
} else {
- /*
- * Either initc is '#', or no initc was given and we need to look
- * under the cursor.
- */
+ // Either initc is '#', or no initc was given and we need to look
+ // under the cursor.
if (initc == '#') {
hash_dir = dir;
} else {
- /*
- * initc was not given, must look for something to match under
- * or near the cursor.
- * Only check for special things when 'cpo' doesn't have '%'.
- */
+ // initc was not given, must look for something to match under
+ // or near the cursor.
+ // Only check for special things when 'cpo' doesn't have '%'.
if (!cpo_match) {
// Are we before or at #if, #else etc.?
ptr = (char_u *)skipwhite((char *)linep);
@@ -1852,16 +1788,12 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
}
}
- /*
- * If we are not on a comment or the # at the start of a line, then
- * look for brace anywhere on this line after the cursor.
- */
+ // If we are not on a comment or the # at the start of a line, then
+ // look for brace anywhere on this line after the cursor.
if (!hash_dir && !comment_dir) {
- /*
- * Find the brace under or after the cursor.
- * If beyond the end of the line, use the last character in
- * the line.
- */
+ // Find the brace under or after the cursor.
+ // If beyond the end of the line, use the last character in
+ // the line.
if (linep[pos.col] == NUL && pos.col) {
pos.col--;
}
@@ -1897,9 +1829,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
}
}
if (hash_dir) {
- /*
- * Look for matching #if, #else, #elif, or #endif
- */
+ // Look for matching #if, #else, #elif, or #endif
if (oap != NULL) {
oap->motion_type = kMTLineWise; // Linewise for this case only
}
@@ -1984,10 +1914,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
}
while (!got_int) {
- /*
- * Go to the next position, forward or backward. We could use
- * inc() and dec() here, but that is much slower
- */
+ // Go to the next position, forward or backward. We could use
+ // inc() and dec() here, but that is much slower
if (backwards) {
// char to match is inside of comment, don't search outside
if (lispcomm && pos.col < (colnr_T)comment_col) {
@@ -2068,10 +1996,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
return &pos;
}
} else { // Searching backwards
- /*
- * A comment may contain / * or / /, it may also start or end
- * with / * /. Ignore a / * after / / and after *.
- */
+ // A comment may contain / * or / /, it may also start or end
+ // with / * /. Ignore a / * after / / and after *.
if (pos.col == 0) {
continue;
} else if (raw_string) {
@@ -2082,7 +2008,7 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
// delimiter we can check if it ends before where we
// started searching, or before the previously found
// raw string start.
- if (!find_rawstring_end(linep, &pos,
+ if (!find_rawstring_end((char *)linep, &pos,
count > 0 ? &match_pos : &curwin->w_cursor)) {
count++;
match_pos = pos;
@@ -2114,18 +2040,14 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
continue;
}
- /*
- * If smart matching ('cpoptions' does not contain '%'), braces inside
- * of quotes are ignored, but only if there is an even number of
- * quotes in the line.
- */
+ // If smart matching ('cpoptions' does not contain '%'), braces inside
+ // of quotes are ignored, but only if there is an even number of
+ // quotes in the line.
if (cpo_match) {
do_quotes = 0;
} else if (do_quotes == -1) {
- /*
- * Count the number of quotes in the line, skipping \" and '"'.
- * Watch out for "\\".
- */
+ // Count the number of quotes in the line, skipping \" and '"'.
+ // Watch out for "\\".
at_start = do_quotes;
for (ptr = linep; *ptr; ptr++) {
if (ptr == linep + pos.col + backwards) {
@@ -2141,10 +2063,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
}
do_quotes &= 1; // result is 1 with even number of quotes
- /*
- * If we find an uneven count, check current line and previous
- * one for a '\' at the end.
- */
+ // If we find an uneven count, check current line and previous
+ // one for a '\' at the end.
if (!do_quotes) {
inquote = false;
if (ptr[-1] == '\\') {
@@ -2180,17 +2100,15 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
start_in_quotes = kFalse;
}
- /*
- * If 'smartmatch' is set:
- * Things inside quotes are ignored by setting 'inquote'. If we
- * find a quote without a preceding '\' invert 'inquote'. At the
- * end of a line not ending in '\' we reset 'inquote'.
- *
- * In lines with an uneven number of quotes (without preceding '\')
- * we do not know which part to ignore. Therefore we only set
- * inquote if the number of quotes in a line is even, unless this
- * line or the previous one ends in a '\'. Complicated, isn't it?
- */
+ // If 'smartmatch' is set:
+ // Things inside quotes are ignored by setting 'inquote'. If we
+ // find a quote without a preceding '\' invert 'inquote'. At the
+ // end of a line not ending in '\' we reset 'inquote'.
+ //
+ // In lines with an uneven number of quotes (without preceding '\')
+ // we do not know which part to ignore. Therefore we only set
+ // inquote if the number of quotes in a line is even, unless this
+ // line or the previous one ends in a '\'. Complicated, isn't it?
const int c = utf_ptr2char((char *)linep + pos.col);
switch (c) {
case NUL:
@@ -2219,13 +2137,11 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
}
break;
- /*
- * If smart matching ('cpoptions' does not contain '%'):
- * Skip things in single quotes: 'x' or '\x'. Be careful for single
- * single quotes, eg jon's. Things like '\233' or '\x3f' are not
- * skipped, there is never a brace in them.
- * Ignore this when finding matches for `'.
- */
+ // If smart matching ('cpoptions' does not contain '%'):
+ // Skip things in single quotes: 'x' or '\x'. Be careful for single
+ // single quotes, eg jon's. Things like '\233' or '\x3f' are not
+ // skipped, there is never a brace in them.
+ // Ignore this when finding matches for `'.
case '\'':
if (!cpo_match && initc != '\'' && findc != '\'') {
if (backwards) {
@@ -2253,10 +2169,8 @@ pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
FALLTHROUGH;
default:
- /*
- * For Lisp skip over backslashed (), {} and [].
- * (actually, we skip #\( et al)
- */
+ // For Lisp skip over backslashed (), {} and [].
+ // (actually, we skip #\( et al)
if (curbuf->b_p_lisp
&& vim_strchr("(){}[]", c) != NULL
&& pos.col > 1
@@ -2368,9 +2282,7 @@ void showmatch(int c)
colnr_T save_dollar_vcol;
char_u *p;
- /*
- * Only show match for chars in the 'matchpairs' option.
- */
+ // Only show match for chars in the 'matchpairs' option.
// 'matchpairs' is "x:y,x:y"
for (p = (char_u *)curbuf->b_p_mps; *p != NUL; p++) {
if (utf_ptr2char((char *)p) == c && (curwin->w_p_rl ^ p_ri)) {
@@ -2426,10 +2338,8 @@ void showmatch(int c)
// and has a higher column number.
dollar_vcol = save_dollar_vcol;
- /*
- * brief pause, unless 'm' is present in 'cpo' and a character is
- * available.
- */
+ // brief pause, unless 'm' is present in 'cpo' and a character is
+ // available.
if (vim_strchr(p_cpo, CPO_SHOWMATCH) != NULL) {
os_delay((uint64_t)p_mat * 100L + 8, true);
} else if (!char_avail()) {
@@ -2807,7 +2717,7 @@ static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, searchst
}
if (done_search) {
xfree(lastpat);
- lastpat = vim_strsave(spats[last_idx].pat);
+ lastpat = (char_u *)xstrdup((char *)spats[last_idx].pat);
chgtick = (int)buf_get_changedtick(curbuf);
lbuf = curbuf;
lastpos = p;
@@ -2917,7 +2827,7 @@ void f_searchcount(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
goto the_end;
}
xfree(spats[last_idx].pat);
- spats[last_idx].pat = vim_strsave(pattern);
+ spats[last_idx].pat = (char_u *)xstrdup((char *)pattern);
}
if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) {
goto the_end; // the previous pattern was never defined
@@ -3193,7 +3103,7 @@ bool fuzzy_match(char_u *const str, const char_u *const pat_arg, const bool matc
*outScore = 0;
- char_u *const save_pat = vim_strsave(pat_arg);
+ char_u *const save_pat = (char_u *)xstrdup((char *)pat_arg);
char_u *pat = save_pat;
char_u *p = pat;
@@ -3598,14 +3508,14 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo
if (inc_opt != NULL && strstr(inc_opt, "\\zs") != NULL) {
// Use text from '\zs' to '\ze' (or end) of 'include'.
- new_fname = find_file_name_in_path(incl_regmatch.startp[0],
- (size_t)(incl_regmatch.endp[0]
- - incl_regmatch.startp[0]),
- FNAME_EXP|FNAME_INCL|FNAME_REL,
- 1L, p_fname);
+ new_fname = (char_u *)find_file_name_in_path(incl_regmatch.startp[0],
+ (size_t)(incl_regmatch.endp[0]
+ - incl_regmatch.startp[0]),
+ FNAME_EXP|FNAME_INCL|FNAME_REL,
+ 1L, (char *)p_fname);
} else {
// Use text after match with 'include'.
- new_fname = file_name_in_line(incl_regmatch.endp[0], 0,
+ new_fname = file_name_in_line((char_u *)incl_regmatch.endp[0], 0,
FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL);
}
already_searched = false;
@@ -3668,26 +3578,24 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo
// 'includeexpr' is set.
msg_outtrans_attr((char *)new_fname, HL_ATTR(HLF_D));
} else {
- /*
- * Isolate the file name.
- * Include the surrounding "" or <> if present.
- */
+ // Isolate the file name.
+ // Include the surrounding "" or <> if present.
if (inc_opt != NULL
&& strstr(inc_opt, "\\zs") != NULL) {
// pattern contains \zs, use the match
- p = incl_regmatch.startp[0];
+ p = (char_u *)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
- for (p = incl_regmatch.endp[0];
+ for (p = (char_u *)incl_regmatch.endp[0];
*p && !vim_isfilec(*p); p++) {}
for (i = 0; vim_isfilec(p[i]); i++) {}
}
if (i == 0) {
// Nothing found, use the rest of the line.
- p = incl_regmatch.endp[0];
+ p = (char_u *)incl_regmatch.endp[0];
i = (int)STRLEN(p);
} else if (p > line) {
// Avoid checking before the start of the line, can
@@ -3764,9 +3672,7 @@ void find_pattern_in_path(char_u *ptr, Direction dir, size_t len, bool whole, bo
}
}
} else {
- /*
- * Check if the line is a define (type == FIND_DEFINE)
- */
+ // Check if the line is a define (type == FIND_DEFINE)
p = line;
search_line:
define_matched = false;
@@ -3775,17 +3681,15 @@ search_line:
// Pattern must be first identifier after 'define', so skip
// to that position before checking for match of pattern. Also
// don't let it match beyond the end of this identifier.
- p = def_regmatch.endp[0];
+ p = (char_u *)def_regmatch.endp[0];
while (*p && !vim_iswordc(*p)) {
p++;
}
define_matched = true;
}
- /*
- * Look for a match. Don't do this if we are looking for a
- * define and this line didn't match define_prog above.
- */
+ // Look for a match. Don't do this if we are looking for a
+ // define and this line didn't match define_prog above.
if (def_regmatch.regprog == NULL || define_matched) {
if (define_matched || compl_status_sol()) {
// compare the first "len" chars from "ptr"
@@ -3802,7 +3706,7 @@ search_line:
} else if (regmatch.regprog != NULL
&& vim_regexec(&regmatch, (char *)line, (colnr_T)(p - line))) {
matched = true;
- startp = regmatch.startp[0];
+ startp = (char_u *)regmatch.startp[0];
// Check if the line is not a comment line (unless we are
// looking for a define). A line starting with "# define"
// is not considered to be a comment line.
@@ -3813,12 +3717,10 @@ search_line:
matched = false;
}
- /*
- * Also check for a "/ *" or "/ /" before the match.
- * Skips lines like "int backwards; / * normal index
- * * /" when looking for "normal".
- * Note: Doesn't skip "/ *" in comments.
- */
+ // Also check for a "/ *" or "/ /" before the match.
+ // Skips lines like "int backwards; / * normal index
+ // * /" when looking for "normal".
+ // Note: Doesn't skip "/ *" in comments.
p = (char_u *)skipwhite((char *)line);
if (matched
|| (p[0] == '/' && p[1] == '*') || p[0] == '*') {
@@ -3908,7 +3810,7 @@ search_line:
cont_s_ipos = true;
}
IObuff[i] = NUL;
- aux = IObuff;
+ aux = (char_u *)IObuff;
if (i == ins_compl_len()) {
goto exit_matched;
@@ -4034,11 +3936,9 @@ exit_matched:
break;
}
- /*
- * Read the next line. When reading an included file and encountering
- * end-of-file, close the file and continue in the file that included
- * it.
- */
+ // Read the next line. When reading an included file and encountering
+ // end-of-file, close the file and continue in the file that included
+ // it.
while (depth >= 0 && !already
&& vim_fgets(line = file_line, LSIZE, files[depth].fp)) {
fclose(files[depth].fp);
diff --git a/src/nvim/shada.c b/src/nvim/shada.c
index e20bce5b34..74d8b30347 100644
--- a/src/nvim/shada.c
+++ b/src/nvim/shada.c
@@ -752,7 +752,7 @@ static int open_shada_file_for_reading(const char *const fname, ShaDaReadDef *sd
return error;
}
- assert(STRCMP(p_enc, "utf-8") == 0);
+ assert(strcmp(p_enc, "utf-8") == 0);
return 0;
}
@@ -882,10 +882,10 @@ static const void *shada_hist_iter(const void *const iter, const uint8_t history
.data = {
.history_item = {
.histtype = history_type,
- .string = (char *)hist_he.hisstr,
+ .string = hist_he.hisstr,
.sep = (char)(history_type == HIST_SEARCH
- ? (char)hist_he.hisstr[STRLEN(hist_he.hisstr) + 1]
- : 0),
+ ? hist_he.hisstr[STRLEN(hist_he.hisstr) + 1]
+ : 0),
.additional_elements = hist_he.additional_elements,
}
}
@@ -1008,7 +1008,7 @@ static inline void hms_to_he_array(const HistoryMergerState *const hms_p,
HMLL_FORALL(&hms_p->hmll, cur_entry, {
hist->timestamp = cur_entry->data.timestamp;
hist->hisnum = (int)(hist - hist_array) + 1;
- hist->hisstr = (char_u *)cur_entry->data.data.history_item.string;
+ hist->hisstr = cur_entry->data.data.history_item.string;
hist->additional_elements =
cur_entry->data.data.history_item.additional_elements;
hist++;
@@ -1053,7 +1053,7 @@ static buf_T *find_buffer(khash_t(fnamebufs) *const fname_bufs, const char *cons
kh_key(fname_bufs, k) = xstrdup(fname);
FOR_ALL_BUFFERS(buf) {
if (buf->b_ffname != NULL) {
- if (FNAMECMP(fname, buf->b_ffname) == 0) {
+ if (path_fnamecmp(fname, buf->b_ffname) == 0) {
kh_val(fname_bufs, k) = buf;
return buf;
}
@@ -1238,7 +1238,7 @@ static void shada_read(ShaDaReadDef *const sd_reader, const int flags)
// string is close to useless: you can only use it with :& or :~ and
// that’s all because s//~ is not available until the first call to
// regtilde. Vim was not calling this for some reason.
- (void)(char *)regtilde((char_u *)cur_entry.data.sub_string.sub, p_magic, false);
+ (void)regtilde(cur_entry.data.sub_string.sub, p_magic, false);
// Do not free shada entry: its allocated memory was saved above.
break;
case kSDItemHistoryEntry:
@@ -1313,9 +1313,9 @@ static void shada_read(ShaDaReadDef *const sd_reader, const int flags)
MERGE_JUMPS(curwin->w_jumplistlen, curwin->w_jumplist, xfmark_T,
fmark.timestamp, fmark.mark, cur_entry,
(buf == NULL
- ? (jl_entry.fname != NULL
- && STRCMP(fm.fname, jl_entry.fname) == 0)
- : fm.fmark.fnum == jl_entry.fmark.fnum),
+ ? (jl_entry.fname != NULL
+ && strcmp(fm.fname, jl_entry.fname) == 0)
+ : fm.fmark.fnum == jl_entry.fmark.fnum),
free_xfmark, SDE_TO_XFMARK, ADJUST_IDX, DUMMY_AFTERFREE);
#undef SDE_TO_XFMARK
#undef ADJUST_IDX
@@ -3098,7 +3098,7 @@ shada_write_file_nomerge: {}
}
}
#endif
- if (vim_rename((char_u *)tempname, (char_u *)fname) == -1) {
+ if (vim_rename(tempname, fname) == -1) {
semsg(_(RNERR "Can't rename ShaDa file from %s to %s!"),
tempname, fname);
} else {
diff --git a/src/nvim/sign.c b/src/nvim/sign.c
index 7d931a853b..ed546cf303 100644
--- a/src/nvim/sign.c
+++ b/src/nvim/sign.c
@@ -86,7 +86,7 @@ static signgroup_T *sign_group_ref(const char *groupname)
STRCPY(group->sg_name, groupname);
group->sg_refcount = 1;
group->sg_next_sign_id = 1;
- hash_add_item(&sg_table, hi, group->sg_name, hash);
+ hash_add_item(&sg_table, hi, (char_u *)group->sg_name, hash);
} else {
// existing group
group = HI2SG(hi);
@@ -119,10 +119,10 @@ static void sign_group_unref(char *groupname)
/// or in a named group. If 'group' is '*', then the sign is part of the group.
static bool sign_in_group(sign_entry_T *sign, const char *group)
{
- return ((group != NULL && STRCMP(group, "*") == 0)
+ return ((group != NULL && strcmp(group, "*") == 0)
|| (group == NULL && sign->se_group == NULL)
|| (group != NULL && sign->se_group != NULL
- && STRCMP(group, sign->se_group->sg_name) == 0));
+ && strcmp(group, sign->se_group->sg_name) == 0));
}
/// Get the next free sign identifier in the specified group
@@ -784,7 +784,7 @@ static int sign_cmd_idx(char *begin_cmd, char *end_cmd)
*end_cmd = NUL;
for (idx = 0;; idx++) {
- if (cmds[idx] == NULL || STRCMP(begin_cmd, cmds[idx]) == 0) {
+ if (cmds[idx] == NULL || strcmp(begin_cmd, cmds[idx]) == 0) {
break;
}
}
@@ -801,7 +801,7 @@ static sign_T *sign_find(const char *name, sign_T **sp_prev)
*sp_prev = NULL;
}
for (sp = first_sign; sp != NULL; sp = sp->sn_next) {
- if (STRCMP(sp->sn_name, name) == 0) {
+ if (strcmp(sp->sn_name, name) == 0) {
break;
}
if (sp_prev != NULL) {
@@ -1034,7 +1034,7 @@ static int sign_place(int *sign_id, const char *sign_group, const char *sign_nam
}
for (sp = first_sign; sp != NULL; sp = sp->sn_next) {
- if (STRCMP(sp->sn_name, sign_name) == 0) {
+ if (strcmp(sp->sn_name, sign_name) == 0) {
break;
}
}
diff --git a/src/nvim/sign_defs.h b/src/nvim/sign_defs.h
index 1efde30008..16e783aab7 100644
--- a/src/nvim/sign_defs.h
+++ b/src/nvim/sign_defs.h
@@ -10,9 +10,9 @@
// Sign group
typedef struct signgroup_S {
- uint16_t sg_refcount; // number of signs in this group
- int sg_next_sign_id; // next sign id for this group
- char_u sg_name[1]; // sign group name
+ uint16_t sg_refcount; // number of signs in this group
+ int sg_next_sign_id; // next sign id for this group
+ char sg_name[1]; // sign group name
} signgroup_T;
// Macros to get the sign group structure from the group name
@@ -51,4 +51,4 @@ typedef enum {
SIGN_TEXT,
} SignType;
-#endif // NVIM_SIGN_DEFS_H
+#endif // NVIM_SIGN_DEFS_H
diff --git a/src/nvim/spell.c b/src/nvim/spell.c
index 7c05c9fe53..42891fd3fb 100644
--- a/src/nvim/spell.c
+++ b/src/nvim/spell.c
@@ -71,6 +71,7 @@
#include "nvim/change.h" // for changed_bytes
#include "nvim/charset.h" // for skipwhite, getwhitecols, skipbin
#include "nvim/cursor.h" // for get_cursor_line_ptr
+#include "nvim/decoration.h"
#include "nvim/drawscreen.h" // for NOT_VALID, redraw_later
#include "nvim/eval/typval.h" // for semsg
#include "nvim/ex_cmds.h" // for do_sub_msg
@@ -193,8 +194,8 @@ int did_set_spelltab;
char *e_format = N_("E759: Format error in spell file");
// Remember what "z?" replaced.
-char_u *repl_from = NULL;
-char_u *repl_to = NULL;
+char *repl_from = NULL;
+char *repl_to = NULL;
/// Main spell-checking function.
/// "ptr" points to a character that could be the start of a word.
@@ -220,7 +221,7 @@ size_t spell_check(win_T *wp, char_u *ptr, hlf_T *attrp, int *capcol, bool docou
size_t nrlen = 0; // found a number first
size_t wrongcaplen = 0;
bool count_word = docount;
- bool use_camel_case = *wp->w_s->b_p_spo != NUL;
+ bool use_camel_case = (wp->w_s->b_p_spo_flags & SPO_CAMEL) != 0;
bool camel_case = false;
// A word never starts at a space or a control character. Return quickly
@@ -368,7 +369,7 @@ size_t spell_check(win_T *wp, char_u *ptr, hlf_T *attrp, int *capcol, bool docou
int r = vim_regexec(&regmatch, (char *)ptr, 0);
wp->w_s->b_cap_prog = regmatch.regprog;
if (r) {
- *capcol = (int)(regmatch.endp[0] - ptr);
+ *capcol = (int)(regmatch.endp[0] - (char *)ptr);
}
}
@@ -1198,6 +1199,24 @@ bool no_spell_checking(win_T *wp)
return false;
}
+static void decor_spell_nav_start(win_T *wp)
+{
+ decor_state = (DecorState){ 0 };
+ decor_redraw_reset(wp->w_buffer, &decor_state);
+}
+
+static bool decor_spell_nav_col(win_T *wp, linenr_T lnum, linenr_T *decor_lnum, int col,
+ char **decor_error)
+{
+ if (*decor_lnum != lnum) {
+ decor_providers_invoke_spell(wp, lnum - 1, col, lnum - 1, -1, decor_error);
+ decor_redraw_line(wp->w_buffer, lnum - 1, &decor_state);
+ *decor_lnum = lnum;
+ }
+ decor_redraw_col(wp->w_buffer, col, col, false, &decor_state);
+ return decor_state.spell;
+}
+
/// Moves to the next spell error.
/// "curline" is false for "[s", "]s", "[S" and "]S".
/// "curline" is true to find word under/after cursor in the same line.
@@ -1216,11 +1235,11 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
hlf_T attr = HLF_COUNT;
size_t len;
int has_syntax = syntax_present(wp);
- int col;
+ colnr_T col;
char_u *buf = NULL;
size_t buflen = 0;
int skip = 0;
- int capcol = -1;
+ colnr_T capcol = -1;
bool found_one = false;
bool wrapped = false;
@@ -1228,6 +1247,8 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
return 0;
}
+ size_t ret = 0;
+
// Start looking for bad word at the start of the line, because we can't
// start halfway through a word, we don't know where it starts or ends.
//
@@ -1240,8 +1261,21 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
linenr_T lnum = wp->w_cursor.lnum;
clearpos(&found_pos);
+ char *decor_error = NULL;
+ // Ephemeral extmarks are currently stored in the global decor_state.
+ // When looking for spell errors, we need to:
+ // - temporarily reset decor_state
+ // - run the _on_spell_nav decor callback for each line we look at
+ // - detect if any spell marks are present
+ // - restore decor_state to the value saved here.
+ // TODO(lewis6991): un-globalize decor_state and allow ephemeral marks to be stored into a
+ // temporary DecorState.
+ DecorState saved_decor_start = decor_state;
+ linenr_T decor_lnum = -1;
+ decor_spell_nav_start(wp);
+
while (!got_int) {
- char_u *line = ml_get_buf(wp->w_buffer, lnum, false);
+ char_u *line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
len = STRLEN(line);
if (buflen < len + MAXWLEN + 2) {
@@ -1258,17 +1292,17 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
// For checking first word with a capital skip white space.
if (capcol == 0) {
- capcol = (int)getwhitecols((char *)line);
+ capcol = (colnr_T)getwhitecols((char *)line);
} else if (curline && wp == curwin) {
// For spellbadword(): check if first word needs a capital.
- col = (int)getwhitecols((char *)line);
+ col = (colnr_T)getwhitecols((char *)line);
if (check_need_cap(lnum, col)) {
capcol = col;
}
// Need to get the line again, may have looked at the previous
// one.
- line = ml_get_buf(wp->w_buffer, lnum, false);
+ line = (char_u *)ml_get_buf(wp->w_buffer, lnum, false);
}
// Copy the line into "buf" and append the start of the next line if
@@ -1278,7 +1312,7 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
STRCPY(buf, line);
if (lnum < wp->w_buffer->b_ml.ml_line_count) {
spell_cat_line(buf + STRLEN(buf),
- ml_get_buf(wp->w_buffer, lnum + 1, false),
+ (char_u *)ml_get_buf(wp->w_buffer, lnum + 1, false),
MAXWLEN);
}
char_u *p = buf + skip;
@@ -1308,33 +1342,37 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
|| ((colnr_T)(curline
? p - buf + (ptrdiff_t)len
: p - buf) > wp->w_cursor.col)) {
- bool can_spell;
- if (has_syntax) {
- col = (int)(p - buf);
- (void)syn_get_id(wp, lnum, (colnr_T)col,
- false, &can_spell, false);
- if (!can_spell) {
- attr = HLF_COUNT;
- }
- } else {
- can_spell = true;
+ col = (colnr_T)(p - buf);
+
+ bool can_spell = (wp->w_s->b_p_spo_flags & SPO_NPBUFFER) == 0;
+
+ if (!can_spell) {
+ can_spell = decor_spell_nav_col(wp, lnum, &decor_lnum, col, &decor_error);
+ }
+
+ if (!can_spell && has_syntax) {
+ (void)syn_get_id(wp, lnum, col, false, &can_spell, false);
+ }
+
+ if (!can_spell) {
+ attr = HLF_COUNT;
}
if (can_spell) {
found_one = true;
found_pos = (pos_T) {
.lnum = lnum,
- .col = (int)(p - buf),
+ .col = col,
.coladd = 0
};
if (dir == FORWARD) {
// No need to search further.
wp->w_cursor = found_pos;
- xfree(buf);
if (attrp != NULL) {
*attrp = attr;
}
- return len;
+ ret = len;
+ goto theend;
} else if (curline) {
// Insert mode completion: put cursor after
// the bad word.
@@ -1358,8 +1396,8 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
if (dir == BACKWARD && found_pos.lnum != 0) {
// Use the last match in the line (before the cursor).
wp->w_cursor = found_pos;
- xfree(buf);
- return found_len;
+ ret = found_len;
+ goto theend;
}
if (curline) {
@@ -1429,8 +1467,12 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
line_breakcheck();
}
+theend:
+ decor_state_free(&decor_state);
+ xfree(decor_error);
+ decor_state = saved_decor_start;
xfree(buf);
- return 0;
+ return ret;
}
// For spell checking: concatenate the start of the following line "line" into
@@ -1517,7 +1559,7 @@ static void spell_load_lang(char_u *lang)
// use "latin1" for "latin9". And limit to 60 characters (just in case).
char_u *spell_enc(void)
{
- if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0) {
+ if (STRLEN(p_enc) < 60 && strcmp(p_enc, "iso-8859-15") != 0) {
return (char_u *)p_enc;
}
return (char_u *)"latin1";
@@ -1531,15 +1573,15 @@ static void int_wordlist_spl(char_u *fname)
int_wordlist, spell_enc());
}
-// Allocate a new slang_T for language "lang". "lang" can be NULL.
-// Caller must fill "sl_next".
-slang_T *slang_alloc(char_u *lang)
+/// Allocate a new slang_T for language "lang". "lang" can be NULL.
+/// Caller must fill "sl_next".
+slang_T *slang_alloc(char *lang)
FUNC_ATTR_NONNULL_RET
{
slang_T *lp = xcalloc(1, sizeof(slang_T));
if (lang != NULL) {
- lp->sl_name = vim_strsave(lang);
+ lp->sl_name = xstrdup(lang);
}
ga_init(&lp->sl_rep, sizeof(fromto_T), 10);
ga_init(&lp->sl_repsal, sizeof(fromto_T), 10);
@@ -1651,7 +1693,7 @@ void slang_clear_sug(slang_T *lp)
static void spell_load_cb(char *fname, void *cookie)
{
spelload_T *slp = (spelload_T *)cookie;
- slang_T *slang = spell_load_file((char_u *)fname, slp->sl_lang, NULL, false);
+ slang_T *slang = spell_load_file(fname, (char *)slp->sl_lang, NULL, false);
if (slang != NULL) {
// When a previously loaded file has NOBREAK also use it for the
// ".add" files.
@@ -1801,25 +1843,25 @@ char *did_set_spelllang(win_T *wp)
{
garray_T ga;
char *splp;
- char_u *region;
- char_u region_cp[3];
+ char *region;
+ char region_cp[3];
bool filename;
int region_mask;
slang_T *slang;
int c;
- char_u lang[MAXWLEN + 1];
- char_u spf_name[MAXPATHL];
+ char lang[MAXWLEN + 1];
+ char spf_name[MAXPATHL];
int len;
- char_u *p;
+ char *p;
int round;
char *spf;
- char_u *use_region = NULL;
+ char *use_region = NULL;
bool dont_use_region = false;
bool nobreak = false;
langp_T *lp, *lp2;
static bool recursive = false;
char *ret_msg = NULL;
- char_u *spl_copy;
+ char *spl_copy;
bufref_T bufref;
set_bufref(&bufref, wp->w_buffer);
@@ -1837,12 +1879,12 @@ char *did_set_spelllang(win_T *wp)
// Make a copy of 'spelllang', the SpellFileMissing autocommands may change
// it under our fingers.
- spl_copy = vim_strsave((char_u *)wp->w_s->b_p_spl);
+ spl_copy = xstrdup(wp->w_s->b_p_spl);
wp->w_s->b_cjk = 0;
// Loop over comma separated language names.
- for (splp = (char *)spl_copy; *splp != NUL;) {
+ for (splp = spl_copy; *splp != NUL;) {
// Get one language name.
copy_option_part(&splp, (char *)lang, MAXWLEN, ",");
region = NULL;
@@ -1852,7 +1894,7 @@ char *did_set_spelllang(win_T *wp)
continue;
}
- if (STRCMP(lang, "cjk") == 0) {
+ if (strcmp(lang, "cjk") == 0) {
wp->w_s->b_cjk = 1;
continue;
}
@@ -1860,11 +1902,11 @@ char *did_set_spelllang(win_T *wp)
// If the name ends in ".spl" use it as the name of the spell file.
// If there is a region name let "region" point to it and remove it
// from the name.
- if (len > 4 && FNAMECMP(lang + len - 4, ".spl") == 0) {
+ if (len > 4 && path_fnamecmp(lang + len - 4, ".spl") == 0) {
filename = true;
// Locate a region and remove it from the file name.
- p = (char_u *)vim_strchr(path_tail((char *)lang), '_');
+ p = vim_strchr(path_tail((char *)lang), '_');
if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2])
&& !ASCII_ISALPHA(p[3])) {
STRLCPY(region_cp, p + 1, 3);
@@ -1901,7 +1943,7 @@ char *did_set_spelllang(win_T *wp)
if (region != NULL) {
// If the region differs from what was used before then don't
// use it for 'spellfile'.
- if (use_region != NULL && STRCMP(region, use_region) != 0) {
+ if (use_region != NULL && strcmp(region, use_region) != 0) {
dont_use_region = true;
}
use_region = region;
@@ -1910,9 +1952,9 @@ char *did_set_spelllang(win_T *wp)
// If not found try loading the language now.
if (slang == NULL) {
if (filename) {
- (void)spell_load_file(lang, lang, NULL, false);
+ (void)spell_load_file((char *)lang, (char *)lang, NULL, false);
} else {
- spell_load_lang(lang);
+ spell_load_lang((char_u *)lang);
// SpellFileMissing autocommands may do anything, including
// destroying the buffer we are using...
if (!bufref_valid(&bufref)) {
@@ -1930,7 +1972,7 @@ char *did_set_spelllang(win_T *wp)
region_mask = REGION_ALL;
if (!filename && region != NULL) {
// find region in sl_regions
- c = find_region(slang->sl_regions, region);
+ c = find_region(slang->sl_regions, (char_u *)region);
if (c == REGION_ALL) {
if (slang->sl_add) {
if (*slang->sl_regions != NUL) {
@@ -1973,7 +2015,7 @@ char *did_set_spelllang(win_T *wp)
if (int_wordlist == NULL) {
continue;
}
- int_wordlist_spl(spf_name);
+ int_wordlist_spl((char_u *)spf_name);
} else {
// One entry in 'spellfile'.
copy_option_part(&spf, (char *)spf_name, MAXPATHL - 5, ",");
@@ -1981,9 +2023,9 @@ char *did_set_spelllang(win_T *wp)
// If it was already found above then skip it.
for (c = 0; c < ga.ga_len; c++) {
- p = (char_u *)LANGP_ENTRY(ga, c)->lp_slang->sl_fname;
+ p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname;
if (p != NULL
- && path_full_compare((char *)spf_name, (char *)p, false, true) == kEqualFiles) {
+ && path_full_compare((char *)spf_name, p, false, true) == kEqualFiles) {
break;
}
}
@@ -2007,12 +2049,12 @@ char *did_set_spelllang(win_T *wp)
STRCPY(lang, "internal wordlist");
} else {
STRLCPY(lang, path_tail((char *)spf_name), MAXWLEN + 1);
- p = (char_u *)vim_strchr((char *)lang, '.');
+ p = vim_strchr((char *)lang, '.');
if (p != NULL) {
*p = NUL; // truncate at ".encoding.add"
}
}
- slang = spell_load_file(spf_name, lang, NULL, true);
+ slang = spell_load_file((char *)spf_name, (char *)lang, NULL, true);
// If one of the languages has NOBREAK we assume the addition
// files also have this.
@@ -2024,7 +2066,7 @@ char *did_set_spelllang(win_T *wp)
region_mask = REGION_ALL;
if (use_region != NULL && !dont_use_region) {
// find region in sl_regions
- c = find_region(slang->sl_regions, use_region);
+ c = find_region(slang->sl_regions, (char_u *)use_region);
if (c != REGION_ALL) {
region_mask = 1 << c;
} else if (*slang->sl_regions != NUL) {
@@ -2104,8 +2146,8 @@ static void clear_midword(win_T *wp)
XFREE_CLEAR(wp->w_s->b_spell_ismw_mb);
}
-// Use the "sl_midword" field of language "lp" for buffer "buf".
-// They add up to any currently used midword characters.
+/// Use the "sl_midword" field of language "lp" for buffer "buf".
+/// They add up to any currently used midword characters.
static void use_midword(slang_T *lp, win_T *wp)
FUNC_ATTR_NONNULL_ALL
{
@@ -2113,20 +2155,20 @@ static void use_midword(slang_T *lp, win_T *wp)
return;
}
- for (char_u *p = lp->sl_midword; *p != NUL;) {
- const int c = utf_ptr2char((char *)p);
- const int l = utfc_ptr2len((char *)p);
+ for (char *p = (char *)lp->sl_midword; *p != NUL;) {
+ const int c = utf_ptr2char(p);
+ const int l = utfc_ptr2len(p);
if (c < 256 && l <= 2) {
wp->w_s->b_spell_ismw[c] = true;
} else if (wp->w_s->b_spell_ismw_mb == NULL) {
// First multi-byte char in "b_spell_ismw_mb".
- wp->w_s->b_spell_ismw_mb = (char *)vim_strnsave(p, (size_t)l);
+ wp->w_s->b_spell_ismw_mb = xstrnsave(p, (size_t)l);
} else {
// Append multi-byte chars to "b_spell_ismw_mb".
const int n = (int)STRLEN(wp->w_s->b_spell_ismw_mb);
- char_u *bp = vim_strnsave((char_u *)wp->w_s->b_spell_ismw_mb, (size_t)n + (size_t)l);
+ char *bp = xstrnsave(wp->w_s->b_spell_ismw_mb, (size_t)n + (size_t)l);
xfree(wp->w_s->b_spell_ismw_mb);
- wp->w_s->b_spell_ismw_mb = (char *)bp;
+ wp->w_s->b_spell_ismw_mb = bp;
STRLCPY(bp + n, p, l + 1);
}
p += l;
@@ -2470,7 +2512,7 @@ bool check_need_cap(linenr_T lnum, colnr_T col)
return false;
}
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
char_u *line_copy = NULL;
colnr_T endcol = 0;
if (getwhitecols((char *)line) >= (int)col) {
@@ -2506,7 +2548,7 @@ bool check_need_cap(linenr_T lnum, colnr_T col)
break;
}
if (vim_regexec(&regmatch, (char *)p, 0)
- && regmatch.endp[0] == line + endcol) {
+ && (char_u *)regmatch.endp[0] == line + endcol) {
need_cap = true;
break;
}
@@ -2548,7 +2590,7 @@ void ex_spellrepall(exarg_T *eap)
// Only replace when the right word isn't there yet. This happens
// when changing "etc" to "etc.".
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col,
repl_to, STRLEN(repl_to)) != 0) {
char_u *p = xmalloc(STRLEN(line) + (size_t)addlen + 1);
@@ -3129,23 +3171,23 @@ void ex_spelldump(exarg_T *eap)
/// @param ic ignore case
/// @param dir direction for adding matches
/// @param dumpflags_arg DUMPFLAG_*
-void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
+void spell_dump_compl(char *pat, int ic, Direction *dir, int dumpflags_arg)
{
langp_T *lp;
slang_T *slang;
idx_T arridx[MAXWLEN];
int curi[MAXWLEN];
- char_u word[MAXWLEN];
+ char word[MAXWLEN];
int c;
- char_u *byts;
+ char *byts;
idx_T *idxs;
linenr_T lnum = 0;
int depth;
int n;
int flags;
- char_u *region_names = NULL; // region names being used
+ char *region_names = NULL; // region names being used
bool do_region = true; // dump region names and numbers
- char_u *p;
+ char *p;
int dumpflags = dumpflags_arg;
int patlen;
@@ -3155,11 +3197,11 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
if (ic) {
dumpflags |= DUMPFLAG_ICASE;
} else {
- n = captype(pat, NULL);
+ n = captype((char_u *)pat, NULL);
if (n == WF_ONECAP) {
dumpflags |= DUMPFLAG_ONECAP;
} else if (n == WF_ALLCAP
- && (int)STRLEN(pat) > utfc_ptr2len((char *)pat)) {
+ && (int)STRLEN(pat) > utfc_ptr2len(pat)) {
dumpflags |= DUMPFLAG_ALLCAP;
}
}
@@ -3169,11 +3211,11 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
// regions or none at all.
for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
- p = lp->lp_slang->sl_regions;
+ p = (char *)lp->lp_slang->sl_regions;
if (p[0] != 0) {
if (region_names == NULL) { // first language with regions
region_names = p;
- } else if (STRCMP(region_names, p) != 0) {
+ } else if (strcmp(region_names, p) != 0) {
do_region = false; // region names are different
break;
}
@@ -3215,11 +3257,11 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
for (int round = 1; round <= 2; round++) {
if (round == 1) {
dumpflags &= ~DUMPFLAG_KEEPCASE;
- byts = slang->sl_fbyts;
+ byts = (char *)slang->sl_fbyts;
idxs = slang->sl_fidxs;
} else {
dumpflags |= DUMPFLAG_KEEPCASE;
- byts = slang->sl_kbyts;
+ byts = (char *)slang->sl_kbyts;
idxs = slang->sl_kidxs;
}
if (byts == NULL) {
@@ -3239,7 +3281,7 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
// Do one more byte at this node.
n = arridx[depth] + curi[depth];
curi[depth]++;
- c = byts[n];
+ c = (uint8_t)byts[n];
if (c == 0 || depth >= MAXWLEN - 1) {
// End of word or reached maximum length, deal with the
// word.
@@ -3262,7 +3304,7 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
// when it's the first one.
c = (int)((unsigned)flags >> 24);
if (c == 0 || curi[depth] == 2) {
- dump_word(slang, word, pat, dir,
+ dump_word(slang, (char_u *)word, (char_u *)pat, dir,
dumpflags, flags, lnum);
if (pat == NULL) {
lnum++;
@@ -3271,13 +3313,13 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
// Apply the prefix, if there is one.
if (c != 0) {
- lnum = dump_prefixes(slang, word, pat, dir,
+ lnum = dump_prefixes(slang, (char_u *)word, (char_u *)pat, dir,
dumpflags, flags, lnum);
}
}
} else {
// Normal char, go one level deeper.
- word[depth++] = (char_u)c;
+ word[depth++] = (char)c;
arridx[depth] = idxs[n];
curi[depth] = 1;
@@ -3289,7 +3331,7 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
// ignore case...
assert(depth >= 0);
if (depth <= patlen
- && mb_strnicmp((char *)word, (char *)pat, (size_t)depth) != 0) {
+ && mb_strnicmp((char *)word, pat, (size_t)depth) != 0) {
depth--;
}
}
@@ -3365,7 +3407,7 @@ static void dump_word(slang_T *slang, char_u *word, char_u *pat, Direction *dir,
if (!HASHITEM_EMPTY(hi)) {
vim_snprintf((char *)IObuff, IOSIZE, "%s\t%d",
tw, HI2WC(hi)->wc_count);
- p = IObuff;
+ p = (char_u *)IObuff;
}
}
@@ -3497,7 +3539,7 @@ int spell_word_start(int startcol)
return startcol;
}
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
char_u *p;
// Find a word character before "startcol".
@@ -3571,7 +3613,7 @@ char *did_set_spell_option(bool is_spellfile)
if (is_spellfile) {
int l = (int)STRLEN(curwin->w_s->b_p_spf);
if (l > 0
- && (l < 4 || STRCMP(curwin->w_s->b_p_spf + l - 4, ".add") != 0)) {
+ && (l < 4 || strcmp(curwin->w_s->b_p_spf + l - 4, ".add") != 0)) {
errmsg = e_invarg;
}
}
diff --git a/src/nvim/spell_defs.h b/src/nvim/spell_defs.h
index 27b9777dc2..2c4aebe420 100644
--- a/src/nvim/spell_defs.h
+++ b/src/nvim/spell_defs.h
@@ -115,7 +115,7 @@ typedef struct slang_S slang_T;
struct slang_S {
slang_T *sl_next; // next language
- char_u *sl_name; // language name "en", "en.rare", "nl", etc.
+ char *sl_name; // language name "en", "en.rare", "nl", etc.
char *sl_fname; // name of .spl file
bool sl_add; // true if it's a .add file.
@@ -252,7 +252,7 @@ typedef struct wordcount_S {
#define MAXWORDCOUNT 0xffff
// Remember what "z?" replaced.
-extern char_u *repl_from;
-extern char_u *repl_to;
+extern char *repl_from;
+extern char *repl_to;
#endif // NVIM_SPELL_DEFS_H
diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c
index c472cac27d..7da5a7ca4f 100644
--- a/src/nvim/spellfile.c
+++ b/src/nvim/spellfile.c
@@ -355,12 +355,12 @@ struct affentry_S {
// Affix header from ".aff" file. Used for af_pref and af_suff.
typedef struct affheader_S {
- char_u ah_key[AH_KEY_LEN]; // key for hashtab == name of affix
+ char ah_key[AH_KEY_LEN]; // key for hashtab == name of affix
unsigned ah_flag; // affix name as number, uses "af_flagtype"
int ah_newID; // prefix ID after renumbering; 0 if not used
int ah_combine; // suffix may combine with prefix
int ah_follows; // another affix block should be following
- affentry_T *ah_first; // first affix entry
+ affentry_T *ah_first; // first affix entry
} affheader_T;
#define HI2AH(hi) ((affheader_T *)(hi)->hi_key)
@@ -572,10 +572,10 @@ static inline int spell_check_magic_string(FILE *const fd)
/// @param silent no error if file doesn't exist
///
/// @return the slang_T the spell file was loaded into. NULL for error.
-slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool silent)
+slang_T *spell_load_file(char *fname, char *lang, slang_T *old_lp, bool silent)
{
FILE *fd;
- char_u *p;
+ char *p;
int n;
int len;
slang_T *lp = NULL;
@@ -583,7 +583,7 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile
int res;
bool did_estack_push = false;
- fd = os_fopen((char *)fname, "r");
+ fd = os_fopen(fname, "r");
if (fd == NULL) {
if (!silent) {
semsg(_(e_notopen), fname);
@@ -604,16 +604,16 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile
lp = slang_alloc(lang);
// Remember the file name, used to reload the file when it's updated.
- lp->sl_fname = (char *)vim_strsave(fname);
+ lp->sl_fname = xstrdup(fname);
// Check for .add.spl.
- lp->sl_add = strstr(path_tail((char *)fname), SPL_FNAME_ADD) != NULL;
+ lp->sl_add = strstr(path_tail(fname), SPL_FNAME_ADD) != NULL;
} else {
lp = old_lp;
}
// Set sourcing_name, so that error messages mention the file name.
- estack_push(ETYPE_SPELL, (char *)fname, 0);
+ estack_push(ETYPE_SPELL, fname, 0);
did_estack_push = true;
// <HEADER>: <fileID>
@@ -697,11 +697,11 @@ slang_T *spell_load_file(char_u *fname, char_u *lang, slang_T *old_lp, bool sile
break;
case SN_MAP:
- p = READ_STRING(fd, len); // <mapstr>
+ p = (char *)READ_STRING(fd, len); // <mapstr>
if (p == NULL) {
goto endFAIL;
}
- set_map_str(lp, p);
+ set_map_str(lp, (char_u *)p);
xfree(p);
break;
@@ -895,7 +895,7 @@ void suggest_load_files(void)
slang->sl_sugloaded = true;
dotp = strrchr(slang->sl_fname, '.');
- if (dotp == NULL || FNAMECMP(dotp, ".spl") != 0) {
+ if (dotp == NULL || path_fnamecmp(dotp, ".spl") != 0) {
continue;
}
STRCPY(dotp, ".sug");
@@ -1824,7 +1824,7 @@ static void spell_reload_one(char_u *fname, bool added_word)
for (slang = first_lang; slang != NULL; slang = slang->sl_next) {
if (path_full_compare((char *)fname, slang->sl_fname, false, true) == kEqualFiles) {
slang_clear(slang);
- if (spell_load_file(fname, NULL, slang, false) == NULL) {
+ if (spell_load_file((char *)fname, NULL, slang, false) == NULL) {
// reloading failed, clear the language
slang_clear(slang);
}
@@ -1994,7 +1994,7 @@ static void spell_print_tree(wordnode_T *root)
}
}
-#endif // SPELL_PRINTTREE
+#endif // SPELL_PRINTTREE
// Reads the affix file "fname".
// Returns an afffile_T, NULL for complete failure.
@@ -2005,17 +2005,17 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
char_u *line;
char_u *pc = NULL;
#define MAXITEMCNT 30
- char_u *(items[MAXITEMCNT]);
+ char *(items[MAXITEMCNT]);
int itemcnt;
- char_u *p;
+ char *p;
int lnum = 0;
affheader_T *cur_aff = NULL;
bool did_postpone_prefix = false;
int aff_todo = 0;
hashtab_T *tp;
- char_u *low = NULL;
- char_u *fol = NULL;
- char_u *upp = NULL;
+ char *low = NULL;
+ char *fol = NULL;
+ char *upp = NULL;
int do_rep;
int do_repsal;
int do_sal;
@@ -2090,8 +2090,8 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
// Split the line up in white separated items. Put a NUL after each
// item.
itemcnt = 0;
- for (p = line;;) {
- while (*p != NUL && *p <= ' ') { // skip white space and CR/NL
+ for (p = (char *)line;;) {
+ while (*p != NUL && (uint8_t)(*p) <= ' ') { // skip white space and CR/NL
p++;
}
if (*p == NUL) {
@@ -2103,11 +2103,11 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
items[itemcnt++] = p;
// A few items have arbitrary text argument, don't split them.
if (itemcnt == 2 && spell_info_item(items[0])) {
- while (*p >= ' ' || *p == TAB) { // skip until CR/NL
+ while ((uint8_t)(*p) >= ' ' || *p == TAB) { // skip until CR/NL
p++;
}
} else {
- while (*p > ' ') { // skip until white space or CR/NL
+ while ((uint8_t)(*p) > ' ') { // skip until white space or CR/NL
p++;
}
}
@@ -2130,11 +2130,11 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
spin->si_conv.vc_fail = true;
} else if (is_aff_rule(items, itemcnt, "FLAG", 2)
&& aff->af_flagtype == AFT_CHAR) {
- if (STRCMP(items[1], "long") == 0) {
+ if (strcmp(items[1], "long") == 0) {
aff->af_flagtype = AFT_LONG;
- } else if (STRCMP(items[1], "num") == 0) {
+ } else if (strcmp(items[1], "num") == 0) {
aff->af_flagtype = AFT_NUM;
- } else if (STRCMP(items[1], "caplong") == 0) {
+ } else if (strcmp(items[1], "caplong") == 0) {
aff->af_flagtype = AFT_CAPLONG;
} else {
smsg(_("Invalid value for FLAG in %s line %d: %s"),
@@ -2166,9 +2166,9 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
STRCAT(p, items[0]);
STRCAT(p, " ");
STRCAT(p, items[1]);
- spin->si_info = p;
+ spin->si_info = (char_u *)p;
} else if (is_aff_rule(items, itemcnt, "MIDWORD", 2) && midword == NULL) {
- midword = (char_u *)getroom_save(spin, items[1]);
+ midword = (char_u *)getroom_save(spin, (char_u *)items[1]);
} else if (is_aff_rule(items, itemcnt, "TRY", 2)) {
// ignored, we look in the tree for what chars may appear
}
@@ -2176,44 +2176,44 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
else if ((is_aff_rule(items, itemcnt, "RAR", 2)
|| is_aff_rule(items, itemcnt, "RARE", 2))
&& aff->af_rare == 0) {
- aff->af_rare = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_rare = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
}
// TODO: remove "KEP" later
else if ((is_aff_rule(items, itemcnt, "KEP", 2)
|| is_aff_rule(items, itemcnt, "KEEPCASE", 2))
&& aff->af_keepcase == 0) {
- aff->af_keepcase = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_keepcase = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if ((is_aff_rule(items, itemcnt, "BAD", 2)
|| is_aff_rule(items, itemcnt, "FORBIDDENWORD", 2))
&& aff->af_bad == 0) {
- aff->af_bad = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_bad = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if (is_aff_rule(items, itemcnt, "NEEDAFFIX", 2)
&& aff->af_needaffix == 0) {
- aff->af_needaffix = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_needaffix = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if (is_aff_rule(items, itemcnt, "CIRCUMFIX", 2)
&& aff->af_circumfix == 0) {
- aff->af_circumfix = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_circumfix = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if (is_aff_rule(items, itemcnt, "NOSUGGEST", 2)
&& aff->af_nosuggest == 0) {
- aff->af_nosuggest = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_nosuggest = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if ((is_aff_rule(items, itemcnt, "NEEDCOMPOUND", 2)
|| is_aff_rule(items, itemcnt, "ONLYINCOMPOUND", 2))
&& aff->af_needcomp == 0) {
- aff->af_needcomp = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_needcomp = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if (is_aff_rule(items, itemcnt, "COMPOUNDROOT", 2)
&& aff->af_comproot == 0) {
- aff->af_comproot = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_comproot = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
} else if (is_aff_rule(items, itemcnt, "COMPOUNDFORBIDFLAG", 2)
&& aff->af_compforbid == 0) {
- aff->af_compforbid = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_compforbid = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
if (aff->af_pref.ht_used > 0) {
smsg(_("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d"),
@@ -2221,7 +2221,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
}
} else if (is_aff_rule(items, itemcnt, "COMPOUNDPERMITFLAG", 2)
&& aff->af_comppermit == 0) {
- aff->af_comppermit = affitem2flag(aff->af_flagtype, items[1],
+ aff->af_comppermit = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
if (aff->af_pref.ht_used > 0) {
smsg(_("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d"),
@@ -2234,7 +2234,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
p = getroom(spin, STRLEN(items[1]) + 2, false);
STRCPY(p, items[1]);
STRCAT(p, "+");
- compflags = p;
+ compflags = (char_u *)p;
} else if (is_aff_rule(items, itemcnt, "COMPOUNDRULES", 2)) {
// We don't use the count, but do check that it's a number and
// not COMPOUNDRULE mistyped.
@@ -2257,7 +2257,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
STRCAT(p, "/");
}
STRCAT(p, items[1]);
- compflags = p;
+ compflags = (char_u *)p;
}
} else if (is_aff_rule(items, itemcnt, "COMPOUNDWORDMAX", 2)
&& compmax == 0) {
@@ -2299,19 +2299,19 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
// Only add the couple if it isn't already there.
for (i = 0; i < gap->ga_len - 1; i += 2) {
- if (STRCMP(((char **)(gap->ga_data))[i], items[1]) == 0
- && STRCMP(((char **)(gap->ga_data))[i + 1], items[2]) == 0) {
+ if (strcmp(((char **)(gap->ga_data))[i], items[1]) == 0
+ && strcmp(((char **)(gap->ga_data))[i + 1], items[2]) == 0) {
break;
}
}
if (i >= gap->ga_len) {
ga_grow(gap, 2);
- ((char **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, items[1]);
- ((char **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, items[2]);
+ ((char **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, (char_u *)items[1]);
+ ((char **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, (char_u *)items[2]);
}
} else if (is_aff_rule(items, itemcnt, "SYLLABLE", 2)
&& syllable == NULL) {
- syllable = (char_u *)getroom_save(spin, items[1]);
+ syllable = (char_u *)getroom_save(spin, (char_u *)items[1]);
} else if (is_aff_rule(items, itemcnt, "NOBREAK", 1)) {
spin->si_nobreak = true;
} else if (is_aff_rule(items, itemcnt, "NOSPLITSUGS", 1)) {
@@ -2324,8 +2324,8 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
aff->af_pfxpostpone = true;
} else if (is_aff_rule(items, itemcnt, "IGNOREEXTRA", 1)) {
aff->af_ignoreextra = true;
- } else if ((STRCMP(items[0], "PFX") == 0
- || STRCMP(items[0], "SFX") == 0)
+ } else if ((strcmp(items[0], "PFX") == 0
+ || strcmp(items[0], "SFX") == 0)
&& aff_todo == 0
&& itemcnt >= 4) {
int lasti = 4;
@@ -2356,7 +2356,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
} else {
// New affix letter.
cur_aff = getroom(spin, sizeof(*cur_aff), true);
- cur_aff->ah_flag = affitem2flag(aff->af_flagtype, items[1],
+ cur_aff->ah_flag = affitem2flag(aff->af_flagtype, (char_u *)items[1],
fname, lnum);
if (cur_aff->ah_flag == 0 || STRLEN(items[1]) >= AH_KEY_LEN) {
break;
@@ -2375,14 +2375,14 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
fname, lnum, items[1]);
}
STRCPY(cur_aff->ah_key, items[1]);
- hash_add(tp, cur_aff->ah_key);
+ hash_add(tp, (char_u *)cur_aff->ah_key);
cur_aff->ah_combine = (*items[2] == 'Y');
}
// Check for the "S" flag, which apparently means that another
// block with the same affix name is following.
- if (itemcnt > lasti && STRCMP(items[lasti], "S") == 0) {
+ if (itemcnt > lasti && strcmp(items[lasti], "S") == 0) {
lasti++;
cur_aff->ah_follows = true;
} else {
@@ -2398,7 +2398,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
smsg(_(e_afftrailing), fname, lnum, items[lasti]);
}
- if (STRCMP(items[2], "Y") != 0 && STRCMP(items[2], "N") != 0) {
+ if (strcmp(items[2], "Y") != 0 && strcmp(items[2], "N") != 0) {
smsg(_("Expected Y or N in %s line %d: %s"),
fname, lnum, items[2]);
}
@@ -2421,10 +2421,10 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
}
aff_todo = atoi((char *)items[3]);
- } else if ((STRCMP(items[0], "PFX") == 0
- || STRCMP(items[0], "SFX") == 0)
+ } else if ((strcmp(items[0], "PFX") == 0
+ || strcmp(items[0], "SFX") == 0)
&& aff_todo > 0
- && STRCMP(cur_aff->ah_key, items[1]) == 0
+ && strcmp(cur_aff->ah_key, items[1]) == 0
&& itemcnt >= 5) {
affentry_T *aff_entry;
bool upper = false;
@@ -2434,7 +2434,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
// mean mistakes go unnoticed. Require a comment-starter.
// Hunspell uses a "-" item.
if (itemcnt > lasti && *items[lasti] != '#'
- && (STRCMP(items[lasti], "-") != 0
+ && (strcmp(items[lasti], "-") != 0
|| itemcnt != lasti + 1)) {
smsg(_(e_afftrailing), fname, lnum, items[lasti]);
}
@@ -2443,11 +2443,11 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
aff_todo--;
aff_entry = getroom(spin, sizeof(*aff_entry), true);
- if (STRCMP(items[2], "0") != 0) {
- aff_entry->ae_chop = (char_u *)getroom_save(spin, items[2]);
+ if (strcmp(items[2], "0") != 0) {
+ aff_entry->ae_chop = (char_u *)getroom_save(spin, (char_u *)items[2]);
}
- if (STRCMP(items[3], "0") != 0) {
- aff_entry->ae_add = (char_u *)getroom_save(spin, items[3]);
+ if (strcmp(items[3], "0") != 0) {
+ aff_entry->ae_add = (char_u *)getroom_save(spin, (char_u *)items[3]);
// Recognize flags on the affix: abcd/XYZ
aff_entry->ae_flags = (char_u *)vim_strchr((char *)aff_entry->ae_add, '/');
@@ -2464,10 +2464,10 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
aff_entry->ae_next = cur_aff->ah_first;
cur_aff->ah_first = aff_entry;
- if (STRCMP(items[4], ".") != 0) {
+ if (strcmp(items[4], ".") != 0) {
char_u buf[MAXLINELEN];
- aff_entry->ae_cond = (char_u *)getroom_save(spin, items[4]);
+ aff_entry->ae_cond = (char_u *)getroom_save(spin, (char_u *)items[4]);
if (*items[0] == 'P') {
sprintf((char *)buf, "^%s", items[4]);
} else {
@@ -2502,10 +2502,10 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
if (c_up != c
&& (aff_entry->ae_cond == NULL
|| utf_ptr2char((char *)aff_entry->ae_cond) == c)) {
- p = aff_entry->ae_add
+ p = (char *)aff_entry->ae_add
+ STRLEN(aff_entry->ae_add);
MB_PTR_BACK(aff_entry->ae_add, p);
- if (utf_ptr2char((char *)p) == c_up) {
+ if (utf_ptr2char(p) == c_up) {
upper = true;
aff_entry->ae_chop = NULL;
*p = NUL;
@@ -2515,7 +2515,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
// upper-case letter.
if (aff_entry->ae_cond != NULL) {
char_u buf[MAXLINELEN];
- onecap_copy(items[4], buf, true);
+ onecap_copy((char_u *)items[4], buf, true);
aff_entry->ae_cond = (char_u *)getroom_save(spin, buf);
if (aff_entry->ae_cond != NULL) {
sprintf((char *)buf, "^%s",
@@ -2534,10 +2534,9 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
int n;
// Find a previously used condition.
- for (idx = spin->si_prefcond.ga_len - 1; idx >= 0;
- --idx) {
- p = ((char_u **)spin->si_prefcond.ga_data)[idx];
- if (str_equal(p, aff_entry->ae_cond)) {
+ for (idx = spin->si_prefcond.ga_len - 1; idx >= 0; idx--) {
+ p = ((char **)spin->si_prefcond.ga_data)[idx];
+ if (str_equal(p, (char *)aff_entry->ae_cond)) {
break;
}
}
@@ -2551,9 +2550,9 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
// Add the prefix to the prefix tree.
if (aff_entry->ae_add == NULL) {
- p = (char_u *)"";
+ p = "";
} else {
- p = aff_entry->ae_add;
+ p = (char *)aff_entry->ae_add;
}
// PFX_FLAGS is a negative number, so that
@@ -2571,7 +2570,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
if (aff_entry->ae_compforbid) {
n |= WFP_COMPFORBID;
}
- tree_add_word(spin, p, spin->si_prefroot, n,
+ tree_add_word(spin, (char_u *)p, spin->si_prefroot, n,
idx, cur_aff->ah_newID);
did_postpone_prefix = true;
}
@@ -2584,11 +2583,11 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
}
}
} else if (is_aff_rule(items, itemcnt, "FOL", 2) && fol == NULL) {
- fol = vim_strsave(items[1]);
+ fol = xstrdup(items[1]);
} else if (is_aff_rule(items, itemcnt, "LOW", 2) && low == NULL) {
- low = vim_strsave(items[1]);
+ low = xstrdup(items[1]);
} else if (is_aff_rule(items, itemcnt, "UPP", 2) && upp == NULL) {
- upp = vim_strsave(items[1]);
+ upp = xstrdup(items[1]);
} else if (is_aff_rule(items, itemcnt, "REP", 2)
|| is_aff_rule(items, itemcnt, "REPSAL", 2)) {
// Ignore REP/REPSAL count
@@ -2596,8 +2595,8 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
smsg(_("Expected REP(SAL) count in %s line %d"),
fname, lnum);
}
- } else if ((STRCMP(items[0], "REP") == 0
- || STRCMP(items[0], "REPSAL") == 0)
+ } else if ((strcmp(items[0], "REP") == 0
+ || strcmp(items[0], "REPSAL") == 0)
&& itemcnt >= 3) {
// REP/REPSAL item
// Myspell ignores extra arguments, we require it starts with
@@ -2619,8 +2618,8 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
}
}
add_fromto(spin, items[0][3] == 'S'
- ? &spin->si_repsal
- : &spin->si_rep, items[1], items[2]);
+ ? &spin->si_repsal
+ : &spin->si_rep, (char_u *)items[1], (char_u *)items[2]);
}
} else if (is_aff_rule(items, itemcnt, "MAP", 2)) {
// MAP item or count
@@ -2640,7 +2639,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
if ((!GA_EMPTY(&spin->si_map)
&& vim_strchr(spin->si_map.ga_data, c)
!= NULL)
- || vim_strchr((char *)p, c) != NULL) {
+ || vim_strchr(p, c) != NULL) {
smsg(_("Duplicate character in MAP in %s line %d"),
fname, lnum);
}
@@ -2657,32 +2656,32 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
if (do_sal) {
// SAL item (sounds-a-like)
// Either one of the known keys or a from-to pair.
- if (STRCMP(items[1], "followup") == 0) {
+ if (strcmp(items[1], "followup") == 0) {
spin->si_followup = sal_to_bool(items[2]);
- } else if (STRCMP(items[1], "collapse_result") == 0) {
+ } else if (strcmp(items[1], "collapse_result") == 0) {
spin->si_collapse = sal_to_bool(items[2]);
- } else if (STRCMP(items[1], "remove_accents") == 0) {
+ } else if (strcmp(items[1], "remove_accents") == 0) {
spin->si_rem_accents = sal_to_bool(items[2]);
} else {
// when "to" is "_" it means empty
- add_fromto(spin, &spin->si_sal, items[1],
- STRCMP(items[2], "_") == 0 ? (char_u *)""
- : items[2]);
+ add_fromto(spin, &spin->si_sal, (char_u *)items[1],
+ strcmp(items[2], "_") == 0 ? (char_u *)""
+ : (char_u *)items[2]);
}
}
} else if (is_aff_rule(items, itemcnt, "SOFOFROM", 2)
&& sofofrom == NULL) {
- sofofrom = (char_u *)getroom_save(spin, items[1]);
+ sofofrom = (char_u *)getroom_save(spin, (char_u *)items[1]);
} else if (is_aff_rule(items, itemcnt, "SOFOTO", 2)
&& sofoto == NULL) {
- sofoto = (char_u *)getroom_save(spin, items[1]);
- } else if (STRCMP(items[0], "COMMON") == 0) {
+ sofoto = (char_u *)getroom_save(spin, (char_u *)items[1]);
+ } else if (strcmp(items[0], "COMMON") == 0) {
int i;
for (i = 1; i < itemcnt; i++) {
if (HASHITEM_EMPTY(hash_find(&spin->si_commonwords, (char *)items[i]))) {
- p = vim_strsave(items[i]);
- hash_add(&spin->si_commonwords, p);
+ p = xstrdup(items[i]);
+ hash_add(&spin->si_commonwords, (char_u *)p);
}
}
} else {
@@ -2745,7 +2744,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
}
if (syllable != NULL) {
- aff_check_string(spin->si_syllable, syllable, "SYLLABLE");
+ aff_check_string((char *)spin->si_syllable, (char *)syllable, "SYLLABLE");
spin->si_syllable = syllable;
}
@@ -2756,15 +2755,15 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
} else if (!GA_EMPTY(&spin->si_sal)) {
smsg(_("Both SAL and SOFO lines in %s"), fname);
} else {
- aff_check_string(spin->si_sofofr, sofofrom, "SOFOFROM");
- aff_check_string(spin->si_sofoto, sofoto, "SOFOTO");
+ aff_check_string((char *)spin->si_sofofr, (char *)sofofrom, "SOFOFROM");
+ aff_check_string((char *)spin->si_sofoto, (char *)sofoto, "SOFOTO");
spin->si_sofofr = sofofrom;
spin->si_sofoto = sofoto;
}
}
if (midword != NULL) {
- aff_check_string(spin->si_midword, midword, "MIDWORD");
+ aff_check_string((char *)spin->si_midword, (char *)midword, "MIDWORD");
spin->si_midword = midword;
}
@@ -2773,11 +2772,11 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
return aff;
}
-// Returns true when items[0] equals "rulename", there are "mincount" items or
-// a comment is following after item "mincount".
-static bool is_aff_rule(char_u **items, int itemcnt, char *rulename, int mincount)
+/// @return true when items[0] equals "rulename", there are "mincount" items or
+/// a comment is following after item "mincount".
+static bool is_aff_rule(char **items, int itemcnt, char *rulename, int mincount)
{
- return STRCMP(items[0], rulename) == 0
+ return strcmp(items[0], rulename) == 0
&& (itemcnt == mincount
|| (itemcnt > mincount && items[mincount][0] == '#'));
}
@@ -2814,15 +2813,15 @@ static void aff_process_flags(afffile_T *affile, affentry_T *entry)
}
}
-// Returns true if "s" is the name of an info item in the affix file.
-static bool spell_info_item(char_u *s)
+/// @return true if "s" is the name of an info item in the affix file.
+static bool spell_info_item(char *s)
{
- return STRCMP(s, "NAME") == 0
- || STRCMP(s, "HOME") == 0
- || STRCMP(s, "VERSION") == 0
- || STRCMP(s, "AUTHOR") == 0
- || STRCMP(s, "EMAIL") == 0
- || STRCMP(s, "COPYRIGHT") == 0;
+ return strcmp(s, "NAME") == 0
+ || strcmp(s, "HOME") == 0
+ || strcmp(s, "VERSION") == 0
+ || strcmp(s, "AUTHOR") == 0
+ || strcmp(s, "EMAIL") == 0
+ || strcmp(s, "COPYRIGHT") == 0;
}
// Turn an affix flag name into a number, according to the FLAG type.
@@ -3014,23 +3013,23 @@ static void aff_check_number(int spinval, int affval, char *name)
}
}
-// Give a warning when "spinval" and "affval" strings are set and not the same.
-static void aff_check_string(char_u *spinval, char_u *affval, char *name)
+/// Give a warning when "spinval" and "affval" strings are set and not the same.
+static void aff_check_string(char *spinval, char *affval, char *name)
{
- if (spinval != NULL && STRCMP(spinval, affval) != 0) {
+ if (spinval != NULL && strcmp(spinval, affval) != 0) {
smsg(_("%s value differs from what is used in another .aff file"),
name);
}
}
-// Returns true if strings "s1" and "s2" are equal. Also consider both being
-// NULL as equal.
-static bool str_equal(char_u *s1, char_u *s2)
+/// @return true if strings "s1" and "s2" are equal. Also consider both being
+/// NULL as equal.
+static bool str_equal(char *s1, char *s2)
{
if (s1 == NULL || s2 == NULL) {
return s1 == s2;
}
- return STRCMP(s1, s2) == 0;
+ return strcmp(s1, s2) == 0;
}
// Add a from-to item to "gap". Used for REP and SAL items.
@@ -3046,10 +3045,10 @@ static void add_fromto(spellinfo_T *spin, garray_T *gap, char_u *from, char_u *t
ftp->ft_to = (char_u *)getroom_save(spin, word);
}
-// Converts a boolean argument in a SAL line to true or false;
-static bool sal_to_bool(char_u *s)
+/// Converts a boolean argument in a SAL line to true or false;
+static bool sal_to_bool(char *s)
{
- return STRCMP(s, "1") == 0 || STRCMP(s, "true") == 0;
+ return strcmp(s, "1") == 0 || strcmp(s, "true") == 0;
}
// Free the structure filled by spell_read_aff().
@@ -4338,13 +4337,13 @@ static bool node_equal(wordnode_T *n1, wordnode_T *n2)
return p1 == NULL && p2 == NULL;
}
-// Function given to qsort() to sort the REP items on "from" string.
+/// Function given to qsort() to sort the REP items on "from" string.
static int rep_compare(const void *s1, const void *s2)
{
fromto_T *p1 = (fromto_T *)s1;
fromto_T *p2 = (fromto_T *)s2;
- return STRCMP(p1->ft_from, p2->ft_from);
+ return strcmp((char *)p1->ft_from, (char *)p2->ft_from);
}
/// Write the Vim .spl file "fname".
@@ -4914,7 +4913,7 @@ static void spell_make_sugfile(spellinfo_T *spin, char *wfname)
}
if (slang == NULL) {
spell_message(spin, _("Reading back spell file..."));
- slang = spell_load_file((char_u *)wfname, NULL, NULL, false);
+ slang = spell_load_file(wfname, NULL, NULL, false);
if (slang == NULL) {
return;
}
@@ -5233,7 +5232,7 @@ static void sug_write(spellinfo_T *spin, char_u *fname)
for (linenr_T lnum = 1; lnum <= wcount; lnum++) {
// <sugline>: <sugnr> ... NUL
- char_u *line = ml_get_buf(spin->si_spellbuf, lnum, false);
+ char_u *line = (char_u *)ml_get_buf(spin->si_spellbuf, lnum, false);
size_t len = STRLEN(line) + 1;
if (fwrite(line, len, 1, fd) == 0) {
emsg(_(e_write));
@@ -5300,7 +5299,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool
if (fcount >= 1) {
len = (int)STRLEN(fnames[0]);
- if (fcount == 1 && len > 4 && STRCMP(fnames[0] + len - 4, ".add") == 0) {
+ if (fcount == 1 && len > 4 && strcmp(fnames[0] + len - 4, ".add") == 0) {
// For ":mkspell path/en.latin1.add" output file is
// "path/en.latin1.add.spl".
incount = 1;
@@ -5310,7 +5309,7 @@ static void mkspell(int fcount, char **fnames, bool ascii, bool over_write, bool
incount = 1;
vim_snprintf(wfname, MAXPATHL, SPL_FNAME_TMPL,
fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc());
- } else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0) {
+ } else if (len > 4 && strcmp(fnames[0] + len - 4, ".spl") == 0) {
// Name ends in ".spl", use as the file name.
STRLCPY(wfname, fnames[0], MAXPATHL);
} else {
@@ -5531,7 +5530,7 @@ void spell_add_word(char_u *word, int len, SpellAddType what, int idx, bool undo
if (idx == 0) { // use internal wordlist
if (int_wordlist == NULL) {
- int_wordlist = vim_tempname();
+ int_wordlist = (char_u *)vim_tempname();
if (int_wordlist == NULL) {
return;
}
diff --git a/src/nvim/spellsuggest.c b/src/nvim/spellsuggest.c
index 23c8c621b5..16af1b72a3 100644
--- a/src/nvim/spellsuggest.c
+++ b/src/nvim/spellsuggest.c
@@ -65,7 +65,7 @@ typedef struct suginfo_S {
/// One word suggestion. Used in "si_ga".
typedef struct {
- char_u *st_word; ///< suggested word, allocated string
+ char *st_word; ///< suggested word, allocated string
int st_wordlen; ///< STRLEN(st_word)
int st_orglen; ///< length of replaced text
int st_score; ///< lower is better
@@ -354,7 +354,7 @@ int spell_check_sps(void)
{
char *p;
char *s;
- char_u buf[MAXPATHL];
+ char buf[MAXPATHL];
int f;
sps_flags = 0;
@@ -370,11 +370,11 @@ int spell_check_sps(void)
if (*s != NUL && !ascii_isdigit(*s)) {
f = -1;
}
- } else if (STRCMP(buf, "best") == 0) {
+ } else if (strcmp(buf, "best") == 0) {
f = SPS_BEST;
- } else if (STRCMP(buf, "fast") == 0) {
+ } else if (strcmp(buf, "fast") == 0) {
f = SPS_FAST;
- } else if (STRCMP(buf, "double") == 0) {
+ } else if (strcmp(buf, "double") == 0) {
f = SPS_DOUBLE;
} else if (STRNCMP(buf, "expr:", 5) != 0
&& STRNCMP(buf, "file:", 5) != 0
@@ -407,7 +407,7 @@ int spell_check_sps(void)
/// When "count" is non-zero use that suggestion.
void spell_suggest(int count)
{
- char_u *line;
+ char *line;
pos_T prev_cursor = curwin->w_cursor;
char_u wcopy[MAXWLEN + 2];
char_u *p;
@@ -454,9 +454,9 @@ void spell_suggest(int count)
// cursor.
curwin->w_cursor = prev_cursor;
line = get_cursor_line_ptr();
- p = line + curwin->w_cursor.col;
+ p = (char_u *)line + curwin->w_cursor.col;
// Backup to before start of word.
- while (p > line && spell_iswordp_nmw(p, curwin)) {
+ while (p > (char_u *)line && spell_iswordp_nmw(p, curwin)) {
MB_PTR_BACK(line, p);
}
// Forward to start of word.
@@ -468,7 +468,7 @@ void spell_suggest(int count)
beep_flush();
return;
}
- curwin->w_cursor.col = (colnr_T)(p - line);
+ curwin->w_cursor.col = (colnr_T)(p - (char_u *)line);
}
// Get the word and its length.
@@ -477,7 +477,7 @@ void spell_suggest(int count)
need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);
// Make a copy of current line since autocommands may free the line.
- line = vim_strsave(get_cursor_line_ptr());
+ line = xstrdup(get_cursor_line_ptr());
spell_suggest_timeout = 5000;
// Get the list of suggestions. Limit to 'lines' - 2 or the number in
@@ -487,7 +487,7 @@ void spell_suggest(int count)
} else {
limit = sps_limit;
}
- spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
+ spell_find_suggest((char_u *)line + curwin->w_cursor.col, badlen, &sug, limit,
true, need_cap, true);
if (GA_EMPTY(&sug.su_ga)) {
@@ -533,7 +533,7 @@ void spell_suggest(int count)
}
vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1);
if (cmdmsg_rl) {
- rl_mirror(IObuff);
+ rl_mirror((char_u *)IObuff);
}
msg_puts((const char *)IObuff);
@@ -559,7 +559,7 @@ void spell_suggest(int count)
}
if (cmdmsg_rl) {
// Mirror the numbers, but keep the leading space.
- rl_mirror(IObuff + 1);
+ rl_mirror((char_u *)IObuff + 1);
}
msg_advance(30);
msg_puts((const char *)IObuff);
@@ -593,20 +593,20 @@ void spell_suggest(int count)
if (sug.su_badlen > stp->st_orglen) {
// Replacing less than "su_badlen", append the remainder to
// repl_to.
- repl_from = vim_strnsave(sug.su_badptr, (size_t)sug.su_badlen);
+ repl_from = xstrnsave((char *)sug.su_badptr, (size_t)sug.su_badlen);
vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word,
sug.su_badlen - stp->st_orglen,
sug.su_badptr + stp->st_orglen);
- repl_to = vim_strsave(IObuff);
+ repl_to = xstrdup((char *)IObuff);
} else {
// Replacing su_badlen or more, use the whole word.
- repl_from = vim_strnsave(sug.su_badptr, (size_t)stp->st_orglen);
- repl_to = vim_strsave(stp->st_word);
+ repl_from = xstrnsave((char *)sug.su_badptr, (size_t)stp->st_orglen);
+ repl_to = xstrdup(stp->st_word);
}
// Replace the word.
p = xmalloc(STRLEN(line) - (size_t)stp->st_orglen + (size_t)stp->st_wordlen + 1);
- c = (int)(sug.su_badptr - line);
+ c = (int)(sug.su_badptr - (char_u *)line);
memmove(p, line, (size_t)c);
STRCPY(p + c, stp->st_word);
STRCAT(p, sug.su_badptr + stp->st_orglen);
@@ -678,7 +678,7 @@ static void spell_find_suggest(char_u *badptr, int badlen, suginfo_T *su, int ma
char_u buf[MAXPATHL];
char *p;
bool do_combine = false;
- char_u *sps_copy;
+ char *sps_copy;
static bool expr_busy = false;
int c;
langp_T *lp;
@@ -748,7 +748,7 @@ static void spell_find_suggest(char_u *badptr, int badlen, suginfo_T *su, int ma
c = utf_ptr2char((char *)su->su_badptr);
if (!SPELL_ISUPPER(c) && attr == HLF_COUNT) {
make_case_word(su->su_badword, buf, WF_ONECAP);
- add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE,
+ add_suggestion(su, &su->su_ga, (char *)buf, su->su_badlen, SCORE_ICASE,
0, true, su->su_sallang, false);
}
@@ -758,10 +758,10 @@ static void spell_find_suggest(char_u *badptr, int badlen, suginfo_T *su, int ma
}
// Make a copy of 'spellsuggest', because the expression may change it.
- sps_copy = vim_strsave((char_u *)p_sps);
+ sps_copy = xstrdup(p_sps);
// Loop over the items in 'spellsuggest'.
- for (p = (char *)sps_copy; *p != NUL;) {
+ for (p = sps_copy; *p != NUL;) {
copy_option_part(&p, (char *)buf, MAXPATHL, ",");
if (STRNCMP(buf, "expr:", 5) == 0) {
@@ -814,7 +814,7 @@ static void spell_suggest_expr(suginfo_T *su, char_u *expr)
// Get the word and the score from the items.
score = get_spellword(TV_LIST_ITEM_TV(li)->vval.v_list, &p);
if (score >= 0 && score <= su->su_maxscore) {
- add_suggestion(su, &su->su_ga, (const char_u *)p, su->su_badlen,
+ add_suggestion(su, &su->su_ga, p, su->su_badlen,
score, 0, true, su->su_sallang, false);
}
}
@@ -864,7 +864,7 @@ static void spell_suggest_file(suginfo_T *su, char_u *fname)
p = cword;
}
- add_suggestion(su, &su->su_ga, p, su->su_badlen,
+ add_suggestion(su, &su->su_ga, (char *)p, su->su_badlen,
SCORE_FILE, 0, true, su->su_sallang, false);
}
}
@@ -985,7 +985,7 @@ static void suggest_try_special(suginfo_T *su)
// Give a soundalike score of 0, compute the score as if deleting one
// character.
- add_suggestion(su, &su->su_ga, word, su->su_badlen,
+ add_suggestion(su, &su->su_ga, (char *)word, su->su_badlen,
RESCORE(SCORE_REP, 0), 0, true, su->su_sallang, false);
}
}
@@ -1114,7 +1114,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
{
char_u tword[MAXWLEN]; // good word collected so far
trystate_T stack[MAXWLEN];
- char_u preword[MAXWLEN * 3] = { 0 }; // word found with proper case;
+ char preword[MAXWLEN * 3] = { 0 }; // word found with proper case;
// concatenation of prefix compound
// words and split word. NUL terminated
// when going deeper but not when coming
@@ -1241,7 +1241,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
// and make find_keepcap_word() works.
tword[sp->ts_twordlen] = NUL;
make_case_word(tword + sp->ts_splitoff,
- preword + sp->ts_prewordlen, flags);
+ (char_u *)preword + sp->ts_prewordlen, flags);
sp->ts_prewordlen = (char_u)STRLEN(preword);
sp->ts_splitoff = sp->ts_twordlen;
}
@@ -1326,11 +1326,11 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
sp->ts_fidx - sp->ts_splitfidx) == 0) {
preword[sp->ts_prewordlen] = NUL;
newscore = score_wordcount_adj(slang, sp->ts_score,
- preword + sp->ts_prewordlen,
+ (char_u *)preword + sp->ts_prewordlen,
sp->ts_prewordlen > 0);
// Add the suggestion if the score isn't too bad.
if (newscore <= su->su_maxscore) {
- add_suggestion(su, &su->su_ga, preword,
+ add_suggestion(su, &su->su_ga, (char *)preword,
sp->ts_splitfidx - repextra,
newscore, 0, false,
lp->lp_sallang, false);
@@ -1362,13 +1362,13 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
sp->ts_twordlen - sp->ts_splitoff + 1);
// Verify CHECKCOMPOUNDPATTERN rules.
- if (match_checkcompoundpattern(preword, sp->ts_prewordlen,
+ if (match_checkcompoundpattern((char_u *)preword, sp->ts_prewordlen,
&slang->sl_comppat)) {
compound_ok = false;
}
if (compound_ok) {
- p = preword;
+ p = (char_u *)preword;
while (*skiptowhite((char *)p) != NUL) {
p = (char_u *)skipwhite(skiptowhite((char *)p));
}
@@ -1381,7 +1381,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
}
// Get pointer to last char of previous word.
- p = preword + sp->ts_prewordlen;
+ p = (char_u *)preword + sp->ts_prewordlen;
MB_PTR_BACK(preword, p);
}
}
@@ -1394,7 +1394,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
} else if (flags & WF_KEEPCAP) {
// Must find the word in the keep-case tree.
find_keepcap_word(slang, tword + sp->ts_splitoff,
- preword + sp->ts_prewordlen);
+ (char_u *)preword + sp->ts_prewordlen);
} else {
// Include badflags: If the badword is onecap or allcap
// use that for the goodword too. But if the badword is
@@ -1413,14 +1413,14 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
c &= ~WF_ONECAP;
}
make_case_word(tword + sp->ts_splitoff,
- preword + sp->ts_prewordlen, c);
+ (char_u *)preword + sp->ts_prewordlen, c);
}
if (!soundfold) {
// Don't use a banned word. It may appear again as a good
// word, thus remember it.
if (flags & WF_BANNED) {
- add_banned(su, preword + sp->ts_prewordlen);
+ add_banned(su, (char_u *)preword + sp->ts_prewordlen);
break;
}
if ((sp->ts_complen == sp->ts_compsplit
@@ -1445,7 +1445,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
}
if (!spell_valid_case(su->su_badflags,
- captype(preword + sp->ts_prewordlen, NULL))) {
+ captype((char_u *)preword + sp->ts_prewordlen, NULL))) {
newscore += SCORE_ICASE;
}
}
@@ -1457,7 +1457,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
&& compound_ok) {
// The badword also ends: add suggestions.
#ifdef DEBUG_TRIEWALK
- if (soundfold && STRCMP(preword, "smwrd") == 0) {
+ if (soundfold && strcmp(preword, "smwrd") == 0) {
int j;
// print the stack of changes that brought us here
@@ -1470,14 +1470,14 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
if (soundfold) {
// For soundfolded words we need to find the original
// words, the edit distance and then add them.
- add_sound_suggest(su, preword, sp->ts_score, lp);
+ add_sound_suggest(su, (char_u *)preword, sp->ts_score, lp);
} else if (sp->ts_fidx > 0) {
// Give a penalty when changing non-word char to word
// char, e.g., "thes," -> "these".
p = fword + sp->ts_fidx;
MB_PTR_BACK(fword, p);
if (!spell_iswordp(p, curwin) && *preword != NUL) {
- p = preword + STRLEN(preword);
+ p = (char_u *)preword + STRLEN(preword);
MB_PTR_BACK(preword, p);
if (spell_iswordp(p, curwin)) {
newscore += SCORE_NONWORD;
@@ -1487,25 +1487,25 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
// Give a bonus to words seen before.
score = score_wordcount_adj(slang,
sp->ts_score + newscore,
- preword + sp->ts_prewordlen,
+ (char_u *)preword + sp->ts_prewordlen,
sp->ts_prewordlen > 0);
// Add the suggestion if the score isn't too bad.
if (score <= su->su_maxscore) {
- add_suggestion(su, &su->su_ga, preword,
+ add_suggestion(su, &su->su_ga, (char *)preword,
sp->ts_fidx - repextra,
score, 0, false, lp->lp_sallang, false);
if (su->su_badflags & WF_MIXCAP) {
// We really don't know if the word should be
// upper or lower case, add both.
- c = captype(preword, NULL);
+ c = captype((char_u *)preword, NULL);
if (c == 0 || c == WF_ALLCAP) {
make_case_word(tword + sp->ts_splitoff,
- preword + sp->ts_prewordlen,
+ (char_u *)preword + sp->ts_prewordlen,
c == 0 ? WF_ALLCAP : 0);
- add_suggestion(su, &su->su_ga, preword,
+ add_suggestion(su, &su->su_ga, (char *)preword,
sp->ts_fidx - repextra,
score + SCORE_ICASE, 0, false,
lp->lp_sallang, false);
@@ -1589,7 +1589,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
&& (flags & WF_NEEDCOMP)) {
break;
}
- p = preword;
+ p = (char_u *)preword;
while (*skiptowhite((char *)p) != NUL) {
p = (char_u *)skipwhite(skiptowhite((char *)p));
}
@@ -1607,7 +1607,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
// Give a bonus to words seen before.
newscore = score_wordcount_adj(slang, newscore,
- preword + sp->ts_prewordlen, true);
+ (char_u *)preword + sp->ts_prewordlen, true);
}
if (TRY_DEEPER(su, stack, depth, newscore)) {
@@ -2494,7 +2494,7 @@ static void score_comp_sal(suginfo_T *su)
if (score < SCORE_MAXMAX) {
// Add the suggestion.
sstp = &SUG(su->su_sga, su->su_sga.ga_len);
- sstp->st_word = vim_strsave(stp->st_word);
+ sstp->st_word = xstrdup(stp->st_word);
sstp->st_wordlen = stp->st_wordlen;
sstp->st_score = score;
sstp->st_altscore = 0;
@@ -2515,8 +2515,8 @@ static void score_combine(suginfo_T *su)
garray_T *gap;
langp_T *lp;
suggest_T *stp;
- char_u *p;
- char_u badsound[MAXWLEN];
+ char *p;
+ char badsound[MAXWLEN];
int round;
slang_T *slang = NULL;
@@ -2526,11 +2526,11 @@ static void score_combine(suginfo_T *su)
if (!GA_EMPTY(&lp->lp_slang->sl_sal)) {
// soundfold the bad word
slang = lp->lp_slang;
- spell_soundfold(slang, su->su_fbadword, true, badsound);
+ spell_soundfold(slang, su->su_fbadword, true, (char_u *)badsound);
for (int i = 0; i < su->su_ga.ga_len; i++) {
stp = &SUG(su->su_ga, i);
- stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
+ stp->st_altscore = stp_sal_score(stp, su, slang, (char_u *)badsound);
if (stp->st_altscore == SCORE_MAXMAX) {
stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
} else {
@@ -2551,8 +2551,7 @@ static void score_combine(suginfo_T *su)
// Add the alternate score to su_sga.
for (int i = 0; i < su->su_sga.ga_len; i++) {
stp = &SUG(su->su_sga, i);
- stp->st_altscore = spell_edit_score(slang,
- su->su_badword, stp->st_word);
+ stp->st_altscore = spell_edit_score(slang, su->su_badword, (char_u *)stp->st_word);
if (stp->st_score == SCORE_MAXMAX) {
stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
} else {
@@ -2582,7 +2581,7 @@ static void score_combine(suginfo_T *su)
p = SUG(*gap, i).st_word;
int j;
for (j = 0; j < ga.ga_len; j++) {
- if (STRCMP(stp[j].st_word, p) == 0) {
+ if (strcmp(stp[j].st_word, p) == 0) {
break;
}
}
@@ -2636,7 +2635,7 @@ static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *
// removing the space. Don't do it when the good word also contains a
// space.
if (ascii_iswhite(su->su_badptr[su->su_badlen])
- && *skiptowhite((char *)stp->st_word) == NUL) {
+ && *skiptowhite(stp->st_word) == NUL) {
for (p = fword; *(p = (char_u *)skiptowhite((char *)p)) != NUL;) {
STRMOVE(p, p + 1);
}
@@ -2654,13 +2653,13 @@ static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *
su->su_badptr + su->su_badlen - lendiff, lendiff + 1);
pgood = goodword;
} else {
- pgood = stp->st_word;
+ pgood = (char_u *)stp->st_word;
}
// Sound-fold the word and compute the score for the difference.
spell_soundfold(slang, pgood, false, goodsound);
- return soundalike_score(goodsound, pbad);
+ return soundalike_score((char *)goodsound, (char *)pbad);
}
/// structure used to store soundfolded words that add_sound_suggest() has
@@ -2807,7 +2806,7 @@ static void add_sound_suggest(suginfo_T *su, char_u *goodword, int score, langp_
}
// Go over the list of good words that produce this soundfold word
- nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)sfwordnr + 1, false);
+ nrline = (char_u *)ml_get_buf(slang->sl_sugbuf, (linenr_T)sfwordnr + 1, false);
orgnr = 0;
while (*nrline != NUL) {
// The wordnr was stored in a minimal nr of bytes as an offset to the
@@ -2883,7 +2882,7 @@ badword:
if (sps_flags & SPS_DOUBLE) {
// Add the suggestion if the score isn't too bad.
if (score <= su->su_maxscore) {
- add_suggestion(su, &su->su_sga, p, su->su_badlen,
+ add_suggestion(su, &su->su_sga, (char *)p, su->su_badlen,
score, 0, false, slang, false);
}
} else {
@@ -2931,7 +2930,7 @@ badword:
// Add the suggestion if the score isn't too bad.
goodscore = RESCORE(goodscore, score);
if (goodscore <= su->su_sfmaxscore) {
- add_suggestion(su, &su->su_ga, p, su->su_badlen,
+ add_suggestion(su, &su->su_ga, (char *)p, su->su_badlen,
goodscore, score, true, slang, true);
}
}
@@ -3061,7 +3060,7 @@ static bool similar_chars(slang_T *slang, int c1, int c2)
/// @param had_bonus value for st_had_bonus
/// @param slang language for sound folding
/// @param maxsf su_maxscore applies to soundfold score, su_sfmaxscore to the total score.
-static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword, int badlenarg,
+static void add_suggestion(suginfo_T *su, garray_T *gap, const char *goodword, int badlenarg,
int score, int altscore, bool had_bonus, slang_T *slang, bool maxsf)
{
int goodlen; // len of goodword changed
@@ -3071,7 +3070,7 @@ static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword,
// Minimize "badlen" for consistency. Avoids that changing "the the" to
// "thee the" is added next to changing the first "the" the "thee".
- const char_u *pgood = goodword + STRLEN(goodword);
+ const char *pgood = goodword + STRLEN(goodword);
char_u *pbad = su->su_badptr + badlenarg;
for (;;) {
goodlen = (int)(pgood - goodword);
@@ -3144,7 +3143,7 @@ static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword,
if (i < 0) {
// Add a suggestion.
stp = GA_APPEND_VIA_PTR(suggest_T, gap);
- stp->st_word = vim_strnsave(goodword, (size_t)goodlen);
+ stp->st_word = xstrnsave(goodword, (size_t)goodlen);
stp->st_wordlen = goodlen;
stp->st_score = score;
stp->st_altscore = altscore;
@@ -3307,15 +3306,15 @@ static int cleanup_suggestions(garray_T *gap, int maxscore, int keep)
///
/// @param goodstart sound-folded good word
/// @param badstart sound-folded bad word
-static int soundalike_score(char_u *goodstart, char_u *badstart)
+static int soundalike_score(char *goodstart, char *badstart)
{
- char_u *goodsound = goodstart;
- char_u *badsound = badstart;
+ char *goodsound = goodstart;
+ char *badsound = badstart;
int goodlen;
int badlen;
int n;
- char_u *pl, *ps;
- char_u *pl2, *ps2;
+ char *pl, *ps;
+ char *pl2, *ps2;
int score = 0;
// Adding/inserting "*" at the start (word starts with vowel) shouldn't be
@@ -3380,7 +3379,7 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
ps++;
}
// strings must be equal after second delete
- if (STRCMP(pl + 1, ps) == 0) {
+ if (strcmp(pl + 1, ps) == 0) {
return score + SCORE_DEL * 2;
}
@@ -3404,12 +3403,12 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
// 2: delete then swap, then rest must be equal
if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
- && STRCMP(pl2 + 2, ps2 + 2) == 0) {
+ && strcmp(pl2 + 2, ps2 + 2) == 0) {
return score + SCORE_DEL + SCORE_SWAP;
}
// 3: delete then substitute, then the rest must be equal
- if (STRCMP(pl2 + 1, ps2 + 1) == 0) {
+ if (strcmp(pl2 + 1, ps2 + 1) == 0) {
return score + SCORE_DEL + SCORE_SUBST;
}
@@ -3422,7 +3421,7 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
ps2++;
}
// delete a char and then strings must be equal
- if (STRCMP(pl2 + 1, ps2) == 0) {
+ if (strcmp(pl2 + 1, ps2) == 0) {
return score + SCORE_SWAP + SCORE_DEL;
}
}
@@ -3435,7 +3434,7 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
ps2++;
}
// delete a char and then strings must be equal
- if (STRCMP(pl2 + 1, ps2) == 0) {
+ if (strcmp(pl2 + 1, ps2) == 0) {
return score + SCORE_SUBST + SCORE_DEL;
}
@@ -3463,12 +3462,12 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
}
// 3: swap and swap again
if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
- && STRCMP(pl2 + 2, ps2 + 2) == 0) {
+ && strcmp(pl2 + 2, ps2 + 2) == 0) {
return score + SCORE_SWAP + SCORE_SWAP;
}
// 4: swap and substitute
- if (STRCMP(pl2 + 1, ps2 + 1) == 0) {
+ if (strcmp(pl2 + 1, ps2 + 1) == 0) {
return score + SCORE_SWAP + SCORE_SUBST;
}
}
@@ -3486,12 +3485,12 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
// 6: substitute and swap
if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
- && STRCMP(pl2 + 2, ps2 + 2) == 0) {
+ && strcmp(pl2 + 2, ps2 + 2) == 0) {
return score + SCORE_SUBST + SCORE_SWAP;
}
// 7: substitute and substitute
- if (STRCMP(pl2 + 1, ps2 + 1) == 0) {
+ if (strcmp(pl2 + 1, ps2 + 1) == 0) {
return score + SCORE_SUBST + SCORE_SUBST;
}
@@ -3502,7 +3501,7 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
pl2++;
ps2++;
}
- if (STRCMP(pl2 + 1, ps2) == 0) {
+ if (strcmp(pl2 + 1, ps2) == 0) {
return score + SCORE_INS + SCORE_DEL;
}
@@ -3513,7 +3512,7 @@ static int soundalike_score(char_u *goodstart, char_u *badstart)
pl2++;
ps2++;
}
- if (STRCMP(pl2, ps2 + 1) == 0) {
+ if (strcmp(pl2, ps2 + 1) == 0) {
return score + SCORE_INS + SCORE_DEL;
}
diff --git a/src/nvim/state.c b/src/nvim/state.c
index 61740800a1..458eed960f 100644
--- a/src/nvim/state.c
+++ b/src/nvim/state.c
@@ -237,7 +237,7 @@ void may_trigger_modechanged(void)
char pattern_buf[2 * MODE_MAX_LENGTH];
get_mode(curr_mode);
- if (STRCMP(curr_mode, last_mode) == 0) {
+ if (strcmp(curr_mode, last_mode) == 0) {
return;
}
diff --git a/src/nvim/statusline.c b/src/nvim/statusline.c
index 9b441ba0a9..5f686ef96f 100644
--- a/src/nvim/statusline.c
+++ b/src/nvim/statusline.c
@@ -426,7 +426,7 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler)
int len;
int fillchar;
char buf[MAXPATHL];
- char_u *stl;
+ char *stl;
char *p;
stl_hlrec_t *hltab;
StlClickRecord *tabtab;
@@ -448,14 +448,14 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler)
// setup environment for the task at hand
if (wp == NULL) {
// Use 'tabline'. Always at the first line of the screen.
- stl = (char_u *)p_tal;
+ stl = p_tal;
row = 0;
fillchar = ' ';
attr = HL_ATTR(HLF_TPF);
maxwidth = Columns;
use_sandbox = was_set_insecurely(wp, "tabline", 0);
} else if (draw_winbar) {
- stl = (char_u *)((*wp->w_p_wbr != NUL) ? wp->w_p_wbr : p_wbr);
+ stl = ((*wp->w_p_wbr != NUL) ? wp->w_p_wbr : p_wbr);
row = -1; // row zero is first row of text
col = 0;
grid = &wp->w_grid;
@@ -491,19 +491,19 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler)
}
if (draw_ruler) {
- stl = (char_u *)p_ruf;
+ stl = p_ruf;
// advance past any leading group spec - implicit in ru_col
if (*stl == '%') {
if (*++stl == '-') {
stl++;
}
- if (atoi((char *)stl)) {
+ if (atoi(stl)) {
while (ascii_isdigit(*stl)) {
stl++;
}
}
if (*stl++ != '(') {
- stl = (char_u *)p_ruf;
+ stl = p_ruf;
}
}
col = ru_col - (Columns - maxwidth);
@@ -522,9 +522,9 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler)
use_sandbox = was_set_insecurely(wp, "rulerformat", 0);
} else {
if (*wp->w_p_stl != NUL) {
- stl = (char_u *)wp->w_p_stl;
+ stl = wp->w_p_stl;
} else {
- stl = (char_u *)p_stl;
+ stl = p_stl;
}
use_sandbox = was_set_insecurely(wp, "statusline", *wp->w_p_stl == NUL ? 0 : OPT_LOCAL);
}
@@ -544,9 +544,9 @@ void win_redr_custom(win_T *wp, bool draw_winbar, bool draw_ruler)
// Make a copy, because the statusline may include a function call that
// might change the option value and free the memory.
- stl = vim_strsave(stl);
+ stl = xstrdup(stl);
width =
- build_stl_str_hl(ewp, buf, sizeof(buf), (char *)stl, use_sandbox,
+ build_stl_str_hl(ewp, buf, sizeof(buf), stl, use_sandbox,
fillchar, maxwidth, &hltab, &tabtab);
xfree(stl);
ewp->w_p_crb = p_crb_save;
@@ -711,7 +711,7 @@ int build_stl_str_hl(win_T *wp, char *out, size_t outlen, char *fmt, int use_san
}
// Get line & check if empty (cursorpos will show "0-1").
- const char *line_ptr = (char *)ml_get_buf(wp->w_buffer, lnum, false);
+ const char *line_ptr = ml_get_buf(wp->w_buffer, lnum, false);
bool empty_line = (*line_ptr == NUL);
// Get the byte value now, in case we need it below. This is more
diff --git a/src/nvim/strings.c b/src/nvim/strings.c
index 16691d0ded..ee6172e7fc 100644
--- a/src/nvim/strings.c
+++ b/src/nvim/strings.c
@@ -49,53 +49,31 @@
#include "nvim/vim.h"
#include "nvim/window.h"
-/// Copy "string" into newly allocated memory.
-char_u *vim_strsave(const char_u *string)
- FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
-{
- return (char_u *)xstrdup((char *)string);
-}
-
/// Copy up to `len` bytes of `string` into newly allocated memory and
/// terminate with a NUL. The allocated memory always has size `len + 1`, even
/// when `string` is shorter.
-char_u *vim_strnsave(const char_u *string, size_t len)
- FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
-{
- // strncpy is intentional: some parts of Vim use `string` shorter than `len`
- // and expect the remainder to be zeroed out.
- return (char_u *)strncpy(xmallocz(len), (char *)string, len);
-}
-
-/// A clone of vim_strnsave() that uses char* instead of char_u*
char *xstrnsave(const char *string, size_t len)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
{
return strncpy(xmallocz(len), string, len); // NOLINT(runtime/printf)
}
-/*
- * Same as vim_strsave(), but any characters found in esc_chars are preceded
- * by a backslash.
- */
+// Same as vim_strsave(), but any characters found in esc_chars are preceded
+// by a backslash.
char_u *vim_strsave_escaped(const char_u *string, const char_u *esc_chars)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
{
return vim_strsave_escaped_ext(string, esc_chars, '\\', false);
}
-/*
- * Same as vim_strsave_escaped(), but when "bsl" is true also escape
- * characters where rem_backslash() would remove the backslash.
- * Escape the characters with "cc".
- */
+// Same as vim_strsave_escaped(), but when "bsl" is true also escape
+// characters where rem_backslash() would remove the backslash.
+// Escape the characters with "cc".
char_u *vim_strsave_escaped_ext(const char_u *string, const char_u *esc_chars, char_u cc, bool bsl)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
{
- /*
- * First count the number of backslashes required.
- * Then allocate the memory and insert them.
- */
+ // First count the number of backslashes required.
+ // Then allocate the memory and insert them.
size_t length = 1; // count the trailing NUL
for (const char_u *p = string; *p; p++) {
const size_t l = (size_t)(utfc_ptr2len((char *)p));
@@ -178,16 +156,14 @@ char *vim_strnsave_unquoted(const char *const string, const size_t length)
return ret;
}
-/*
- * Escape "string" for use as a shell argument with system().
- * This uses single quotes, except when we know we need to use double quotes
- * (MS-Windows without 'shellslash' set).
- * Escape a newline, depending on the 'shell' option.
- * When "do_special" is true also replace "!", "%", "#" and things starting
- * with "<" like "<cfile>".
- * When "do_newline" is false do not escape newline unless it is csh shell.
- * Returns the result in allocated memory.
- */
+// Escape "string" for use as a shell argument with system().
+// This uses single quotes, except when we know we need to use double quotes
+// (MS-Windows without 'shellslash' set).
+// Escape a newline, depending on the 'shell' option.
+// When "do_special" is true also replace "!", "%", "#" and things starting
+// with "<" like "<cfile>".
+// When "do_newline" is false do not escape newline unless it is csh shell.
+// Returns the result in allocated memory.
char_u *vim_strsave_shellescape(const char_u *string, bool do_special, bool do_newline)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
{
@@ -197,10 +173,10 @@ char_u *vim_strsave_shellescape(const char_u *string, bool do_special, bool do_n
int csh_like;
bool fish_like;
- /* Only csh and similar shells expand '!' within single quotes. For sh and
- * the like we must not put a backslash before it, it will be taken
- * literally. If do_special is set the '!' will be escaped twice.
- * Csh also needs to have "\n" escaped twice when do_special is set. */
+ // Only csh and similar shells expand '!' within single quotes. For sh and
+ // the like we must not put a backslash before it, it will be taken
+ // literally. If do_special is set the '!' will be escaped twice.
+ // Csh also needs to have "\n" escaped twice when do_special is set.
csh_like = csh_like_shell();
// Fish shell uses '\' as an escape character within single quotes, so '\'
@@ -304,35 +280,29 @@ char_u *vim_strsave_shellescape(const char_u *string, bool do_special, bool do_n
return escaped_string;
}
-/*
- * Like vim_strsave(), but make all characters uppercase.
- * This uses ASCII lower-to-upper case translation, language independent.
- */
+// Like vim_strsave(), but make all characters uppercase.
+// This uses ASCII lower-to-upper case translation, language independent.
char_u *vim_strsave_up(const char_u *string)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
{
- char_u *p1;
+ char *p1;
- p1 = vim_strsave(string);
- vim_strup(p1);
- return p1;
+ p1 = xstrdup((char *)string);
+ vim_strup((char_u *)p1);
+ return (char_u *)p1;
}
-/*
- * Like vim_strnsave(), but make all characters uppercase.
- * This uses ASCII lower-to-upper case translation, language independent.
- */
-char_u *vim_strnsave_up(const char_u *string, size_t len)
+/// Like xstrnsave(), but make all characters uppercase.
+/// This uses ASCII lower-to-upper case translation, language independent.
+char *vim_strnsave_up(const char *string, size_t len)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
{
- char_u *p1 = vim_strnsave(string, len);
- vim_strup(p1);
+ char *p1 = xstrnsave(string, len);
+ vim_strup((char_u *)p1);
return p1;
}
-/*
- * ASCII lower-to-upper case translation, language independent.
- */
+// ASCII lower-to-upper case translation, language independent.
void vim_strup(char_u *p)
FUNC_ATTR_NONNULL_ALL
{
@@ -386,9 +356,7 @@ char *strcase_save(const char *const orig, bool upper)
return res;
}
-/*
- * delete spaces at the end of a string
- */
+// delete spaces at the end of a string
void del_trailing_spaces(char_u *ptr)
FUNC_ATTR_NONNULL_ALL
{
@@ -413,11 +381,9 @@ size_t xstrnlen(const char *s, size_t n)
#endif
#if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP))
-/*
- * Compare two strings, ignoring case, using current locale.
- * Doesn't work for multi-byte characters.
- * return 0 for match, < 0 for smaller, > 0 for bigger
- */
+// Compare two strings, ignoring case, using current locale.
+// Doesn't work for multi-byte characters.
+// return 0 for match, < 0 for smaller, > 0 for bigger
int vim_stricmp(const char *s1, const char *s2)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
{
@@ -439,11 +405,9 @@ int vim_stricmp(const char *s1, const char *s2)
#endif
#if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP))
-/*
- * Compare two strings, for length "len", ignoring case, using current locale.
- * Doesn't work for multi-byte characters.
- * return 0 for match, < 0 for smaller, > 0 for bigger
- */
+// Compare two strings, for length "len", ignoring case, using current locale.
+// Doesn't work for multi-byte characters.
+// return 0 for match, < 0 for smaller, > 0 for bigger
int vim_strnicmp(const char *s1, const char *s2, size_t len)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
{
@@ -488,9 +452,7 @@ char *vim_strchr(const char *const string, const int c)
}
}
-/*
- * Sort an array of strings.
- */
+// Sort an array of strings.
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "strings.c.generated.h"
@@ -498,7 +460,7 @@ char *vim_strchr(const char *const string, const int c)
static int sort_compare(const void *s1, const void *s2)
FUNC_ATTR_NONNULL_ALL
{
- return STRCMP(*(char **)s1, *(char **)s2);
+ return strcmp(*(char **)s1, *(char **)s2);
}
void sort_strings(char **files, int count)
@@ -506,10 +468,8 @@ void sort_strings(char **files, int count)
qsort((void *)files, (size_t)count, sizeof(char *), sort_compare);
}
-/*
- * Return true if string "s" contains a non-ASCII character (128 or higher).
- * When "s" is NULL false is returned.
- */
+// Return true if string "s" contains a non-ASCII character (128 or higher).
+// When "s" is NULL false is returned.
bool has_non_ascii(const char_u *s)
FUNC_ATTR_PURE
{
diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c
index d8de23182c..ce952147f7 100644
--- a/src/nvim/syntax.c
+++ b/src/nvim/syntax.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * syntax.c: code for syntax highlighting
- */
+// syntax.c: code for syntax highlighting
#include <assert.h>
#include <ctype.h>
@@ -93,22 +91,20 @@ typedef struct syn_pattern {
int16_t *sp_cont_list; // cont. group IDs, if non-zero
int16_t *sp_next_list; // next group IDs, if non-zero
struct sp_syn sp_syn; // struct passed to in_id_list()
- char_u *sp_pattern; // regexp to match, pattern
+ char *sp_pattern; // regexp to match, pattern
regprog_T *sp_prog; // regexp to match, program
syn_time_T sp_time;
} synpat_T;
typedef struct syn_cluster_S {
char_u *scl_name; // syntax cluster name
- char_u *scl_name_u; // uppercase of scl_name
+ char *scl_name_u; // uppercase of scl_name
int16_t *scl_list; // IDs in this syntax cluster
} syn_cluster_T;
-/*
- * For the current state we need to remember more than just the idx.
- * When si_m_endpos.lnum is 0, the items other than si_idx are unknown.
- * (The end positions have the column number of the next char)
- */
+// For the current state we need to remember more than just the idx.
+// When si_m_endpos.lnum is 0, the items other than si_idx are unknown.
+// (The end positions have the column number of the next char)
typedef struct state_item {
int si_idx; // index of syntax pattern or
// KEYWORD_IDX
@@ -133,10 +129,8 @@ typedef struct state_item {
// pattern
} stateitem_T;
-/*
- * Struct to reduce the number of arguments to get_syn_options(), it's used
- * very often.
- */
+// Struct to reduce the number of arguments to get_syn_options(), it's used
+// very often.
typedef struct {
int flags; // flags for contained and transparent
bool keyword; // true for ":syn keyword"
@@ -184,9 +178,7 @@ static char *(spo_name_tab[SPO_COUNT]) =
#define NONE_IDX (-2) // value of sp_sync_idx for "NONE"
-/*
- * Flags for b_syn_sync_flags:
- */
+// Flags for b_syn_sync_flags:
#define SF_CCOMMENT 0x01 // sync on a C-style comment
#define SF_MATCH 0x02 // sync by matching a pattern
@@ -194,9 +186,7 @@ static char *(spo_name_tab[SPO_COUNT]) =
#define MAXKEYWLEN 80 // maximum length of a keyword
-/*
- * The attributes of the syntax item that has been recognized.
- */
+// The attributes of the syntax item that has been recognized.
static int current_attr = 0; // attr of current syntax word
static int current_id = 0; // ID of current char for syn_get_id()
static int current_trans_id = 0; // idem, transparency removed
@@ -204,23 +194,19 @@ static int current_flags = 0;
static int current_seqnr = 0;
static int current_sub_char = 0;
-/*
- * Methods of combining two clusters
- */
+// Methods of combining two clusters
#define CLUSTER_REPLACE 1 // replace first list with second
#define CLUSTER_ADD 2 // add second list to first
#define CLUSTER_SUBTRACT 3 // subtract second list from first
#define SYN_CLSTR(buf) ((syn_cluster_T *)((buf)->b_syn_clusters.ga_data))
-/*
- * Syntax group IDs have different types:
- * 0 - 19999 normal syntax groups
- * 20000 - 20999 ALLBUT indicator (current_syn_inc_tag added)
- * 21000 - 21999 TOP indicator (current_syn_inc_tag added)
- * 22000 - 22999 CONTAINED indicator (current_syn_inc_tag added)
- * 23000 - 32767 cluster IDs (subtract SYNID_CLUSTER for the cluster ID)
- */
+// Syntax group IDs have different types:
+// 0 - 19999 normal syntax groups
+// 20000 - 20999 ALLBUT indicator (current_syn_inc_tag added)
+// 21000 - 21999 TOP indicator (current_syn_inc_tag added)
+// 22000 - 22999 CONTAINED indicator (current_syn_inc_tag added)
+// 23000 - 32767 cluster IDs (subtract SYNID_CLUSTER for the cluster ID)
#define SYNID_ALLBUT MAX_HL_ID // syntax group ID for contains=ALLBUT
#define SYNID_TOP 21000 // syntax group ID for contains=TOP
#define SYNID_CONTAINED 22000 // syntax group ID for contains=CONTAINED
@@ -234,21 +220,17 @@ static int current_sub_char = 0;
// instead of passing it to them, we stow it here.
static char **syn_cmdlinep;
-/*
- * Another Annoying Hack(TM): To prevent rules from other ":syn include"'d
- * files from leaking into ALLBUT lists, we assign a unique ID to the
- * rules in each ":syn include"'d file.
- */
+// Another Annoying Hack(TM): To prevent rules from other ":syn include"'d
+// files from leaking into ALLBUT lists, we assign a unique ID to the
+// rules in each ":syn include"'d file.
static int current_syn_inc_tag = 0;
static int running_syn_inc_tag = 0;
-/*
- * In a hashtable item "hi_key" points to "keyword" in a keyentry.
- * This avoids adding a pointer to the hashtable item.
- * KE2HIKEY() converts a var pointer to a hashitem key pointer.
- * HIKEY2KE() converts a hashitem key pointer to a var pointer.
- * HI2KE() converts a hashitem pointer to a var pointer.
- */
+// In a hashtable item "hi_key" points to "keyword" in a keyentry.
+// This avoids adding a pointer to the hashtable item.
+// KE2HIKEY() converts a var pointer to a hashitem key pointer.
+// HIKEY2KE() converts a hashitem key pointer to a var pointer.
+// HI2KE() converts a hashitem pointer to a var pointer.
static keyentry_T dumkey;
#define KE2HIKEY(kp) ((kp)->keyword)
#define HIKEY2KE(p) ((keyentry_T *)((p) - (dumkey.keyword - (char_u *)&dumkey)))
@@ -256,11 +238,9 @@ static keyentry_T dumkey;
// -V:HI2KE:782
-/*
- * To reduce the time spent in keepend(), remember at which level in the state
- * stack the first item with "keepend" is present. When "-1", there is no
- * "keepend" on the stack.
- */
+// To reduce the time spent in keepend(), remember at which level in the state
+// stack the first item with "keepend" is present. When "-1", there is no
+// "keepend" on the stack.
static int keepend_level = -1;
static char msg_no_items[] = N_("No Syntax items defined for this buffer");
@@ -272,13 +252,11 @@ static char msg_no_items[] = N_("No Syntax items defined for this buffer");
static int next_seqnr = 1; // value to use for si_seqnr
-/*
- * The next possible match in the current line for any pattern is remembered,
- * to avoid having to try for a match in each column.
- * If next_match_idx == -1, not tried (in this line) yet.
- * If next_match_col == MAXCOL, no match found in this line.
- * (All end positions have the column of the char after the end)
- */
+// The next possible match in the current line for any pattern is remembered,
+// to avoid having to try for a match in each column.
+// If next_match_idx == -1, not tried (in this line) yet.
+// If next_match_col == MAXCOL, no match found in this line.
+// (All end positions have the column of the char after the end)
static int next_match_col; // column for start of next match
static lpos_T next_match_m_endpos; // position for end of next match
static lpos_T next_match_h_startpos; // pos. for highl. start of next match
@@ -290,17 +268,13 @@ static lpos_T next_match_eoe_pos; // pos. for end of end pattern
static int next_match_end_idx; // ID of group for end pattn or zero
static reg_extmatch_T *next_match_extmatch = NULL;
-/*
- * A state stack is an array of integers or stateitem_T, stored in a
- * garray_T. A state stack is invalid if its itemsize entry is zero.
- */
+// A state stack is an array of integers or stateitem_T, stored in a
+// garray_T. A state stack is invalid if its itemsize entry is zero.
#define INVALID_STATE(ssp) ((ssp)->ga_itemsize == 0)
#define VALID_STATE(ssp) ((ssp)->ga_itemsize != 0)
-/*
- * The current state (within the line) of the recognition engine.
- * When current_state.ga_itemsize is 0 the current state is invalid.
- */
+// The current state (within the line) of the recognition engine.
+// When current_state.ga_itemsize is 0 the current state is invalid.
static win_T *syn_win; // current window for highlighting
static buf_T *syn_buf; // current buffer for highlighting
static synblock_T *syn_block; // current buffer for highlighting
@@ -328,13 +302,11 @@ void syn_set_timeout(proftime_T *tm)
syn_tm = tm;
}
-/*
- * Start the syntax recognition for a line. This function is normally called
- * from the screen updating, once for each displayed line.
- * The buffer is remembered in syn_buf, because get_syntax_attr() doesn't get
- * it. Careful: curbuf and curwin are likely to point to another buffer and
- * window.
- */
+// Start the syntax recognition for a line. This function is normally called
+// from the screen updating, once for each displayed line.
+// The buffer is remembered in syn_buf, because get_syntax_attr() doesn't get
+// it. Careful: curbuf and curwin are likely to point to another buffer and
+// window.
void syntax_start(win_T *wp, linenr_T lnum)
{
synstate_T *p;
@@ -348,11 +320,9 @@ void syntax_start(win_T *wp, linenr_T lnum)
current_sub_char = NUL;
- /*
- * After switching buffers, invalidate current_state.
- * Also do this when a change was made, the current state may be invalid
- * then.
- */
+ // After switching buffers, invalidate current_state.
+ // Also do this when a change was made, the current state may be invalid
+ // then.
if (syn_block != wp->w_s
|| syn_buf != wp->w_buffer
|| changedtick != buf_get_changedtick(syn_buf)) {
@@ -363,18 +333,14 @@ void syntax_start(win_T *wp, linenr_T lnum)
changedtick = buf_get_changedtick(syn_buf);
syn_win = wp;
- /*
- * Allocate syntax stack when needed.
- */
+ // Allocate syntax stack when needed.
syn_stack_alloc();
if (syn_block->b_sst_array == NULL) {
return; // out of memory
}
syn_block->b_sst_lasttick = display_tick;
- /*
- * If the state of the end of the previous line is useful, store it.
- */
+ // If the state of the end of the previous line is useful, store it.
if (VALID_STATE(&current_state)
&& current_lnum < lnum
&& current_lnum < syn_buf->b_ml.ml_line_count) {
@@ -384,11 +350,9 @@ void syntax_start(win_T *wp, linenr_T lnum)
(void)store_current_state();
}
- /*
- * If the current_lnum is now the same as "lnum", keep the current
- * state (this happens very often!). Otherwise invalidate
- * current_state and figure it out below.
- */
+ // If the current_lnum is now the same as "lnum", keep the current
+ // state (this happens very often!). Otherwise invalidate
+ // current_state and figure it out below.
if (current_lnum != lnum) {
invalidate_current_state();
}
@@ -396,10 +360,8 @@ void syntax_start(win_T *wp, linenr_T lnum)
invalidate_current_state();
}
- /*
- * Try to synchronize from a saved state in b_sst_array[].
- * Only do this if lnum is not before and not to far beyond a saved state.
- */
+ // Try to synchronize from a saved state in b_sst_array[].
+ // Only do this if lnum is not before and not to far beyond a saved state.
if (INVALID_STATE(&current_state) && syn_block->b_sst_array != NULL) {
// Find last valid saved state before start_lnum.
for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) {
@@ -418,10 +380,8 @@ void syntax_start(win_T *wp, linenr_T lnum)
}
}
- /*
- * If "lnum" is before or far beyond a line with a saved state, need to
- * re-synchronize.
- */
+ // If "lnum" is before or far beyond a line with a saved state, need to
+ // re-synchronize.
if (INVALID_STATE(&current_state)) {
syn_sync(wp, lnum, last_valid);
if (current_lnum == 1) {
@@ -436,10 +396,8 @@ void syntax_start(win_T *wp, linenr_T lnum)
first_stored = current_lnum;
}
- /*
- * Advance from the sync point or saved state until the current line.
- * Save some entries for syncing with later on.
- */
+ // Advance from the sync point or saved state until the current line.
+ // Save some entries for syncing with later on.
if (syn_block->b_sst_len <= Rows) {
dist = 999999;
} else {
@@ -506,10 +464,8 @@ void syntax_start(win_T *wp, linenr_T lnum)
syn_start_line();
}
-/*
- * We cannot simply discard growarrays full of state_items or buf_states; we
- * have to manually release their extmatch pointers first.
- */
+// We cannot simply discard growarrays full of state_items or buf_states; we
+// have to manually release their extmatch pointers first.
static void clear_syn_state(synstate_T *p)
{
if (p->sst_stacksize > SST_FIX_STATES) {
@@ -522,24 +478,20 @@ static void clear_syn_state(synstate_T *p)
}
}
-/*
- * Cleanup the current_state stack.
- */
+// Cleanup the current_state stack.
static void clear_current_state(void)
{
#define UNREF_STATEITEM_EXTMATCH(si) unref_extmatch((si)->si_extmatch)
GA_DEEP_CLEAR(&current_state, stateitem_T, UNREF_STATEITEM_EXTMATCH);
}
-/*
- * Try to find a synchronisation point for line "lnum".
- *
- * This sets current_lnum and the current state. One of three methods is
- * used:
- * 1. Search backwards for the end of a C-comment.
- * 2. Search backwards for given sync patterns.
- * 3. Simply start on a given number of lines above "lnum".
- */
+// Try to find a synchronisation point for line "lnum".
+//
+// This sets current_lnum and the current state. One of three methods is
+// used:
+// 1. Search backwards for the end of a C-comment.
+// 2. Search backwards for given sync patterns.
+// 3. Simply start on a given number of lines above "lnum".
static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
{
buf_T *curbuf_save;
@@ -560,19 +512,15 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
lpos_T found_m_endpos;
colnr_T prev_current_col;
- /*
- * Clear any current state that might be hanging around.
- */
+ // Clear any current state that might be hanging around.
invalidate_current_state();
- /*
- * Start at least "minlines" back. Default starting point for parsing is
- * there.
- * Start further back, to avoid that scrolling backwards will result in
- * resyncing for every line. Now it resyncs only one out of N lines,
- * where N is minlines * 1.5, or minlines * 2 if minlines is small.
- * Watch out for overflow when minlines is MAXLNUM.
- */
+ // Start at least "minlines" back. Default starting point for parsing is
+ // there.
+ // Start further back, to avoid that scrolling backwards will result in
+ // resyncing for every line. Now it resyncs only one out of N lines,
+ // where N is minlines * 1.5, or minlines * 2 if minlines is small.
+ // Watch out for overflow when minlines is MAXLNUM.
if (syn_block->b_syn_sync_minlines > start_lnum) {
start_lnum = 1;
} else {
@@ -595,9 +543,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
}
current_lnum = start_lnum;
- /*
- * 1. Search backwards for the end of a C-style comment.
- */
+ // 1. Search backwards for the end of a C-style comment.
if (syn_block->b_syn_sync_flags & SF_CCOMMENT) {
// Need to make syn_buf the current buffer for a moment, to be able to
// use find_start_comment().
@@ -606,9 +552,7 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
curbuf_save = curbuf;
curbuf = syn_buf;
- /*
- * Skip lines that end in a backslash.
- */
+ // Skip lines that end in a backslash.
for (; start_lnum > 1; start_lnum--) {
line = (char_u *)ml_get(start_lnum - 1);
if (*line == NUL || *(line + STRLEN(line) - 1) != '\\') {
@@ -622,11 +566,9 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
wp->w_cursor.lnum = start_lnum;
wp->w_cursor.col = 0;
- /*
- * If the line is inside a comment, need to find the syntax item that
- * defines the comment.
- * Restrict the search for the end of a comment to b_syn_sync_maxlines.
- */
+ // If the line is inside a comment, need to find the syntax item that
+ // defines the comment.
+ // Restrict the search for the end of a comment to b_syn_sync_maxlines.
if (find_start_comment((int)syn_block->b_syn_sync_maxlines) != NULL) {
for (idx = syn_block->b_syn_patterns.ga_len; --idx >= 0;) {
if (SYN_ITEMS(syn_block)[idx].sp_syn.id
@@ -644,11 +586,8 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
wp->w_cursor = cursor_save;
curwin = curwin_save;
curbuf = curbuf_save;
- }
- /*
- * 2. Search backwards for given sync patterns.
- */
- else if (syn_block->b_syn_sync_flags & SF_MATCH) {
+ } else if (syn_block->b_syn_sync_flags & SF_MATCH) {
+ // 2. Search backwards for given sync patterns.
if (syn_block->b_syn_sync_maxlines != 0
&& start_lnum > syn_block->b_syn_sync_maxlines) {
break_lnum = start_lnum - syn_block->b_syn_sync_maxlines;
@@ -675,16 +614,12 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
break;
}
- /*
- * Check if the previous line has the line-continuation pattern.
- */
+ // Check if the previous line has the line-continuation pattern.
if (lnum > 1 && syn_match_linecont(lnum - 1)) {
continue;
}
- /*
- * Start with nothing on the state stack
- */
+ // Start with nothing on the state stack
validate_current_state();
for (current_lnum = lnum; current_lnum < end_lnum; current_lnum++) {
@@ -712,10 +647,8 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
found_current_lnum = current_lnum;
found_current_col = current_col;
found_m_endpos = cur_si->si_m_endpos;
- /*
- * Continue after the match (be aware of a zero-length
- * match).
- */
+ // Continue after the match (be aware of a zero-length
+ // match).
if (found_m_endpos.lnum > current_lnum) {
current_lnum = found_m_endpos.lnum;
current_col = found_m_endpos.col;
@@ -743,27 +676,21 @@ static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
}
}
- /*
- * If a sync point was encountered, break here.
- */
+ // If a sync point was encountered, break here.
if (found_flags) {
- /*
- * Put the item that was specified by the sync point on the
- * state stack. If there was no item specified, make the
- * state stack empty.
- */
+ // Put the item that was specified by the sync point on the
+ // state stack. If there was no item specified, make the
+ // state stack empty.
clear_current_state();
if (found_match_idx >= 0) {
push_current_state(found_match_idx);
update_si_attr(current_state.ga_len - 1);
}
- /*
- * When using "grouphere", continue from the sync point
- * match, until the end of the line. Parsing starts at
- * the next line.
- * For "groupthere" the parsing starts at start_lnum.
- */
+ // When using "grouphere", continue from the sync point
+ // match, until the end of the line. Parsing starts at
+ // the next line.
+ // For "groupthere" the parsing starts at start_lnum.
if (found_flags & HL_SYNC_HERE) {
if (!GA_EMPTY(&current_state)) {
cur_si = &CUR_STATE(current_state.ga_len - 1);
@@ -833,18 +760,14 @@ static int syn_match_linecont(linenr_T lnum)
return false;
}
-/*
- * Prepare the current state for the start of a line.
- */
+// Prepare the current state for the start of a line.
static void syn_start_line(void)
{
current_finished = false;
current_col = 0;
- /*
- * Need to update the end of a start/skip/end that continues from the
- * previous line and regions that have "keepend".
- */
+ // Need to update the end of a start/skip/end that continues from the
+ // previous line and regions that have "keepend".
if (!GA_EMPTY(&current_state)) {
syn_update_ends(true);
check_state_ends();
@@ -881,15 +804,13 @@ static void syn_update_ends(bool startofline)
}
}
- /*
- * Need to update the end of a start/skip/end that continues from the
- * previous line. And regions that have "keepend", because they may
- * influence contained items. If we've just removed "extend"
- * (startofline == 0) then we should update ends of normal regions
- * contained inside "keepend" because "extend" could have extended
- * these "keepend" regions as well as contained normal regions.
- * Then check for items ending in column 0.
- */
+ // Need to update the end of a start/skip/end that continues from the
+ // previous line. And regions that have "keepend", because they may
+ // influence contained items. If we've just removed "extend"
+ // (startofline == 0) then we should update ends of normal regions
+ // contained inside "keepend" because "extend" could have extended
+ // these "keepend" regions as well as contained normal regions.
+ // Then check for items ending in column 0.
int i = current_state.ga_len - 1;
if (keepend_level >= 0) {
for (; i > keepend_level; i--) {
@@ -923,37 +844,35 @@ static void syn_update_ends(bool startofline)
/////////////////////////////////////////
// Handling of the state stack cache.
-/*
- * EXPLANATION OF THE SYNTAX STATE STACK CACHE
- *
- * To speed up syntax highlighting, the state stack for the start of some
- * lines is cached. These entries can be used to start parsing at that point.
- *
- * The stack is kept in b_sst_array[] for each buffer. There is a list of
- * valid entries. b_sst_first points to the first one, then follow sst_next.
- * The entries are sorted on line number. The first entry is often for line 2
- * (line 1 always starts with an empty stack).
- * There is also a list for free entries. This construction is used to avoid
- * having to allocate and free memory blocks too often.
- *
- * When making changes to the buffer, this is logged in b_mod_*. When calling
- * update_screen() to update the display, it will call
- * syn_stack_apply_changes() for each displayed buffer to adjust the cached
- * entries. The entries which are inside the changed area are removed,
- * because they must be recomputed. Entries below the changed have their line
- * number adjusted for deleted/inserted lines, and have their sst_change_lnum
- * set to indicate that a check must be made if the changed lines would change
- * the cached entry.
- *
- * When later displaying lines, an entry is stored for each line. Displayed
- * lines are likely to be displayed again, in which case the state at the
- * start of the line is needed.
- * For not displayed lines, an entry is stored for every so many lines. These
- * entries will be used e.g., when scrolling backwards. The distance between
- * entries depends on the number of lines in the buffer. For small buffers
- * the distance is fixed at SST_DIST, for large buffers there is a fixed
- * number of entries SST_MAX_ENTRIES, and the distance is computed.
- */
+// EXPLANATION OF THE SYNTAX STATE STACK CACHE
+//
+// To speed up syntax highlighting, the state stack for the start of some
+// lines is cached. These entries can be used to start parsing at that point.
+//
+// The stack is kept in b_sst_array[] for each buffer. There is a list of
+// valid entries. b_sst_first points to the first one, then follow sst_next.
+// The entries are sorted on line number. The first entry is often for line 2
+// (line 1 always starts with an empty stack).
+// There is also a list for free entries. This construction is used to avoid
+// having to allocate and free memory blocks too often.
+//
+// When making changes to the buffer, this is logged in b_mod_*. When calling
+// update_screen() to update the display, it will call
+// syn_stack_apply_changes() for each displayed buffer to adjust the cached
+// entries. The entries which are inside the changed area are removed,
+// because they must be recomputed. Entries below the changed have their line
+// number adjusted for deleted/inserted lines, and have their sst_change_lnum
+// set to indicate that a check must be made if the changed lines would change
+// the cached entry.
+//
+// When later displaying lines, an entry is stored for each line. Displayed
+// lines are likely to be displayed again, in which case the state at the
+// start of the line is needed.
+// For not displayed lines, an entry is stored for every so many lines. These
+// entries will be used e.g., when scrolling backwards. The distance between
+// entries depends on the number of lines in the buffer. For small buffers
+// the distance is fixed at SST_DIST, for large buffers there is a fixed
+// number of entries SST_MAX_ENTRIES, and the distance is computed.
static void syn_stack_free_block(synblock_T *block)
{
@@ -968,10 +887,8 @@ static void syn_stack_free_block(synblock_T *block)
block->b_sst_len = 0;
}
}
-/*
- * Free b_sst_array[] for buffer "buf".
- * Used when syntax items changed to force resyncing everywhere.
- */
+// Free b_sst_array[] for buffer "buf".
+// Used when syntax items changed to force resyncing everywhere.
void syn_stack_free_all(synblock_T *block)
{
syn_stack_free_block(block);
@@ -984,12 +901,10 @@ void syn_stack_free_all(synblock_T *block)
}
}
-/*
- * Allocate the syntax state stack for syn_buf when needed.
- * If the number of entries in b_sst_array[] is much too big or a bit too
- * small, reallocate it.
- * Also used to allocate b_sst_array[] for the first time.
- */
+// Allocate the syntax state stack for syn_buf when needed.
+// If the number of entries in b_sst_array[] is much too big or a bit too
+// small, reallocate it.
+// Also used to allocate b_sst_array[] for the first time.
static void syn_stack_alloc(void)
{
synstate_T *to, *from;
@@ -1056,12 +971,10 @@ static void syn_stack_alloc(void)
}
}
-/*
- * Check for changes in a buffer to affect stored syntax states. Uses the
- * b_mod_* fields.
- * Called from update_screen(), before screen is being updated, once for each
- * displayed buffer.
- */
+// Check for changes in a buffer to affect stored syntax states. Uses the
+// b_mod_* fields.
+// Called from update_screen(), before screen is being updated, once for each
+// displayed buffer.
void syn_stack_apply_changes(buf_T *buf)
{
syn_stack_apply_changes_block(&buf->b_s, buf);
@@ -1137,11 +1050,9 @@ static bool syn_stack_cleanup(void)
dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1;
}
- /*
- * Go through the list to find the "tick" for the oldest entry that can
- * be removed. Set "above" when the "tick" for the oldest entry is above
- * "b_sst_lasttick" (the display tick wraps around).
- */
+ // Go through the list to find the "tick" for the oldest entry that can
+ // be removed. Set "above" when the "tick" for the oldest entry is above
+ // "b_sst_lasttick" (the display tick wraps around).
tick = syn_block->b_sst_lasttick;
bool above = false;
prev = syn_block->b_sst_first;
@@ -1158,10 +1069,8 @@ static bool syn_stack_cleanup(void)
}
}
- /*
- * Go through the list to make the entries for the oldest tick at an
- * interval of several lines.
- */
+ // Go through the list to make the entries for the oldest tick at an
+ // interval of several lines.
prev = syn_block->b_sst_first;
for (p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) {
if (p->sst_tick == tick && prev->sst_lnum + dist > p->sst_lnum) {
@@ -1175,10 +1084,8 @@ static bool syn_stack_cleanup(void)
return retval;
}
-/*
- * Free the allocated memory for a syn_state item.
- * Move the entry into the free list.
- */
+// Free the allocated memory for a syn_state item.
+// Move the entry into the free list.
static void syn_stack_free_entry(synblock_T *block, synstate_T *p)
{
clear_syn_state(p);
@@ -1187,10 +1094,8 @@ static void syn_stack_free_entry(synblock_T *block, synstate_T *p)
block->b_sst_freecount++;
}
-/*
- * Find an entry in the list of state stacks at or before "lnum".
- * Returns NULL when there is no entry or the first entry is after "lnum".
- */
+// Find an entry in the list of state stacks at or before "lnum".
+// Returns NULL when there is no entry or the first entry is after "lnum".
static synstate_T *syn_stack_find_entry(linenr_T lnum)
{
synstate_T *p, *prev;
@@ -1207,10 +1112,8 @@ static synstate_T *syn_stack_find_entry(linenr_T lnum)
return prev;
}
-/*
- * Try saving the current state in b_sst_array[].
- * The current state must be valid for the start of the current_lnum line!
- */
+// Try saving the current state in b_sst_array[].
+// The current state must be valid for the start of the current_lnum line!
static synstate_T *store_current_state(void)
{
int i;
@@ -1219,10 +1122,8 @@ static synstate_T *store_current_state(void)
stateitem_T *cur_si;
synstate_T *sp = syn_stack_find_entry(current_lnum);
- /*
- * If the current state contains a start or end pattern that continues
- * from the previous line, we can't use it. Don't store it then.
- */
+ // If the current state contains a start or end pattern that continues
+ // from the previous line, we can't use it. Don't store it then.
for (i = current_state.ga_len - 1; i >= 0; i--) {
cur_si = &CUR_STATE(i);
if (cur_si->si_h_startpos.lnum >= current_lnum
@@ -1254,9 +1155,7 @@ static synstate_T *store_current_state(void)
sp = NULL;
}
} else if (sp == NULL || sp->sst_lnum != current_lnum) {
- /*
- * Add a new entry
- */
+ // Add a new entry
// If no free items, cleanup the array first.
if (syn_block->b_sst_freecount == 0) {
(void)syn_stack_cleanup();
@@ -1316,9 +1215,7 @@ static synstate_T *store_current_state(void)
return sp;
}
-/*
- * Copy a state stack from "from" in b_sst_array[] to current_state;
- */
+// Copy a state stack from "from" in b_sst_array[] to current_state;
static void load_current_state(synstate_T *from)
{
int i;
@@ -1422,16 +1319,14 @@ static bool syn_stack_equal(synstate_T *sp)
return i < 0 ? true : false;
}
-/*
- * We stop parsing syntax above line "lnum". If the stored state at or below
- * this line depended on a change before it, it now depends on the line below
- * the last parsed line.
- * The window looks like this:
- * line which changed
- * displayed line
- * displayed line
- * lnum -> line below window
- */
+// We stop parsing syntax above line "lnum". If the stored state at or below
+// this line depended on a change before it, it now depends on the line below
+// the last parsed line.
+// The window looks like this:
+// line which changed
+// displayed line
+// displayed line
+// lnum -> line below window
void syntax_end_parsing(linenr_T lnum)
{
synstate_T *sp;
@@ -1446,9 +1341,8 @@ void syntax_end_parsing(linenr_T lnum)
}
}
-/*
- * End of handling of the state stack.
- ****************************************/
+// End of handling of the state stack.
+// **************************************
static void invalidate_current_state(void)
{
@@ -1473,33 +1367,25 @@ bool syntax_check_changed(linenr_T lnum)
bool retval = true;
synstate_T *sp;
- /*
- * Check the state stack when:
- * - lnum is just below the previously syntaxed line.
- * - lnum is not before the lines with saved states.
- * - lnum is not past the lines with saved states.
- * - lnum is at or before the last changed line.
- */
+ // Check the state stack when:
+ // - lnum is just below the previously syntaxed line.
+ // - lnum is not before the lines with saved states.
+ // - lnum is not past the lines with saved states.
+ // - lnum is at or before the last changed line.
if (VALID_STATE(&current_state) && lnum == current_lnum + 1) {
sp = syn_stack_find_entry(lnum);
if (sp != NULL && sp->sst_lnum == lnum) {
- /*
- * finish the previous line (needed when not all of the line was
- * drawn)
- */
+ // finish the previous line (needed when not all of the line was
+ // drawn)
(void)syn_finish_line(false);
- /*
- * Compare the current state with the previously saved state of
- * the line.
- */
+ // Compare the current state with the previously saved state of
+ // the line.
if (syn_stack_equal(sp)) {
retval = false;
}
- /*
- * Store the current state in b_sst_array[] for later use.
- */
+ // Store the current state in b_sst_array[] for later use.
current_lnum++;
(void)store_current_state();
}
@@ -1587,9 +1473,7 @@ int get_syntax_attr(const colnr_T col, bool *const can_spell, const bool keep_st
validate_current_state();
}
- /*
- * Skip from the current column to "col", get the attributes for "col".
- */
+ // Skip from the current column to "col", get the attributes for "col".
while (current_col <= col) {
attr = syn_current_attr(false, true, can_spell,
current_col == col ? keep_state : false);
@@ -1638,9 +1522,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
// Do try matching with an empty line (could be the start of a region).
line = (char_u *)syn_getcurline();
if (line[current_col] == NUL && current_col != 0) {
- /*
- * If we found a match after the last column, use it.
- */
+ // If we found a match after the last column, use it.
if (next_match_idx >= 0 && next_match_col >= (int)current_col
&& next_match_col != MAXCOL) {
(void)push_next_match();
@@ -1657,11 +1539,9 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
current_state_stored = false;
}
- /*
- * When in the previous column there was a match but it could not be used
- * (empty match or already matched in this column) need to try again in
- * the next column.
- */
+ // When in the previous column there was a match but it could not be used
+ // (empty match or already matched in this column) need to try again in
+ // the next column.
if (try_next_column) {
next_match_idx = -1;
try_next_column = false;
@@ -1679,23 +1559,19 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
// use syntax iskeyword option
save_chartab((char *)buf_chartab);
- /*
- * Repeat matching keywords and patterns, to find contained items at the
- * same column. This stops when there are no extra matches at the current
- * column.
- */
+ // Repeat matching keywords and patterns, to find contained items at the
+ // same column. This stops when there are no extra matches at the current
+ // column.
do {
found_match = false;
keep_next_list = false;
int syn_id = 0;
- /*
- * 1. Check for a current state.
- * Only when there is no current state, or if the current state may
- * contain other things, we need to check for keywords and patterns.
- * Always need to check for contained items if some item has the
- * "containedin" argument (takes extra time!).
- */
+ // 1. Check for a current state.
+ // Only when there is no current state, or if the current state may
+ // contain other things, we need to check for keywords and patterns.
+ // Always need to check for contained items if some item has the
+ // "containedin" argument (takes extra time!).
if (current_state.ga_len) {
cur_si = &CUR_STATE(current_state.ga_len - 1);
} else {
@@ -1709,9 +1585,10 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
if (do_keywords) {
line = (char_u *)syn_getcurline();
const char_u *cur_pos = line + current_col;
- if (vim_iswordp_buf(cur_pos, syn_buf)
+ if (vim_iswordp_buf((char *)cur_pos, syn_buf)
&& (current_col == 0
- || !vim_iswordp_buf(cur_pos - 1 - utf_head_off((char *)line, (char *)cur_pos - 1),
+ || !vim_iswordp_buf((char *)cur_pos - 1 -
+ utf_head_off((char *)line, (char *)cur_pos - 1),
syn_buf))) {
syn_id = check_keyword_id((char *)line, (int)current_col, &endcol, &flags,
&next_list, cur_si, &cchar);
@@ -1757,21 +1634,15 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
}
}
- /*
- * 3. Check for patterns (only if no keyword found).
- */
+ // 3. Check for patterns (only if no keyword found).
if (syn_id == 0 && syn_block->b_syn_patterns.ga_len) {
- /*
- * If we didn't check for a match yet, or we are past it, check
- * for any match with a pattern.
- */
+ // If we didn't check for a match yet, or we are past it, check
+ // for any match with a pattern.
if (next_match_idx < 0 || next_match_col < (int)current_col) {
- /*
- * Check all relevant patterns for a match at this
- * position. This is complicated, because matching with a
- * pattern takes quite a bit of time, thus we want to
- * avoid doing it when it's not needed.
- */
+ // Check all relevant patterns for a match at this
+ // position. This is complicated, because matching with a
+ // pattern takes quite a bit of time, thus we want to
+ // avoid doing it when it's not needed.
next_match_idx = 0; // no match in this line yet
next_match_col = MAXCOL;
for (int idx = syn_block->b_syn_patterns.ga_len; --idx >= 0;) {
@@ -1813,9 +1684,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
continue;
}
- /*
- * Compute the first column of the match.
- */
+ // Compute the first column of the match.
syn_add_start_off(&pos, &regmatch,
spp, SPO_MS_OFF, -1);
if (pos.lnum > current_lnum) {
@@ -1830,19 +1699,15 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
// matches in the current line
spp->sp_startcol = startcol;
- /*
- * If a previously found match starts at a lower
- * column number, don't use this one.
- */
+ // If a previously found match starts at a lower
+ // column number, don't use this one.
if (startcol >= next_match_col) {
continue;
}
- /*
- * If we matched this pattern at this position
- * before, skip it. Must retry in the next
- * column, because it may match from there.
- */
+ // If we matched this pattern at this position
+ // before, skip it. Must retry in the next
+ // column, because it may match from there.
if (did_match_already(idx, &zero_width_next_ga)) {
try_next_column = true;
continue;
@@ -1860,10 +1725,8 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
syn_add_end_off(&eos_pos, &regmatch,
spp, SPO_RS_OFF, 0);
- /*
- * Grab the external submatches before they get
- * overwritten. Reference count doesn't change.
- */
+ // Grab the external submatches before they get
+ // overwritten. Reference count doesn't change.
unref_extmatch(cur_extmatch);
cur_extmatch = re_extmatch_out;
re_extmatch_out = NULL;
@@ -1874,12 +1737,10 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
end_idx = 0;
hl_endpos.lnum = 0;
- /*
- * For a "oneline" the end must be found in the
- * same line too. Search for it after the end of
- * the match with the start pattern. Set the
- * resulting end positions at the same time.
- */
+ // For a "oneline" the end must be found in the
+ // same line too. Search for it after the end of
+ // the match with the start pattern. Set the
+ // resulting end positions at the same time.
if (spp->sp_type == SPTYPE_START
&& (spp->sp_flags & HL_ONELINE)) {
lpos_T startpos;
@@ -1890,23 +1751,18 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
if (endpos.lnum == 0) {
continue; // not found
}
- }
- /*
- * For a "match" the size must be > 0 after the
- * end offset needs has been added. Except when
- * syncing.
- */
- else if (spp->sp_type == SPTYPE_MATCH) {
+ } else if (spp->sp_type == SPTYPE_MATCH) {
+ // For a "match" the size must be > 0 after the
+ // end offset needs has been added. Except when
+ // syncing.
syn_add_end_off(&hl_endpos, &regmatch, spp,
SPO_HE_OFF, 0);
syn_add_end_off(&endpos, &regmatch, spp,
SPO_ME_OFF, 0);
if (endpos.lnum == current_lnum
&& (int)endpos.col + syncing < startcol) {
- /*
- * If an empty string is matched, may need
- * to try matching again at next column.
- */
+ // If an empty string is matched, may need
+ // to try matching again at next column.
if (regmatch.startpos[0].col == regmatch.endpos[0].col) {
try_next_column = true;
}
@@ -1914,9 +1770,8 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
}
}
- /*
- * keep the best match so far in next_match_*
- */
+ // keep the best match so far in next_match_*
+
// Highlighting must start after startpos and end
// before endpos.
if (hl_startpos.lnum == current_lnum
@@ -1941,9 +1796,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
}
}
- /*
- * If we found a match at the current column, use it.
- */
+ // If we found a match at the current column, use it.
if (next_match_idx >= 0 && next_match_col == (int)current_col) {
synpat_T *lspp;
@@ -1971,9 +1824,7 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
}
}
- /*
- * Handle searching for nextgroup match.
- */
+ // Handle searching for nextgroup match.
if (current_next_list != NULL && !keep_next_list) {
// If a nextgroup was not found, continue looking for one if:
// - this is an empty line and the "skipempty" option was given
@@ -1988,14 +1839,12 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
}
}
- /*
- * If a nextgroup was found: Use it, and continue looking for
- * contained matches.
- * If a nextgroup was not found: Continue looking for a normal
- * match.
- * When did set current_next_list for a zero-width item and no
- * match was found don't loop (would get stuck).
- */
+ // If a nextgroup was found: Use it, and continue looking for
+ // contained matches.
+ // If a nextgroup was not found: Continue looking for a normal
+ // match.
+ // When did set current_next_list for a zero-width item and no
+ // match was found don't loop (would get stuck).
current_next_list = NULL;
next_match_idx = -1;
if (!zero_width_next_list) {
@@ -2006,10 +1855,8 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
restore_chartab((char *)buf_chartab);
- /*
- * Use attributes from the current state, if within its highlighting.
- * If not, use attributes from the current-but-one state, etc.
- */
+ // Use attributes from the current state, if within its highlighting.
+ // If not, use attributes from the current-but-one state, etc.
current_attr = 0;
current_id = 0;
current_trans_id = 0;
@@ -2075,14 +1922,12 @@ static int syn_current_attr(const bool syncing, const bool displaying, bool *con
}
}
- /*
- * Check for end of current state (and the states before it) at the
- * next column. Don't do this for syncing, because we would miss a
- * single character match.
- * First check if the current state ends at the current column. It
- * may be for an empty match and a containing item might end in the
- * current column.
- */
+ // Check for end of current state (and the states before it) at the
+ // next column. Don't do this for syncing, because we would miss a
+ // single character match.
+ // First check if the current state ends at the current column. It
+ // may be for an empty match and a containing item might end in the
+ // current column.
if (!syncing && !keep_state) {
check_state_ends();
if (!GA_EMPTY(&current_state)
@@ -2142,9 +1987,7 @@ static bool did_match_already(int idx, garray_T *gap)
return false;
}
-/*
- * Push the next match onto the stack.
- */
+// Push the next match onto the stack.
static stateitem_T *push_next_match(void)
{
stateitem_T *cur_si;
@@ -2153,15 +1996,11 @@ static stateitem_T *push_next_match(void)
spp = &(SYN_ITEMS(syn_block)[next_match_idx]);
- /*
- * Push the item in current_state stack;
- */
+ // Push the item in current_state stack;
push_current_state(next_match_idx);
{
- /*
- * If it's a start-skip-end type that crosses lines, figure out how
- * much it continues in this line. Otherwise just fill in the length.
- */
+ // If it's a start-skip-end type that crosses lines, figure out how
+ // much it continues in this line. Otherwise just fill in the length.
cur_si = &CUR_STATE(current_state.ga_len - 1);
cur_si->si_h_startpos = next_match_h_startpos;
cur_si->si_m_startcol = current_col;
@@ -2194,10 +2033,8 @@ static stateitem_T *push_next_match(void)
update_si_attr(current_state.ga_len - 1);
save_flags = cur_si->si_flags & (HL_CONCEAL | HL_CONCEALENDS);
- /*
- * If the start pattern has another highlight group, push another item
- * on the stack for the start pattern.
- */
+ // If the start pattern has another highlight group, push another item
+ // on the stack for the start pattern.
if (spp->sp_type == SPTYPE_START && spp->sp_syn_match_id != 0) {
push_current_state(next_match_idx);
cur_si = &CUR_STATE(current_state.ga_len - 1);
@@ -2225,9 +2062,7 @@ static stateitem_T *push_next_match(void)
return cur_si;
}
-/*
- * Check for end of current state (and the states before it).
- */
+// Check for end of current state (and the states before it).
static void check_state_ends(void)
{
stateitem_T *cur_si;
@@ -2239,12 +2074,10 @@ static void check_state_ends(void)
&& (cur_si->si_m_endpos.lnum < current_lnum
|| (cur_si->si_m_endpos.lnum == current_lnum
&& cur_si->si_m_endpos.col <= current_col))) {
- /*
- * If there is an end pattern group ID, highlight the end pattern
- * now. No need to pop the current item from the stack.
- * Only do this if the end pattern continues beyond the current
- * position.
- */
+ // If there is an end pattern group ID, highlight the end pattern
+ // now. No need to pop the current item from the stack.
+ // Only do this if the end pattern continues beyond the current
+ // position.
if (cur_si->si_end_idx
&& (cur_si->si_eoe_pos.lnum > current_lnum
|| (cur_si->si_eoe_pos.lnum == current_lnum
@@ -2321,10 +2154,8 @@ static void check_state_ends(void)
}
}
-/*
- * Update an entry in the current_state stack for a match or region. This
- * fills in si_attr, si_next_list and si_cont_list.
- */
+// Update an entry in the current_state stack for a match or region. This
+// fills in si_attr, si_next_list and si_cont_list.
static void update_si_attr(int idx)
{
stateitem_T *sip = &CUR_STATE(idx);
@@ -2349,11 +2180,9 @@ static void update_si_attr(int idx)
sip->si_cont_list = spp->sp_cont_list;
}
- /*
- * For transparent items, take attr from outer item.
- * Also take cont_list, if there is none.
- * Don't do this for the matchgroup of a start or end pattern.
- */
+ // For transparent items, take attr from outer item.
+ // Also take cont_list, if there is none.
+ // Don't do this for the matchgroup of a start or end pattern.
if ((spp->sp_flags & HL_TRANSP) && !(sip->si_flags & HL_MATCH)) {
if (idx == 0) {
sip->si_attr = 0;
@@ -2372,10 +2201,8 @@ static void update_si_attr(int idx)
}
}
-/*
- * Check the current stack for patterns with "keepend" flag.
- * Propagate the match-end to contained items, until a "skipend" item is found.
- */
+// Check the current stack for patterns with "keepend" flag.
+// Propagate the match-end to contained items, until a "skipend" item is found.
static void check_keepend(void)
{
int i;
@@ -2383,19 +2210,15 @@ static void check_keepend(void)
lpos_T maxpos_h;
stateitem_T *sip;
- /*
- * This check can consume a lot of time; only do it from the level where
- * there really is a keepend.
- */
+ // This check can consume a lot of time; only do it from the level where
+ // there really is a keepend.
if (keepend_level < 0) {
return;
}
- /*
- * Find the last index of an "extend" item. "keepend" items before that
- * won't do anything. If there is no "extend" item "i" will be
- * "keepend_level" and all "keepend" items will work normally.
- */
+ // Find the last index of an "extend" item. "keepend" items before that
+ // won't do anything. If there is no "extend" item "i" will be
+ // "keepend_level" and all "keepend" items will work normally.
for (i = current_state.ga_len - 1; i > keepend_level; i--) {
if (CUR_STATE(i).si_flags & HL_EXTEND) {
break;
@@ -2455,10 +2278,8 @@ static void update_si_end(stateitem_T *sip, int startcol, bool force)
return;
}
- /*
- * We need to find the end of the region. It may continue in the next
- * line.
- */
+ // We need to find the end of the region. It may continue in the next
+ // line.
int end_idx = 0;
lpos_T startpos = {
.lnum = current_lnum,
@@ -2491,10 +2312,8 @@ static void update_si_end(stateitem_T *sip, int startcol, bool force)
}
}
-/*
- * Add a new state to the current state stack.
- * It is cleared and the index set to "idx".
- */
+// Add a new state to the current state stack.
+// It is cleared and the index set to "idx".
static void push_current_state(int idx)
{
stateitem_T *p = GA_APPEND_VIA_PTR(stateitem_T, &current_state);
@@ -2502,9 +2321,7 @@ static void push_current_state(int idx)
p->si_idx = idx;
}
-/*
- * Remove a state from the current_state stack.
- */
+// Remove a state from the current_state stack.
static void pop_current_state(void)
{
if (!GA_EMPTY(&current_state)) {
@@ -2555,20 +2372,16 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
return;
}
- /*
- * Check for being called with a START pattern.
- * Can happen with a match that continues to the next line, because it
- * contained a region.
- */
+ // Check for being called with a START pattern.
+ // Can happen with a match that continues to the next line, because it
+ // contained a region.
spp = &(SYN_ITEMS(syn_block)[idx]);
if (spp->sp_type != SPTYPE_START) {
*hl_endpos = *startpos;
return;
}
- /*
- * Find the SKIP or first END pattern after the last START pattern.
- */
+ // Find the SKIP or first END pattern after the last START pattern.
for (;;) {
spp = &(SYN_ITEMS(syn_block)[idx]);
if (spp->sp_type != SPTYPE_START) {
@@ -2577,9 +2390,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
idx++;
}
- /*
- * Lookup the SKIP pattern (if present)
- */
+ // Lookup the SKIP pattern (if present)
if (spp->sp_type == SPTYPE_SKIP) {
spp_skip = spp;
idx++;
@@ -2599,9 +2410,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
save_chartab((char *)buf_chartab);
for (;;) {
- /*
- * Find end pattern that matches first after "matchcol".
- */
+ // Find end pattern that matches first after "matchcol".
best_idx = -1;
for (idx = start_idx; idx < syn_block->b_syn_patterns.ga_len; idx++) {
int lc_col = matchcol;
@@ -2630,18 +2439,14 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
}
}
- /*
- * If all end patterns have been tried, and there is no match, the
- * item continues until end-of-line.
- */
+ // If all end patterns have been tried, and there is no match, the
+ // item continues until end-of-line.
if (best_idx == -1) {
break;
}
- /*
- * If the skip pattern matches before the end pattern,
- * continue searching after the skip pattern.
- */
+ // If the skip pattern matches before the end pattern,
+ // continue searching after the skip pattern.
if (spp_skip != NULL) {
int lc_col = matchcol - spp_skip->sp_offsets[SPO_LC_OFF];
@@ -2663,7 +2468,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
break;
}
- line = ml_get_buf(syn_buf, startpos->lnum, false);
+ line = (char_u *)ml_get_buf(syn_buf, startpos->lnum, false);
int line_len = (int)STRLEN(line);
// take care of an empty match or negative offset
@@ -2687,10 +2492,8 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
}
}
- /*
- * Match from start pattern to end pattern.
- * Correct for match and highlight offset of end pattern.
- */
+ // Match from start pattern to end pattern.
+ // Correct for match and highlight offset of end pattern.
spp = &(SYN_ITEMS(syn_block)[best_idx]);
syn_add_end_off(m_endpos, &best_regmatch, spp, SPO_ME_OFF, 1);
// can't end before the start
@@ -2707,9 +2510,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
// can't end after the match
limit_pos(end_endpos, m_endpos);
- /*
- * If the end group is highlighted differently, adjust the pointers.
- */
+ // If the end group is highlighted differently, adjust the pointers.
if (spp->sp_syn_match_id != spp->sp_syn.id && spp->sp_syn_match_id != 0) {
*end_idx = best_idx;
if (spp->sp_off_flags & (1 << (SPO_RE_OFF + SPO_COUNT))) {
@@ -2754,9 +2555,7 @@ static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_
re_extmatch_in = NULL;
}
-/*
- * Limit "pos" not to be after "limit".
- */
+// Limit "pos" not to be after "limit".
static void limit_pos(lpos_T *pos, lpos_T *limit)
{
if (pos->lnum > limit->lnum) {
@@ -2766,9 +2565,7 @@ static void limit_pos(lpos_T *pos, lpos_T *limit)
}
}
-/*
- * Limit "pos" not to be after "limit", unless pos->lnum is zero.
- */
+// Limit "pos" not to be after "limit", unless pos->lnum is zero.
static void limit_pos_zero(lpos_T *pos, lpos_T *limit)
{
if (pos->lnum == 0) {
@@ -2807,7 +2604,7 @@ static void syn_add_end_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *spp
if (result->lnum > syn_buf->b_ml.ml_line_count) {
col = 0;
} else if (off != 0) {
- base = ml_get_buf(syn_buf, result->lnum, false);
+ base = (char_u *)ml_get_buf(syn_buf, result->lnum, false);
p = base + col;
if (off > 0) {
while (off-- > 0 && *p != NUL) {
@@ -2852,7 +2649,7 @@ static void syn_add_start_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *s
col = (int)STRLEN(ml_get_buf(syn_buf, result->lnum, false));
}
if (off != 0) {
- base = ml_get_buf(syn_buf, result->lnum, false);
+ base = (char_u *)ml_get_buf(syn_buf, result->lnum, false);
p = base + col;
if (off > 0) {
while (off-- && *p != NUL) {
@@ -2871,13 +2668,11 @@ static void syn_add_start_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *s
/// Get current line in syntax buffer.
static char *syn_getcurline(void)
{
- return (char *)ml_get_buf(syn_buf, current_lnum, false);
+ return ml_get_buf(syn_buf, current_lnum, false);
}
-/*
- * Call vim_regexec() to find a match with "rmp" in "syn_buf".
- * Returns true when there is a match.
- */
+// Call vim_regexec() to find a match with "rmp" in "syn_buf".
+// Returns true when there is a match.
static int syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T *st)
{
int timed_out = 0;
@@ -2942,7 +2737,7 @@ static int check_keyword_id(char *const line, const int startcol, int *const end
int kwlen = 0;
do {
kwlen += utfc_ptr2len(kwp + kwlen);
- } while (vim_iswordp_buf((char_u *)kwp + kwlen, syn_buf));
+ } while (vim_iswordp_buf(kwp + kwlen, syn_buf));
if (kwlen > MAXKEYWLEN) {
return 0;
@@ -3000,9 +2795,7 @@ static keyentry_T *match_keyword(char *keyword, hashtab_T *ht, stateitem_T *cur_
return NULL;
}
-/*
- * Handle ":syntax conceal" command.
- */
+// Handle ":syntax conceal" command.
static void syn_cmd_conceal(exarg_T *eap, int syncing)
{
char_u *arg = (char_u *)eap->arg;
@@ -3170,9 +2963,7 @@ static void syn_cmd_iskeyword(exarg_T *eap, int syncing)
redraw_later(curwin, UPD_NOT_VALID);
}
-/*
- * Clear all syntax info for one buffer.
- */
+// Clear all syntax info for one buffer.
void syntax_clear(synblock_T *block)
{
block->b_syn_error = false; // clear previous error
@@ -3220,9 +3011,7 @@ void syntax_clear(synblock_T *block)
running_syn_inc_tag = 0;
}
-/*
- * Get rid of ownsyntax for window "wp".
- */
+// Get rid of ownsyntax for window "wp".
void reset_synblock(win_T *wp)
{
if (wp->w_s != &wp->w_buffer->b_s) {
@@ -3232,9 +3021,7 @@ void reset_synblock(win_T *wp)
}
}
-/*
- * Clear syncing info for one buffer.
- */
+// Clear syncing info for one buffer.
static void syntax_sync_clear(void)
{
// free the syntax patterns
@@ -3257,9 +3044,7 @@ static void syntax_sync_clear(void)
syn_stack_free_all(curwin->w_s); // Need to recompute all syntax.
}
-/*
- * Remove one pattern from the buffer's pattern list.
- */
+// Remove one pattern from the buffer's pattern list.
static void syn_remove_pattern(synblock_T *block, int idx)
{
synpat_T *spp;
@@ -3273,10 +3058,8 @@ static void syn_remove_pattern(synblock_T *block, int idx)
block->b_syn_patterns.ga_len--;
}
-/*
- * Clear and free one syntax pattern. When clearing all, must be called from
- * last to first!
- */
+// Clear and free one syntax pattern. When clearing all, must be called from
+// last to first!
static void syn_clear_pattern(synblock_T *block, int i)
{
xfree(SYN_ITEMS(block)[i].sp_pattern);
@@ -3289,9 +3072,7 @@ static void syn_clear_pattern(synblock_T *block, int i)
}
}
-/*
- * Clear and free one syntax cluster.
- */
+// Clear and free one syntax cluster.
static void syn_clear_cluster(synblock_T *block, int i)
{
xfree(SYN_CLSTR(block)[i].scl_name);
@@ -3311,20 +3092,16 @@ static void syn_cmd_clear(exarg_T *eap, int syncing)
return;
}
- /*
- * We have to disable this within ":syn include @group filename",
- * because otherwise @group would get deleted.
- * Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn
- * clear".
- */
+ // We have to disable this within ":syn include @group filename",
+ // because otherwise @group would get deleted.
+ // Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn
+ // clear".
if (curwin->w_s->b_syn_topgrp != 0) {
return;
}
if (ends_excmd(*arg)) {
- /*
- * No argument: Clear all syntax items.
- */
+ // No argument: Clear all syntax items.
if (syncing) {
syntax_sync_clear();
} else {
@@ -3335,9 +3112,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing)
do_unlet(S_LEN("w:current_syntax"), true);
}
} else {
- /*
- * Clear the group IDs that are in the argument.
- */
+ // Clear the group IDs that are in the argument.
while (!ends_excmd(*arg)) {
arg_end = skiptowhite(arg);
if (*arg == '@') {
@@ -3369,9 +3144,7 @@ static void syn_cmd_clear(exarg_T *eap, int syncing)
syn_stack_free_all(curwin->w_s); // Need to recompute all syntax.
}
-/*
- * Clear one syntax group for the current buffer.
- */
+// Clear one syntax group for the current buffer.
static void syn_clear_one(const int id, const bool syncing)
{
synpat_T *spp;
@@ -3392,18 +3165,14 @@ static void syn_clear_one(const int id, const bool syncing)
}
}
-/*
- * Handle ":syntax on" command.
- */
+// Handle ":syntax on" command.
static void syn_cmd_on(exarg_T *eap, int syncing)
{
syn_cmd_onoff(eap, "syntax");
}
-/*
- * Handle ":syntax reset" command.
- * It actually resets highlighting, not syntax.
- */
+// Handle ":syntax reset" command.
+// It actually resets highlighting, not syntax.
static void syn_cmd_reset(exarg_T *eap, int syncing)
{
eap->nextcmd = check_nextcmd(eap->arg);
@@ -3412,17 +3181,13 @@ static void syn_cmd_reset(exarg_T *eap, int syncing)
}
}
-/*
- * Handle ":syntax manual" command.
- */
+// Handle ":syntax manual" command.
static void syn_cmd_manual(exarg_T *eap, int syncing)
{
syn_cmd_onoff(eap, "manual");
}
-/*
- * Handle ":syntax off" command.
- */
+// Handle ":syntax off" command.
static void syn_cmd_off(exarg_T *eap, int syncing)
{
syn_cmd_onoff(eap, "nosyntax");
@@ -3502,9 +3267,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing)
msg_puts_title(_("\n--- Syntax items ---"));
}
if (ends_excmd(*arg)) {
- /*
- * No argument: List all group IDs and all syntax clusters.
- */
+ // No argument: List all group IDs and all syntax clusters.
for (int id = 1; id <= highlight_num_groups() && !got_int; id++) {
syn_list_one(id, syncing, false);
}
@@ -3512,9 +3275,7 @@ static void syn_cmd_list(exarg_T *eap, int syncing)
syn_list_cluster(id);
}
} else {
- /*
- * List the group IDs and syntax clusters that are in the argument.
- */
+ // List the group IDs and syntax clusters that are in the argument.
while (!ends_excmd(*arg) && !got_int) {
arg_end = (char_u *)skiptowhite((char *)arg);
if (*arg == '@') {
@@ -3692,9 +3453,7 @@ static void syn_list_flags(struct name_list *nlist, int flags, int attr)
}
}
-/*
- * List one syntax cluster, for ":syntax" or "syntax list syntax_name".
- */
+// List one syntax cluster, for ":syntax" or "syntax list syntax_name".
static void syn_list_cluster(int id)
{
int endcol = 15;
@@ -3772,14 +3531,14 @@ static void put_pattern(const char *const s, const int c, const synpat_T *const
msg_putchar(c);
// output the pattern, in between a char that is not in the pattern
- for (i = 0; vim_strchr((char *)spp->sp_pattern, sepchars[i]) != NULL;) {
+ for (i = 0; vim_strchr(spp->sp_pattern, sepchars[i]) != NULL;) {
if (sepchars[++i] == NUL) {
i = 0; // no good char found, just use the first one
break;
}
}
msg_putchar(sepchars[i]);
- msg_outtrans((char *)spp->sp_pattern);
+ msg_outtrans(spp->sp_pattern);
msg_putchar(sepchars[i]);
// output any pattern options
@@ -3938,9 +3697,7 @@ static void syn_clear_keyword(int id, hashtab_T *ht)
hash_unlock(ht);
}
-/*
- * Clear a whole keyword table.
- */
+// Clear a whole keyword table.
static void clear_keywtab(hashtab_T *ht)
{
hashitem_T *hi;
@@ -4048,7 +3805,7 @@ static char *get_group_name(char *arg, char **name_end)
/// Return NULL for any error;
static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, int skip)
{
- char_u *gname_start, *gname;
+ char *gname_start, *gname;
int syn_id;
int len = 0;
char *p;
@@ -4087,11 +3844,9 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i
}
for (;;) {
- /*
- * This is used very often when a large number of keywords is defined.
- * Need to skip quickly when no option name is found.
- * Also avoid tolower(), it's slow.
- */
+ // This is used very often when a large number of keywords is defined.
+ // Need to skip quickly when no option name is found.
+ // Also avoid tolower(), it's slow.
if (strchr(first_letters, *arg) == NULL) {
break;
}
@@ -4157,16 +3912,16 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i
emsg(_("E393: group[t]here not accepted here"));
return NULL;
}
- gname_start = (char_u *)arg;
+ gname_start = arg;
arg = skiptowhite(arg);
- if (gname_start == (char_u *)arg) {
+ if (gname_start == arg) {
return NULL;
}
- gname = vim_strnsave(gname_start, (size_t)((char_u *)arg - gname_start));
- if (STRCMP(gname, "NONE") == 0) {
+ gname = xstrnsave(gname_start, (size_t)(arg - gname_start));
+ if (strcmp(gname, "NONE") == 0) {
*opt->sync_idx = NONE_IDX;
} else {
- syn_id = syn_name2id((char *)gname);
+ syn_id = syn_name2id(gname);
int i;
for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0;) {
if (SYN_ITEMS(curwin->w_s)[i].sp_syn.id == syn_id
@@ -4195,11 +3950,9 @@ static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, i
return arg;
}
-/*
- * Adjustments to syntax item when declared in a ":syn include"'d file.
- * Set the contained flag, and if the item is not already contained, add it
- * to the specified top-level group, if any.
- */
+// Adjustments to syntax item when declared in a ":syn include"'d file.
+// Set the contained flag, and if the item is not already contained, add it
+// to the specified top-level group, if any.
static void syn_incl_toplevel(int id, int *flagsp)
{
if ((*flagsp & HL_CONTAINED) || curwin->w_s->b_syn_topgrp == 0) {
@@ -4218,9 +3971,7 @@ static void syn_incl_toplevel(int id, int *flagsp)
}
}
-/*
- * Handle ":syntax include [@{group-name}] filename" command.
- */
+// Handle ":syntax include [@{group-name}] filename" command.
static void syn_cmd_include(exarg_T *eap, int syncing)
{
char *arg = eap->arg;
@@ -4252,10 +4003,8 @@ static void syn_cmd_include(exarg_T *eap, int syncing)
eap->arg = rest;
}
- /*
- * Everything that's left, up to the next command, should be the
- * filename to include.
- */
+ // Everything that's left, up to the next command, should be the
+ // filename to include.
eap->argt |= (EX_XFILE | EX_NOSPC);
separate_nextcmd(eap);
if (*eap->arg == '<' || *eap->arg == '$' || path_is_absolute((char_u *)eap->arg)) {
@@ -4271,10 +4020,8 @@ static void syn_cmd_include(exarg_T *eap, int syncing)
}
}
- /*
- * Save and restore the existing top-level grouplist id and ":syn
- * include" tag around the actual inclusion.
- */
+ // Save and restore the existing top-level grouplist id and ":syn
+ // include" tag around the actual inclusion.
if (running_syn_inc_tag >= MAX_SYN_INC_TAG) {
emsg(_("E847: Too many syntax includes"));
return;
@@ -4292,9 +4039,7 @@ static void syn_cmd_include(exarg_T *eap, int syncing)
current_syn_inc_tag = prev_syn_inc_tag;
}
-/*
- * Handle ":syntax keyword {group-name} [{option}] keyword .." command.
- */
+// Handle ":syntax keyword {group-name} [{option}] keyword .." command.
static void syn_cmd_keyword(exarg_T *eap, int syncing)
{
char *arg = eap->arg;
@@ -4443,18 +4188,14 @@ static void syn_cmd_match(exarg_T *eap, int syncing)
rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip);
if (rest != NULL) { // all arguments are valid
- /*
- * Check for trailing command and illegal trailing arguments.
- */
+ // Check for trailing command and illegal trailing arguments.
eap->nextcmd = check_nextcmd(rest);
if (!ends_excmd(*rest) || eap->skip) {
rest = NULL;
} else {
if ((syn_id = syn_check_group(arg, (size_t)(group_name_end - arg))) != 0) {
syn_incl_toplevel(syn_id, &syn_opt_arg.flags);
- /*
- * Store the pattern in the syn_items list
- */
+ // Store the pattern in the syn_items list
synpat_T *spp = GA_APPEND_VIA_PTR(synpat_T,
&curwin->w_s->b_syn_patterns);
*spp = item;
@@ -4487,9 +4228,7 @@ static void syn_cmd_match(exarg_T *eap, int syncing)
}
}
- /*
- * Something failed, free the allocated memory.
- */
+ // Something failed, free the allocated memory.
vim_regfree(item.sp_prog);
xfree(item.sp_pattern);
xfree(syn_opt_arg.cont_list);
@@ -4566,14 +4305,14 @@ static void syn_cmd_region(exarg_T *eap, int syncing)
key_end++;
}
xfree(key);
- key = (char *)vim_strnsave_up((char_u *)rest, (size_t)(key_end - rest));
- if (STRCMP(key, "MATCHGROUP") == 0) {
+ key = vim_strnsave_up(rest, (size_t)(key_end - rest));
+ if (strcmp(key, "MATCHGROUP") == 0) {
item = ITEM_MATCHGROUP;
- } else if (STRCMP(key, "START") == 0) {
+ } else if (strcmp(key, "START") == 0) {
item = ITEM_START;
- } else if (STRCMP(key, "END") == 0) {
+ } else if (strcmp(key, "END") == 0) {
item = ITEM_END;
- } else if (STRCMP(key, "SKIP") == 0) {
+ } else if (strcmp(key, "SKIP") == 0) {
if (pat_ptrs[ITEM_SKIP] != NULL) { // One skip pattern allowed.
illegal = true;
break;
@@ -4607,11 +4346,9 @@ static void syn_cmd_region(exarg_T *eap, int syncing)
}
rest = skipwhite(p);
} else {
- /*
- * Allocate room for a syn_pattern, and link it in the list of
- * syn_patterns for this item, at the start (because the list is
- * used from end to start).
- */
+ // Allocate room for a syn_pattern, and link it in the list of
+ // syn_patterns for this item, at the start (because the list is
+ // used from end to start).
ppp = xmalloc(sizeof(struct pat_ptr));
ppp->pp_next = pat_ptrs[item];
pat_ptrs[item] = ppp;
@@ -4649,10 +4386,8 @@ static void syn_cmd_region(exarg_T *eap, int syncing)
}
if (rest != NULL) {
- /*
- * Check for trailing garbage or command.
- * If OK, add the item.
- */
+ // Check for trailing garbage or command.
+ // If OK, add the item.
eap->nextcmd = check_nextcmd(rest);
if (!ends_excmd(*rest) || eap->skip) {
rest = NULL;
@@ -4660,9 +4395,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing)
ga_grow(&(curwin->w_s->b_syn_patterns), pat_count);
if ((syn_id = syn_check_group(arg, (size_t)(group_name_end - arg))) != 0) {
syn_incl_toplevel(syn_id, &syn_opt_arg.flags);
- /*
- * Store the start/skip/end in the syn_items list
- */
+ // Store the start/skip/end in the syn_items list
int idx = curwin->w_s->b_syn_patterns.ga_len;
for (item = ITEM_START; item <= ITEM_END; item++) {
for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp->pp_next) {
@@ -4703,9 +4436,7 @@ static void syn_cmd_region(exarg_T *eap, int syncing)
}
}
- /*
- * Free the allocated memory.
- */
+ // Free the allocated memory.
for (item = ITEM_START; item <= ITEM_END; item++) {
for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp_next) {
if (!success && ppp->pp_synp != NULL) {
@@ -4749,9 +4480,7 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con
const int16_t *g2;
int16_t *clstr = NULL;
- /*
- * Handle degenerate cases.
- */
+ // Handle degenerate cases.
if (*clstr2 == NULL) {
return;
}
@@ -4787,13 +4516,9 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con
g2 = *clstr2;
int count = 0;
- /*
- * First, loop through the lists until one of them is empty.
- */
+ // First, loop through the lists until one of them is empty.
while (*g1 && *g2) {
- /*
- * We always want to add from the first list.
- */
+ // We always want to add from the first list.
if (*g1 < *g2) {
if (round == 2) {
clstr[count] = *g1;
@@ -4802,10 +4527,8 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con
g1++;
continue;
}
- /*
- * We only want to add from the second list if we're adding the
- * lists.
- */
+ // We only want to add from the second list if we're adding the
+ // lists.
if (list_op == CLUSTER_ADD) {
if (round == 2) {
clstr[count] = *g2;
@@ -4818,11 +4541,9 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con
g2++;
}
- /*
- * Now add the leftovers from whichever list didn't get finished
- * first. As before, we only want to add from the second list if
- * we're adding the lists.
- */
+ // Now add the leftovers from whichever list didn't get finished
+ // first. As before, we only want to add from the second list if
+ // we're adding the lists.
for (; *g1; g1++, count++) {
if (round == 2) {
clstr[count] = *g1;
@@ -4837,10 +4558,8 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con
}
if (round == 1) {
- /*
- * If the group ended up empty, we don't need to allocate any
- * space for it.
- */
+ // If the group ended up empty, we don't need to allocate any
+ // space for it.
if (count == 0) {
clstr = NULL;
break;
@@ -4850,9 +4569,7 @@ static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, con
}
}
- /*
- * Finally, put the new list in place.
- */
+ // Finally, put the new list in place.
xfree(*clstr1);
xfree(*clstr2);
*clstr1 = clstr;
@@ -4867,7 +4584,7 @@ static int syn_scl_name2id(char *name)
int i;
for (i = curwin->w_s->b_syn_clusters.ga_len; --i >= 0;) {
if (SYN_CLSTR(curwin->w_s)[i].scl_name_u != NULL
- && STRCMP(name_u, SYN_CLSTR(curwin->w_s)[i].scl_name_u) == 0) {
+ && strcmp(name_u, SYN_CLSTR(curwin->w_s)[i].scl_name_u) == 0) {
break;
}
}
@@ -4908,9 +4625,7 @@ static int syn_check_cluster(char *pp, int len)
/// @return 0 for failure.
static int syn_add_cluster(char *name)
{
- /*
- * First call for this growarray: init growing array.
- */
+ // First call for this growarray: init growing array.
if (curwin->w_s->b_syn_clusters.ga_data == NULL) {
curwin->w_s->b_syn_clusters.ga_itemsize = sizeof(syn_cluster_T);
ga_set_growsize(&curwin->w_s->b_syn_clusters, 10);
@@ -4927,7 +4642,7 @@ static int syn_add_cluster(char *name)
&curwin->w_s->b_syn_clusters);
CLEAR_POINTER(scp);
scp->scl_name = (char_u *)name;
- scp->scl_name_u = vim_strsave_up((char_u *)name);
+ scp->scl_name_u = (char *)vim_strsave_up((char_u *)name);
scp->scl_list = NULL;
if (STRICMP(name, "Spell") == 0) {
@@ -4940,10 +4655,8 @@ static int syn_add_cluster(char *name)
return len + SYNID_CLUSTER;
}
-/*
- * Handle ":syntax cluster {cluster-name} [contains={groupname},..]
- * [add={groupname},..] [remove={groupname},..]".
- */
+// Handle ":syntax cluster {cluster-name} [contains={groupname},..]
+// [add={groupname},..] [remove={groupname},..]".
static void syn_cmd_cluster(exarg_T *eap, int syncing)
{
char *arg = eap->arg;
@@ -5012,9 +4725,7 @@ static void syn_cmd_cluster(exarg_T *eap, int syncing)
}
}
-/*
- * On first call for current buffer: Init growing array.
- */
+// On first call for current buffer: Init growing array.
static void init_syn_patterns(void)
{
curwin->w_s->b_syn_patterns.ga_itemsize = sizeof(synpat_T);
@@ -5043,12 +4754,12 @@ static char *get_syn_pattern(char *arg, synpat_T *ci)
return NULL;
}
// store the pattern and compiled regexp program
- ci->sp_pattern = vim_strnsave((char_u *)arg + 1, (size_t)(end - arg) - 1);
+ ci->sp_pattern = xstrnsave(arg + 1, (size_t)(end - arg) - 1);
// Make 'cpoptions' empty, to avoid the 'l' flag
cpo_save = p_cpo;
p_cpo = empty_option;
- ci->sp_prog = vim_regcomp((char *)ci->sp_pattern, RE_MAGIC);
+ ci->sp_prog = vim_regcomp(ci->sp_pattern, RE_MAGIC);
p_cpo = cpo_save;
if (ci->sp_prog == NULL) {
@@ -5057,9 +4768,7 @@ static char *get_syn_pattern(char *arg, synpat_T *ci)
ci->sp_ic = curwin->w_s->b_syn_ic;
syn_clear_time(&ci->sp_time);
- /*
- * Check for a match, highlight or region offset.
- */
+ // Check for a match, highlight or region offset.
end++;
do {
for (idx = SPO_COUNT; --idx >= 0;) {
@@ -5137,8 +4846,8 @@ static void syn_cmd_sync(exarg_T *eap, int syncing)
arg_end = skiptowhite(arg_start);
next_arg = skipwhite(arg_end);
xfree(key);
- key = (char *)vim_strnsave_up((char_u *)arg_start, (size_t)(arg_end - arg_start));
- if (STRCMP(key, "CCOMMENT") == 0) {
+ key = vim_strnsave_up(arg_start, (size_t)(arg_end - arg_start));
+ if (strcmp(key, "CCOMMENT") == 0) {
if (!eap->skip) {
curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT;
}
@@ -5177,12 +4886,12 @@ static void syn_cmd_sync(exarg_T *eap, int syncing)
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;
@@ -5221,11 +4930,11 @@ 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 {
illegal = true;
@@ -5288,10 +4997,10 @@ static int get_id_list(char **const arg, const int keylen, int16_t **const list,
for (end = p; *end && !ascii_iswhite(*end) && *end != ','; end++) {}
char *const name = xmalloc((size_t)(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') {
semsg(_("E407: %s not allowed here"), name + 1);
failed = true;
@@ -5323,9 +5032,7 @@ static int get_id_list(char **const arg, const int keylen, int16_t **const list,
id = syn_check_cluster(name + 2, (int)(end - p - 1));
}
} else {
- /*
- * Handle full group name.
- */
+ // Handle full group name.
if (strpbrk(name + 1, "\\.*^$~[") == NULL) {
id = syn_check_group((name + 1), (size_t)(end - p));
} else {
@@ -5410,9 +5117,7 @@ static int get_id_list(char **const arg, const int keylen, int16_t **const list,
return OK;
}
-/*
- * Make a copy of an ID list.
- */
+// Make a copy of an ID list.
static int16_t *copy_id_list(const int16_t *const list)
{
if (list == NULL) {
@@ -5469,10 +5174,8 @@ static int in_id_list(stateitem_T *cur_si, int16_t *list, struct sp_syn *ssp, in
return false;
}
- /*
- * If list is ID_LIST_ALL, we are in a transparent item that isn't
- * inside anything. Only allow not-contained groups.
- */
+ // If list is ID_LIST_ALL, we are in a transparent item that isn't
+ // inside anything. Only allow not-contained groups.
if (list == ID_LIST_ALL) {
return !contained;
}
@@ -5504,9 +5207,7 @@ static int in_id_list(stateitem_T *cur_si, int16_t *list, struct sp_syn *ssp, in
retval = true;
}
- /*
- * Return "retval" if id is in the contains list.
- */
+ // Return "retval" if id is in the contains list.
while (item != 0) {
if (item == id) {
return retval;
@@ -5579,7 +5280,7 @@ void ex_syntax(exarg_T *eap)
semsg(_("E410: Invalid :syntax subcommand: %s"), subcmd_name);
break;
}
- if (STRCMP(subcmd_name, subcommands[i].name) == 0) {
+ if (strcmp(subcmd_name, subcommands[i].name) == 0) {
eap->arg = skipwhite(subcmd_end);
(subcommands[i].func)(eap, false);
break;
@@ -5650,19 +5351,15 @@ static enum {
EXP_CLUSTER, // expand ":syn list @cluster" arguments
} expand_what;
-/*
- * Reset include_link, include_default, include_none to 0.
- * Called when we are done expanding.
- */
+// Reset include_link, include_default, include_none to 0.
+// Called when we are done expanding.
void reset_expand_highlight(void)
{
include_link = include_default = include_none = 0;
}
-/*
- * Handle command line completion for :match and :echohl command: Add "None"
- * as highlight group.
- */
+// Handle command line completion for :match and :echohl command: Add "None"
+// as highlight group.
void set_context_in_echohl_cmd(expand_T *xp, const char *arg)
{
xp->xp_context = EXPAND_HIGHLIGHT;
@@ -5670,9 +5367,7 @@ void set_context_in_echohl_cmd(expand_T *xp, const char *arg)
include_none = 1;
}
-/*
- * Handle command line completion for :syntax command.
- */
+// Handle command line completion for :syntax command.
void set_context_in_syntax_cmd(expand_T *xp, const char *arg)
{
// Default: expand subcommands.
@@ -5713,10 +5408,8 @@ void set_context_in_syntax_cmd(expand_T *xp, const char *arg)
}
}
-/*
- * Function given to ExpandGeneric() to obtain the list syntax names for
- * expansion.
- */
+// Function given to ExpandGeneric() to obtain the list syntax names for
+// expansion.
char *get_syntax_name(expand_T *xp, int idx)
{
switch (expand_what) {
@@ -5772,12 +5465,10 @@ int syn_get_id(win_T *wp, linenr_T lnum, colnr_T col, int trans, bool *spellp, i
return trans ? current_trans_id : current_id;
}
-/*
- * Get extra information about the syntax item. Must be called right after
- * get_syntax_attr().
- * Stores the current item sequence nr in "*seqnrp".
- * Returns the current flags.
- */
+// Get extra information about the syntax item. Must be called right after
+// get_syntax_attr().
+// Stores the current item sequence nr in "*seqnrp".
+// Returns the current flags.
int get_syntax_info(int *seqnrp)
{
*seqnrp = current_seqnr;
@@ -5801,19 +5492,15 @@ int syn_get_concealed_id(win_T *wp, linenr_T lnum, colnr_T col)
return 0;
}
-/*
- * Return conceal substitution character
- */
+// Return conceal substitution character
int syn_get_sub_char(void)
{
return current_sub_char;
}
-/*
- * Return the syntax ID at position "i" in the current stack.
- * The caller must have called syn_get_id() before to fill the stack.
- * Returns -1 when "i" is out of range.
- */
+// Return the syntax ID at position "i" in the current stack.
+// The caller must have called syn_get_id() before to fill the stack.
+// Returns -1 when "i" is out of range.
int syn_get_stack_item(int i)
{
if (i >= current_state.ga_len) {
@@ -5876,18 +5563,16 @@ int syn_get_foldlevel(win_T *wp, linenr_T lnum)
return level;
}
-/*
- * ":syntime".
- */
+// ":syntime".
void ex_syntime(exarg_T *eap)
{
- if (STRCMP(eap->arg, "on") == 0) {
+ if (strcmp(eap->arg, "on") == 0) {
syn_time_on = true;
- } else if (STRCMP(eap->arg, "off") == 0) {
+ } else if (strcmp(eap->arg, "off") == 0) {
syn_time_on = false;
- } else if (STRCMP(eap->arg, "clear") == 0) {
+ } else if (strcmp(eap->arg, "clear") == 0) {
syntime_clear();
- } else if (STRCMP(eap->arg, "report") == 0) {
+ } else if (strcmp(eap->arg, "report") == 0) {
syntime_report();
} else {
semsg(_(e_invarg2), eap->arg);
@@ -5902,9 +5587,7 @@ static void syn_clear_time(syn_time_T *st)
st->match = 0;
}
-/*
- * Clear the syntax timing for the current buffer.
- */
+// Clear the syntax timing for the current buffer.
static void syntime_clear(void)
{
synpat_T *spp;
@@ -5919,10 +5602,8 @@ static void syntime_clear(void)
}
}
-/*
- * Function given to ExpandGeneric() to obtain the possible arguments of the
- * ":syntime {on,off,clear,report}" command.
- */
+// Function given to ExpandGeneric() to obtain the possible arguments of the
+// ":syntime {on,off,clear,report}" command.
char *get_syntime_arg(expand_T *xp, int idx)
{
switch (idx) {
@@ -5946,9 +5627,7 @@ static int syn_compare_syntime(const void *v1, const void *v2)
return profile_cmp(s1->total, s2->total);
}
-/*
- * Clear the syntax timing for the current buffer.
- */
+// Clear the syntax timing for the current buffer.
static void syntime_report(void)
{
if (!syntax_present(curwin)) {
@@ -5975,7 +5654,7 @@ static void syntime_report(void)
proftime_T tm = profile_divide(spp->sp_time.total, (int)spp->sp_time.count);
p->average = tm;
p->id = spp->sp_syn.id;
- p->pattern = spp->sp_pattern;
+ p->pattern = (char_u *)spp->sp_pattern;
}
}
diff --git a/src/nvim/tag.c b/src/nvim/tag.c
index 648eb751fe..36f797da06 100644
--- a/src/nvim/tag.c
+++ b/src/nvim/tag.c
@@ -1,9 +1,7 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-/*
- * Code to handle tags and the tag stack
- */
+// Code to handle tags and the tag stack
#include <assert.h>
#include <inttypes.h>
@@ -51,13 +49,10 @@
#include "nvim/vim.h"
#include "nvim/window.h"
-/*
- * Structure to hold pointers to various items in a tag line.
- */
+// Structure to hold pointers to various items in a tag line.
typedef struct tag_pointers {
// filled in by parse_tag_line():
- char_u *tagname; // start of tag name (skip "file:")
- //
+ char *tagname; // start of tag name (skip "file:")
char_u *tagname_end; // char after tag name
char_u *fname; // first char of file name
char_u *fname_end; // char after file name
@@ -66,16 +61,14 @@ typedef struct tag_pointers {
char_u *command_end; // first char after command
char_u *tag_fname; // file name of the tags file. This is used
// when 'tr' is set.
- char_u *tagkind; // "kind:" value
- char_u *tagkind_end; // end of tagkind
- char_u *user_data; // user_data string
+ char_u *tagkind; // "kind:" value
+ char_u *tagkind_end; // end of tagkind
+ char *user_data; // user_data string
char_u *user_data_end; // end of user_data
- linenr_T tagline; // "line:" value
+ linenr_T tagline; // "line:" value
} tagptrs_T;
-/*
- * Structure to hold info about the tag pattern being used.
- */
+// Structure to hold info about the tag pattern being used.
typedef struct {
char_u *pat; // the pattern
int len; // length of pat[]
@@ -102,7 +95,7 @@ static char *mt_names[MT_COUNT/2] =
{ "FSC", "F C", "F ", "FS ", " SC", " C", " ", " S " };
#define NOTAGFILE 99 // return value for jumpto_tag
-static char_u *nofile_fname = NULL; // fname for NOTAGFILE error
+static char *nofile_fname = NULL; // fname for NOTAGFILE error
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "tag.c.generated.h"
@@ -115,12 +108,10 @@ static char_u *recurmsg
static char_u *tfu_inv_ret_msg
= (char_u *)N_("E987: invalid return value from tagfunc");
-static char_u *tagmatchname = NULL; // name of last used tag
+static char *tagmatchname = NULL; // name of last used tag
-/*
- * Tag for preview window is remembered separately, to avoid messing up the
- * normal tagstack.
- */
+// Tag for preview window is remembered separately, to avoid messing up the
+// normal tagstack.
static taggy_T ptag_entry = { NULL, INIT_FMARK, 0, 0, NULL };
static int tfu_in_use = false; // disallow recursive call of tagfunc
@@ -150,7 +141,7 @@ static int tfu_in_use = false; // disallow recursive call of tagfunc
/// @param tag tag (pattern) to jump to
/// @param forceit :ta with !
/// @param verbose print "tag not found" message
-bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
+bool do_tag(char *tag, int type, int count, int forceit, int verbose)
{
taggy_T *tagstack = curwin->w_tagstack;
int tagstackidx = curwin->w_tagstackidx;
@@ -203,7 +194,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
}
prev_num_matches = num_matches;
- free_string_option((char *)nofile_fname);
+ free_string_option(nofile_fname);
nofile_fname = NULL;
clearpos(&saved_fmark.mark); // shutup gcc 4.0
@@ -216,7 +207,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
new_tag = true;
if (g_do_tagpreview != 0) {
tagstack_clear_entry(&ptag_entry);
- ptag_entry.tagname = (char *)vim_strsave(tag);
+ ptag_entry.tagname = xstrdup(tag);
}
} else {
if (g_do_tagpreview != 0) {
@@ -233,20 +224,18 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
)) {
if (g_do_tagpreview != 0) {
if (ptag_entry.tagname != NULL
- && STRCMP(ptag_entry.tagname, tag) == 0) {
+ && strcmp(ptag_entry.tagname, tag) == 0) {
// Jumping to same tag: keep the current match, so that
// the CursorHold autocommand example works.
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
} else {
tagstack_clear_entry(&ptag_entry);
- ptag_entry.tagname = (char *)vim_strsave(tag);
+ ptag_entry.tagname = xstrdup(tag);
}
} else {
- /*
- * If the last used entry is not at the top, delete all tag
- * stack entries above it.
- */
+ // If the last used entry is not at the top, delete all tag
+ // stack entries above it.
while (tagstackidx < tagstacklen) {
tagstack_clear_entry(&tagstack[--tagstacklen]);
}
@@ -262,7 +251,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
}
// put the tag name in the tag stack
- tagstack[tagstackidx].tagname = (char *)vim_strsave(tag);
+ tagstack[tagstackidx].tagname = xstrdup(tag);
curwin->w_tagstacklen = tagstacklen;
@@ -300,10 +289,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
// tagstack before it's used.
saved_fmark = tagstack[tagstackidx].fmark;
if (saved_fmark.fnum != curbuf->b_fnum) {
- /*
- * Jump to other file. If this fails (e.g. because the
- * file was changed) keep original position in tag stack.
- */
+ // Jump to other file. If this fails (e.g. because the
+ // file was changed) keep original position in tag stack.
if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,
GETF_SETMARK, forceit) == FAIL) {
tagstackidx = oldtagstackidx; // back to old posn
@@ -340,11 +327,9 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
// ":tag" (no argument): go to newer pattern
save_pos = true; // save the cursor position below
if ((tagstackidx += count - 1) >= tagstacklen) {
- /*
- * Beyond the last one, just give an error message and
- * go to the last one. Don't store the cursor
- * position.
- */
+ // Beyond the last one, just give an error message and
+ // go to the last one. Don't store the cursor
+ // position.
tagstackidx = tagstacklen - 1;
emsg(_(topmsg));
save_pos = false;
@@ -401,9 +386,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
ptag_entry.cur_fnum = cur_fnum;
}
} else {
- /*
- * For ":tag [arg]" or ":tselect" remember position before the jump.
- */
+ // For ":tag [arg]" or ":tselect" remember position before the jump.
saved_fmark = tagstack[tagstackidx].fmark;
if (save_pos) {
tagstack[tagstackidx].fmark.mark = curwin->w_cursor;
@@ -432,28 +415,26 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
}
}
- /*
- * Repeat searching for tags, when a file has not been found.
- */
+ // Repeat searching for tags, when a file has not been found.
for (;;) {
int other_name;
- char_u *name;
+ char *name;
// When desired match not found yet, try to find it (and others).
if (use_tagstack) {
- name = (char_u *)tagstack[tagstackidx].tagname;
+ name = tagstack[tagstackidx].tagname;
} else if (g_do_tagpreview != 0) {
- name = (char_u *)ptag_entry.tagname;
+ name = ptag_entry.tagname;
} else {
name = tag;
}
- other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);
+ other_name = (tagmatchname == NULL || strcmp(tagmatchname, name) != 0);
if (new_tag
|| (cur_match >= num_matches && max_num_matches != MAXCOL)
|| other_name) {
if (other_name) {
xfree(tagmatchname);
- tagmatchname = vim_strsave(name);
+ tagmatchname = xstrdup(name);
}
if (type == DT_SELECT || type == DT_JUMP
@@ -484,7 +465,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
flags |= TAG_NO_TAGFUNC;
}
- if (find_tags((char *)name, &new_num_matches, &new_matches, flags,
+ if (find_tags(name, &new_num_matches, &new_matches, flags,
max_num_matches, (char *)buf_ffname) == OK
&& new_num_matches < max_num_matches) {
max_num_matches = MAXCOL; // If less than max_num_matches
@@ -505,7 +486,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
parse_match(matches[j], &tagp);
for (i = idx; i < new_num_matches; i++) {
parse_match(new_matches[i], &tagp2);
- if (STRCMP(tagp.tagname, tagp2.tagname) == 0) {
+ if (strcmp(tagp.tagname, tagp2.tagname) == 0) {
char_u *p = (char_u *)new_matches[i];
for (k = i; k > idx; k--) {
new_matches[k] = new_matches[k - 1];
@@ -540,7 +521,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
print_tag_list(new_tag, use_tagstack, num_matches, matches);
ask_for_selection = true;
} else if (type == DT_LTAG) {
- if (add_llist_tags(tag, num_matches, matches) == FAIL) {
+ if (add_llist_tags((char_u *)tag, num_matches, matches) == FAIL) {
goto end_do_tag;
}
@@ -588,9 +569,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
if (use_tfu && parse_match(matches[cur_match], &tagp2) == OK
&& tagp2.user_data) {
XFREE_CLEAR(tagstack[tagstackidx].user_data);
- tagstack[tagstackidx].user_data = (char *)vim_strnsave(tagp2.user_data,
- (size_t)(tagp2.user_data_end -
- tagp2.user_data));
+ tagstack[tagstackidx].user_data =
+ xstrnsave(tagp2.user_data, (size_t)(tagp2.user_data_end - (char_u *)tagp2.user_data));
}
tagstackidx++;
@@ -599,10 +579,8 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
ptag_entry.cur_fnum = cur_fnum;
}
- /*
- * Only when going to try the next match, report that the previous
- * file didn't exist. Otherwise an emsg() is given below.
- */
+ // Only when going to try the next match, report that the previous
+ // file didn't exist. Otherwise an emsg() is given below.
if (nofile_fname != NULL && error_cur_match != cur_match) {
smsg(_("File \"%s\" does not exist"), nofile_fname);
}
@@ -641,9 +619,7 @@ bool do_tag(char_u *tag, int type, int count, int forceit, int verbose)
vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name);
set_vim_var_string(VV_SWAPCOMMAND, (char *)IObuff, -1);
- /*
- * Jump to the desired match.
- */
+ // Jump to the desired match.
i = jumpto_tag((char_u *)matches[cur_match], forceit, type != DT_CSCOPE);
set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
@@ -706,7 +682,7 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char
// Assume that the first match indicates how long the tags can
// be, and align the file names to that.
parse_match(matches[0], &tagp);
- taglen = (int)(tagp.tagname_end - tagp.tagname + 2);
+ taglen = (int)(tagp.tagname_end - (char_u *)tagp.tagname + 2);
if (taglen < 18) {
taglen = 18;
}
@@ -742,8 +718,8 @@ static void print_tag_list(int new_tag, int use_tagstack, int num_matches, char
(int)(tagp.tagkind_end - tagp.tagkind));
}
msg_advance(13);
- msg_outtrans_len_attr((char *)tagp.tagname,
- (int)(tagp.tagname_end - tagp.tagname),
+ msg_outtrans_len_attr(tagp.tagname,
+ (int)(tagp.tagname_end - (char_u *)tagp.tagname),
HL_ATTR(HLF_T));
msg_putchar(' ');
taglen_advance(taglen);
@@ -900,7 +876,7 @@ static int add_llist_tags(char_u *tag, int num_matches, char **matches)
parse_match(matches[i], &tagp);
// Save the tag name
- len = (int)(tagp.tagname_end - tagp.tagname);
+ len = (int)(tagp.tagname_end - (char_u *)tagp.tagname);
if (len > 128) {
len = 128;
}
@@ -1006,9 +982,7 @@ static int add_llist_tags(char_u *tag, int num_matches, char **matches)
return OK;
}
-/*
- * Free cached tags.
- */
+// Free cached tags.
void tag_freematch(void)
{
XFREE_CLEAR(tagmatchname);
@@ -1024,9 +998,7 @@ static void taglen_advance(int l)
}
}
-/*
- * Print the tag stack
- */
+// Print the tag stack
void do_tags(exarg_T *eap)
{
int i;
@@ -1062,11 +1034,9 @@ void do_tags(exarg_T *eap)
}
}
-/*
- * Compare two strings, for length "len", ignoring case the ASCII way.
- * return 0 for match, < 0 for smaller, > 0 for bigger
- * Make sure case is folded to uppercase in comparison (like for 'sort -f')
- */
+// Compare two strings, for length "len", ignoring case the ASCII way.
+// return 0 for match, < 0 for smaller, > 0 for bigger
+// Make sure case is folded to uppercase in comparison (like for 'sort -f')
static int tag_strnicmp(char_u *s1, char_u *s2, size_t len)
{
int i;
@@ -1086,9 +1056,7 @@ static int tag_strnicmp(char_u *s1, char_u *s2, size_t len)
return 0; // strings match
}
-/*
- * Extract info from the tag search pattern "pats->pat".
- */
+// Extract info from the tag search pattern "pats->pat".
static void prepare_pats(pat_T *pats, int has_re)
{
pats->head = pats->pat;
@@ -1203,7 +1171,7 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl
taglist = rettv.vval.v_list;
TV_LIST_ITER_CONST(taglist, li, {
- char_u *res_name;
+ char *res_name;
char_u *res_fname;
char_u *res_cmd;
char_u *res_kind;
@@ -1222,7 +1190,7 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl
res_kind = NULL;
TV_DICT_ITER(TV_LIST_ITEM_TV(li)->vval.v_dict, di, {
- const char_u *dict_key = di->di_key;
+ const char *dict_key = (char *)di->di_key;
typval_T *tv = &di->di_tv;
if (tv->v_type != VAR_STRING || tv->vval.v_string == NULL) {
@@ -1230,20 +1198,20 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl
}
len += strlen(tv->vval.v_string) + 1; // Space for "\tVALUE"
- if (!STRCMP(dict_key, "name")) {
- res_name = (char_u *)tv->vval.v_string;
+ if (!strcmp(dict_key, "name")) {
+ res_name = tv->vval.v_string;
continue;
}
- if (!STRCMP(dict_key, "filename")) {
+ if (!strcmp(dict_key, "filename")) {
res_fname = (char_u *)tv->vval.v_string;
continue;
}
- if (!STRCMP(dict_key, "cmd")) {
+ if (!strcmp(dict_key, "cmd")) {
res_cmd = (char_u *)tv->vval.v_string;
continue;
}
has_extra = 1;
- if (!STRCMP(dict_key, "kind")) {
+ if (!strcmp(dict_key, "kind")) {
res_kind = (char_u *)tv->vval.v_string;
continue;
}
@@ -1261,10 +1229,10 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl
break;
}
- char_u *const mfp = name_only ? vim_strsave(res_name) : xmalloc(len + 2);
+ char *const mfp = name_only ? xstrdup(res_name) : xmalloc(len + 2);
if (!name_only) {
- char_u *p = mfp;
+ char_u *p = (char_u *)mfp;
*p++ = MT_GL_OTH + 1; // mtt
*p++ = TAG_SEP; // no tag file name
@@ -1291,22 +1259,22 @@ static int find_tagfunc_tags(char_u *pat, garray_T *ga, int *match_count, int fl
}
TV_DICT_ITER(TV_LIST_ITEM_TV(li)->vval.v_dict, di, {
- const char_u *dict_key = di->di_key;
+ const char *dict_key = (char *)di->di_key;
typval_T *tv = &di->di_tv;
if (tv->v_type != VAR_STRING || tv->vval.v_string == NULL) {
continue;
}
- if (!STRCMP(dict_key, "name")) {
+ if (!strcmp(dict_key, "name")) {
continue;
}
- if (!STRCMP(dict_key, "filename")) {
+ if (!strcmp(dict_key, "filename")) {
continue;
}
- if (!STRCMP(dict_key, "cmd")) {
+ if (!strcmp(dict_key, "cmd")) {
continue;
}
- if (!STRCMP(dict_key, "kind")) {
+ if (!strcmp(dict_key, "kind")) {
continue;
}
@@ -1425,7 +1393,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
int help_pri = 0;
char_u *help_lang_find = NULL; // lang to be found
char_u help_lang[3]; // lang of current tags file
- char_u *saved_pat = NULL; // copy of pat[]
+ char *saved_pat = NULL; // copy of pat[]
bool is_txt = false;
pat_T orgpat; // holds unconverted pattern info
@@ -1473,9 +1441,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
orgpat.regmatch.regprog = NULL;
vimconv.vc_type = CONV_NONE;
- /*
- * Allocate memory for the buffers that are used
- */
+ // Allocate memory for the buffers that are used
lbuf = xmalloc((size_t)lbuf_size);
tag_fname = xmalloc(MAXPATHL + 1);
for (mtt = 0; mtt < MT_COUNT; mtt++) {
@@ -1485,9 +1451,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
STRCPY(tag_fname, "from cscope"); // for error messages
- /*
- * Initialize a few variables
- */
+ // Initialize a few variables
if (help_only) { // want tags from help file
curbuf->b_help = true; // will be restored later
} else if (use_cscope) {
@@ -1503,9 +1467,9 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
if (orgpat.len > 3 && pat[orgpat.len - 3] == '@'
&& ASCII_ISALPHA(pat[orgpat.len - 2])
&& ASCII_ISALPHA(pat[orgpat.len - 1])) {
- saved_pat = vim_strnsave((char_u *)pat, (size_t)orgpat.len - 3);
+ saved_pat = xstrnsave(pat, (size_t)orgpat.len - 3);
help_lang_find = (char_u *)&pat[orgpat.len - 2];
- orgpat.pat = saved_pat;
+ orgpat.pat = (char_u *)saved_pat;
orgpat.len -= 3;
}
}
@@ -1535,16 +1499,15 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
}
}
- /*
- * When finding a specified number of matches, first try with matching
- * case, so binary search can be used, and try ignore-case matches in a
- * second loop.
- * When finding all matches, 'tagbsearch' is off, or there is no fixed
- * string to look for, ignore case right away to avoid going though the
- * tags files twice.
- * When the tag file is case-fold sorted, it is either one or the other.
- * Only ignore case when TAG_NOIC not used or 'ignorecase' set.
- */
+ // When finding a specified number of matches, first try with matching
+ // case, so binary search can be used, and try ignore-case matches in a
+ // second loop.
+ // When finding all matches, 'tagbsearch' is off, or there is no fixed
+ // string to look for, ignore case right away to avoid going though the
+ // tags files twice.
+ // When the tag file is case-fold sorted, it is either one or the other.
+ // Only ignore case when TAG_NOIC not used or 'ignorecase' set.
+
// Set a flag if the file extension is .txt
if ((flags & TAG_KEEP_LANG)
&& help_lang_find == NULL
@@ -1635,9 +1598,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
state = TS_START; // we're at the start of the file
- /*
- * Read and parse the lines in the file one by one
- */
+ // Read and parse the lines in the file one by one
for (;;) {
// check for CTRL-C typed, more often when jumping around
if (state == TS_BINARY || state == TS_SKIP_BACK) {
@@ -1662,9 +1623,7 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
if (get_it_again) {
goto line_read_in;
}
- /*
- * For binary search: compute the next offset to use.
- */
+ // For binary search: compute the next offset to use.
if (state == TS_BINARY) {
offset = search_info.low_offset + ((search_info.high_offset
- search_info.low_offset) / 2);
@@ -1683,10 +1642,8 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
}
}
- /*
- * When jumping around in the file, first read a line to find the
- * start of the next line.
- */
+ // When jumping around in the file, first read a line to find the
+ // start of the next line.
if (state == TS_BINARY || state == TS_SKIP_BACK) {
// Adjust the search file offset to the correct position
search_info.curr_offset_used = search_info.curr_offset;
@@ -1715,11 +1672,9 @@ int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int minc
search_info.curr_offset = search_info.curr_offset_used;
continue;
}
- }
- /*
- * Not jumping around in the file: Read the next line.
- */
- else {
+ } else {
+ // Not jumping around in the file: Read the next line.
+
// skip empty and blank lines
do {
eof = use_cscope
@@ -1755,10 +1710,8 @@ line_read_in:
}
}
- /*
- * When still at the start of the file, check for Emacs tags file
- * format, and for "not sorted" flag.
- */
+ // When still at the start of the file, check for Emacs tags file
+ // format, and for "not sorted" flag.
if (state == TS_START) {
// The header ends when the line sorts below "!_TAG_". When
// case is folded lower case letters sort before "_".
@@ -1769,9 +1722,7 @@ line_read_in:
goto parse_line;
}
- /*
- * Read header line.
- */
+ // Read header line.
if (STRNCMP(lbuf, "!_TAG_FILE_SORTED\t", 18) == 0) {
tag_file_sorted = lbuf[18];
}
@@ -1789,15 +1740,13 @@ line_read_in:
// Headers ends.
- /*
- * When there is no tag head, or ignoring case, need to do a
- * linear search.
- * When no "!_TAG_" is found, default to binary search. If
- * the tag file isn't sorted, the second loop will find it.
- * When "!_TAG_FILE_SORTED" found: start binary search if
- * flag set.
- * For cscope, it's always linear.
- */
+ // When there is no tag head, or ignoring case, need to do a
+ // linear search.
+ // When no "!_TAG_" is found, default to binary search. If
+ // the tag file isn't sorted, the second loop will find it.
+ // When "!_TAG_FILE_SORTED" found: start binary search if
+ // flag set.
+ // For cscope, it's always linear.
if (linear || use_cscope) {
state = TS_LINEAR;
} else if (tag_file_sorted == NUL) {
@@ -1864,7 +1813,7 @@ parse_line:
// This speeds up tag searching a lot!
if (orgpat.headlen) {
CLEAR_FIELD(tagp);
- tagp.tagname = lbuf;
+ tagp.tagname = (char *)lbuf;
tagp.tagname_end = (char_u *)vim_strchr((char *)lbuf, TAB);
if (tagp.tagname_end == NULL) {
// Corrupted tag line.
@@ -1872,11 +1821,9 @@ parse_line:
break;
}
- /*
- * Skip this line if the length of the tag is different and
- * there is no regexp, or the tag is too short.
- */
- cmplen = (int)(tagp.tagname_end - tagp.tagname);
+ // Skip this line if the length of the tag is different and
+ // there is no regexp, or the tag is too short.
+ cmplen = (int)(tagp.tagname_end - (char_u *)tagp.tagname);
if (p_tl != 0 && cmplen > p_tl) { // adjust for 'taglength'
cmplen = (int)p_tl;
}
@@ -1887,9 +1834,7 @@ parse_line:
}
if (state == TS_BINARY) {
- /*
- * Simplistic check for unsorted tags file.
- */
+ // Simplistic check for unsorted tags file.
i = (int)tagp.tagname[0];
if (sortic) {
i = TOUPPER_ASC(tagp.tagname[0]);
@@ -1898,20 +1843,16 @@ parse_line:
sort_error = true;
}
- /*
- * Compare the current tag with the searched tag.
- */
+ // Compare the current tag with the searched tag.
if (sortic) {
- tagcmp = tag_strnicmp(tagp.tagname, orgpat.head,
+ tagcmp = tag_strnicmp((char_u *)tagp.tagname, orgpat.head,
(size_t)cmplen);
} else {
tagcmp = STRNCMP(tagp.tagname, orgpat.head, cmplen);
}
- /*
- * A match with a shorter tag means to search forward.
- * A match with a longer tag means to search backward.
- */
+ // A match with a shorter tag means to search forward.
+ // A match with a longer tag means to search backward.
if (tagcmp == 0) {
if (cmplen < orgpat.headlen) {
tagcmp = -1;
@@ -1935,7 +1876,7 @@ parse_line:
search_info.low_char =
TOUPPER_ASC(tagp.tagname[0]);
} else {
- search_info.low_char = tagp.tagname[0];
+ search_info.low_char = (uint8_t)tagp.tagname[0];
}
continue;
}
@@ -1947,7 +1888,7 @@ parse_line:
search_info.high_char =
TOUPPER_ASC(tagp.tagname[0]);
} else {
- search_info.high_char = tagp.tagname[0];
+ search_info.high_char = (uint8_t)tagp.tagname[0];
}
continue;
}
@@ -1956,7 +1897,7 @@ parse_line:
break;
} else if (state == TS_SKIP_BACK) {
assert(cmplen >= 0);
- if (mb_strnicmp((char *)tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) {
+ if (mb_strnicmp(tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) {
state = TS_STEP_FORWARD;
} else {
// Have to skip back more. Restore the curr_offset
@@ -1966,7 +1907,7 @@ parse_line:
continue;
} else if (state == TS_STEP_FORWARD) {
assert(cmplen >= 0);
- if (mb_strnicmp((char *)tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) {
+ if (mb_strnicmp(tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) {
if ((off_T)vim_ftell(fp) > search_info.match_offset) {
break; // past last match
} else {
@@ -1977,7 +1918,7 @@ parse_line:
// skip this match if it can't match
assert(cmplen >= 0);
}
- if (mb_strnicmp((char *)tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) {
+ if (mb_strnicmp(tagp.tagname, (char *)orgpat.head, (size_t)cmplen) != 0) {
continue;
}
@@ -1999,11 +1940,9 @@ parse_line:
break;
}
- /*
- * First try matching with the pattern literally (also when it is
- * a regexp).
- */
- cmplen = (int)(tagp.tagname_end - tagp.tagname);
+ // First try matching with the pattern literally (also when it is
+ // a regexp).
+ cmplen = (int)(tagp.tagname_end - (char_u *)tagp.tagname);
if (p_tl != 0 && cmplen > p_tl) { // adjust for 'taglength'
cmplen = (int)p_tl;
}
@@ -2013,7 +1952,7 @@ parse_line:
} else {
if (orgpat.regmatch.rm_ic) {
assert(cmplen >= 0);
- match = mb_strnicmp((char *)tagp.tagname, (char *)orgpat.pat, (size_t)cmplen) == 0;
+ match = mb_strnicmp(tagp.tagname, (char *)orgpat.pat, (size_t)cmplen) == 0;
if (match) {
match_no_ic = (STRNCMP(tagp.tagname, orgpat.pat,
cmplen) == 0);
@@ -2023,21 +1962,19 @@ parse_line:
}
}
- /*
- * Has a regexp: Also find tags matching regexp.
- */
+ // Has a regexp: Also find tags matching regexp.
match_re = false;
if (!match && orgpat.regmatch.regprog != NULL) {
int cc;
cc = *tagp.tagname_end;
*tagp.tagname_end = NUL;
- match = vim_regexec(&orgpat.regmatch, (char *)tagp.tagname, (colnr_T)0);
+ match = vim_regexec(&orgpat.regmatch, tagp.tagname, (colnr_T)0);
if (match) {
matchoff = (int)(orgpat.regmatch.startp[0] - tagp.tagname);
if (orgpat.regmatch.rm_ic) {
orgpat.regmatch.rm_ic = false;
- match_no_ic = vim_regexec(&orgpat.regmatch, (char *)tagp.tagname, (colnr_T)0);
+ match_no_ic = vim_regexec(&orgpat.regmatch, tagp.tagname, (colnr_T)0);
orgpat.regmatch.rm_ic = true;
}
}
@@ -2091,7 +2028,7 @@ parse_line:
// detecting duplicates.
// The format is {tagname}@{lang}NUL{heuristic}NUL
*tagp.tagname_end = NUL;
- len = (size_t)(tagp.tagname_end - tagp.tagname);
+ len = (size_t)(tagp.tagname_end - (char_u *)tagp.tagname);
mfp = xmalloc(sizeof(char) + len + 10 + ML_EXTRA + 1);
p = (char_u *)mfp;
@@ -2099,7 +2036,7 @@ parse_line:
p[len] = '@';
STRCPY(p + len + 1, help_lang);
snprintf((char *)p + len + 1 + ML_EXTRA, STRLEN(p) + len + 1 + ML_EXTRA, "%06d",
- help_heuristic((char *)tagp.tagname,
+ help_heuristic(tagp.tagname,
match_re ? matchoff : 0, !match_no_ic)
+ help_pri);
@@ -2125,7 +2062,7 @@ parse_line:
}
get_it_again = false;
} else {
- len = (size_t)(tagp.tagname_end - tagp.tagname);
+ len = (size_t)(tagp.tagname_end - (char_u *)tagp.tagname);
mfp = xmalloc(sizeof(char) + len + 1);
STRLCPY(mfp, tagp.tagname, len + 1);
@@ -2212,9 +2149,7 @@ parse_line:
sort_error = false;
}
- /*
- * Stop searching if sufficient tags have been found.
- */
+ // Stop searching if sufficient tags have been found.
if (match_count >= mincount) {
retval = OK;
stop_searching = true;
@@ -2252,10 +2187,8 @@ findtag_end:
vim_regfree(orgpat.regmatch.regprog);
xfree(tag_fname);
- /*
- * Move the matches from the ga_match[] arrays into one list of
- * matches. When retval == FAIL, free the matches.
- */
+ // Move the matches from the ga_match[] arrays into one list of
+ // matches. When retval == FAIL, free the matches.
if (retval == FAIL) {
match_count = 0;
}
@@ -2304,19 +2237,17 @@ findtag_end:
static garray_T tag_fnames = GA_EMPTY_INIT_VALUE;
-/*
- * Callback function for finding all "tags" and "tags-??" files in
- * 'runtimepath' doc directories.
- */
+// Callback function for finding all "tags" and "tags-??" files in
+// 'runtimepath' doc directories.
static void found_tagfile_cb(char *fname, void *cookie)
{
- char_u *const tag_fname = vim_strsave((char_u *)fname);
+ char *const tag_fname = xstrdup(fname);
#ifdef BACKSLASH_IN_FILENAME
slash_adjust(tag_fname);
#endif
- simplify_filename(tag_fname);
- GA_APPEND(char_u *, &tag_fnames, tag_fname);
+ simplify_filename((char_u *)tag_fname);
+ GA_APPEND(char *, &tag_fnames, tag_fname);
}
#if defined(EXITFREE)
@@ -2349,11 +2280,9 @@ int get_tagfname(tagname_T *tnp, int first, char *buf)
}
if (curbuf->b_help) {
- /*
- * For help files it's done in a completely different way:
- * Find "doc/tags" and "doc/tags-??" in all directories in
- * 'runtimepath'.
- */
+ // For help files it's done in a completely different way:
+ // Find "doc/tags" and "doc/tags-??" in all directories in
+ // 'runtimepath'.
if (first) {
ga_clear_strings(&tag_fnames);
ga_init(&tag_fnames, (int)sizeof(char *), 10);
@@ -2376,7 +2305,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf)
simplify_filename((char_u *)buf);
for (int i = 0; i < tag_fnames.ga_len; i++) {
- if (STRCMP(buf, ((char **)(tag_fnames.ga_data))[i]) == 0) {
+ if (strcmp(buf, ((char **)(tag_fnames.ga_data))[i]) == 0) {
return FAIL; // avoid duplicate file names
}
}
@@ -2389,16 +2318,14 @@ int get_tagfname(tagname_T *tnp, int first, char *buf)
if (first) {
// Init. We make a copy of 'tags', because autocommands may change
// the value without notifying us.
- tnp->tn_tags = vim_strsave((*curbuf->b_p_tags != NUL) ? (char_u *)curbuf->b_p_tags : p_tags);
- tnp->tn_np = (char *)tnp->tn_tags;
+ tnp->tn_tags = xstrdup((*curbuf->b_p_tags != NUL) ? curbuf->b_p_tags : (char *)p_tags);
+ tnp->tn_np = tnp->tn_tags;
}
- /*
- * Loop until we have found a file name that can be used.
- * There are two states:
- * tnp->tn_did_filefind_init == false: setup for next part in 'tags'.
- * tnp->tn_did_filefind_init == true: find next file in this part.
- */
+ // Loop until we have found a file name that can be used.
+ // There are two states:
+ // tnp->tn_did_filefind_init == false: setup for next part in 'tags'.
+ // tnp->tn_did_filefind_init == true: find next file in this part.
for (;;) {
if (tnp->tn_did_filefind_init) {
fname = (char *)vim_findfile(tnp->tn_search_ctx);
@@ -2417,9 +2344,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf)
return FAIL;
}
- /*
- * Copy next file name into buf.
- */
+ // Copy next file name into buf.
buf[0] = NUL;
(void)copy_option_part(&tnp->tn_np, buf, MAXPATHL - 1, " ,");
@@ -2430,11 +2355,11 @@ int get_tagfname(tagname_T *tnp, int first, char *buf)
STRMOVE(filename + 1, filename);
*filename++ = NUL;
- tnp->tn_search_ctx = vim_findfile_init((char_u *)buf, filename,
- (char_u *)r_ptr, 100,
+ tnp->tn_search_ctx = vim_findfile_init(buf, (char *)filename,
+ r_ptr, 100,
false, // don't free visited list
FINDFILE_FILE, // we search for a file
- tnp->tn_search_ctx, true, (char_u *)curbuf->b_ffname);
+ tnp->tn_search_ctx, true, curbuf->b_ffname);
if (tnp->tn_search_ctx != NULL) {
tnp->tn_did_filefind_init = true;
}
@@ -2446,9 +2371,7 @@ int get_tagfname(tagname_T *tnp, int first, char *buf)
return OK;
}
-/*
- * Free the contents of a tagname_T that was filled by get_tagfname().
- */
+// Free the contents of a tagname_T that was filled by get_tagfname().
void tagname_free(tagname_T *tnp)
{
xfree(tnp->tn_tags);
@@ -2470,7 +2393,7 @@ static int parse_tag_line(char_u *lbuf, tagptrs_T *tagp)
char_u *p;
// Isolate the tagname, from lbuf up to the first white
- tagp->tagname = lbuf;
+ tagp->tagname = (char *)lbuf;
p = (char_u *)vim_strchr((char *)lbuf, TAB);
if (p == NULL) {
return FAIL;
@@ -2500,20 +2423,18 @@ static int parse_tag_line(char_u *lbuf, tagptrs_T *tagp)
return OK;
}
-/*
- * Check if tagname is a static tag
- *
- * Static tags produced by the older ctags program have the format:
- * 'file:tag file /pattern'.
- * This is only recognized when both occurrence of 'file' are the same, to
- * avoid recognizing "string::string" or ":exit".
- *
- * Static tags produced by the new ctags program have the format:
- * 'tag file /pattern/;"<Tab>file:' "
- *
- * Return true if it is a static tag and adjust *tagname to the real tag.
- * Return false if it is not a static tag.
- */
+// Check if tagname is a static tag
+//
+// Static tags produced by the older ctags program have the format:
+// 'file:tag file /pattern'.
+// This is only recognized when both occurrence of 'file' are the same, to
+// avoid recognizing "string::string" or ":exit".
+//
+// Static tags produced by the new ctags program have the format:
+// 'tag file /pattern/;"<Tab>file:' "
+//
+// Return true if it is a static tag and adjust *tagname to the real tag.
+// Return false if it is not a static tag.
static bool test_for_static(tagptrs_T *tagp)
{
char_u *p;
@@ -2584,7 +2505,7 @@ static int parse_match(char *lbuf, tagptrs_T *tagp)
if (STRNCMP(p, "kind:", 5) == 0) {
tagp->tagkind = (char_u *)p + 5;
} else if (STRNCMP(p, "user_data:", 10) == 0) {
- tagp->user_data = (char_u *)p + 10;
+ tagp->user_data = p + 10;
} else if (STRNCMP(p, "line:", 5) == 0) {
tagp->tagline = atoi(p + 5);
}
@@ -2612,7 +2533,7 @@ static int parse_match(char *lbuf, tagptrs_T *tagp)
tagp->tagkind_end = (char_u *)p;
}
if (tagp->user_data != NULL) {
- for (p = (char *)tagp->user_data;
+ for (p = tagp->user_data;
*p && *p != '\t' && *p != '\r' && *p != '\n';
MB_PTR_ADV(p)) {}
tagp->user_data_end = (char_u *)p;
@@ -2621,16 +2542,15 @@ static int parse_match(char *lbuf, tagptrs_T *tagp)
return retval;
}
-/*
- * Find out the actual file name of a tag. Concatenate the tags file name
- * with the matching tag file name.
- * Returns an allocated string.
- */
+// Find out the actual file name of a tag. Concatenate the tags file name
+// with the matching tag file name.
+// Returns an allocated string.
static char_u *tag_full_fname(tagptrs_T *tagp)
{
int c = *tagp->fname_end;
*tagp->fname_end = NUL;
- char_u *fullname = expand_tag_fname(tagp->fname, tagp->tag_fname, false);
+ char_u *fullname =
+ (char_u *)expand_tag_fname((char *)tagp->fname, (char *)tagp->tag_fname, false);
*tagp->fname_end = (char_u)c;
return fullname;
@@ -2653,7 +2573,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
char_u *pbuf; // search pattern buffer
char_u *pbuf_end;
char_u *tofree_fname = NULL;
- char_u *fname;
+ char *fname;
tagptrs_T tagp;
int retval = FAIL;
int getfile_result = GETFILE_UNUSED;
@@ -2676,7 +2596,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
// truncate the file name, so it can be used as a string
*tagp.fname_end = NUL;
- fname = tagp.fname;
+ fname = (char *)tagp.fname;
// copy the command to pbuf[], remove trailing CR/NL
str = tagp.command;
@@ -2689,9 +2609,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
*pbuf_end = NUL;
{
- /*
- * Remove the "<Tab>fieldname:value" stuff; we don't need it here.
- */
+ // Remove the "<Tab>fieldname:value" stuff; we don't need it here.
str = pbuf;
if (find_extra(&str) == OK) {
pbuf_end = str;
@@ -2699,24 +2617,19 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
}
}
- /*
- * Expand file name, when needed (for environment variables).
- * If 'tagrelative' option set, may change file name.
- */
- fname = expand_tag_fname(fname, tagp.tag_fname, true);
- tofree_fname = fname; // free() it later
+ // Expand file name, when needed (for environment variables).
+ // If 'tagrelative' option set, may change file name.
+ fname = expand_tag_fname(fname, (char *)tagp.tag_fname, true);
+ tofree_fname = (char_u *)fname; // free() it later
- /*
- * Check if the file with the tag exists before abandoning the current
- * file. Also accept a file name for which there is a matching BufReadCmd
- * autocommand event (e.g., http://sys/file).
- */
- if (!os_path_exists((char *)fname)
- && !has_autocmd(EVENT_BUFREADCMD, (char *)fname,
- NULL)) {
+ // Check if the file with the tag exists before abandoning the current
+ // file. Also accept a file name for which there is a matching BufReadCmd
+ // autocommand event (e.g., http://sys/file).
+ if (!os_path_exists(fname)
+ && !has_autocmd(EVENT_BUFREADCMD, fname, NULL)) {
retval = NOTAGFILE;
xfree(nofile_fname);
- nofile_fname = vim_strsave(fname);
+ nofile_fname = xstrdup(fname);
goto erret;
}
@@ -2726,19 +2639,15 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
postponed_split = 0; // don't split again below
curwin_save = curwin; // Save current window
- /*
- * If we are reusing a window, we may change dir when
- * entering it (autocommands) so turn the tag filename
- * into a fullpath
- */
+ // If we are reusing a window, we may change dir when
+ // entering it (autocommands) so turn the tag filename
+ // into a fullpath
if (!curwin->w_p_pvw) {
- full_fname = (char_u *)FullName_save((char *)fname, false);
- fname = full_fname;
+ full_fname = (char_u *)FullName_save(fname, false);
+ fname = (char *)full_fname;
- /*
- * Make the preview window the current window.
- * Open a preview window when needed.
- */
+ // Make the preview window the current window.
+ // Open a preview window when needed.
prepare_tagpreview(true);
}
}
@@ -2746,7 +2655,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
// If it was a CTRL-W CTRL-] command split window now. For ":tab tag"
// open a new tab page.
if (postponed_split && (swb_flags & (SWB_USEOPEN | SWB_USETAB))) {
- buf_T *const existing_buf = buflist_findname_exp((char *)fname);
+ buf_T *const existing_buf = buflist_findname_exp(fname);
if (existing_buf != NULL) {
const win_T *wp = NULL;
@@ -2791,7 +2700,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
if (getfile_result == GETFILE_UNUSED) {
// Careful: getfile() may trigger autocommands and call jumpto_tag()
// recursively.
- getfile_result = getfile(0, (char *)fname, NULL, true, (linenr_T)0, forceit);
+ getfile_result = getfile(0, fname, NULL, true, (linenr_T)0, forceit);
}
keep_help_flag = false;
@@ -2804,25 +2713,21 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
// Save value of no_hlsearch, jumping to a tag is not a real search
const bool save_no_hlsearch = no_hlsearch;
- /*
- * If 'cpoptions' contains 't', store the search pattern for the "n"
- * command. If 'cpoptions' does not contain 't', the search pattern
- * is not stored.
- */
+ // If 'cpoptions' contains 't', store the search pattern for the "n"
+ // command. If 'cpoptions' does not contain 't', the search pattern
+ // is not stored.
if (vim_strchr(p_cpo, CPO_TAGPAT) != NULL) {
search_options = 0;
} else {
search_options = SEARCH_KEEP;
}
- /*
- * If the command is a search, try here.
- *
- * Reset 'smartcase' for the search, since the search pattern was not
- * typed by the user.
- * Only use do_search() when there is a full search command, without
- * anything following.
- */
+ // If the command is a search, try here.
+ //
+ // Reset 'smartcase' for the search, since the search pattern was not
+ // typed by the user.
+ // Only use do_search() when there is a full search command, without
+ // anything following.
str = pbuf;
if (pbuf[0] == '/' || pbuf[0] == '?') {
str = (char_u *)skip_regexp((char *)pbuf + 1, pbuf[0], false, NULL) + 1;
@@ -2849,9 +2754,7 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
int found = 1;
int cc;
- /*
- * try again, ignore case now
- */
+ // try again, ignore case now
p_ic = true;
if (!do_search(NULL, pbuf[0], pbuf[0], pbuf + 1, (long)1,
search_options, NULL)) {
@@ -2876,10 +2779,8 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
emsg(_("E434: Can't find tag pattern"));
curwin->w_cursor.lnum = save_lnum;
} else {
- /*
- * Only give a message when really guessed, not when 'ic'
- * is set and match found while ignoring case.
- */
+ // Only give a message when really guessed, not when 'ic'
+ // is set and match found while ignoring case.
if (found == 2 || !save_p_ic) {
msg(_("E435: Couldn't find tag, just guessing!"));
if (!msg_scrolled && msg_silent == 0) {
@@ -2928,10 +2829,8 @@ static int jumpto_tag(const char_u *lbuf_arg, int forceit, int keep_help)
}
if (retval == OK) {
- /*
- * For a help buffer: Put the cursor line at the top of the window,
- * the help subject will be below it.
- */
+ // For a help buffer: Put the cursor line at the top of the window,
+ // the help subject will be below it.
if (curbuf->b_help) {
set_topline(curwin, curwin->w_cursor.lnum);
}
@@ -2967,19 +2866,18 @@ erret:
return retval;
}
-// If "expand" is true, expand wildcards in fname.
-// If 'tagrelative' option set, change fname (name of file containing tag)
-// according to tag_fname (name of tag file containing fname).
-// Returns a pointer to allocated memory.
-static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bool expand)
+/// If "expand" is true, expand wildcards in fname.
+/// If 'tagrelative' option set, change fname (name of file containing tag)
+/// according to tag_fname (name of tag file containing fname).
+///
+/// @return a pointer to allocated memory.
+static char *expand_tag_fname(char *fname, char *const tag_fname, const bool expand)
{
- char_u *p;
- char_u *expanded_fname = NULL;
+ char *p;
+ char *expanded_fname = NULL;
expand_T xpc;
- /*
- * Expand file name (for environment variables) when needed.
- */
+ // Expand file name (for environment variables) when needed.
if (expand && path_has_wildcard(fname)) {
ExpandInit(&xpc);
xpc.xp_context = EXPAND_FILES;
@@ -2990,20 +2888,18 @@ static char_u *expand_tag_fname(char_u *fname, char_u *const tag_fname, const bo
}
}
- char_u *retval;
+ char *retval;
if ((p_tr || curbuf->b_help)
- && !vim_isAbsName(fname)
- && (p = (char_u *)path_tail((char *)tag_fname)) != tag_fname) {
+ && !vim_isAbsName((char_u *)fname)
+ && (p = path_tail(tag_fname)) != tag_fname) {
retval = xmalloc(MAXPATHL);
STRCPY(retval, tag_fname);
STRLCPY(retval + (p - tag_fname), fname,
MAXPATHL - (p - tag_fname));
- /*
- * Translate names like "src/a/../b/file.c" into "src/b/file.c".
- */
- simplify_filename(retval);
+ // Translate names like "src/a/../b/file.c" into "src/b/file.c".
+ simplify_filename((char_u *)retval);
} else {
- retval = vim_strsave(fname);
+ retval = xstrdup(fname);
}
xfree(expanded_fname);
@@ -3026,7 +2922,7 @@ static int test_for_current(char *fname, char *fname_end, char *tag_fname, char
c = (unsigned char)(*fname_end);
*fname_end = NUL;
}
- char *fullname = (char *)expand_tag_fname((char_u *)fname, (char_u *)tag_fname, true);
+ char *fullname = expand_tag_fname(fname, tag_fname, true);
retval = (path_full_compare(fullname, buf_ffname, true, true) & kEqualFiles);
xfree(fullname);
*fname_end = (char)c;
@@ -3035,10 +2931,8 @@ static int test_for_current(char *fname, char *fname_end, char *tag_fname, char
return retval;
}
-/*
- * Find the end of the tagaddress.
- * Return OK if ";\"" is following, FAIL otherwise.
- */
+// Find the end of the tagaddress.
+// Return OK if ";\"" is following, FAIL otherwise.
static int find_extra(char_u **pp)
{
char_u *str = *pp;
@@ -3120,7 +3014,7 @@ int expand_tags(int tagnames, char_u *pat, int *num_file, char ***file)
size_t len;
parse_match((*file)[i], &t_p);
- len = (size_t)(t_p.tagname_end - t_p.tagname);
+ len = (size_t)(t_p.tagname_end - (char_u *)t_p.tagname);
if (len > name_buf_size - 3) {
char_u *buf;
@@ -3217,7 +3111,7 @@ int get_tags(list_T *list, char_u *pat, char_u *buf_fname)
tv_list_append_dict(list, dict);
full_fname = tag_full_fname(&tp);
- if (add_tag_field(dict, "name", (char *)tp.tagname, (char *)tp.tagname_end) == FAIL
+ if (add_tag_field(dict, "name", tp.tagname, (char *)tp.tagname_end) == FAIL
|| add_tag_field(dict, "filename", (char *)full_fname, NULL) == FAIL
|| add_tag_field(dict, "cmd", (char *)tp.command, (char *)tp.command_end) == FAIL
|| add_tag_field(dict, "kind", (char *)tp.tagkind,
diff --git a/src/nvim/tag.h b/src/nvim/tag.h
index 0b4039afb6..7f2ef8d6d7 100644
--- a/src/nvim/tag.h
+++ b/src/nvim/tag.h
@@ -34,7 +34,7 @@
// Structure used for get_tagfname().
typedef struct {
- char_u *tn_tags; // value of 'tags' when starting
+ char *tn_tags; // value of 'tags' when starting
char *tn_np; // current position in tn_tags
int tn_did_filefind_init;
int tn_hf_idx;
diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c
index 90966bcfad..46f141492b 100644
--- a/src/nvim/terminal.c
+++ b/src/nvim/terminal.c
@@ -120,6 +120,10 @@ struct terminal {
// window height has increased) and must be deleted from the terminal buffer
int sb_pending;
+ char *title; // VTermStringFragment buffer
+ size_t title_len; // number of rows pushed to sb_buffer
+ size_t title_size; // sb_buffer size
+
// buf_T instance that acts as a "drawing surface" for libvterm
// we can't store a direct reference to the buffer because the
// refresh_timer_cb may be called after the buffer was freed, and there's
@@ -230,7 +234,7 @@ Terminal *terminal_open(buf_T *buf, TerminalOptions opts)
set_option_value("wrap", false, NULL, OPT_LOCAL);
set_option_value("list", false, NULL, OPT_LOCAL);
if (buf->b_ffname != NULL) {
- buf_set_term_title(buf, buf->b_ffname);
+ buf_set_term_title(buf, buf->b_ffname, strlen(buf->b_ffname));
}
RESET_BINDING(curwin);
// Reset cursor in current window.
@@ -424,7 +428,7 @@ bool terminal_enter(void)
long save_w_p_so = curwin->w_p_so;
long save_w_p_siso = curwin->w_p_siso;
if (curwin->w_p_cul && curwin->w_p_culopt_flags & CULOPT_NBR) {
- if (STRCMP(curwin->w_p_culopt, "number")) {
+ if (strcmp(curwin->w_p_culopt, "number")) {
save_w_p_culopt = curwin->w_p_culopt;
curwin->w_p_culopt = xstrdup("number");
}
@@ -636,6 +640,7 @@ void terminal_destroy(Terminal **termpp)
xfree(term->sb_buffer[i]);
}
xfree(term->sb_buffer);
+ xfree(term->title);
vterm_free(term->vt);
xfree(term);
*termpp = NULL; // coverity[dead-store]
@@ -858,13 +863,13 @@ static int term_movecursor(VTermPos new, VTermPos old, int visible, void *data)
return 1;
}
-static void buf_set_term_title(buf_T *buf, char *title)
+static void buf_set_term_title(buf_T *buf, const char *title, size_t len)
FUNC_ATTR_NONNULL_ALL
{
Error err = ERROR_INIT;
dict_set_var(buf->b_vars,
STATIC_CSTR_AS_STRING("term_title"),
- STRING_OBJ(cstr_as_string(title)),
+ STRING_OBJ(((String){ .data = (char *)title, .size = len })),
false,
false,
&err);
@@ -887,7 +892,34 @@ static int term_settermprop(VTermProp prop, VTermValue *val, void *data)
case VTERM_PROP_TITLE: {
buf_T *buf = handle_get_buffer(term->buf_handle);
- buf_set_term_title(buf, val->string);
+#if VTERM_VERSION_MAJOR > 0 || (VTERM_VERSION_MAJOR == 0 && VTERM_VERSION_MINOR >= 2)
+ VTermStringFragment frag = val->string;
+
+ if (frag.initial && frag.final) {
+ buf_set_term_title(buf, frag.str, frag.len);
+ break;
+ }
+
+ if (frag.initial) {
+ term->title_len = 0;
+ term->title_size = MAX(frag.len, 1024);
+ term->title = xmalloc(sizeof(char *) * term->title_size);
+ } else if (term->title_len + frag.len > term->title_size) {
+ term->title_size *= 2;
+ term->title = xrealloc(term->title, sizeof(char *) * term->title_size);
+ }
+
+ memcpy(term->title + term->title_len, frag.str, frag.len);
+ term->title_len += frag.len;
+
+ if (frag.final) {
+ buf_set_term_title(buf, term->title, term->title_len);
+ xfree(term->title);
+ term->title = NULL;
+ }
+#else
+ buf_set_term_title(buf, val->string, strlen(val->string));
+#endif
break;
}
diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim
index bc06e70ff4..e40ff65051 100644
--- a/src/nvim/testdir/test_cmdline.vim
+++ b/src/nvim/testdir/test_cmdline.vim
@@ -1055,6 +1055,18 @@ func Test_cmdline_write_alternatefile()
bw!
endfunc
+func Test_cmdline_expand_cur_alt_file()
+ enew
+ file http://some.com/file.txt
+ call feedkeys(":e %\<Tab>\<C-B>\"\<CR>", 'xt')
+ call assert_equal('"e http://some.com/file.txt', @:)
+ edit another
+ call feedkeys(":e #\<Tab>\<C-B>\"\<CR>", 'xt')
+ call assert_equal('"e http://some.com/file.txt', @:)
+ bwipe
+ bwipe http://some.com/file.txt
+endfunc
+
" using a leading backslash here
set cpo+=C
diff --git a/src/nvim/testdir/test_cursor_func.vim b/src/nvim/testdir/test_cursor_func.vim
index f13842edc8..2e625f2388 100644
--- a/src/nvim/testdir/test_cursor_func.vim
+++ b/src/nvim/testdir/test_cursor_func.vim
@@ -373,4 +373,26 @@ func Test_setcursorcharpos()
%bw!
endfunc
+" Test for virtcol2col()
+func Test_virtcol2col()
+ new
+ call setline(1, ["a\tb\tc"])
+ call assert_equal(1, virtcol2col(0, 1, 1))
+ call assert_equal(2, virtcol2col(0, 1, 2))
+ call assert_equal(2, virtcol2col(0, 1, 8))
+ call assert_equal(3, virtcol2col(0, 1, 9))
+ call assert_equal(4, virtcol2col(0, 1, 10))
+ call assert_equal(4, virtcol2col(0, 1, 16))
+ call assert_equal(5, virtcol2col(0, 1, 17))
+ call assert_equal(-1, virtcol2col(10, 1, 1))
+ call assert_equal(-1, virtcol2col(0, 10, 1))
+ call assert_equal(-1, virtcol2col(0, -1, 1))
+ call assert_equal(-1, virtcol2col(0, 1, -1))
+ call assert_equal(5, virtcol2col(0, 1, 20))
+ call assert_fails('echo virtcol2col("0", 1, 20)', 'E1210:')
+ call assert_fails('echo virtcol2col(0, "1", 20)', 'E1210:')
+ call assert_fails('echo virtcol2col(0, 1, "1")', 'E1210:')
+ bw!
+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 eff1376d3c..dc110af356 100644
--- a/src/nvim/testdir/test_eval_stuff.vim
+++ b/src/nvim/testdir/test_eval_stuff.vim
@@ -1,5 +1,8 @@
" Tests for various eval things.
+source view_util.vim
+source shared.vim
+
function s:foo() abort
try
return [] == 0
@@ -87,22 +90,47 @@ func Test_for_over_null_string()
let &enc = save_enc
endfunc
+func Test_for_invalid_line_count()
+ let lines =<< trim END
+ 111111111111111111111111 for line in ['one']
+ endfor
+ END
+ call writefile(lines, 'XinvalidFor')
+ " only test that this doesn't crash
+ call RunVim([], [], '-u NONE -e -s -S XinvalidFor -c qa')
+
+ call delete('XinvalidFor')
+endfunc
+
func Test_readfile_binary()
new
call setline(1, ['one', 'two', 'three'])
setlocal ff=dos
- silent write XReadfile
- let lines = readfile('XReadfile')
+ silent write XReadfile_bin
+ let lines = 'XReadfile_bin'->readfile()
call assert_equal(['one', 'two', 'three'], lines)
- let lines = readfile('XReadfile', '', 2)
+ let lines = readfile('XReadfile_bin', '', 2)
call assert_equal(['one', 'two'], lines)
- let lines = readfile('XReadfile', 'b')
+ let lines = readfile('XReadfile_bin', 'b')
call assert_equal(["one\r", "two\r", "three\r", ""], lines)
- let lines = readfile('XReadfile', 'b', 2)
+ let lines = readfile('XReadfile_bin', 'b', 2)
call assert_equal(["one\r", "two\r"], lines)
bwipe!
- call delete('XReadfile')
+ call delete('XReadfile_bin')
+endfunc
+
+func Test_readfile_bom()
+ call writefile(["\ufeffFOO", "FOO\ufeffBAR"], 'XReadfile_bom')
+ call assert_equal(['FOO', 'FOOBAR'], readfile('XReadfile_bom'))
+ call delete('XReadfile_bom')
+endfunc
+
+func Test_readfile_max()
+ call writefile(range(1, 4), 'XReadfile_max')
+ call assert_equal(['1', '2'], readfile('XReadfile_max', '', 2))
+ call assert_equal(['3', '4'], readfile('XReadfile_max', '', -2))
+ call delete('XReadfile_max')
endfunc
func Test_let_errmsg()
diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim
index 68ce9148a4..8d7c8f0c87 100644
--- a/src/nvim/testdir/test_filetype.vim
+++ b/src/nvim/testdir/test_filetype.vim
@@ -88,6 +88,7 @@ let s:filename_checks = {
\ 'bindzone': ['named.root', '/bind/db.file', '/named/db.file', 'any/bind/db.file', 'any/named/db.file'],
\ 'bitbake': ['file.bb', 'file.bbappend', 'file.bbclass', 'build/conf/local.conf', 'meta/conf/layer.conf', 'build/conf/bbappend.conf', 'meta-layer/conf/distro/foo.conf'],
\ 'blank': ['file.bl'],
+ \ 'blueprint': ['file.blp'],
\ 'bsdl': ['file.bsd', 'file.bsdl'],
\ 'bst': ['file.bst'],
\ 'bzl': ['file.bazel', 'file.bzl', 'WORKSPACE'],
@@ -213,8 +214,10 @@ let s:filename_checks = {
\ 'gedcom': ['file.ged', 'lltxxxxx.txt', '/tmp/lltmp', '/tmp/lltmp-file', 'any/tmp/lltmp', 'any/tmp/lltmp-file'],
\ 'gemtext': ['file.gmi', 'file.gemini'],
\ 'gift': ['file.gift'],
+ \ 'gitattributes': ['file.git/info/attributes', '.gitattributes', '/.config/git/attributes', '/etc/gitattributes', '/usr/local/etc/gitattributes', 'some.git/info/attributes'],
\ 'gitcommit': ['COMMIT_EDITMSG', 'MERGE_MSG', 'TAG_EDITMSG', 'NOTES_EDITMSG', 'EDIT_DESCRIPTION'],
\ 'gitconfig': ['file.git/config', 'file.git/config.worktree', 'file.git/worktrees/x/config.worktree', '.gitconfig', '.gitmodules', 'file.git/modules//config', '/.config/git/config', '/etc/gitconfig', '/usr/local/etc/gitconfig', '/etc/gitconfig.d/file', 'any/etc/gitconfig.d/file', '/.gitconfig.d/file', 'any/.config/git/config', 'any/.gitconfig.d/file', 'some.git/config', 'some.git/modules/any/config'],
+ \ 'gitignore': ['file.git/info/exclude', '.gitignore', '/.config/git/ignore', 'some.git/info/exclude'],
\ 'gitolite': ['gitolite.conf', '/gitolite-admin/conf/file', 'any/gitolite-admin/conf/file'],
\ 'gitrebase': ['git-rebase-todo'],
\ 'gitsendemail': ['.gitsendemail.msg.xxxxxx'],
@@ -275,7 +278,7 @@ let s:filename_checks = {
\ 'jam': ['file.jpl', 'file.jpr', 'JAM-file.file', 'JAM.file', 'Prl-file.file', 'Prl.file'],
\ 'java': ['file.java', 'file.jav'],
\ 'javacc': ['file.jj', 'file.jjt'],
- \ 'javascript': ['file.js', 'file.javascript', 'file.es', 'file.mjs', 'file.cjs'],
+ \ 'javascript': ['file.js', 'file.jsm', 'file.javascript', 'file.es', 'file.mjs', 'file.cjs'],
\ 'javascript.glimmer': ['file.gjs'],
\ 'javascriptreact': ['file.jsx'],
\ 'jess': ['file.clp'],
@@ -285,6 +288,7 @@ let s:filename_checks = {
\ 'json': ['file.json', 'file.jsonp', 'file.json-patch', 'file.webmanifest', 'Pipfile.lock', 'file.ipynb', '.babelrc', '.eslintrc', '.prettierrc', '.firebaserc', 'file.slnf'],
\ 'json5': ['file.json5'],
\ 'jsonc': ['file.jsonc'],
+ \ 'jsonnet': ['file.jsonnet', 'file.libjsonnet'],
\ 'jsp': ['file.jsp'],
\ 'julia': ['file.jl'],
\ 'kconfig': ['Kconfig', 'Kconfig.debug', 'Kconfig.file'],
@@ -407,7 +411,7 @@ let s:filename_checks = {
\ 'perl': ['file.plx', 'file.al', 'file.psgi', 'gitolite.rc', '.gitolite.rc', 'example.gitolite.rc'],
\ 'pf': ['pf.conf'],
\ 'pfmain': ['main.cf'],
- \ 'php': ['file.php', 'file.php9', 'file.phtml', 'file.ctp', 'file.phpt'],
+ \ 'php': ['file.php', 'file.php9', 'file.phtml', 'file.ctp', 'file.phpt', 'file.theme'],
\ 'pike': ['file.pike', 'file.pmod'],
\ 'pilrc': ['file.rcp'],
\ 'pine': ['.pinerc', 'pinerc', '.pinercex', 'pinercex'],
@@ -532,7 +536,7 @@ let s:filename_checks = {
\ 'stata': ['file.ado', 'file.do', 'file.imata', 'file.mata'],
\ 'stp': ['file.stp'],
\ 'sudoers': ['any/etc/sudoers', 'sudoers.tmp', '/etc/sudoers', 'any/etc/sudoers.d/file'],
- \ 'supercollider': ['file.quark'],
+ \ 'supercollider': ['file.quark'],
\ 'surface': ['file.sface'],
\ 'svelte': ['file.svelte'],
\ 'svg': ['file.svg'],
@@ -1350,7 +1354,7 @@ func Test_mod_file()
unlet g:filetype_mod
bwipe!
- " RAPID header start with a line containing only "%%%",
+ " RAPID header start with a line containing only "%%%",
" but is not always present.
call writefile(['%%%'], 'modfile.mod')
split modfile.mod
@@ -1366,7 +1370,7 @@ func Test_mod_file()
bwipe!
call delete('modfile.Mod')
- " RAPID is not case sensitive, embedded spaces, sysmodule,
+ " RAPID is not case sensitive, embedded spaces, sysmodule,
" file starts with empty line(s).
call writefile(['', 'MODULE rapidmödüle (SYSMODULE,NOSTEPIN)'], 'modfile.MOD')
split modfile.MOD
@@ -1494,7 +1498,7 @@ func Test_prg_file()
unlet g:filetype_prg
bwipe!
- " RAPID header start with a line containing only "%%%",
+ " RAPID header start with a line containing only "%%%",
" but is not always present.
call writefile(['%%%'], 'prgfile.prg')
split prgfile.prg
@@ -1510,7 +1514,7 @@ func Test_prg_file()
bwipe!
call delete('prgfile.Prg')
- " RAPID is not case sensitive, embedded spaces, sysmodule,
+ " RAPID is not case sensitive, embedded spaces, sysmodule,
" file starts with empty line(s).
call writefile(['', 'MODULE rapidmödüle (SYSMODULE,NOSTEPIN)'], 'prgfile.PRG')
split prgfile.PRG
@@ -1621,7 +1625,7 @@ func Test_sys_file()
unlet g:filetype_sys
bwipe!
- " RAPID header start with a line containing only "%%%",
+ " RAPID header start with a line containing only "%%%",
" but is not always present.
call writefile(['%%%'], 'sysfile.sys')
split sysfile.sys
@@ -1637,7 +1641,7 @@ func Test_sys_file()
bwipe!
call delete('sysfile.Sys')
- " RAPID is not case sensitive, embedded spaces, sysmodule,
+ " RAPID is not case sensitive, embedded spaces, sysmodule,
" file starts with empty line(s).
call writefile(['', 'MODULE rapidmödüle (SYSMODULE,NOSTEPIN)'], 'sysfile.SYS')
split sysfile.SYS
@@ -1824,6 +1828,44 @@ func Test_sig_file()
filetype off
endfunc
+" Test dist#ft#FTsil()
+func Test_sil_file()
+ filetype on
+
+ split Xfile.sil
+ call assert_equal('sil', &filetype)
+ bwipe!
+
+ let lines =<< trim END
+ // valid
+ let protoErasedPathA = \ABCProtocol.a
+
+ // also valid
+ let protoErasedPathA =
+ \ABCProtocol.a
+ END
+ call writefile(lines, 'Xfile.sil')
+
+ split Xfile.sil
+ call assert_equal('sil', &filetype)
+ bwipe!
+
+ " SILE
+
+ call writefile(['% some comment'], 'Xfile.sil')
+ split Xfile.sil
+ call assert_equal('sile', &filetype)
+ bwipe!
+
+ call writefile(['\begin[papersize=a6]{document}foo\end{document}'], 'Xfile.sil')
+ split Xfile.sil
+ call assert_equal('sile', &filetype)
+ bwipe!
+
+ call delete('Xfile.sil')
+ filetype off
+endfunc
+
func Test_inc_file()
filetype on
diff --git a/src/nvim/testdir/test_fnamemodify.vim b/src/nvim/testdir/test_fnamemodify.vim
index 5ae2a5ee17..258a2093bd 100644
--- a/src/nvim/testdir/test_fnamemodify.vim
+++ b/src/nvim/testdir/test_fnamemodify.vim
@@ -11,6 +11,7 @@ func Test_fnamemodify()
call assert_equal('/', fnamemodify('.', ':p')[-1:])
call assert_equal('r', fnamemodify('.', ':p:h')[-1:])
call assert_equal('t', fnamemodify('test.out', ':p')[-1:])
+ call assert_equal($HOME .. "/foo" , fnamemodify('~/foo', ':p'))
call assert_equal('test.out', fnamemodify('test.out', ':.'))
call assert_equal('a', fnamemodify('../testdir/a', ':.'))
call assert_equal('~/testdir/test.out', fnamemodify('test.out', ':~'))
@@ -95,4 +96,9 @@ func Test_fnamemodify_er()
call assert_equal('', fnamemodify(v:_null_string, v:_null_string))
endfunc
+func Test_fnamemodify_fail()
+ call assert_fails('call fnamemodify({}, ":p")', 'E731:')
+ call assert_fails('call fnamemodify("x", {})', 'E731:')
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim
index 147eda5b0a..c41884936e 100644
--- a/src/nvim/testdir/test_functions.vim
+++ b/src/nvim/testdir/test_functions.vim
@@ -2015,6 +2015,27 @@ func Test_getmousepos()
bwipe!
endfunc
+" Test for glob()
+func Test_glob()
+ call assert_equal('', glob(v:_null_string))
+ call assert_equal('', globpath(v:_null_string, v:_null_string))
+
+ call writefile([], 'Xglob1')
+ call writefile([], 'XGLOB2')
+ set wildignorecase
+ " Sort output of glob() otherwise we end up with different
+ " ordering depending on whether file system is case-sensitive.
+ call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
+ " wildignorecase shall be applied even when the pattern contains no wildcards.
+ call assert_equal('XGLOB2', glob('xglob2'))
+ set wildignorecase&
+
+ call delete('Xglob1')
+ call delete('XGLOB2')
+
+ call assert_fails("call glob('*', 0, {})", 'E728:')
+endfunc
+
func HasDefault(msg = 'msg')
return a:msg
endfunc
diff --git a/src/nvim/testdir/test_listdict.vim b/src/nvim/testdir/test_listdict.vim
index 08c415a069..9cef6905a5 100644
--- a/src/nvim/testdir/test_listdict.vim
+++ b/src/nvim/testdir/test_listdict.vim
@@ -165,6 +165,13 @@ func Test_dict()
call assert_equal({'c': 'ccc', '1': 99, 'b': [1, 2, function('strlen')], '3': 33, '-1': {'a': 1}}, d)
call filter(d, 'v:key =~ ''[ac391]''')
call assert_equal({'c': 'ccc', '1': 99, '3': 33, '-1': {'a': 1}}, d)
+
+ " allow key starting with number at the start, not a curly expression
+ call assert_equal({'1foo': 77}, #{1foo: 77})
+
+ " #{expr} is not a curly expression
+ let x = 'x'
+ call assert_equal(#{g: x}, #{g:x})
endfunc
" Dictionary identity
diff --git a/src/nvim/testdir/test_profile.vim b/src/nvim/testdir/test_profile.vim
index fdb6f13e2b..4225b91bc4 100644
--- a/src/nvim/testdir/test_profile.vim
+++ b/src/nvim/testdir/test_profile.vim
@@ -40,8 +40,8 @@ func Test_profile_func()
call writefile(lines, 'Xprofile_func.vim')
call system(GetVimCommand()
\ . ' -es --clean'
- \ . ' -c "so Xprofile_func.vim"'
- \ . ' -c "qall!"')
+ \ . ' --cmd "so Xprofile_func.vim"'
+ \ . ' --cmd "qall!"')
call assert_equal(0, v:shell_error)
let lines = readfile('Xprofile_func.log')
@@ -475,7 +475,7 @@ func Test_profdel_func()
call Foo3()
[CODE]
call writefile(lines, 'Xprofile_file.vim')
- call system(GetVimCommandClean() . ' -es -c "so Xprofile_file.vim" -c q')
+ call system(GetVimCommandClean() . ' -es --cmd "so Xprofile_file.vim" --cmd q')
call assert_equal(0, v:shell_error)
let lines = readfile('Xprofile_file.log')
diff --git a/src/nvim/testdir/test_window_cmd.vim b/src/nvim/testdir/test_window_cmd.vim
index 1f4b9b77c6..1f9d6b59b7 100644
--- a/src/nvim/testdir/test_window_cmd.vim
+++ b/src/nvim/testdir/test_window_cmd.vim
@@ -1464,4 +1464,19 @@ func Test_win_move_statusline()
%bwipe!
endfunc
+func Test_win_equal_last_status()
+ let save_lines = &lines
+ set lines=20
+ set splitbelow
+ set laststatus=0
+
+ split | split | quit
+ call assert_equal(winheight(1), winheight(2))
+
+ let &lines = save_lines
+ set splitbelow&
+ set laststatus&
+endfunc
+
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testing.c b/src/nvim/testing.c
index 4a252dca3e..348d5c6e29 100644
--- a/src/nvim/testing.c
+++ b/src/nvim/testing.c
@@ -419,7 +419,7 @@ static int assert_equalfile(typval_T *argvars)
line2[lineidx] = NUL;
ga_concat(&ga, " after \"");
ga_concat(&ga, line1);
- if (STRCMP(line1, line2) != 0) {
+ if (strcmp(line1, line2) != 0) {
ga_concat(&ga, "\" vs \"");
ga_concat(&ga, line2);
}
diff --git a/src/nvim/textformat.c b/src/nvim/textformat.c
index 5ded0c9ab2..5c53f84700 100644
--- a/src/nvim/textformat.c
+++ b/src/nvim/textformat.c
@@ -97,7 +97,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on
colnr_T len;
colnr_T virtcol;
int orig_col = 0;
- char_u *saved_text = NULL;
+ char *saved_text = NULL;
colnr_T col;
colnr_T end_col;
bool did_do_comment = false;
@@ -117,7 +117,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on
// Don't break until after the comment leader
if (do_comments) {
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
leader_len = get_leader_len((char *)line, NULL, false, true);
if (leader_len == 0 && curbuf->b_p_cin) {
// Check for a line comment after code.
@@ -353,7 +353,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on
if (State & VREPLACE_FLAG) {
// In MODE_VREPLACE state, we will backspace over the text to be
// wrapped, so save a copy now to put on the next line.
- saved_text = vim_strsave(get_cursor_pos_ptr());
+ saved_text = xstrdup(get_cursor_pos_ptr());
curwin->w_cursor.col = orig_col;
saved_text[startcol] = NUL;
@@ -425,7 +425,7 @@ void internal_format(int textwidth, int second_indent, int flags, bool format_on
if (State & VREPLACE_FLAG) {
// In MODE_VREPLACE state we have backspaced over the text to be
// moved, now we re-insert it into the new line.
- ins_bytes((char *)saved_text);
+ ins_bytes(saved_text);
xfree(saved_text);
} else {
// Check if cursor is not past the NUL off the line, cindent
@@ -508,13 +508,13 @@ static bool ends_in_white(linenr_T lnum)
/// @param lnum The first line. White-space is ignored.
///
/// @note the whole of 'leader1' must match 'leader2_len' characters from 'leader2'.
-static bool same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, int leader2_len,
- char_u *leader2_flags)
+static bool same_leader(linenr_T lnum, int leader1_len, char *leader1_flags, int leader2_len,
+ char *leader2_flags)
{
int idx1 = 0, idx2 = 0;
- char_u *p;
- char_u *line1;
- char_u *line2;
+ char *p;
+ char *line1;
+ char *line2;
if (leader1_len == 0) {
return leader2_len == 0;
@@ -552,9 +552,9 @@ static bool same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, i
// Get current line and next line, compare the leaders.
// The first line has to be saved, only one line can be locked at a time.
- line1 = vim_strsave((char_u *)ml_get(lnum));
+ line1 = xstrdup(ml_get(lnum));
for (idx1 = 0; ascii_iswhite(line1[idx1]); idx1++) {}
- line2 = (char_u *)ml_get(lnum + 1);
+ line2 = ml_get(lnum + 1);
for (idx2 = 0; idx2 < leader2_len; idx2++) {
if (!ascii_iswhite(line2[idx2])) {
if (line1[idx1++] != line2[idx2]) {
@@ -605,8 +605,8 @@ static bool paragraph_start(linenr_T lnum)
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)) {
+ if (!same_leader(lnum - 1, leader_len, (char *)leader_flags,
+ next_leader_len, (char *)next_leader_flags)) {
return true; // change of comment leader.
}
return false;
@@ -624,8 +624,8 @@ void auto_format(bool trailblank, bool prev_line)
{
pos_T pos;
colnr_T len;
- char_u *old;
- char_u *new, *pnew;
+ char *old;
+ char *new, *pnew;
int wasatend;
int cc;
@@ -663,7 +663,7 @@ void auto_format(bool trailblank, bool prev_line)
// With the 'c' flag in 'formatoptions' and 't' missing: only format
// comments.
if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
- && get_leader_len((char *)old, NULL, false, true) == 0) {
+ && get_leader_len(old, NULL, false, true) == 0) {
return;
}
@@ -700,10 +700,10 @@ void auto_format(bool trailblank, bool prev_line)
new = get_cursor_line_ptr();
len = (colnr_T)STRLEN(new);
if (curwin->w_cursor.col == len) {
- pnew = vim_strnsave(new, (size_t)len + 2);
+ pnew = xstrnsave(new, (size_t)len + 2);
pnew[len] = ' ';
pnew[len + 1] = NUL;
- ml_replace(curwin->w_cursor.lnum, (char *)pnew, false);
+ ml_replace(curwin->w_cursor.lnum, pnew, false);
// remove the space later
did_add_space = true;
} else {
@@ -1018,15 +1018,15 @@ void format_lines(linenr_T line_count, bool avoid_fex)
// When the comment leader changes, it's the end of the paragraph.
if (curwin->w_cursor.lnum >= curbuf->b_ml.ml_line_count
|| !same_leader(curwin->w_cursor.lnum,
- leader_len, leader_flags,
+ leader_len, (char *)leader_flags,
next_leader_len,
- next_leader_flags)) {
+ (char *)next_leader_flags)) {
// Special case: If the next line starts with a line comment
// and this line has a line comment after some text, the
// paragraph doesn't really end.
if (next_leader_flags == NULL
|| STRNCMP(next_leader_flags, "://", 3) != 0
- || check_linecomment((char *)get_cursor_line_ptr()) == MAXCOL) {
+ || check_linecomment(get_cursor_line_ptr()) == MAXCOL) {
is_end_par = true;
}
}
diff --git a/src/nvim/textobject.c b/src/nvim/textobject.c
index a8f4cc7aeb..621efa44cf 100644
--- a/src/nvim/textobject.c
+++ b/src/nvim/textobject.c
@@ -1032,7 +1032,7 @@ int current_block(oparg_T *oap, long count, bool include, int what, int other)
/// @return true if the cursor is on a "<aaa>" tag. Ignore "<aaa/>".
static bool in_html_tag(bool end_tag)
{
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
char_u *p;
int c;
int lc = NUL;
@@ -1157,7 +1157,7 @@ again:
// Search for matching "</aaa>". First isolate the "aaa".
inc_cursor();
- p = get_cursor_pos_ptr();
+ p = (char_u *)get_cursor_pos_ptr();
for (cp = p;
*cp != NUL && *cp != '>' && !ascii_iswhite(*cp);
MB_PTR_ADV(cp)) {}
@@ -1196,7 +1196,7 @@ again:
}
}
} else {
- char_u *c = get_cursor_pos_ptr();
+ char_u *c = (char_u *)get_cursor_pos_ptr();
// Exclude the '<' of the end tag.
// If the closing tag is on new line, do not decrement cursor, but make
// operation exclusive, so that the linefeed will be selected
@@ -1493,7 +1493,7 @@ static int find_prev_quote(char_u *line, int col_start, int quotechar, char_u *e
bool current_quote(oparg_T *oap, long count, bool include, int quotechar)
FUNC_ATTR_NONNULL_ALL
{
- char_u *line = get_cursor_line_ptr();
+ char_u *line = (char_u *)get_cursor_line_ptr();
int col_end;
int col_start = curwin->w_cursor.col;
bool inclusive = false;
diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c
index d269878f46..728520c20c 100644
--- a/src/nvim/tui/input.c
+++ b/src/nvim/tui/input.c
@@ -406,8 +406,8 @@ static void forward_mouse_event(TermInput *input, TermKeyKey *key)
}
}
- if (button == 0 || (ev != TERMKEY_MOUSE_PRESS && ev != TERMKEY_MOUSE_DRAG
- && ev != TERMKEY_MOUSE_RELEASE)) {
+ if ((button == 0 && ev != TERMKEY_MOUSE_RELEASE)
+ || (ev != TERMKEY_MOUSE_PRESS && ev != TERMKEY_MOUSE_DRAG && ev != TERMKEY_MOUSE_RELEASE)) {
return;
}
@@ -453,7 +453,8 @@ static void forward_mouse_event(TermInput *input, TermKeyKey *key)
len += (size_t)snprintf(buf + len, sizeof(buf) - len, "Drag");
break;
case TERMKEY_MOUSE_RELEASE:
- len += (size_t)snprintf(buf + len, sizeof(buf) - len, "Release");
+ len += (size_t)snprintf(buf + len, sizeof(buf) - len, button ? "Release" : "MouseMove");
+ last_pressed_button = 0;
break;
case TERMKEY_MOUSE_UNKNOWN:
abort();
diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c
index 38e8c15762..471a3fb859 100644
--- a/src/nvim/tui/tui.c
+++ b/src/nvim/tui/tui.c
@@ -103,6 +103,7 @@ struct TUIData {
bool immediate_wrap_after_last_column;
bool bce;
bool mouse_enabled;
+ bool mouse_move_enabled;
bool busy, is_invisible, want_invisible;
bool cork, overflow;
bool cursor_color_changed;
@@ -117,6 +118,7 @@ struct TUIData {
ModeShape showing_mode;
struct {
int enable_mouse, disable_mouse;
+ int enable_mouse_move, disable_mouse_move;
int enable_bracketed_paste, disable_bracketed_paste;
int enable_lr_margin, disable_lr_margin;
int enter_strikethrough_mode;
@@ -236,6 +238,8 @@ static void terminfo_start(UI *ui)
data->showing_mode = SHAPE_IDX_N;
data->unibi_ext.enable_mouse = -1;
data->unibi_ext.disable_mouse = -1;
+ data->unibi_ext.enable_mouse_move = -1;
+ data->unibi_ext.disable_mouse_move = -1;
data->unibi_ext.set_cursor_color = -1;
data->unibi_ext.reset_cursor_color = -1;
data->unibi_ext.enable_bracketed_paste = -1;
@@ -1138,6 +1142,9 @@ static void tui_mouse_on(UI *ui)
TUIData *data = ui->data;
if (!data->mouse_enabled) {
unibi_out_ext(ui, data->unibi_ext.enable_mouse);
+ if (data->mouse_move_enabled) {
+ unibi_out_ext(ui, data->unibi_ext.enable_mouse_move);
+ }
data->mouse_enabled = true;
}
}
@@ -1146,6 +1153,9 @@ static void tui_mouse_off(UI *ui)
{
TUIData *data = ui->data;
if (data->mouse_enabled) {
+ if (data->mouse_move_enabled) {
+ unibi_out_ext(ui, data->unibi_ext.disable_mouse_move);
+ }
unibi_out_ext(ui, data->unibi_ext.disable_mouse);
data->mouse_enabled = false;
}
@@ -1457,9 +1467,18 @@ static void tui_screenshot(UI *ui, String path)
static void tui_option_set(UI *ui, String name, Object value)
{
TUIData *data = ui->data;
- if (strequal(name.data, "termguicolors")) {
+ if (strequal(name.data, "mousemoveevent")) {
+ if (data->mouse_move_enabled != value.data.boolean) {
+ if (data->mouse_enabled) {
+ tui_mouse_off(ui);
+ data->mouse_move_enabled = value.data.boolean;
+ tui_mouse_on(ui);
+ } else {
+ data->mouse_move_enabled = value.data.boolean;
+ }
+ }
+ } else if (strequal(name.data, "termguicolors")) {
ui->rgb = value.data.boolean;
-
data->print_attr_id = -1;
invalidate(ui, 0, data->grid.height, 0, data->grid.width);
} else if (strequal(name.data, "ttimeout")) {
@@ -2135,6 +2154,10 @@ static void augment_terminfo(TUIData *data, const char *term, long vte_version,
"\x1b[?1002h\x1b[?1006h");
data->unibi_ext.disable_mouse = (int)unibi_add_ext_str(ut, "ext.disable_mouse",
"\x1b[?1002l\x1b[?1006l");
+ data->unibi_ext.enable_mouse_move = (int)unibi_add_ext_str(ut, "ext.enable_mouse_move",
+ "\x1b[?1003h");
+ data->unibi_ext.disable_mouse_move = (int)unibi_add_ext_str(ut, "ext.disable_mouse_move",
+ "\x1b[?1003l");
// Extended underline.
// terminfo will have Smulx for this (but no support for colors yet).
diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c
index b8c7834e2b..2fb70eae8a 100644
--- a/src/nvim/ui_compositor.c
+++ b/src/nvim/ui_compositor.c
@@ -98,7 +98,7 @@ void ui_comp_free_all_mem(void)
{
UIEventCallback *event_cb;
map_foreach_value(&ui_event_cbs, event_cb, {
- xfree(event_cb);
+ free_ui_event_callback(event_cb);
})
pmap_destroy(uint32_t)(&ui_event_cbs);
}
diff --git a/src/nvim/undo.c b/src/nvim/undo.c
index 5f086df4e9..891a42380e 100644
--- a/src/nvim/undo.c
+++ b/src/nvim/undo.c
@@ -621,7 +621,7 @@ void u_compute_hash(buf_T *buf, char_u *hash)
context_sha256_T ctx;
sha256_start(&ctx);
for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
- char_u *p = ml_get_buf(buf, lnum, false);
+ char_u *p = (char_u *)ml_get_buf(buf, lnum, false);
sha256_update(&ctx, p, (uint32_t)(STRLEN(p) + 1));
}
sha256_finish(&ctx, hash);
@@ -1038,7 +1038,7 @@ static bool serialize_uep(bufinfo_T *bi, u_entry_T *uep)
if (!undo_write_bytes(bi, len, 4)) {
return false;
}
- if (len > 0 && !undo_write(bi, uep->ue_array[i], len)) {
+ if (len > 0 && !undo_write(bi, (char_u *)uep->ue_array[i], len)) {
return false;
}
}
@@ -1064,7 +1064,7 @@ static u_entry_T *unserialize_uep(bufinfo_T *bi, bool *error, const char *file_n
memset(array, 0, sizeof(char_u *) * (size_t)uep->ue_size);
}
}
- uep->ue_array = array;
+ uep->ue_array = (char **)array;
for (size_t i = 0; i < (size_t)uep->ue_size; i++) {
int line_len = undo_read_4c(bi);
@@ -2283,7 +2283,7 @@ static void u_undoredo(int undo, bool do_buf_event)
// line.
long i;
for (i = 0; i < newsize && i < oldsize; i++) {
- if (STRCMP(uep->ue_array[i], ml_get(top + 1 + (linenr_T)i)) != 0) {
+ if (strcmp(uep->ue_array[i], ml_get(top + 1 + (linenr_T)i)) != 0) {
break;
}
}
@@ -2327,9 +2327,9 @@ static void u_undoredo(int undo, bool do_buf_event)
// If the file is empty, there is an empty line 1 that we
// should get rid of, by replacing it with the new line
if (empty_buffer && lnum == 0) {
- ml_replace((linenr_T)1, (char *)uep->ue_array[i], true);
+ ml_replace((linenr_T)1, uep->ue_array[i], true);
} else {
- ml_append(lnum, (char *)uep->ue_array[i], (colnr_T)0, false);
+ ml_append(lnum, uep->ue_array[i], (colnr_T)0, false);
}
xfree(uep->ue_array[i]);
}
@@ -2363,7 +2363,7 @@ static void u_undoredo(int undo, bool do_buf_event)
u_newcount += newsize;
u_oldcount += oldsize;
uep->ue_size = oldsize;
- uep->ue_array = newarray;
+ uep->ue_array = (char **)newarray;
uep->ue_bot = top + newsize + 1;
// insert this entry in front of the new entry list
@@ -2636,14 +2636,14 @@ void ex_undolist(exarg_T *eap)
if (uhp->uh_prev.ptr == NULL && uhp->uh_walk != nomark
&& uhp->uh_walk != mark) {
vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7d ", uhp->uh_seq, changes);
- undo_fmt_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff), uhp->uh_time);
+ undo_fmt_time((char_u *)IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff), uhp->uh_time);
if (uhp->uh_save_nr > 0) {
while (STRLEN(IObuff) < 33) {
STRCAT(IObuff, " ");
}
vim_snprintf_add((char *)IObuff, IOSIZE, " %3ld", uhp->uh_save_nr);
}
- GA_APPEND(char_u *, &ga, vim_strsave(IObuff));
+ GA_APPEND(char *, &ga, xstrdup((char *)IObuff));
}
uhp->uh_walk = mark;
@@ -2744,7 +2744,7 @@ void u_find_first_changed(void)
linenr_T lnum;
for (lnum = 1; lnum < curbuf->b_ml.ml_line_count
&& lnum <= uep->ue_size; lnum++) {
- if (STRCMP(ml_get_buf(curbuf, lnum, false), uep->ue_array[lnum - 1]) != 0) {
+ if (strcmp(ml_get_buf(curbuf, lnum, false), uep->ue_array[lnum - 1]) != 0) {
clearpos(&(uhp->uh_cursor));
uhp->uh_cursor.lnum = lnum;
return;
@@ -3027,16 +3027,16 @@ void u_blockfree(buf_T *buf)
/// @param lnum the line to copy
static char_u *u_save_line(linenr_T lnum)
{
- return u_save_line_buf(curbuf, lnum);
+ return (char_u *)u_save_line_buf(curbuf, lnum);
}
/// Allocate memory and copy line into it
///
/// @param lnum line to copy
/// @param buf buffer to copy from
-static char_u *u_save_line_buf(buf_T *buf, linenr_T lnum)
+static char *u_save_line_buf(buf_T *buf, linenr_T lnum)
{
- return vim_strsave(ml_get_buf(buf, lnum, false));
+ return xstrdup(ml_get_buf(buf, lnum, false));
}
/// Check if the 'modified' flag is set, or 'ff' has changed (only need to
diff --git a/src/nvim/undo_defs.h b/src/nvim/undo_defs.h
index 4b64f97919..7c065c540b 100644
--- a/src/nvim/undo_defs.h
+++ b/src/nvim/undo_defs.h
@@ -21,11 +21,11 @@ typedef struct {
typedef struct u_entry u_entry_T;
struct u_entry {
- u_entry_T *ue_next; // pointer to next entry in list
+ u_entry_T *ue_next; // pointer to next entry in list
linenr_T ue_top; // number of line above undo block
linenr_T ue_bot; // number of line below undo block
linenr_T ue_lcount; // linecount when u_save called
- char_u **ue_array; // array of lines in undo block
+ char **ue_array; // array of lines in undo block
long ue_size; // number of lines in ue_array
#ifdef U_DEBUG
int ue_magic; // magic number to check allocation
diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c
index 3726273d28..6d6ba2466e 100644
--- a/src/nvim/usercmd.c
+++ b/src/nvim/usercmd.c
@@ -280,7 +280,7 @@ char *get_user_commands(expand_T *xp FUNC_ATTR_UNUSED, int idx)
char *name = USER_CMD(idx)->uc_name;
for (int i = 0; i < buf->b_ucmds.ga_len; i++) {
- if (STRCMP(name, USER_CMD_GA(&buf->b_ucmds, i)->uc_name) == 0) {
+ if (strcmp(name, USER_CMD_GA(&buf->b_ucmds, i)->uc_name) == 0) {
// global command is overruled by buffer-local one
return "";
}
@@ -1006,7 +1006,7 @@ void ex_delcommand(exarg_T *eap)
for (;;) {
for (i = 0; i < gap->ga_len; i++) {
cmd = USER_CMD_GA(gap, i);
- res = STRCMP(arg, cmd->uc_name);
+ res = strcmp(arg, cmd->uc_name);
if (res <= 0) {
break;
}
diff --git a/src/nvim/vim.h b/src/nvim/vim.h
index ec8d6ab153..af0f231b37 100644
--- a/src/nvim/vim.h
+++ b/src/nvim/vim.h
@@ -205,7 +205,6 @@ enum { FOLD_TEXT_LEN = 51, }; //!< buffer size for get_foldtext()
#define STRCPY(d, s) strcpy((char *)(d), (char *)(s))
#define STRNCPY(d, s, n) strncpy((char *)(d), (char *)(s), (size_t)(n))
#define STRLCPY(d, s, n) xstrlcpy((char *)(d), (char *)(s), (size_t)(n))
-#define STRCMP(d, s) strcmp((char *)(d), (char *)(s))
#define STRNCMP(d, s, n) strncmp((char *)(d), (char *)(s), (size_t)(n))
#ifdef HAVE_STRCASECMP
# define STRICMP(d, s) strcasecmp((char *)(d), (char *)(s))
@@ -231,7 +230,6 @@ enum { FOLD_TEXT_LEN = 51, }; //!< buffer size for get_foldtext()
#endif
#define STRCAT(d, s) strcat((char *)(d), (char *)(s)) // NOLINT(runtime/printf)
-#define STRLCAT(d, s, n) xstrlcat((char *)(d), (char *)(s), (size_t)(n))
// Character used as separated in autoload function/variable names.
#define AUTOLOAD_CHAR '#'
@@ -246,23 +244,6 @@ enum { FOLD_TEXT_LEN = 51, }; //!< buffer size for get_foldtext()
#include "nvim/path.h"
-/// Compare file names
-///
-/// On some systems case in a file name does not matter, on others it does.
-///
-/// @note Does not account for maximum name lengths and things like "../dir",
-/// thus it is not 100% accurate. OS may also use different algorithm for
-/// case-insensitive comparison.
-///
-/// @param[in] x First file name to compare.
-/// @param[in] y Second file name to compare.
-///
-/// @return 0 for equal file names, non-zero otherwise.
-#define FNAMECMP(x, y) path_fnamecmp((const char *)(x), (const char *)(y))
-#define FNAMENCMP(x, y, n) path_fnamencmp((const char *)(x), \
- (const char *)(y), \
- (size_t)(n))
-
// Enums need a typecast to be used as array index.
#define HL_ATTR(n) hl_attr_active[(int)(n)]
diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c
index 387b9d61f2..d12a690b83 100644
--- a/src/nvim/viml/parser/expressions.c
+++ b/src/nvim/viml/parser/expressions.c
@@ -66,8 +66,6 @@
#include "nvim/viml/parser/expressions.h"
#include "nvim/viml/parser/parser.h"
-#define VIM_STR2NR(s, ...) vim_str2nr((const char_u *)(s), __VA_ARGS__)
-
typedef kvec_withinit_t(ExprASTNode **, 16) ExprASTStack;
/// Which nodes may be wanted
@@ -371,7 +369,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags)
significand_part = significand_part * 10 + (pline.data[i] - '0');
}
if (exp_start) {
- VIM_STR2NR(pline.data + exp_start, NULL, NULL, 0, NULL, &exp_part,
+ vim_str2nr(pline.data + exp_start, NULL, NULL, 0, NULL, &exp_part,
(int)(ret.len - exp_start), false);
}
if (exp_negative) {
@@ -389,7 +387,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags)
} else {
int len;
int prep;
- VIM_STR2NR(pline.data, &prep, &len, STR2NR_ALL, NULL,
+ vim_str2nr(pline.data, &prep, &len, STR2NR_ALL, NULL,
&ret.data.num.val.integer, (int)pline.size, false);
ret.len = (size_t)len;
const uint8_t bases[] = {
@@ -696,8 +694,7 @@ LexExprToken viml_pexpr_next_token(ParserState *const pstate, const int flags)
// Everything else is not valid.
default:
- ret.len = (size_t)utfc_ptr2len_len((const char_u *)pline.data,
- (int)pline.size);
+ ret.len = (size_t)utfc_ptr2len_len(pline.data, (int)pline.size);
ret.type = kExprLexInvalid;
ret.data.err.type = kExprLexPlainIdentifier;
ret.data.err.msg = _("E15: Unidentified character: %.*s");
diff --git a/src/nvim/window.c b/src/nvim/window.c
index c0b73ff837..63a6eb9fb6 100644
--- a/src/nvim/window.c
+++ b/src/nvim/window.c
@@ -970,21 +970,19 @@ static int check_split_disallowed(void)
return OK;
}
-/*
- * split the current window, implements CTRL-W s and :split
- *
- * "size" is the height or width for the new window, 0 to use half of current
- * height or width.
- *
- * "flags":
- * WSP_ROOM: require enough room for new window
- * WSP_VERT: vertical split.
- * WSP_TOP: open window at the top-left of the screen (help window).
- * WSP_BOT: open window at the bottom-right of the screen (quickfix window).
- * WSP_HELP: creating the help window, keep layout snapshot
- *
- * return FAIL for failure, OK otherwise
- */
+// split the current window, implements CTRL-W s and :split
+//
+// "size" is the height or width for the new window, 0 to use half of current
+// height or width.
+//
+// "flags":
+// WSP_ROOM: require enough room for new window
+// WSP_VERT: vertical split.
+// WSP_TOP: open window at the top-left of the screen (help window).
+// WSP_BOT: open window at the bottom-right of the screen (quickfix window).
+// WSP_HELP: creating the help window, keep layout snapshot
+//
+// return FAIL for failure, OK otherwise
int win_split(int size, int flags)
{
if (check_split_disallowed() == FAIL) {
@@ -1014,12 +1012,10 @@ int win_split(int size, int flags)
return win_split_ins(size, flags, NULL, 0);
}
-/*
- * When "new_wp" is NULL: split the current window in two.
- * When "new_wp" is not NULL: insert this window at the far
- * top/left/right/bottom.
- * return FAIL for failure, OK otherwise
- */
+// When "new_wp" is NULL: split the current window in two.
+// When "new_wp" is not NULL: insert this window at the far
+// top/left/right/bottom.
+// return FAIL for failure, OK otherwise
int win_split_ins(int size, int flags, win_T *new_wp, int dir)
{
win_T *wp = new_wp;
@@ -1069,10 +1065,8 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
layout = FR_ROW;
- /*
- * Check if we are able to split the current window and compute its
- * width.
- */
+ // Check if we are able to split the current window and compute its
+ // width.
// Current window requires at least 1 space.
wmw1 = (p_wmw == 0 ? 1 : (int)p_wmw);
needed = wmw1 + 1;
@@ -1243,9 +1237,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
}
}
- /*
- * allocate new window structure and link it in the window list
- */
+ // allocate new window structure and link it in the window list
if ((flags & WSP_TOP) == 0
&& ((flags & WSP_BOT)
|| (flags & WSP_BELOW)
@@ -1282,9 +1274,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
CLEAR_FIELD(wp->w_border_adj);
}
- /*
- * Reorganise the tree of frames to insert the new window.
- */
+ // Reorganise the tree of frames to insert the new window.
if (flags & (WSP_TOP | WSP_BOT)) {
if ((topframe->fr_layout == FR_COL && (flags & WSP_VERT) == 0)
|| (topframe->fr_layout == FR_ROW && (flags & WSP_VERT) != 0)) {
@@ -1489,9 +1479,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
msg_col = 0; // put position back at start of line
}
- /*
- * equalize the window sizes.
- */
+ // equalize the window sizes.
if (do_equal || dir != 0) {
win_equal(wp, true, (flags & WSP_VERT) ? (dir == 'v' ? 'b' : 'h') : (dir == 'h' ? 'b' : 'v'));
}
@@ -1527,13 +1515,11 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
return OK;
}
-/*
- * Initialize window "newp" from window "oldp".
- * Used when splitting a window and when creating a new tab page.
- * The windows will both edit the same buffer.
- * WSP_NEWLOC may be specified in flags to prevent the location list from
- * being copied.
- */
+// Initialize window "newp" from window "oldp".
+// Used when splitting a window and when creating a new tab page.
+// The windows will both edit the same buffer.
+// WSP_NEWLOC may be specified in flags to prevent the location list from
+// being copied.
static void win_init(win_T *newp, win_T *oldp, int flags)
{
int i;
@@ -1591,10 +1577,8 @@ static void win_init(win_T *newp, win_T *oldp, int flags)
newp->w_winbar_height = oldp->w_winbar_height;
}
-/*
- * Initialize window "newp" from window "old".
- * Only the essential things are copied.
- */
+// Initialize window "newp" from window "old".
+// Only the essential things are copied.
static void win_init_some(win_T *newp, win_T *oldp)
{
// Use the same argument list.
@@ -1671,9 +1655,7 @@ bool win_valid_any_tab(win_T *win) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
return false;
}
-/*
- * Return the number of windows.
- */
+// Return the number of windows.
int win_count(void)
{
int count = 0;
@@ -1746,9 +1728,7 @@ int make_windows(int count, bool vertical)
return count - todo;
}
-/*
- * Exchange current and next window
- */
+// Exchange current and next window
static void win_exchange(long Prenum)
{
frame_T *frp;
@@ -1768,9 +1748,7 @@ static void win_exchange(long Prenum)
return;
}
- /*
- * find window to exchange with
- */
+ // find window to exchange with
if (Prenum) {
frp = curwin->w_frame->fr_parent->fr_child;
while (frp != NULL && --Prenum > 0) {
@@ -1789,14 +1767,12 @@ static void win_exchange(long Prenum)
}
wp = frp->fr_win;
- /*
- * 1. remove curwin from the list. Remember after which window it was in wp2
- * 2. insert curwin before wp in the list
- * if wp != wp2
- * 3. remove wp from the list
- * 4. insert wp after wp2
- * 5. exchange the status line height, winbar height, hsep height and vsep width.
- */
+ // 1. remove curwin from the list. Remember after which window it was in wp2
+ // 2. insert curwin before wp in the list
+ // if wp != wp2
+ // 3. remove wp from the list
+ // 4. insert wp after wp2
+ // 5. exchange the status line height, winbar height, hsep height and vsep width.
wp2 = curwin->w_prev;
frp2 = curwin->w_frame->fr_prev;
if (wp->w_prev != curwin) {
@@ -1927,9 +1903,7 @@ static void win_rotate(bool upwards, int count)
redraw_all_later(UPD_NOT_VALID);
}
-/*
- * Move the current window to the very top/bottom/left/right of the screen.
- */
+// Move the current window to the very top/bottom/left/right of the screen.
static void win_totop(int size, int flags)
{
int dir = 0;
@@ -1973,10 +1947,8 @@ static void win_totop(int size, int flags)
}
}
-/*
- * Move window "win1" to below/right of "win2" and make "win1" the current
- * window. Only works within the same frame!
- */
+// Move window "win1" to below/right of "win2" and make "win1" the current
+// window. Only works within the same frame!
void win_move_after(win_T *win1, win_T *win2)
{
int height;
@@ -2076,7 +2048,7 @@ static int get_maximum_wincount(frame_T *fr, int height)
}
/// Make all windows the same height.
-///'next_curwin' will soon be the current window, make sure it has enough rows.
+/// '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
@@ -2146,11 +2118,9 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
totwincount = (n + extra_sep) / ((int)p_wmw + 1);
has_next_curwin = frame_has_win(topfr, next_curwin);
- /*
- * Compute width for "next_curwin" window and room available for
- * other windows.
- * "m" is the minimal width when counting p_wiw for "next_curwin".
- */
+ // Compute width for "next_curwin" window and room available for
+ // other windows.
+ // "m" is the minimal width when counting p_wiw for "next_curwin".
m = frame_minwidth(topfr, next_curwin);
room = width - m;
if (room < 0) {
@@ -2274,11 +2244,9 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
totwincount = get_maximum_wincount(topfr, n + extra_sep);
has_next_curwin = frame_has_win(topfr, next_curwin);
- /*
- * Compute height for "next_curwin" window and room available for
- * other windows.
- * "m" is the minimal height when counting p_wh for "next_curwin".
- */
+ // Compute height for "next_curwin" window and room available for
+ // other windows.
+ // "m" is the minimal height when counting p_wh for "next_curwin".
m = frame_minheight(topfr, next_curwin);
room = height - m;
if (room < 0) {
@@ -2594,14 +2562,12 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev
free_buf = false;
}
- /*
- * Closing the last window in a tab page. First go to another tab
- * page and then close the window and the tab page. This avoids that
- * curwin and curtab are invalid while we are freeing memory, they may
- * be used in GUI events.
- * Don't trigger autocommands yet, they may use wrong values, so do
- * that below.
- */
+ // Closing the last window in a tab page. First go to another tab
+ // page and then close the window and the tab page. This avoids that
+ // curwin and curtab are invalid while we are freeing memory, they may
+ // be used in GUI events.
+ // Don't trigger autocommands yet, they may use wrong values, so do
+ // that below.
goto_tabpage_tp(alt_tabpage(), false, true);
redraw_tabline = true;
@@ -2745,10 +2711,8 @@ int win_close(win_T *win, bool free_buf, bool force)
}
}
- /*
- * Be careful: If autocommands delete the window or cause this window
- * to be the last one left, return now.
- */
+ // Be careful: If autocommands delete the window or cause this window
+ // to be the last one left, return now.
if (wp->w_buffer != curbuf) {
reset_VIsual_and_resel(); // stop Visual mode
@@ -2860,10 +2824,8 @@ int win_close(win_T *win, bool free_buf, bool force)
if (win == curwin) {
curwin = wp;
if (wp->w_p_pvw || bt_quickfix(wp->w_buffer)) {
- /*
- * If the cursor goes to the preview or the quickfix window, try
- * finding another window to go to.
- */
+ // If the cursor goes to the preview or the quickfix window, try
+ // finding another window to go to.
for (;;) {
if (wp->w_next == NULL) {
wp = firstwin;
@@ -2887,6 +2849,11 @@ int win_close(win_T *win, bool free_buf, bool force)
check_cursor();
}
+ // If last window has a status line now and we don't want one,
+ // remove the status line. Do this before win_equal(), because
+ // it may change the height of a window.
+ last_status(false);
+
if (!was_floating) {
if (!curwin->w_floating && p_ea && (*p_ead == 'b' || *p_ead == dir)) {
// If the frame of the closed window contains the new current window,
@@ -2908,12 +2875,6 @@ int win_close(win_T *win, bool free_buf, bool force)
split_disallowed--;
- /*
- * If last window has a status line now and we don't want one,
- * remove the status line.
- */
- last_status(false);
-
// After closing the help window, try restoring the window layout from
// before it was opened.
if (help_window) {
@@ -2955,13 +2916,11 @@ static void do_autocmd_winclosed(win_T *win)
recursive = false;
}
-/*
- * Close window "win" in tab page "tp", which is not the current tab page.
- * This may be the last window in that tab page and result in closing the tab,
- * thus "tp" may become invalid!
- * Caller must check if buffer is hidden and whether the tabline needs to be
- * updated.
- */
+// Close window "win" in tab page "tp", which is not the current tab page.
+// This may be the last window in that tab page and result in closing the tab,
+// thus "tp" may become invalid!
+// Caller must check if buffer is hidden and whether the tabline needs to be
+// updated.
void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp)
{
int dir;
@@ -3138,16 +3097,12 @@ win_T *winframe_remove(win_T *win, int *dirp, tabpage_T *tp)
frame_T *frp_close = win->w_frame;
win_T *wp;
- /*
- * If there is only one window there is nothing to remove.
- */
+ // If there is only one window there is nothing to remove.
if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin) {
return NULL;
}
- /*
- * Remove the window from its frame.
- */
+ // Remove the window from its frame.
frp2 = win_altframe(win, tp);
wp = frame2win(frp2);
@@ -3334,9 +3289,7 @@ static frame_T *win_altframe(win_T *win, tabpage_T *tp)
return target_fr;
}
-/*
- * Return the tabpage that will be used if the current one is closed.
- */
+// Return the tabpage that will be used if the current one is closed.
static tabpage_T *alt_tabpage(void)
{
tabpage_T *tp;
@@ -3351,9 +3304,7 @@ static tabpage_T *alt_tabpage(void)
return tp;
}
-/*
- * Find the left-upper window in frame "frp".
- */
+// Find the left-upper window in frame "frp".
win_T *frame2win(frame_T *frp)
{
while (frp->fr_win == NULL) {
@@ -3557,10 +3508,8 @@ static bool frame_fixed_width(frame_T *frp)
return true;
}
-/*
- * Add a status line to windows at the bottom of "frp".
- * Note: Does not check if there is room!
- */
+// Add a status line to windows at the bottom of "frp".
+// Note: Does not check if there is room!
static void frame_add_statusline(frame_T *frp)
{
win_T *wp;
@@ -3748,17 +3697,13 @@ static void frame_add_hsep(const frame_T *frp)
}
}
-/*
- * Set frame width from the window it contains.
- */
+// Set frame width from the window it contains.
static void frame_fix_width(win_T *wp)
{
wp->w_frame->fr_width = wp->w_width + wp->w_vsep_width;
}
-/*
- * Set frame height from the window it contains.
- */
+// Set frame height from the window it contains.
static void frame_fix_height(win_T *wp)
FUNC_ATTR_NONNULL_ALL
{
@@ -3913,12 +3858,10 @@ void close_others(int message, int forceit)
}
}
-/*
- * Allocate the first window and put an empty buffer in it.
- * Called from main().
- *
- * Return FAIL when something goes wrong.
- */
+// Allocate the first window and put an empty buffer in it.
+// Called from main().
+//
+// Return FAIL when something goes wrong.
int win_alloc_first(void)
{
if (win_alloc_firstwin(NULL) == FAIL) {
@@ -3949,12 +3892,10 @@ void win_alloc_aucmd_win(void)
RESET_BINDING(aucmd_win);
}
-/*
- * Allocate the first window or the first window in a new tab page.
- * When "oldwin" is NULL create an empty buffer for it.
- * When "oldwin" is not NULL copy info from it to the new window.
- * Return FAIL when something goes wrong (out of memory).
- */
+// Allocate the first window or the first window in a new tab page.
+// When "oldwin" is NULL create an empty buffer for it.
+// When "oldwin" is not NULL copy info from it to the new window.
+// Return FAIL when something goes wrong (out of memory).
static int win_alloc_firstwin(win_T *oldwin)
{
curwin = win_alloc(NULL, false);
@@ -3986,9 +3927,7 @@ static int win_alloc_firstwin(win_T *oldwin)
return OK;
}
-/*
- * Create a frame for window "wp".
- */
+// Create a frame for window "wp".
static void new_frame(win_T *wp)
{
frame_T *frp = xcalloc(1, sizeof(frame_T));
@@ -3998,9 +3937,7 @@ static void new_frame(win_T *wp)
frp->fr_win = wp;
}
-/*
- * Initialize the window and frame size to the maximum.
- */
+// Initialize the window and frame size to the maximum.
void win_init_size(void)
{
firstwin->w_height = (int)ROWS_AVAIL;
@@ -4014,9 +3951,7 @@ void win_init_size(void)
topframe->fr_width = Columns;
}
-/*
- * Allocate a new tabpage_T and init the values.
- */
+// Allocate a new tabpage_T and init the values.
static tabpage_T *alloc_tabpage(void)
{
static int last_tp_handle = 0;
@@ -4138,11 +4073,9 @@ int win_new_tabpage(int after, char_u *filename)
return FAIL;
}
-/*
- * Open a new tab page if ":tab cmd" was used. It will edit the same buffer,
- * like with ":split".
- * Returns OK if a new tab page was created, FAIL otherwise.
- */
+// Open a new tab page if ":tab cmd" was used. It will edit the same buffer,
+// like with ":split".
+// Returns OK if a new tab page was created, FAIL otherwise.
int may_open_tabpage(void)
{
int n = (cmdmod.cmod_tab == 0) ? postponed_split_tab : cmdmod.cmod_tab;
@@ -4155,10 +4088,8 @@ int may_open_tabpage(void)
return FAIL;
}
-/*
- * Create up to "maxcount" tabpages with empty windows.
- * Returns the number of resulting tab pages.
- */
+// Create up to "maxcount" tabpages with empty windows.
+// Returns the number of resulting tab pages.
int make_tabpages(int maxcount)
{
int count = maxcount;
@@ -4169,10 +4100,8 @@ int make_tabpages(int maxcount)
count = (int)p_tpm;
}
- /*
- * Don't execute autocommands while creating the tab pages. Must do that
- * when putting the buffers in the windows.
- */
+ // Don't execute autocommands while creating the tab pages. Must do that
+ // when putting the buffers in the windows.
block_autocmds();
for (todo = count - 1; todo > 0; todo--) {
@@ -4239,9 +4168,7 @@ void close_tabpage(tabpage_T *tab)
free_tabpage(tab);
}
-/*
- * Find tab page "n" (first one is 1). Returns NULL when not found.
- */
+// Find tab page "n" (first one is 1). Returns NULL when not found.
tabpage_T *find_tabpage(int n)
{
tabpage_T *tp;
@@ -4253,10 +4180,8 @@ tabpage_T *find_tabpage(int n)
return tp;
}
-/*
- * Get index of tab page "tp". First one has index 1.
- * When not found returns number of tab pages plus one.
- */
+// Get index of tab page "tp". First one has index 1.
+// When not found returns number of tab pages plus one.
int tabpage_index(tabpage_T *ftp)
{
int i = 1;
@@ -4412,10 +4337,8 @@ static void tabpage_check_windows(tabpage_T *old_curtab)
}
}
-/*
- * Go to tab page "n". For ":tab N" and "Ngt".
- * When "n" is 9999 go to the last tab page.
- */
+// Go to tab page "n". For ":tab N" and "Ngt".
+// When "n" is 9999 go to the last tab page.
void goto_tabpage(int n)
{
tabpage_T *tp = NULL; // shut up compiler
@@ -4504,10 +4427,8 @@ bool goto_tabpage_lastused(void)
return false;
}
-/*
- * Enter window "wp" in tab page "tp".
- * Also updates the GUI tab.
- */
+// Enter window "wp" in tab page "tp".
+// Also updates the GUI tab.
void goto_tabpage_win(tabpage_T *tp, win_T *wp)
{
goto_tabpage_tp(tp, true, true);
@@ -4570,13 +4491,11 @@ void tabpage_move(int nr)
redraw_tabline = true;
}
-/*
- * Go to another window.
- * When jumping to another buffer, stop Visual mode. Do this before
- * changing windows so we can yank the selection into the '*' register.
- * When jumping to another window on the same buffer, adjust its cursor
- * position to keep the same Visual area.
- */
+// Go to another window.
+// When jumping to another buffer, stop Visual mode. Do this before
+// changing windows so we can yank the selection into the '*' register.
+// When jumping to another window on the same buffer, adjust its cursor
+// position to keep the same Visual area.
void win_goto(win_T *wp)
{
win_T *owp = curwin;
@@ -4603,9 +4522,7 @@ void win_goto(win_T *wp)
}
}
-/*
- * Find the tabpage for window "win".
- */
+// Find the tabpage for window "win".
tabpage_T *win_find_tabpage(win_T *win)
{
FOR_ALL_TAB_WINDOWS(tp, wp) {
@@ -4638,10 +4555,8 @@ win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count)
}
while (count--) {
- /*
- * First go upwards in the tree of frames until we find an upwards or
- * downwards neighbor.
- */
+ // First go upwards in the tree of frames until we find an upwards or
+ // downwards neighbor.
fr = foundfr;
for (;;) {
if (fr == tp->tp_topframe) {
@@ -4658,9 +4573,7 @@ win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, long count)
fr = fr->fr_parent;
}
- /*
- * Now go downwards to find the bottom or top frame in it.
- */
+ // Now go downwards to find the bottom or top frame in it.
for (;;) {
if (nfr->fr_layout == FR_LEAF) {
foundfr = nfr;
@@ -4721,10 +4634,8 @@ win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count)
}
while (count--) {
- /*
- * First go upwards in the tree of frames until we find a left or
- * right neighbor.
- */
+ // First go upwards in the tree of frames until we find a left or
+ // right neighbor.
fr = foundfr;
for (;;) {
if (fr == tp->tp_topframe) {
@@ -4741,9 +4652,7 @@ win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, long count)
fr = fr->fr_parent;
}
- /*
- * Now go downwards to find the leftmost or rightmost frame in it.
- */
+ // Now go downwards to find the leftmost or rightmost frame in it.
for (;;) {
if (nfr->fr_layout == FR_LEAF) {
foundfr = nfr;
@@ -5036,9 +4945,7 @@ static win_T *win_alloc(win_T *after, bool hidden)
// initialized yet. gui_create_scrollbar() may trigger a FocusGained
// event.
block_autocmds();
- /*
- * link the window in the window list
- */
+ // link the window in the window list
if (!hidden) {
win_append(after, new_wp);
}
@@ -5202,9 +5109,7 @@ void win_free_grid(win_T *wp, bool reinit)
}
}
-/*
- * Append window "wp" in the window list after window "after".
- */
+// Append window "wp" in the window list after window "after".
void win_append(win_T *after, win_T *wp)
{
win_T *before;
@@ -5250,9 +5155,7 @@ void win_remove(win_T *wp, tabpage_T *tp)
}
}
-/*
- * Append frame "frp" in a frame list after frame "after".
- */
+// Append frame "frp" in a frame list after frame "after".
static void frame_append(frame_T *after, frame_T *frp)
{
frp->fr_next = after->fr_next;
@@ -5263,9 +5166,7 @@ static void frame_append(frame_T *after, frame_T *frp)
frp->fr_prev = after;
}
-/*
- * Insert frame "frp" in a frame list before frame "before".
- */
+// Insert frame "frp" in a frame list before frame "before".
static void frame_insert(frame_T *before, frame_T *frp)
{
frp->fr_next = before;
@@ -5278,9 +5179,7 @@ static void frame_insert(frame_T *before, frame_T *frp)
}
}
-/*
- * Remove a frame from a frame list.
- */
+// Remove a frame from a frame list.
static void frame_remove(frame_T *frp)
{
if (frp->fr_prev != NULL) {
@@ -5390,9 +5289,7 @@ void may_trigger_winscrolled(void)
}
}
-/*
- * Save the size of all windows in "gap".
- */
+// Save the size of all windows in "gap".
void win_size_save(garray_T *gap)
{
ga_init(gap, (int)sizeof(int), 1);
@@ -5459,12 +5356,10 @@ void win_reconfig_floats(void)
}
}
-/*
- * Update the position of the windows in frame "topfrp", using the width and
- * height of the frames.
- * "*row" and "*col" are the top-left position of the frame. They are updated
- * to the bottom-right position plus one.
- */
+// Update the position of the windows in frame "topfrp", using the width and
+// height of the frames.
+// "*row" and "*col" are the top-left position of the frame. They are updated
+// to the bottom-right position plus one.
static void frame_comp_pos(frame_T *topfrp, int *row, int *col)
{
win_T *wp;
@@ -5500,19 +5395,15 @@ static void frame_comp_pos(frame_T *topfrp, int *row, int *col)
}
}
-/*
- * Set current window height and take care of repositioning other windows to
- * fit around it.
- */
+// Set current window height and take care of repositioning other windows to
+// fit around it.
void win_setheight(int height)
{
win_setheight_win(height, curwin);
}
-/*
- * Set the window height of window "win" and take care of repositioning other
- * windows to fit around it.
- */
+// Set the window height of window "win" and take care of repositioning other
+// windows to fit around it.
void win_setheight_win(int height, win_T *win)
{
// Always keep current window at least one line high, even when 'winminheight' is zero.
@@ -5547,19 +5438,17 @@ void win_setheight_win(int height, win_T *win)
}
}
-/*
- * Set the height of a frame to "height" and take care that all frames and
- * windows inside it are resized. Also resize frames on the left and right if
- * the are in the same FR_ROW frame.
- *
- * Strategy:
- * If the frame is part of a FR_COL frame, try fitting the frame in that
- * frame. If that doesn't work (the FR_COL frame is too small), recursively
- * go to containing frames to resize them and make room.
- * If the frame is part of a FR_ROW frame, all frames must be resized as well.
- * Check for the minimal height of the FR_ROW frame.
- * At the top level we can also use change the command line height.
- */
+// Set the height of a frame to "height" and take care that all frames and
+// windows inside it are resized. Also resize frames on the left and right if
+// the are in the same FR_ROW frame.
+//
+// Strategy:
+// If the frame is part of a FR_COL frame, try fitting the frame in that
+// frame. If that doesn't work (the FR_COL frame is too small), recursively
+// go to containing frames to resize them and make room.
+// If the frame is part of a FR_ROW frame, all frames must be resized as well.
+// Check for the minimal height of the FR_ROW frame.
+// At the top level we can also use change the command line height.
static void frame_setheight(frame_T *curfrp, int height)
{
int room; // total number of lines available
@@ -5595,16 +5484,13 @@ static void frame_setheight(frame_T *curfrp, int height)
}
frame_setheight(curfrp->fr_parent, height);
} else {
- /*
- * Column of frames: try to change only frames in this column.
- */
- /*
- * Do this twice:
- * 1: compute room available, if it's not enough try resizing the
- * containing frame.
- * 2: compute the room available and adjust the height to it.
- * Try not to reduce the height of a window with 'winfixheight' set.
- */
+ // Column of frames: try to change only frames in this column.
+
+ // Do this twice:
+ // 1: compute room available, if it's not enough try resizing the
+ // containing frame.
+ // 2: compute the room available and adjust the height to it.
+ // Try not to reduce the height of a window with 'winfixheight' set.
for (run = 1; run <= 2; run++) {
room = 0;
room_reserved = 0;
@@ -5639,13 +5525,11 @@ static void frame_setheight(frame_T *curfrp, int height)
}
frame_setheight(curfrp->fr_parent, height
+ frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1);
- //NOTREACHED
+ // NOTREACHED
}
- /*
- * Compute the number of lines we will take from others frames (can be
- * negative!).
- */
+ // Compute the number of lines we will take from others frames (can be
+ // negative!).
take = height - curfrp->fr_height;
// If there is not enough room, also reduce the height of a window
@@ -5668,16 +5552,12 @@ static void frame_setheight(frame_T *curfrp, int height)
topframe->fr_height += room_cmdline;
}
- /*
- * set the current frame to the new height
- */
+ // set the current frame to the new height
frame_new_height(curfrp, height, false, false);
- /*
- * First take lines from the frames after the current frame. If
- * that is not enough, takes lines from frames above the current
- * frame.
- */
+ // First take lines from the frames after the current frame. If
+ // that is not enough, takes lines from frames above the current
+ // frame.
for (run = 0; run < 2; run++) {
if (run == 0) {
frp = curfrp->fr_next; // 1st run: start with next window
@@ -5718,10 +5598,8 @@ static void frame_setheight(frame_T *curfrp, int height)
}
}
-/*
- * Set current window width and take care of repositioning other windows to
- * fit around it.
- */
+// Set current window width and take care of repositioning other windows to
+// fit around it.
void win_setwidth(int width)
{
win_setwidth_win(width, curwin);
@@ -5754,13 +5632,11 @@ void win_setwidth_win(int width, win_T *wp)
}
}
-/*
- * Set the width of a frame to "width" and take care that all frames and
- * windows inside it are resized. Also resize frames above and below if the
- * are in the same FR_ROW frame.
- *
- * Strategy is similar to frame_setheight().
- */
+// Set the width of a frame to "width" and take care that all frames and
+// windows inside it are resized. Also resize frames above and below if the
+// are in the same FR_ROW frame.
+//
+// Strategy is similar to frame_setheight().
static void frame_setwidth(frame_T *curfrp, int width)
{
int room; // total number of lines available
@@ -5789,14 +5665,12 @@ static void frame_setwidth(frame_T *curfrp, int width)
}
frame_setwidth(curfrp->fr_parent, width);
} else {
- /*
- * Row of frames: try to change only frames in this row.
- *
- * Do this twice:
- * 1: compute room available, if it's not enough try resizing the
- * containing frame.
- * 2: compute the room available and adjust the width to it.
- */
+ // Row of frames: try to change only frames in this row.
+ //
+ // Do this twice:
+ // 1: compute room available, if it's not enough try resizing the
+ // containing frame.
+ // 2: compute the room available and adjust the width to it.
for (run = 1; run <= 2; run++) {
room = 0;
room_reserved = 0;
@@ -5823,10 +5697,8 @@ static void frame_setwidth(frame_T *curfrp, int width)
+ frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1);
}
- /*
- * Compute the number of lines we will take from others frames (can be
- * negative!).
- */
+ // Compute the number of lines we will take from others frames (can be
+ // negative!).
take = width - curfrp->fr_width;
// If there is not enough room, also reduce the width of a window
@@ -5840,16 +5712,12 @@ static void frame_setwidth(frame_T *curfrp, int width)
room_reserved = 0;
}
- /*
- * set the current frame to the new width
- */
+ // set the current frame to the new width
frame_new_width(curfrp, width, false, false);
- /*
- * First take lines from the frames right of the current frame. If
- * that is not enough, takes lines from frames left of the current
- * frame.
- */
+ // First take lines from the frames right of the current frame. If
+ // that is not enough, takes lines from frames left of the current
+ // frame.
for (run = 0; run < 2; run++) {
if (run == 0) {
frp = curfrp->fr_next; // 1st run: start with next window
@@ -6016,10 +5884,8 @@ void win_drag_status_line(win_T *dragwin, int offset)
return;
}
- /*
- * Grow frame fr by "offset" lines.
- * Doesn't happen when dragging the last status line up.
- */
+ // Grow frame fr by "offset" lines.
+ // Doesn't happen when dragging the last status line up.
if (fr != NULL) {
frame_new_height(fr, fr->fr_height + offset, up, false);
}
@@ -6029,9 +5895,7 @@ void win_drag_status_line(win_T *dragwin, int offset)
} else {
fr = curfr->fr_next; // next frame gets smaller
}
- /*
- * Now make the other frames smaller.
- */
+ // Now make the other frames smaller.
while (fr != NULL && offset > 0) {
n = frame_minheight(fr, NULL);
if (fr->fr_height - offset <= n) {
@@ -6059,9 +5923,7 @@ void win_drag_status_line(win_T *dragwin, int offset)
showmode();
}
-/*
- * Separator line of dragwin is dragged "offset" lines right (negative is left).
- */
+// Separator line of dragwin is dragged "offset" lines right (negative is left).
void win_drag_vsep_line(win_T *dragwin, int offset)
{
frame_T *curfr;
@@ -6214,10 +6076,8 @@ void scroll_to_fraction(win_T *wp, int prev_height)
&& (!wp->w_p_scb || wp == curwin)
&& (height < wp->w_buffer->b_ml.ml_line_count
|| wp->w_topline > 1)) {
- /*
- * Find a value for w_topline that shows the cursor at the same
- * relative position in the window as before (more or less).
- */
+ // Find a value for w_topline that shows the cursor at the same
+ // relative position in the window as before (more or less).
lnum = wp->w_cursor.lnum;
if (lnum < 1) { // can happen when starting up
lnum = 1;
@@ -6237,11 +6097,9 @@ void scroll_to_fraction(win_T *wp, int prev_height)
}
if (sline < 0) {
- /*
- * Cursor line would go off top of screen if w_wrow was this high.
- * Make cursor line the first line in the window. If not enough
- * room use w_skipcol;
- */
+ // Cursor line would go off top of screen if w_wrow was this high.
+ // Make cursor line the first line in the window. If not enough
+ // room use w_skipcol;
wp->w_wrow = line_size;
if (wp->w_wrow >= wp->w_height_inner
&& (wp->w_width_inner - win_col_off(wp)) > 0) {
@@ -6273,10 +6131,8 @@ void scroll_to_fraction(win_T *wp, int prev_height)
}
if (sline < 0) {
- /*
- * Line we want at top would go off top of screen. Use next
- * line instead.
- */
+ // Line we want at top would go off top of screen. Use next
+ // line instead.
(void)hasFoldingWin(wp, lnum, NULL, &lnum, true, NULL);
lnum++;
wp->w_wrow -= line_size + sline;
@@ -6403,9 +6259,7 @@ void win_comp_scroll(win_T *wp)
}
}
-/*
- * command_height: called whenever p_ch has been changed
- */
+// command_height: called whenever p_ch has been changed
void command_height(void)
{
int h;
@@ -6417,12 +6271,6 @@ void command_height(void)
// p_ch was changed in another tab page.
curtab->tp_ch_used = p_ch;
- // If the space for the command line is already more than 'cmdheight' there
- // is nothing to do (window size must have decreased).
- if (p_ch > old_p_ch && cmdline_row <= Rows - p_ch) {
- return;
- }
-
// If cmdline_row is smaller than what it is supposed to be for 'cmdheight'
// then set old_p_ch to what it would be, so that the windows get resized
// properly for the new value.
@@ -6488,10 +6336,8 @@ void command_height(void)
}
}
-/*
- * Resize frame "frp" to be "n" lines higher (negative for less high).
- * Also resize the frames it is contained in.
- */
+// Resize frame "frp" to be "n" lines higher (negative for less high).
+// Also resize the frames it is contained in.
static void frame_add_height(frame_T *frp, int n)
{
frame_new_height(frp, frp->fr_height + n, false, false);
@@ -6504,11 +6350,9 @@ static void frame_add_height(frame_T *frp, int n)
}
}
-/*
- * Get the file name at the cursor.
- * If Visual mode is active, use the selected text if it's in one line.
- * Returns the name in allocated memory, NULL for failure.
- */
+// Get the file name at the cursor.
+// If Visual mode is active, use the selected text if it's in one line.
+// Returns the name in allocated memory, NULL for failure.
char_u *grab_file_name(long count, linenr_T *file_lnum)
{
int options = FNAME_MESS | FNAME_EXP | FNAME_REL | FNAME_UNESC;
@@ -6524,27 +6368,25 @@ char_u *grab_file_name(long count, linenr_T *file_lnum)
*file_lnum = (linenr_T)getdigits_long(&p, false, 0);
}
- return find_file_name_in_path((char_u *)ptr, len, options, count, (char_u *)curbuf->b_ffname);
+ return (char_u *)find_file_name_in_path(ptr, len, options, count, curbuf->b_ffname);
}
return file_name_at_cursor(options | FNAME_HYP, count, file_lnum);
}
-/*
- * Return the file name under or after the cursor.
- *
- * The 'path' option is searched if the file name is not absolute.
- * The string returned has been alloc'ed and should be freed by the caller.
- * NULL is returned if the file name or file is not found.
- *
- * options:
- * FNAME_MESS give error messages
- * FNAME_EXP expand to path
- * FNAME_HYP check for hypertext link
- * FNAME_INCL apply "includeexpr"
- */
+// Return the file name under or after the cursor.
+//
+// The 'path' option is searched if the file name is not absolute.
+// The string returned has been alloc'ed and should be freed by the caller.
+// NULL is returned if the file name or file is not found.
+//
+// options:
+// FNAME_MESS give error messages
+// FNAME_EXP expand to path
+// FNAME_HYP check for hypertext link
+// FNAME_INCL apply "includeexpr"
char_u *file_name_at_cursor(int options, long count, linenr_T *file_lnum)
{
- return file_name_in_line(get_cursor_line_ptr(),
+ return file_name_in_line((char_u *)get_cursor_line_ptr(),
curwin->w_cursor.col, options, count, (char_u *)curbuf->b_ffname,
file_lnum);
}
@@ -6561,9 +6403,7 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u
bool in_type = true;
bool is_url = false;
- /*
- * search forward for what could be the start of a file name
- */
+ // search forward for what could be the start of a file name
ptr = (char *)line + col;
while (*ptr != NUL && !vim_isfilec(*ptr)) {
MB_PTR_ADV(ptr);
@@ -6575,10 +6415,8 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u
return NULL;
}
- /*
- * Search backward for first char of the file name.
- * Go one char back to ":" before "//" even when ':' is not in 'isfname'.
- */
+ // Search backward for first char of the file name.
+ // Go one char back to ":" before "//" even when ':' is not in 'isfname'.
while ((char_u *)ptr > line) {
if ((len = (size_t)(utf_head_off((char *)line, ptr - 1))) > 0) {
ptr -= len + 1;
@@ -6589,10 +6427,8 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u
}
}
- /*
- * Search forward for the last char of the file name.
- * Also allow ":/" when ':' is not in 'isfname'.
- */
+ // Search forward for the last char of the file name.
+ // Also allow ":/" when ':' is not in 'isfname'.
len = 0;
while (vim_isfilec(ptr[len]) || (ptr[len] == '\\' && ptr[len + 1] == ' ')
|| ((options & FNAME_HYP) && path_is_url(ptr + len))
@@ -6615,10 +6451,8 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u
len += (size_t)(utfc_ptr2len(ptr + len));
}
- /*
- * If there is trailing punctuation, remove it.
- * But don't remove "..", could be a directory name.
- */
+ // If there is trailing punctuation, remove it.
+ // But don't remove "..", could be a directory name.
if (len > 2 && vim_strchr(".,:;!", ptr[len - 1]) != NULL
&& ptr[len - 2] != '.') {
len--;
@@ -6651,7 +6485,7 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u
}
}
- return find_file_name_in_path((char_u *)ptr, len, options, count, rel_fname);
+ return (char_u *)find_file_name_in_path(ptr, len, options, count, (char *)rel_fname);
}
/// Add or remove a status line from window(s), according to the
@@ -6972,21 +6806,17 @@ void reset_lnums(void)
}
}
-/*
- * A snapshot of the window sizes, to restore them after closing the help
- * window.
- * Only these fields are used:
- * fr_layout
- * fr_width
- * fr_height
- * fr_next
- * fr_child
- * fr_win (only valid for the old curwin, NULL otherwise)
- */
+// A snapshot of the window sizes, to restore them after closing the help
+// window.
+// Only these fields are used:
+// fr_layout
+// fr_width
+// fr_height
+// fr_next
+// fr_child
+// fr_win (only valid for the old curwin, NULL otherwise)
-/*
- * Create a snapshot of the current frame sizes.
- */
+// Create a snapshot of the current frame sizes.
void make_snapshot(int idx)
{
clear_snapshot(curtab, idx);
@@ -7010,9 +6840,7 @@ static void make_snapshot_rec(frame_T *fr, frame_T **frp)
}
}
-/*
- * Remove any existing snapshot.
- */
+// Remove any existing snapshot.
static void clear_snapshot(tabpage_T *tp, int idx)
{
clear_snapshot_rec(tp->tp_snapshot[idx]);
@@ -7097,11 +6925,9 @@ static int check_snapshot_rec(frame_T *sn, frame_T *fr)
return OK;
}
-/*
- * Copy the size of snapshot frame "sn" to frame "fr". Do the same for all
- * following frames and children.
- * Returns a pointer to the old current window, or NULL.
- */
+// Copy the size of snapshot frame "sn" to frame "fr". Do the same for all
+// following frames and children.
+// Returns a pointer to the old current window, or NULL.
static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr)
{
win_T *wp = NULL;
diff --git a/src/nvim/window.h b/src/nvim/window.h
index 3137035b25..a564a0cfad 100644
--- a/src/nvim/window.h
+++ b/src/nvim/window.h
@@ -45,8 +45,8 @@ typedef struct {
do { \
win_T *const wp_ = (wp); \
const pos_T curpos_ = wp_->w_cursor; \
- char_u cwd_[MAXPATHL]; \
- char_u autocwd_[MAXPATHL]; \
+ char cwd_[MAXPATHL]; \
+ char autocwd_[MAXPATHL]; \
bool apply_acd_ = false; \
int cwd_status_ = FAIL; \
/* Getting and setting directory can be slow on some systems, only do */ \
@@ -56,13 +56,13 @@ typedef struct {
&& (curwin->w_localdir != NULL || wp->w_localdir != NULL \
|| (curtab != tp && (curtab->tp_localdir != NULL || tp->tp_localdir != NULL)) \
|| p_acd)) { \
- cwd_status_ = os_dirname(cwd_, MAXPATHL); \
+ cwd_status_ = os_dirname((char_u *)cwd_, MAXPATHL); \
} \
/* If 'acd' is set, check we are using that directory. If yes, then */ \
/* apply 'acd' afterwards, otherwise restore the current directory. */ \
if (cwd_status_ == OK && p_acd) { \
do_autochdir(); \
- apply_acd_ = os_dirname(autocwd_, MAXPATHL) == OK && STRCMP(cwd_, autocwd_) == 0; \
+ apply_acd_ = os_dirname((char_u *)autocwd_, MAXPATHL) == OK && strcmp(cwd_, autocwd_) == 0; \
} \
switchwin_T switchwin_; \
if (switch_win_noblock(&switchwin_, wp_, (tp), true) == OK) { \
@@ -73,7 +73,7 @@ typedef struct {
if (apply_acd_) { \
do_autochdir(); \
} else if (cwd_status_ == OK) { \
- os_chdir((char *)cwd_); \
+ os_chdir(cwd_); \
} \
/* Update the status line if the cursor moved. */ \
if (win_valid(wp_) && !equalpos(curpos_, wp_->w_cursor)) { \
diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua
index 2d8bf23f5b..44a19d8348 100644
--- a/test/functional/api/command_spec.lua
+++ b/test/functional/api/command_spec.lua
@@ -136,7 +136,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -172,7 +172,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -208,7 +208,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -244,7 +244,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "botright",
- tab = 0,
+ tab = -1,
unsilent = true,
verbose = -1,
vertical = false,
@@ -280,7 +280,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -316,7 +316,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -364,7 +364,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -401,7 +401,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -448,7 +448,7 @@ describe('nvim_create_user_command', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -523,8 +523,29 @@ describe('nvim_create_user_command', function()
vim.api.nvim_cmd({ cmd = 'echo', args = { '&verbose' }, mods = opts.smods }, {})
end, {})
]]
-
eq("3", meths.cmd({ cmd = 'MyEcho', mods = { verbose = 3 } }, { output = true }))
+
+ eq(1, #meths.list_tabpages())
+ exec_lua[[
+ vim.api.nvim_create_user_command('MySplit', function(opts)
+ vim.api.nvim_cmd({ cmd = 'split', mods = opts.smods }, {})
+ end, {})
+ ]]
+ meths.cmd({ cmd = 'MySplit' }, {})
+ eq(1, #meths.list_tabpages())
+ eq(2, #meths.list_wins())
+ meths.cmd({ cmd = 'MySplit', mods = { tab = 1 } }, {})
+ eq(2, #meths.list_tabpages())
+ eq(2, funcs.tabpagenr())
+ meths.cmd({ cmd = 'MySplit', mods = { tab = 1 } }, {})
+ eq(3, #meths.list_tabpages())
+ eq(2, funcs.tabpagenr())
+ meths.cmd({ cmd = 'MySplit', mods = { tab = 3 } }, {})
+ eq(4, #meths.list_tabpages())
+ eq(4, funcs.tabpagenr())
+ meths.cmd({ cmd = 'MySplit', mods = { tab = 0 } }, {})
+ eq(5, #meths.list_tabpages())
+ eq(1, funcs.tabpagenr())
end)
end)
diff --git a/test/functional/api/server_notifications_spec.lua b/test/functional/api/server_notifications_spec.lua
index 1c00f001ff..1c554b05a3 100644
--- a/test/functional/api/server_notifications_spec.lua
+++ b/test/functional/api/server_notifications_spec.lua
@@ -7,6 +7,7 @@ local exec_lua = helpers.exec_lua
local retry = helpers.retry
local isCI = helpers.isCI
local assert_alive = helpers.assert_alive
+local uname = helpers.uname
describe('notify', function()
local channel
@@ -78,6 +79,9 @@ describe('notify', function()
end)
it('cancels stale events on channel close', function()
+ if uname() == 'freebsd' then
+ pending('Failing FreeBSD test')
+ end
if isCI() then
pending('hangs on CI #14083 #15251')
return
diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua
index 2e37c4787d..44775ef85c 100644
--- a/test/functional/api/vim_spec.lua
+++ b/test/functional/api/vim_spec.lua
@@ -2732,8 +2732,8 @@ describe('API', function()
it('should have information about window options', function()
eq({
- allows_duplicates = true,
- commalist = false;
+ allows_duplicates = false,
+ commalist = true;
default = "";
flaglist = false;
global_local = false;
@@ -3206,7 +3206,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3248,7 +3248,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3290,7 +3290,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3332,7 +3332,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3374,7 +3374,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3416,7 +3416,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3458,7 +3458,7 @@ describe('API', function()
sandbox = false,
silent = true,
split = "topleft",
- tab = 2,
+ tab = 1,
unsilent = false,
verbose = 15,
vertical = false,
@@ -3503,7 +3503,7 @@ describe('API', function()
verbose = 0,
vertical = false,
},
- }, meths.parse_cmd('0verbose unsilent botright confirm filter! /foo/ split foo.txt', {}))
+ }, meths.parse_cmd('0verbose unsilent botright 0tab confirm filter! /foo/ split foo.txt', {}))
end)
it('works with user commands', function()
command('command -bang -nargs=+ -range -addr=lines MyCommand echo foo')
@@ -3541,7 +3541,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3583,7 +3583,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3626,7 +3626,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
@@ -3719,7 +3719,7 @@ describe('API', function()
sandbox = false,
silent = false,
split = "",
- tab = 0,
+ tab = -1,
unsilent = false,
verbose = -1,
vertical = false,
diff --git a/test/functional/core/fileio_spec.lua b/test/functional/core/fileio_spec.lua
index a4d22685e8..e71131dcf8 100644
--- a/test/functional/core/fileio_spec.lua
+++ b/test/functional/core/fileio_spec.lua
@@ -23,6 +23,7 @@ local iswin = helpers.iswin
local assert_alive = helpers.assert_alive
local expect_exit = helpers.expect_exit
local write_file = helpers.write_file
+local uname = helpers.uname
describe('fileio', function()
before_each(function()
@@ -83,6 +84,9 @@ describe('fileio', function()
end)
it('backup #9709', function()
+ if uname() == 'freebsd' then
+ pending('Failing FreeBSD test')
+ end
clear({ args={ '-i', 'Xtest_startup_shada',
'--cmd', 'set directory=Xtest_startup_swapdir' } })
@@ -102,6 +106,9 @@ describe('fileio', function()
end)
it('backup with full path #11214', function()
+ if uname() == 'freebsd' then
+ pending('Failing FreeBSD test')
+ end
clear()
mkdir('Xtest_backupdir')
command('set backup')
diff --git a/test/functional/ex_cmds/source_spec.lua b/test/functional/ex_cmds/source_spec.lua
index cd1f43f9fd..10ebefd8cd 100644
--- a/test/functional/ex_cmds/source_spec.lua
+++ b/test/functional/ex_cmds/source_spec.lua
@@ -104,7 +104,7 @@ describe(':source', function()
eq("0zBEEFCAFE", meths.exec('echo d', true))
exec('set cpoptions+=C')
- eq('Vim(let):E15: Invalid expression: #{', exc_exec('source'))
+ eq('Vim(let):E723: Missing end of Dictionary \'}\': ', exc_exec('source'))
end)
it('selection in current buffer', function()
@@ -138,7 +138,7 @@ describe(':source', function()
eq('Vim(echo):E117: Unknown function: s:C', exc_exec('echo D()'))
exec('set cpoptions+=C')
- eq('Vim(let):E15: Invalid expression: #{', exc_exec("'<,'>source"))
+ eq('Vim(let):E723: Missing end of Dictionary \'}\': ', exc_exec("'<,'>source"))
end)
it('does not break if current buffer is modified while sourced', function()
diff --git a/test/functional/ex_cmds/write_spec.lua b/test/functional/ex_cmds/write_spec.lua
index 32fe397c03..14035a4341 100644
--- a/test/functional/ex_cmds/write_spec.lua
+++ b/test/functional/ex_cmds/write_spec.lua
@@ -9,6 +9,7 @@ local feed_command = helpers.feed_command
local funcs = helpers.funcs
local meths = helpers.meths
local iswin = helpers.iswin
+local uname = helpers.uname
local fname = 'Xtest-functional-ex_cmds-write'
local fname_bak = fname .. '~'
@@ -52,6 +53,9 @@ describe(':write', function()
end)
it('&backupcopy=no replaces symlink with new file', function()
+ if uname() == 'freebsd' then
+ pending('Failing FreeBSD test')
+ end
command('set backupcopy=no')
write_file('test_bkc_file.txt', 'content0')
if iswin() then
@@ -91,6 +95,9 @@ describe(':write', function()
end)
it('errors out correctly', function()
+ if uname() == 'freebsd' then
+ pending('Failing FreeBSD test')
+ end
command('let $HOME=""')
eq(funcs.fnamemodify('.', ':p:h'), funcs.fnamemodify('.', ':p:h:~'))
-- Message from check_overwrite
diff --git a/test/functional/helpers.lua b/test/functional/helpers.lua
index 93fb0f245e..d672037a1e 100644
--- a/test/functional/helpers.lua
+++ b/test/functional/helpers.lua
@@ -755,16 +755,6 @@ function module.pending_win32(pending_fn)
end
end
-function module.pending_c_parser(pending_fn)
- local status, _ = unpack(module.exec_lua([[ return {pcall(vim.treesitter.require_language, 'c')} ]]))
- if not status then
- pending_fn 'no C parser, skipping'
- return true
- end
- module.exec_lua [[vim._ts_remove_language 'c']]
- return false
-end
-
-- Calls pending() and returns `true` if the system is too slow to
-- run fragile or expensive tests. Else returns `false`.
function module.skip_fragile(pending_fn, cond)
diff --git a/test/functional/lua/diagnostic_spec.lua b/test/functional/lua/diagnostic_spec.lua
index 4226bcebac..1514dadca8 100644
--- a/test/functional/lua/diagnostic_spec.lua
+++ b/test/functional/lua/diagnostic_spec.lua
@@ -148,6 +148,15 @@ describe('vim.diagnostic', function()
vim.cmd('bwipeout!')
return #vim.diagnostic.get()
]])
+ eq(2, exec_lua [[
+ vim.api.nvim_set_current_buf(diagnostic_bufnr)
+ vim.opt_local.buflisted = false
+ return #vim.diagnostic.get()
+ ]])
+ eq(0, exec_lua [[
+ vim.cmd('bwipeout!')
+ return #vim.diagnostic.get()
+ ]])
end)
it('resolves buffer number 0 to the current buffer', function()
diff --git a/test/functional/lua/vim_spec.lua b/test/functional/lua/vim_spec.lua
index f2fb661b70..cd3240cd30 100644
--- a/test/functional/lua/vim_spec.lua
+++ b/test/functional/lua/vim_spec.lua
@@ -2754,6 +2754,24 @@ describe('lua stdlib', function()
end)
+ describe("vim.defaulttable", function()
+ it("creates nested table by default", function()
+ eq({ b = {c = 1 } }, exec_lua[[
+ local a = vim.defaulttable()
+ a.b.c = 1
+ return a
+ ]])
+ end)
+
+ it("allows to create default objects", function()
+ eq({ b = 1 }, exec_lua[[
+ local a = vim.defaulttable(function() return 0 end)
+ a.b = a.b + 1
+ return a
+ ]])
+ end)
+ end)
+
end)
describe('lua: builtin modules', function()
diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua
index fa731f6faf..e0035e2e8b 100644
--- a/test/functional/plugin/lsp_spec.lua
+++ b/test/functional/plugin/lsp_spec.lua
@@ -418,6 +418,42 @@ describe('LSP', function()
}
end)
+ it('should detach buffer on bufwipe', function()
+ local result = exec_lua([[
+ local server = function(dispatchers)
+ local closing = false
+ return {
+ request = function(method, params, callback)
+ if method == 'initialize' then
+ callback(nil, { capabilities = {} })
+ end
+ end,
+ notify = function(...)
+ end,
+ is_closing = function() return closing end,
+ terminate = function() closing = true end
+ }
+ end
+ local bufnr = vim.api.nvim_create_buf(false, true)
+ vim.api.nvim_set_current_buf(bufnr)
+ local client_id = vim.lsp.start({ name = 'detach-dummy', cmd = server })
+ assert(client_id, "lsp.start must return client_id")
+ local client = vim.lsp.get_client_by_id(client_id)
+ local num_attached_before = vim.tbl_count(client.attached_buffers)
+ vim.api.nvim_buf_delete(bufnr, { force = true })
+ local num_attached_after = vim.tbl_count(client.attached_buffers)
+ return {
+ bufnr = bufnr,
+ client_id = client_id,
+ num_attached_before = num_attached_before,
+ num_attached_after = num_attached_after,
+ }
+ ]])
+ eq(true, result ~= nil, "exec_lua must return result")
+ eq(1, result.num_attached_before)
+ eq(0, result.num_attached_after)
+ end)
+
it('client should return settings via workspace/configuration handler', function()
local expected_handlers = {
{NIL, {}, {method="shutdown", client_id=1}};
@@ -3180,8 +3216,54 @@ describe('LSP', function()
end,
}
end)
+ it('format formats range in visual mode', function()
+ local result = exec_lua([[
+ local messages = {}
+ local server = function(dispatchers)
+ local closing = false
+ return {
+ request = function(method, params, callback)
+ table.insert(messages, {
+ method = method,
+ params = params,
+ })
+ if method == 'initialize' then
+ callback(nil, {
+ capabilities = {
+ documentFormattingProvider = true,
+ documentRangeFormattingProvider = true,
+ }
+ })
+ end
+ end,
+ notify = function(...)
+ end,
+ is_closing = function()
+ return closing
+ end,
+ terminate = function()
+ closing = true
+ end
+ }
+ end
+ local bufnr = vim.api.nvim_get_current_buf()
+ local client_id = vim.lsp.start({ name = 'dummy', cmd = server })
+ vim.api.nvim_win_set_buf(0, bufnr)
+ vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, {'foo', 'bar'})
+ vim.api.nvim_win_set_cursor(0, { 1, 0 })
+ vim.cmd.normal('v')
+ vim.api.nvim_win_set_cursor(0, { 2, 3 })
+ vim.lsp.buf.format({ bufnr = bufnr, false })
+ return messages
+ ]])
+ eq("textDocument/rangeFormatting", result[2].method)
+ local expected_range = {
+ start = { line = 0, character = 0 },
+ ['end'] = { line = 1, character = 4 },
+ }
+ eq(expected_range, result[2].params.range)
+ end)
end)
-
describe('cmd', function()
it('can connect to lsp server via rpc.connect', function()
local result = exec_lua [[
diff --git a/test/functional/plugin/man_spec.lua b/test/functional/plugin/man_spec.lua
index 9304aa6da9..3e63c5df9a 100644
--- a/test/functional/plugin/man_spec.lua
+++ b/test/functional/plugin/man_spec.lua
@@ -1,7 +1,8 @@
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
-local command, eval, rawfeed = helpers.command, helpers.eval, helpers.rawfeed
+local command, rawfeed = helpers.command, helpers.rawfeed
local clear = helpers.clear
+local exec_lua = helpers.exec_lua
local funcs = helpers.funcs
local nvim_prog = helpers.nvim_prog
local matches = helpers.matches
@@ -50,7 +51,7 @@ describe(':Man', function()
|
]]}
- eval('man#init_pager()')
+ exec_lua[[require'man'.init_pager()]]
screen:expect([[
^this {b:is} {b:a} test |
@@ -74,7 +75,7 @@ describe(':Man', function()
|
]=]}
- eval('man#init_pager()')
+ exec_lua[[require'man'.init_pager()]]
screen:expect([[
^this {b:is }{bi:a }{biu:test} |
@@ -89,7 +90,7 @@ describe(':Man', function()
rawfeed([[
ithis i<C-v><C-h>is<C-v><C-h>s あ<C-v><C-h>あ test
with _<C-v><C-h>ö_<C-v><C-h>v_<C-v><C-h>e_<C-v><C-h>r_<C-v><C-h>s_<C-v><C-h>t_<C-v><C-h>r_<C-v><C-h>u_<C-v><C-h>̃_<C-v><C-h>c_<C-v><C-h>k te<C-v><ESC>[3mxt¶<C-v><ESC>[0m<ESC>]])
- eval('man#init_pager()')
+ exec_lua[[require'man'.init_pager()]]
screen:expect([[
^this {b:is} {b:あ} test |
@@ -105,7 +106,7 @@ describe(':Man', function()
i_<C-v><C-h>_b<C-v><C-h>be<C-v><C-h>eg<C-v><C-h>gi<C-v><C-h>in<C-v><C-h>ns<C-v><C-h>s
m<C-v><C-h>mi<C-v><C-h>id<C-v><C-h>d_<C-v><C-h>_d<C-v><C-h>dl<C-v><C-h>le<C-v><C-h>e
_<C-v><C-h>m_<C-v><C-h>i_<C-v><C-h>d_<C-v><C-h>__<C-v><C-h>d_<C-v><C-h>l_<C-v><C-h>e<ESC>]])
- eval('man#init_pager()')
+ exec_lua[[require'man'.init_pager()]]
screen:expect([[
{b:^_begins} |
@@ -121,7 +122,7 @@ describe(':Man', function()
i· ·<C-v><C-h>·
+<C-v><C-h>o
+<C-v><C-h>+<C-v><C-h>o<C-v><C-h>o double<ESC>]])
- eval('man#init_pager()')
+ exec_lua[[require'man'.init_pager()]]
screen:expect([[
^· {b:·} |
@@ -138,7 +139,7 @@ describe(':Man', function()
<C-v><C-[>[44m 4 <C-v><C-[>[45m 5 <C-v><C-[>[46m 6 <C-v><C-[>[47m 7 <C-v><C-[>[100m 8 <C-v><C-[>[101m 9
<C-v><C-[>[102m 10 <C-v><C-[>[103m 11 <C-v><C-[>[104m 12 <C-v><C-[>[105m 13 <C-v><C-[>[106m 14 <C-v><C-[>[107m 15
<C-v><C-[>[48:5:16m 16 <ESC>]])
- eval('man#init_pager()')
+ exec_lua[[require'man'.init_pager()]]
screen:expect([[
^ 0 1 2 3 |
diff --git a/test/functional/terminal/altscreen_spec.lua b/test/functional/terminal/altscreen_spec.lua
index 155a156d15..e4e1aa5fa2 100644
--- a/test/functional/terminal/altscreen_spec.lua
+++ b/test/functional/terminal/altscreen_spec.lua
@@ -126,13 +126,13 @@ describe(':terminal altscreen', function()
wait_removal()
feed('<c-\\><c-n>4k')
screen:expect([[
- ^line3 |
+ ^ |
|
|
rows: 4, cols: 50 |
|
]])
- eq(8, curbuf('line_count'))
+ eq(9, curbuf('line_count'))
end)
describe('and after exit', function()
@@ -142,15 +142,11 @@ describe(':terminal altscreen', function()
end)
it('restore buffer state', function()
- -- FIXME(tarruda): Note that the last line was lost after restoring the
- -- screen. This is a libvterm bug: When the main screen is restored it
- -- seems to "cut" lines that would have been left below the new visible
- -- screen.
screen:expect([[
- line4 |
line5 |
line6 |
line7 |
+ line8 |
{3:-- TERMINAL --} |
]])
end)
diff --git a/test/functional/terminal/ex_terminal_spec.lua b/test/functional/terminal/ex_terminal_spec.lua
index 23b69319f0..36f9f90143 100644
--- a/test/functional/terminal/ex_terminal_spec.lua
+++ b/test/functional/terminal/ex_terminal_spec.lua
@@ -10,6 +10,7 @@ local retry = helpers.retry
local ok = helpers.ok
local iswin = helpers.iswin
local command = helpers.command
+local uname = helpers.uname
describe(':terminal', function()
local screen
@@ -45,6 +46,9 @@ describe(':terminal', function()
end)
it("reads output buffer on terminal reporting #4151", function()
+ if uname() == 'freebsd' then
+ pending('Failing FreeBSD test')
+ end
if helpers.pending_win32(pending) then return end
if iswin() then
feed_command([[terminal powershell -NoProfile -NoLogo -Command Write-Host -NoNewline "\"$([char]27)[6n\""; Start-Sleep -Milliseconds 500 ]])
diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua
index 4f444316c3..3c56ad5f79 100644
--- a/test/functional/terminal/tui_spec.lua
+++ b/test/functional/terminal/tui_spec.lua
@@ -21,6 +21,7 @@ local nvim_set = helpers.nvim_set
local ok = helpers.ok
local read_file = helpers.read_file
local funcs = helpers.funcs
+local meths = helpers.meths
if helpers.pending_win32(pending) then return end
@@ -666,6 +667,57 @@ describe('TUI', function()
]], attrs)
end)
+ it('mouse events work with right-click menu', function()
+ child_session:request('nvim_command', [[
+ call setline(1, 'popup menu test')
+ set mouse=a mousemodel=popup
+
+ aunmenu PopUp
+ menu PopUp.foo :let g:menustr = 'foo'<CR>
+ menu PopUp.bar :let g:menustr = 'bar'<CR>
+ menu PopUp.baz :let g:menustr = 'baz'<CR>
+ highlight Pmenu ctermbg=NONE ctermfg=NONE cterm=underline,reverse
+ highlight PmenuSel ctermbg=NONE ctermfg=NONE cterm=underline,reverse,bold
+ ]])
+ local attrs = screen:get_default_attr_ids()
+ attrs[11] = {underline = true, reverse = true}
+ attrs[12] = {underline = true, reverse = true, bold = true}
+ meths.input_mouse('right', 'press', '', 0, 0, 4)
+ screen:expect([[
+ {1:p}opup menu test |
+ {4:~ }{11: foo }{4: }|
+ {4:~ }{11: bar }{4: }|
+ {4:~ }{11: baz }{4: }|
+ {5:[No Name] [+] }|
+ |
+ {3:-- TERMINAL --} |
+ ]], attrs)
+ meths.input_mouse('right', 'release', '', 0, 0, 4)
+ screen:expect_unchanged()
+ meths.input_mouse('move', '', '', 0, 3, 6)
+ screen:expect([[
+ {1:p}opup menu test |
+ {4:~ }{11: foo }{4: }|
+ {4:~ }{11: bar }{4: }|
+ {4:~ }{12: baz }{4: }|
+ {5:[No Name] [+] }|
+ |
+ {3:-- TERMINAL --} |
+ ]], attrs)
+ meths.input_mouse('left', 'press', '', 0, 2, 6)
+ screen:expect([[
+ {1:p}opup menu test |
+ {4:~ }|
+ {4:~ }|
+ {4:~ }|
+ {5:[No Name] [+] }|
+ :let g:menustr = 'bar' |
+ {3:-- TERMINAL --} |
+ ]], attrs)
+ meths.input_mouse('left', 'release', '', 0, 2, 6)
+ screen:expect_unchanged()
+ end)
+
it('paste: Insert mode', function()
-- "bracketed paste"
feed_data('i""\027i\027[200~')
diff --git a/test/functional/treesitter/highlight_spec.lua b/test/functional/treesitter/highlight_spec.lua
index 4b0bd1eb50..d557b2c012 100644
--- a/test/functional/treesitter/highlight_spec.lua
+++ b/test/functional/treesitter/highlight_spec.lua
@@ -5,7 +5,6 @@ local clear = helpers.clear
local insert = helpers.insert
local exec_lua = helpers.exec_lua
local feed = helpers.feed
-local pending_c_parser = helpers.pending_c_parser
local command = helpers.command
local meths = helpers.meths
local eq = helpers.eq
@@ -107,12 +106,11 @@ describe('treesitter highlighting', function()
}
exec_lua([[ hl_query = ... ]], hl_query)
+ command [[ hi link @error ErrorMsg ]]
command [[ hi link @warning WarningMsg ]]
end)
it('is updated with edits', function()
- if pending_c_parser(pending) then return end
-
insert(hl_text)
screen:expect{grid=[[
/// Schedule Lua callback on main loop's event queue |
@@ -276,8 +274,6 @@ describe('treesitter highlighting', function()
end)
it('is updated with :sort', function()
- if pending_c_parser(pending) then return end
-
insert(test_text)
exec_lua [[
local parser = vim.treesitter.get_parser(0, "c")
@@ -351,8 +347,6 @@ describe('treesitter highlighting', function()
end)
it("supports with custom parser", function()
- if pending_c_parser(pending) then return end
-
screen:set_default_attr_ids {
[1] = {bold = true, foreground = Screen.colors.SeaGreen4};
}
@@ -417,8 +411,6 @@ describe('treesitter highlighting', function()
end)
it("supports injected languages", function()
- if pending_c_parser(pending) then return end
-
insert([[
int x = INT_MAX;
#define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y))
@@ -479,8 +471,6 @@ describe('treesitter highlighting', function()
end)
it("supports overriding queries, like ", function()
- if pending_c_parser(pending) then return end
-
insert([[
int x = INT_MAX;
#define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y))
@@ -520,8 +510,6 @@ describe('treesitter highlighting', function()
end)
it("supports highlighting with custom highlight groups", function()
- if pending_c_parser(pending) then return end
-
insert(hl_text)
exec_lua [[
@@ -577,8 +565,6 @@ describe('treesitter highlighting', function()
end)
it("supports highlighting with priority", function()
- if pending_c_parser(pending) then return end
-
insert([[
int x = INT_MAX;
#define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y))
@@ -594,9 +580,9 @@ describe('treesitter highlighting', function()
-- expect everything to have Error highlight
screen:expect{grid=[[
{12:int}{8: x = INT_MAX;} |
- {8:#define READ_STRING(x, y) (char_u *)read_string((x), (size_t)(y))}|
- {8:#define foo void main() { \} |
- {8: return 42; \} |
+ {8:#define READ_STRING(x, y) (}{12:char_u}{8: *)read_string((x), (}{12:size_t}{8:)(y))}|
+ {8:#define foo }{12:void}{8: main() { \} |
+ {8: }{12:return}{8: 42; \} |
{8: }} |
^ |
{1:~ }|
@@ -625,8 +611,6 @@ describe('treesitter highlighting', function()
end)
it("allows to use captures with dots (don't use fallback when specialization of foo exists)", function()
- if pending_c_parser(pending) then return end
-
insert([[
char* x = "Will somebody ever read this?";
]])
@@ -708,7 +692,6 @@ describe('treesitter highlighting', function()
end)
it("supports conceal attribute", function()
- if pending_c_parser(pending) then return end
insert(hl_text)
-- conceal can be empty or a single cchar.
diff --git a/test/functional/treesitter/language_spec.lua b/test/functional/treesitter/language_spec.lua
index 8e9941d797..ed84dedb5a 100644
--- a/test/functional/treesitter/language_spec.lua
+++ b/test/functional/treesitter/language_spec.lua
@@ -6,7 +6,6 @@ local command = helpers.command
local exec_lua = helpers.exec_lua
local pcall_err = helpers.pcall_err
local matches = helpers.matches
-local pending_c_parser = helpers.pending_c_parser
local insert = helpers.insert
before_each(clear)
@@ -28,15 +27,11 @@ describe('treesitter language API', function()
eq("Error executing lua: .../language.lua:0: no parser for 'borklang' language, see :help treesitter-parsers",
pcall_err(exec_lua, "parser = vim.treesitter.inspect_language('borklang')"))
- if not pending_c_parser(pending) then
- matches("Error executing lua: Failed to load parser: uv_dlsym: .+",
- pcall_err(exec_lua, 'vim.treesitter.require_language("c", nil, false, "borklang")'))
- end
+ matches("Error executing lua: Failed to load parser: uv_dlsym: .+",
+ pcall_err(exec_lua, 'vim.treesitter.require_language("c", nil, false, "borklang")'))
end)
it('inspects language', function()
- if pending_c_parser(pending) then return end
-
local keys, fields, symbols = unpack(exec_lua([[
local lang = vim.treesitter.inspect_language('c')
local keys, symbols = {}, {}
@@ -76,7 +71,6 @@ describe('treesitter language API', function()
end)
it('checks if vim.treesitter.get_parser tries to create a new parser on filetype change', function ()
- if pending_c_parser(pending) then return end
command("set filetype=c")
-- Should not throw an error when filetype is c
eq('c', exec_lua("return vim.treesitter.get_parser(0):lang()"))
@@ -87,7 +81,6 @@ describe('treesitter language API', function()
end)
it('retrieve the tree given a range', function ()
- if pending_c_parser(pending) then return end
insert([[
int main() {
int x = 3;
@@ -102,7 +95,6 @@ describe('treesitter language API', function()
end)
it('retrieve the node given a range', function ()
- if pending_c_parser(pending) then return end
insert([[
int main() {
int x = 3;
diff --git a/test/functional/treesitter/node_spec.lua b/test/functional/treesitter/node_spec.lua
index 87ce1b973c..a82dce47b7 100644
--- a/test/functional/treesitter/node_spec.lua
+++ b/test/functional/treesitter/node_spec.lua
@@ -4,7 +4,6 @@ local clear = helpers.clear
local eq = helpers.eq
local exec_lua = helpers.exec_lua
local insert = helpers.insert
-local pending_c_parser = helpers.pending_c_parser
before_each(clear)
@@ -15,10 +14,6 @@ end
describe('treesitter node API', function()
clear()
- if pending_c_parser(pending) then
- return
- end
-
it('can move between siblings', function()
insert([[
int main(int x, int y, int z) {
diff --git a/test/functional/treesitter/parser_spec.lua b/test/functional/treesitter/parser_spec.lua
index 7f3b0e770a..ccbd55df0e 100644
--- a/test/functional/treesitter/parser_spec.lua
+++ b/test/functional/treesitter/parser_spec.lua
@@ -5,13 +5,11 @@ local eq = helpers.eq
local insert = helpers.insert
local exec_lua = helpers.exec_lua
local feed = helpers.feed
-local pending_c_parser = helpers.pending_c_parser
before_each(clear)
describe('treesitter parser API', function()
clear()
- if pending_c_parser(pending) then return end
it('parses buffer', function()
if helpers.pending_win32(pending) then return end
@@ -249,7 +247,6 @@ void ui_refresh(void)
end)
it('supports getting text of multiline node', function()
- if pending_c_parser(pending) then return end
insert(test_text)
local res = exec_lua([[
local parser = vim.treesitter.get_parser(0, "c")
diff --git a/test/functional/treesitter/utils_spec.lua b/test/functional/treesitter/utils_spec.lua
index 4f4c18a748..7f5a864c3d 100644
--- a/test/functional/treesitter/utils_spec.lua
+++ b/test/functional/treesitter/utils_spec.lua
@@ -4,7 +4,6 @@ local clear = helpers.clear
local insert = helpers.insert
local eq = helpers.eq
local exec_lua = helpers.exec_lua
-local pending_c_parser = helpers.pending_c_parser
before_each(clear)
@@ -12,7 +11,6 @@ describe('treesitter utils', function()
before_each(clear)
it('can find an ancestor', function()
- if pending_c_parser(pending) then return end
insert([[
int main() {
diff --git a/test/functional/ui/decorations_spec.lua b/test/functional/ui/decorations_spec.lua
index 789f1c6487..db5a775632 100644
--- a/test/functional/ui/decorations_spec.lua
+++ b/test/functional/ui/decorations_spec.lua
@@ -31,6 +31,8 @@ describe('decorations providers', function()
[12] = {foreground = tonumber('0x990000')};
[13] = {background = Screen.colors.LightBlue};
[14] = {background = Screen.colors.WebGray, foreground = Screen.colors.DarkBlue};
+ [15] = {special = Screen.colors.Blue1, undercurl = true},
+ [16] = {special = Screen.colors.Red, undercurl = true},
}
end)
@@ -56,7 +58,7 @@ describe('decorations providers', function()
a.nvim_set_decoration_provider(_G.ns1, {
on_start = on_do; on_buf = on_do;
on_win = on_do; on_line = on_do;
- on_end = on_do;
+ on_end = on_do; _on_spell_nav = on_do;
})
return _G.ns1
]])
@@ -95,7 +97,7 @@ describe('decorations providers', function()
|
]]}
check_trace {
- { "start", 4, 40 };
+ { "start", 4 };
{ "win", 1000, 1, 0, 8 };
{ "line", 1000, 1, 0 };
{ "line", 1000, 1, 1 };
@@ -119,7 +121,7 @@ describe('decorations providers', function()
|
]]}
check_trace {
- { "start", 5, 10 };
+ { "start", 5 };
{ "buf", 1 };
{ "win", 1000, 1, 0, 8 };
{ "line", 1000, 1, 6 };
@@ -156,6 +158,84 @@ describe('decorations providers', function()
]]}
end)
+ it('can indicate spellchecked points', function()
+ exec [[
+ set spell
+ set spelloptions=noplainbuffer
+ syntax off
+ ]]
+
+ insert [[
+ I am well written text.
+ i am not capitalized.
+ I am a speling mistakke.
+ ]]
+
+ setup_provider [[
+ local ns = a.nvim_create_namespace "spell"
+ beamtrace = {}
+ local function on_do(kind, ...)
+ if kind == 'win' or kind == 'spell' then
+ a.nvim_buf_set_extmark(0, ns, 0, 0, { end_row = 2, end_col = 23, spell = true, ephemeral = true })
+ end
+ table.insert(beamtrace, {kind, ...})
+ end
+ ]]
+
+ check_trace {
+ { "start", 5 };
+ { "win", 1000, 1, 0, 5 };
+ { "line", 1000, 1, 0 };
+ { "line", 1000, 1, 1 };
+ { "line", 1000, 1, 2 };
+ { "line", 1000, 1, 3 };
+ { "end", 5 };
+ }
+
+ feed "gg0"
+
+ screen:expect{grid=[[
+ ^I am well written text. |
+ {15:i} am not capitalized. |
+ I am a {16:speling} {16:mistakke}. |
+ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ |
+ ]]}
+
+ feed "]s"
+ check_trace {
+ { "spell", 1000, 1, 1, 0, 1, -1 };
+ }
+ screen:expect{grid=[[
+ I am well written text. |
+ {15:^i} am not capitalized. |
+ I am a {16:speling} {16:mistakke}. |
+ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ |
+ ]]}
+
+ feed "]s"
+ check_trace {
+ { "spell", 1000, 1, 2, 7, 2, -1 };
+ }
+ screen:expect{grid=[[
+ I am well written text. |
+ {15:i} am not capitalized. |
+ I am a {16:^speling} {16:mistakke}. |
+ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ |
+ ]]}
+ end)
+
it('can predefine highlights', function()
screen:try_resize(40, 16)
insert(mulholland)
diff --git a/test/functional/ui/mouse_spec.lua b/test/functional/ui/mouse_spec.lua
index 9896b11218..8c5475ecce 100644
--- a/test/functional/ui/mouse_spec.lua
+++ b/test/functional/ui/mouse_spec.lua
@@ -1585,7 +1585,20 @@ describe('ui/mouse/input', function()
eq(0, meths.get_var('mouse_up2'))
end)
- it('feeding <MouseMove> does not use uninitialized memory #19480', function()
+ it('<MouseMove> is not translated into multiclicks and can be mapped', function()
+ meths.set_var('mouse_move', 0)
+ meths.set_var('mouse_move2', 0)
+ command('nnoremap <MouseMove> <Cmd>let g:mouse_move += 1<CR>')
+ command('nnoremap <2-MouseMove> <Cmd>let g:mouse_move2 += 1<CR>')
+ feed('<MouseMove><0,0>')
+ feed('<MouseMove><0,0>')
+ meths.input_mouse('move', '', '', 0, 0, 0)
+ meths.input_mouse('move', '', '', 0, 0, 0)
+ eq(4, meths.get_var('mouse_move'))
+ eq(0, meths.get_var('mouse_move2'))
+ end)
+
+ it('feeding <MouseMove> in Normal mode does not use uninitialized memory #19480', function()
feed('<MouseMove>')
helpers.poke_eventloop()
helpers.assert_alive()
diff --git a/test/functional/ui/options_spec.lua b/test/functional/ui/options_spec.lua
index 8d7c404637..bd0d2104db 100644
--- a/test/functional/ui/options_spec.lua
+++ b/test/functional/ui/options_spec.lua
@@ -19,6 +19,7 @@ describe('UI receives option updates', function()
linespace=0,
pumblend=0,
mousefocus=false,
+ mousemoveevent=false,
showtabline=1,
termguicolors=false,
ttimeout=true,
@@ -131,6 +132,12 @@ describe('UI receives option updates', function()
eq(expected, screen.options)
end)
+ command("set mousemoveevent")
+ expected.mousemoveevent = true
+ screen:expect(function()
+ eq(expected, screen.options)
+ end)
+
command("set nottimeout")
expected.ttimeout = false
screen:expect(function()
diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua
index dcd4ad3d9a..3c752875f0 100644
--- a/test/functional/ui/popupmenu_spec.lua
+++ b/test/functional/ui/popupmenu_spec.lua
@@ -2755,7 +2755,7 @@ describe('builtin popupmenu', function()
menu PopUp.bar :let g:menustr = 'bar'<CR>
menu PopUp.baz :let g:menustr = 'baz'<CR>
]])
- meths.input_mouse('right', 'press', '', 0, 0, 4)
+ feed('<RightMouse><4,0>')
screen:expect([[
^popup menu test |
{1:~ }{n: foo }{1: }|
@@ -2792,7 +2792,7 @@ describe('builtin popupmenu', function()
:let g:menustr = 'bar' |
]])
eq('bar', meths.get_var('menustr'))
- meths.input_mouse('right', 'press', '', 0, 1, 20)
+ feed('<RightMouse><20,1>')
screen:expect([[
^popup menu test |
{1:~ }|
@@ -2801,7 +2801,7 @@ describe('builtin popupmenu', function()
{1:~ }{n: baz }{1: }|
:let g:menustr = 'bar' |
]])
- meths.input_mouse('left', 'press', '', 0, 4, 22)
+ feed('<LeftMouse><22,4>')
screen:expect([[
^popup menu test |
{1:~ }|
@@ -2811,7 +2811,7 @@ describe('builtin popupmenu', function()
:let g:menustr = 'baz' |
]])
eq('baz', meths.get_var('menustr'))
- meths.input_mouse('right', 'press', '', 0, 0, 4)
+ feed('<RightMouse><4,0>')
screen:expect([[
^popup menu test |
{1:~ }{n: foo }{1: }|
@@ -2820,7 +2820,7 @@ describe('builtin popupmenu', function()
{1:~ }|
:let g:menustr = 'baz' |
]])
- meths.input_mouse('right', 'drag', '', 0, 3, 6)
+ feed('<RightDrag><6,3>')
screen:expect([[
^popup menu test |
{1:~ }{n: foo }{1: }|
@@ -2829,7 +2829,7 @@ describe('builtin popupmenu', function()
{1:~ }|
:let g:menustr = 'baz' |
]])
- meths.input_mouse('right', 'release', '', 0, 1, 6)
+ feed('<RightRelease><6,1>')
screen:expect([[
^popup menu test |
{1:~ }|
@@ -2839,6 +2839,38 @@ describe('builtin popupmenu', function()
:let g:menustr = 'foo' |
]])
eq('foo', meths.get_var('menustr'))
+ eq(false, screen.options.mousemoveevent)
+ feed('<RightMouse><4,0>')
+ screen:expect([[
+ ^popup menu test |
+ {1:~ }{n: foo }{1: }|
+ {1:~ }{n: bar }{1: }|
+ {1:~ }{n: baz }{1: }|
+ {1:~ }|
+ :let g:menustr = 'foo' |
+ ]])
+ eq(true, screen.options.mousemoveevent)
+ feed('<MouseMove><6,3>')
+ screen:expect([[
+ ^popup menu test |
+ {1:~ }{n: foo }{1: }|
+ {1:~ }{n: bar }{1: }|
+ {1:~ }{s: baz }{1: }|
+ {1:~ }|
+ :let g:menustr = 'foo' |
+ ]])
+ eq(true, screen.options.mousemoveevent)
+ feed('<LeftMouse><6,2>')
+ screen:expect([[
+ ^popup menu test |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ :let g:menustr = 'bar' |
+ ]])
+ eq(false, screen.options.mousemoveevent)
+ eq('bar', meths.get_var('menustr'))
end)
end)
@@ -3047,5 +3079,72 @@ describe('builtin popupmenu with ui/ext_multigrid', function()
:let g:menustr = 'foo' |
]]})
eq('foo', meths.get_var('menustr'))
+ eq(false, screen.options.mousemoveevent)
+ meths.input_mouse('right', 'press', '', 2, 0, 4)
+ screen:expect({grid=[[
+ ## grid 1
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [3:--------------------------------]|
+ ## grid 2
+ ^popup menu test |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ ## grid 3
+ :let g:menustr = 'foo' |
+ ## grid 4
+ {n: foo }|
+ {n: bar }|
+ {n: baz }|
+ ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 3, false, 100}}})
+ eq(true, screen.options.mousemoveevent)
+ meths.input_mouse('move', '', '', 2, 3, 6)
+ screen:expect({grid=[[
+ ## grid 1
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [3:--------------------------------]|
+ ## grid 2
+ ^popup menu test |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ ## grid 3
+ :let g:menustr = 'foo' |
+ ## grid 4
+ {n: foo }|
+ {n: bar }|
+ {s: baz }|
+ ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 3, false, 100}}})
+ eq(true, screen.options.mousemoveevent)
+ meths.input_mouse('left', 'press', '', 2, 2, 6)
+ screen:expect({grid=[[
+ ## grid 1
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [3:--------------------------------]|
+ ## grid 2
+ ^popup menu test |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ ## grid 3
+ :let g:menustr = 'bar' |
+ ]]})
+ eq(false, screen.options.mousemoveevent)
+ eq('bar', meths.get_var('menustr'))
end)
end)
diff --git a/test/functional/vimscript/executable_spec.lua b/test/functional/vimscript/executable_spec.lua
index b4162b2336..b49eb09512 100644
--- a/test/functional/vimscript/executable_spec.lua
+++ b/test/functional/vimscript/executable_spec.lua
@@ -34,11 +34,13 @@ describe('executable()', function()
it('fails for invalid values', function()
for _, input in ipairs({'v:null', 'v:true', 'v:false', '{}', '[]'}) do
- eq('Vim(call):E928: String required', exc_exec('call executable('..input..')'))
+ eq('Vim(call):E1174: String required for argument 1',
+ exc_exec('call executable('..input..')'))
end
command('let $PATH = fnamemodify("./test/functional/fixtures/bin", ":p")')
for _, input in ipairs({'v:null', 'v:true', 'v:false'}) do
- eq('Vim(call):E928: String required', exc_exec('call executable('..input..')'))
+ eq('Vim(call):E1174: String required for argument 1',
+ exc_exec('call executable('..input..')'))
end
end)
diff --git a/test/functional/vimscript/exepath_spec.lua b/test/functional/vimscript/exepath_spec.lua
index bbca954511..439dd96fcd 100644
--- a/test/functional/vimscript/exepath_spec.lua
+++ b/test/functional/vimscript/exepath_spec.lua
@@ -21,12 +21,12 @@ describe('exepath()', function()
it('fails for invalid values', function()
for _, input in ipairs({'v:null', 'v:true', 'v:false', '{}', '[]'}) do
- eq('Vim(call):E928: String required', exc_exec('call exepath('..input..')'))
+ eq('Vim(call):E1174: String required for argument 1', exc_exec('call exepath('..input..')'))
end
- eq('Vim(call):E1142: Non-empty string required', exc_exec('call exepath("")'))
+ eq('Vim(call):E1142: Non-empty string required for argument 1', exc_exec('call exepath("")'))
command('let $PATH = fnamemodify("./test/functional/fixtures/bin", ":p")')
for _, input in ipairs({'v:null', 'v:true', 'v:false'}) do
- eq('Vim(call):E928: String required', exc_exec('call exepath('..input..')'))
+ eq('Vim(call):E1174: String required for argument 1', exc_exec('call exepath('..input..')'))
end
end)
diff --git a/test/helpers.lua b/test/helpers.lua
index 7ec9beea92..499b91488b 100644
--- a/test/helpers.lua
+++ b/test/helpers.lua
@@ -790,10 +790,9 @@ end
function module.isCI(name)
local any = (name == nil)
- assert(any or name == 'sourcehut' or name == 'github')
- local sh = ((any or name == 'sourcehut') and nil ~= os.getenv('SOURCEHUT'))
+ assert(any or name == 'github')
local gh = ((any or name == 'github') and nil ~= os.getenv('GITHUB_ACTIONS'))
- return sh or gh
+ return gh
end
diff --git a/test/unit/message_spec.lua b/test/unit/message_spec.lua
index 7e92b5c857..549eff6e03 100644
--- a/test/unit/message_spec.lua
+++ b/test/unit/message_spec.lua
@@ -22,7 +22,7 @@ describe('trunc_string', function()
local function test_copy(s, expected, room)
room = room and room or 20
local buf = cimp.xmalloc(ffi.sizeof('char_u') * buflen)
- local str = cimp.vim_strsave(to_cstr(s))
+ local str = cimp.xstrdup(to_cstr(s))
cimp.trunc_string(str, buf, room, buflen)
eq(expected, ffi.string(buf))
cimp.xfree(buf)