aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml17
-rw-r--r--CMakeLists.txt27
-rw-r--r--CONTRIBUTING.md36
-rw-r--r--README.md3
-rw-r--r--ci/common/suite.sh7
-rw-r--r--cmake/InstallHelpers.cmake9
-rw-r--r--cmake/RunTests.cmake4
-rw-r--r--contrib/local.mk.example5
-rw-r--r--runtime/autoload/health/provider.vim2
-rw-r--r--runtime/autoload/man.vim11
-rw-r--r--runtime/autoload/provider/clipboard.vim6
-rw-r--r--runtime/autoload/provider/ruby.vim12
-rw-r--r--runtime/autoload/shada.vim3
-rw-r--r--runtime/doc/eval.txt131
-rw-r--r--runtime/doc/gui.txt26
-rw-r--r--runtime/doc/if_pyth.txt2
-rw-r--r--runtime/doc/intro.txt9
-rw-r--r--runtime/doc/job_control.txt1
-rw-r--r--runtime/doc/nvim_terminal_emulator.txt14
-rw-r--r--runtime/doc/options.txt18
-rw-r--r--runtime/doc/provider.txt13
-rw-r--r--runtime/doc/starting.txt112
-rw-r--r--runtime/doc/syntax.txt4
-rw-r--r--runtime/doc/usr_02.txt8
-rw-r--r--runtime/doc/usr_05.txt16
-rw-r--r--runtime/doc/various.txt14
-rwxr-xr-xscripts/genappimage.sh11
-rwxr-xr-xscripts/pvscheck.sh34
-rwxr-xr-xscripts/vim-patch.sh2
-rwxr-xr-xsrc/clint.py17
-rw-r--r--src/nvim/api/buffer.c58
-rw-r--r--src/nvim/api/private/helpers.c41
-rw-r--r--src/nvim/api/tabpage.c14
-rw-r--r--src/nvim/api/ui.c12
-rw-r--r--src/nvim/api/ui_events.in.h56
-rw-r--r--src/nvim/api/vim.c86
-rw-r--r--src/nvim/api/window.c32
-rw-r--r--src/nvim/buffer.c211
-rw-r--r--src/nvim/buffer.h8
-rw-r--r--src/nvim/buffer_defs.h31
-rw-r--r--src/nvim/bufhl_defs.h23
-rw-r--r--src/nvim/charset.c49
-rw-r--r--src/nvim/cursor_shape.c2
-rw-r--r--src/nvim/diff.c2
-rw-r--r--src/nvim/eval.c394
-rw-r--r--src/nvim/eval.lua2
-rw-r--r--src/nvim/eval/decode.c8
-rw-r--r--src/nvim/eval/executor.c6
-rw-r--r--src/nvim/eval/typval.c6
-rw-r--r--src/nvim/eval/typval.h13
-rw-r--r--src/nvim/event/loop.c21
-rw-r--r--src/nvim/event/socket.c197
-rw-r--r--src/nvim/event/socket.h2
-rw-r--r--src/nvim/ex_cmds.c42
-rw-r--r--src/nvim/ex_docmd.c21
-rw-r--r--src/nvim/ex_getln.c10
-rw-r--r--src/nvim/fileio.c39
-rw-r--r--src/nvim/fold.c2
-rw-r--r--src/nvim/func_attr.h18
-rw-r--r--src/nvim/garray.h2
-rw-r--r--src/nvim/getchar.c27
-rw-r--r--src/nvim/globals.h151
-rw-r--r--src/nvim/highlight_defs.h126
-rw-r--r--src/nvim/if_cscope.c2
-rw-r--r--src/nvim/indent.c4
-rw-r--r--src/nvim/indent_c.c39
-rw-r--r--src/nvim/keymap.c2
-rw-r--r--src/nvim/lib/kbtree.h451
-rw-r--r--src/nvim/log.c106
-rw-r--r--src/nvim/log.h74
-rw-r--r--src/nvim/lua/executor.c2
-rw-r--r--src/nvim/main.c7
-rw-r--r--src/nvim/map.c1
-rw-r--r--src/nvim/map.h1
-rw-r--r--src/nvim/mark.c19
-rw-r--r--src/nvim/mark.h3
-rw-r--r--src/nvim/memfile.c20
-rw-r--r--src/nvim/memline.c9
-rw-r--r--src/nvim/misc1.c6
-rw-r--r--src/nvim/msgpack_rpc/channel.c109
-rw-r--r--src/nvim/msgpack_rpc/server.c48
-rw-r--r--src/nvim/ops.c99
-rw-r--r--src/nvim/option.c29
-rw-r--r--src/nvim/os/fs.c4
-rw-r--r--src/nvim/os/pty_process_unix.c2
-rw-r--r--src/nvim/os/shell.c10
-rw-r--r--src/nvim/os_unix.c6
-rw-r--r--src/nvim/path.c2
-rw-r--r--src/nvim/popupmnu.c8
-rw-r--r--src/nvim/quickfix.c24
-rw-r--r--src/nvim/screen.c419
-rw-r--r--src/nvim/search.c7
-rw-r--r--src/nvim/shada.c88
-rw-r--r--src/nvim/strings.c9
-rw-r--r--src/nvim/syntax_defs.h3
-rw-r--r--src/nvim/tag.c86
-rw-r--r--src/nvim/terminal.c10
-rw-r--r--src/nvim/testdir/Makefile4
-rw-r--r--src/nvim/testdir/runtest.vim115
-rw-r--r--src/nvim/testdir/shared.vim2
-rw-r--r--src/nvim/testdir/test49.vim2
-rw-r--r--src/nvim/testdir/test_alot.vim2
-rw-r--r--src/nvim/testdir/test_cscope.vim2
-rw-r--r--src/nvim/testdir/test_cursor_func.vim8
-rw-r--r--src/nvim/testdir/test_expr.vim31
-rw-r--r--src/nvim/testdir/test_float_func.vim332
-rw-r--r--src/nvim/testdir/test_functions.vim19
-rw-r--r--src/nvim/testdir/test_largefile.vim34
-rw-r--r--src/nvim/testdir/test_menu.vim2
-rw-r--r--src/nvim/testdir/test_popup.vim2
-rw-r--r--src/nvim/testdir/test_search.vim12
-rw-r--r--src/nvim/testdir/test_startup.vim2
-rw-r--r--src/nvim/testdir/test_stat.vim64
-rw-r--r--src/nvim/testdir/test_vimscript.vim (renamed from src/nvim/testdir/test_viml.vim)151
-rw-r--r--src/nvim/tui/tui.c198
-rw-r--r--src/nvim/undo.c8
-rw-r--r--src/nvim/version.c22
-rw-r--r--src/nvim/window.c4
-rw-r--r--test/README.md2
-rw-r--r--test/functional/api/keymap_spec.lua246
-rw-r--r--test/functional/api/server_requests_spec.lua73
-rw-r--r--test/functional/eval/function_spec.lua29
-rw-r--r--test/functional/eval/map_functions_spec.lua120
-rw-r--r--test/functional/eval/msgpack_functions_spec.lua6
-rw-r--r--test/functional/eval/server_spec.lua47
-rw-r--r--test/functional/ex_cmds/mksession_spec.lua49
-rw-r--r--test/functional/helpers.lua31
-rw-r--r--test/functional/legacy/assert_spec.lua10
-rw-r--r--test/functional/legacy/eval_spec.lua9
-rw-r--r--test/functional/options/defaults_spec.lua52
-rw-r--r--test/functional/options/pastetoggle_spec.lua35
-rw-r--r--test/functional/plugin/shada_spec.lua37
-rw-r--r--test/functional/shada/registers_spec.lua36
-rw-r--r--test/functional/ui/highlight_spec.lua170
-rw-r--r--test/functional/ui/screen.lua5
-rw-r--r--test/functional/viml/function_spec.lua232
-rw-r--r--test/helpers.lua7
-rw-r--r--test/unit/os/shell_spec.lua22
-rw-r--r--third-party/CMakeLists.txt29
-rw-r--r--third-party/cmake/BuildLuarocks.cmake7
140 files changed, 4687 insertions, 1578 deletions
diff --git a/.travis.yml b/.travis.yml
index 8ca6f58fec..45c2dcb832 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,7 +10,7 @@ env:
# http://docs.travis-ci.com/user/speeding-up-the-build/#Paralellizing-your-build-on-one-VM
- MAKE_CMD="make -j2"
# Update PATH for pip.
- - PATH="$(python2.7 -c 'import site; print(site.getuserbase())')/bin:/usr/lib/llvm-symbolizer-3.9/bin:$PATH"
+ - PATH="$(python2.7 -c 'import site; print(site.getuserbase())')/bin:/usr/lib/llvm-symbolizer-4.0/bin:$PATH"
# Build directory for Neovim.
- BUILD_DIR="$TRAVIS_BUILD_DIR/build"
# Build directory for third-party dependencies.
@@ -21,14 +21,15 @@ env:
- INSTALL_PREFIX="$HOME/nvim-install"
# Log directory for Clang sanitizers and Valgrind.
- LOG_DIR="$BUILD_DIR/log"
+ # Nvim log file.
+ - NVIM_LOG_FILE="$BUILD_DIR/.nvimlog"
# Default CMake flags.
- CMAKE_FLAGS="-DTRAVIS_CI_BUILD=ON
-DCMAKE_BUILD_TYPE=Debug
-DCMAKE_INSTALL_PREFIX:PATH=$INSTALL_PREFIX
-DBUSTED_OUTPUT_TYPE=nvim
-DDEPS_PREFIX=$DEPS_BUILD_DIR/usr
- -DMIN_LOG_LEVEL=3
- -DDISABLE_LOG=1"
+ -DMIN_LOG_LEVEL=3"
- DEPS_CMAKE_FLAGS="-DDEPS_DOWNLOAD_DIR:PATH=$DEPS_DOWNLOAD_DIR"
# Additional CMake flags for 32-bit builds.
- CMAKE_FLAGS_32BIT="-DCMAKE_SYSTEM_LIBRARY_PATH=/lib32:/usr/lib32:/usr/local/lib32
@@ -52,12 +53,12 @@ jobs:
include:
- stage: sanitizers
os: linux
- compiler: clang-3.9
+ compiler: clang-4.0
env: >
CLANG_SANITIZER=ASAN_UBSAN
CMAKE_FLAGS="$CMAKE_FLAGS -DPREFER_LUA=ON"
- os: linux
- compiler: clang-3.9
+ compiler: clang-4.0
env: CLANG_SANITIZER=TSAN
- stage: normal builds
os: linux
@@ -97,13 +98,13 @@ addons:
apt:
sources:
- ubuntu-toolchain-r-test
- - llvm-toolchain-trusty-3.9
+ - llvm-toolchain-trusty-4.0
packages:
- autoconf
- automake
- apport
- build-essential
- - clang-3.9
+ - clang-4.0
- cmake
- cscope
- g++-5-multilib
@@ -114,7 +115,7 @@ addons:
- language-pack-tr
- libc6-dev-i386
- libtool
- - llvm-3.9-dev
+ - llvm-4.0-dev
- locales
- pkg-config
- unzip
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e2c99d9fd8..1699ffa8fa 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -96,15 +96,15 @@ if(CMAKE_C_FLAGS_RELEASE MATCHES "-O3")
string(REPLACE "-O3" "-O2" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
endif()
-# Disable logging for release-type builds.
-if(NOT CMAKE_C_FLAGS_RELEASE MATCHES DDISABLE_LOG)
- set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -DDISABLE_LOG")
+# Minimize logging for release-type builds.
+if(NOT CMAKE_C_FLAGS_RELEASE MATCHES DMIN_LOG_LEVEL)
+ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -DMIN_LOG_LEVEL=3")
endif()
-if(NOT CMAKE_C_FLAGS_MINSIZEREL MATCHES DDISABLE_LOG)
- set(CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL} -DDISABLE_LOG")
+if(NOT CMAKE_C_FLAGS_MINSIZEREL MATCHES DMIN_LOG_LEVEL)
+ set(CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL} -DMIN_LOG_LEVEL=3")
endif()
-if(NOT CMAKE_C_FLAGS_RELWITHDEBINFO MATCHES DDISABLE_LOG)
- set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} -DDISABLE_LOG")
+if(NOT CMAKE_C_FLAGS_RELWITHDEBINFO MATCHES DMIN_LOG_LEVEL)
+ set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} -DMIN_LOG_LEVEL=3")
endif()
# Enable assertions for RelWithDebInfo.
@@ -228,7 +228,7 @@ else()
# On FreeBSD 64 math.h uses unguarded C11 extension, which taints clang
# 3.4.1 used there.
- if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
+ if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" AND CMAKE_C_COMPILER_ID MATCHES "Clang")
add_definitions(-Wno-c11-extensions)
endif()
endif()
@@ -445,11 +445,7 @@ message(STATUS "Using the Lua interpreter ${LUA_PRG}.")
find_program(BUSTED_PRG NAMES busted busted.bat)
find_program(BUSTED_LUA_PRG busted-lua)
if(NOT BUSTED_OUTPUT_TYPE)
- if(WIN32)
- set(BUSTED_OUTPUT_TYPE "plainTerminal")
- else()
- set(BUSTED_OUTPUT_TYPE "utfTerminal")
- endif()
+ set(BUSTED_OUTPUT_TYPE "nvim")
endif()
find_program(LUACHECK_PRG luacheck)
@@ -460,7 +456,6 @@ include(InstallHelpers)
file(GLOB MANPAGES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
man/nvim.1)
-
install_helper(
FILES ${MANPAGES}
DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
@@ -468,11 +463,11 @@ install_helper(
# MIN_LOG_LEVEL for log.h
if(DEFINED MIN_LOG_LEVEL)
if(NOT MIN_LOG_LEVEL MATCHES "^[0-3]$")
- message(FATAL_ERROR "MIN_LOG_LEVEL must be a number 0-3")
+ message(FATAL_ERROR "invalid MIN_LOG_LEVEL: " ${MIN_LOG_LEVEL})
endif()
message(STATUS "MIN_LOG_LEVEL set to ${MIN_LOG_LEVEL}")
else()
- message(STATUS "MIN_LOG_LEVEL not specified, defaulting to INFO(1)")
+ message(STATUS "MIN_LOG_LEVEL not specified, defaulting to 1 (INFO)")
endif()
# Go down the tree.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d40ea3a59d..8580e8ef39 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -6,9 +6,10 @@ Getting started
If you want to help but don't know where to start, here are some
low-risk/isolated tasks:
-- Merge a [Vim patch].
+- [Merge a Vim patch].
- Try a [complexity:low] issue.
-- Fix bugs found by [clang-scan], [coverity](#coverity), and [PVS](#pvs-studio).
+- Fix bugs found by [clang scan-build](#clang-scan-build),
+ [coverity](#coverity), and [PVS](#pvs-studio).
Developer guidelines
--------------------
@@ -22,18 +23,16 @@ Reporting problems
- Check the [**FAQ**][wiki-faq].
- Search [existing issues][github-issues] (including closed!)
- Update Neovim to the latest version to see if your problem persists.
-- If you're using a plugin manager, comment out your plugins, then add them back
- in one by one, to narrow down the cause of the issue.
-- Crash reports which include a stacktrace are 10x more valuable.
-- [Bisecting][git-bisect] to the cause of a regression often leads to an
- immediate fix.
+- Disable plugins incrementally, to narrow down the cause of the issue.
+- When reporting a crash, include a stacktrace.
+- [Bisect][git-bisect] to the cause of a regression, if you are able. This is _extremely_ helpful.
+- Check `$NVIM_LOG_FILE`, if it exists.
Pull requests ("PRs")
---------------------
- To avoid duplicate work, create a `[WIP]` pull request as soon as possible.
-- Avoid cosmetic changes to unrelated files in the same commit: noise makes
- reviews take longer.
+- Avoid cosmetic changes to unrelated files in the same commit.
- Use a [feature branch][git-feature-branch] instead of the master branch.
- Use a **rebase workflow** for small PRs.
- After addressing review comments, it's fine to rebase and force-push.
@@ -86,10 +85,11 @@ the VCS/git logs more valuable.
### Automated builds (CI)
-Each pull request must pass the automated builds ([travis CI] and [quickbuild]).
+Each pull request must pass the automated builds on [travis CI], [quickbuild]
+and [AppVeyor].
-- CI builds are compiled with [`-Werror`][gcc-warnings], so if your PR
- introduces any compiler warnings, the build will fail.
+- CI builds are compiled with [`-Werror`][gcc-warnings], so compiler warnings
+ will fail the build.
- If any tests fail, the build will fail.
See [Building Neovim#running-tests][wiki-run-tests] to run tests locally.
Passing locally doesn't guarantee passing the CI build, because of the
@@ -112,6 +112,15 @@ QuickBuild uses this invocation:
VERBOSE=1 nvim unittest-prereqs functionaltest-prereqs
+### Clang scan-build
+
+The auto-generated [clang-scan] report presents walk-throughs of bugs found by
+Clang's [scan-build](https://clang-analyzer.llvm.org/scan-build.html) static
+analyzer. To verify a fix locally, run `scan-build` like this:
+
+ rm -rf build/
+ scan-build --use-analyzer=/usr/bin/clang make
+
### Coverity
[Coverity](https://scan.coverity.com/projects/neovim-neovim) runs against the
@@ -163,6 +172,7 @@ as context, use the `-W` argument as well.
[3174]: https://github.com/neovim/neovim/issues/3174
[travis CI]: https://travis-ci.org/neovim/neovim
[quickbuild]: http://neovim-qb.szakmeister.net/dashboard
-[Vim patch]: https://github.com/neovim/neovim/wiki/Merging-patches-from-upstream-Vim
+[AppVeyor]: https://ci.appveyor.com/project/neovim/neovim
+[Merge a Vim patch]: https://github.com/neovim/neovim/wiki/Merging-patches-from-upstream-Vim
[clang-scan]: https://neovim.io/doc/reports/clang/
[complexity:low]: https://github.com/neovim/neovim/issues?q=is%3Aopen+is%3Aissue+label%3Acomplexity%3Alow
diff --git a/README.md b/README.md
index dc64f776d4..cb3ac46a24 100644
--- a/README.md
+++ b/README.md
@@ -42,7 +42,7 @@ Install from package
Pre-built packages for Windows, macOS, and Linux are found at the
[Releases](https://github.com/neovim/neovim/releases/) page.
-Managed packages are in [Homebrew], [Debian], [Ubuntu], [Fedora], [Arch Linux],
+Managed packages are in [Homebrew], [Debian], [Ubuntu], [Fedora], [Arch Linux], [Gentoo],
and [more](https://github.com/neovim/neovim/wiki/Installing-Neovim)!
Project layout
@@ -110,5 +110,6 @@ See `LICENSE` for details.
[Ubuntu]: http://packages.ubuntu.com/search?keywords=neovim
[Fedora]: https://admin.fedoraproject.org/pkgdb/package/rpms/neovim
[Arch Linux]: https://www.archlinux.org/packages/?q=neovim
+[Gentoo]: https://packages.gentoo.org/packages/app-editors/neovim
<!-- vim: set tw=80: -->
diff --git a/ci/common/suite.sh b/ci/common/suite.sh
index 8feb642547..d3fbcd1eda 100644
--- a/ci/common/suite.sh
+++ b/ci/common/suite.sh
@@ -39,6 +39,13 @@ enter_suite() {
exit_suite() {
set +x
+ if test -f "$NVIM_LOG_FILE" ; then
+ printf "===============================================================================\n"
+ printf "NVIM_LOG_FILE: $NVIM_LOG_FILE\n"
+ cat "$NVIM_LOG_FILE" 2>/dev/null || printf '(empty)'
+ printf "\n"
+ rm -rf "$NVIM_LOG_FILE"
+ fi
travis_fold end "${NVIM_TEST_CURRENT_SUITE}"
if test $FAILED -ne 0 ; then
echo "Suite ${NVIM_TEST_CURRENT_SUITE} failed, summary:"
diff --git a/cmake/InstallHelpers.cmake b/cmake/InstallHelpers.cmake
index ee07ba2c66..ca20ddf354 100644
--- a/cmake/InstallHelpers.cmake
+++ b/cmake/InstallHelpers.cmake
@@ -1,3 +1,12 @@
+# Fix CMAKE_INSTALL_MANDIR on BSD before including GNUInstallDirs. #6771
+if(CMAKE_SYSTEM_NAME MATCHES "BSD" AND NOT DEFINED CMAKE_INSTALL_MANDIR)
+ if(DEFINED ENV{MANPREFIX})
+ set(CMAKE_INSTALL_MANDIR "$ENV{MANPREFIX}/man")
+ else()
+ set(CMAKE_INSTALL_MANDIR "/usr/local/man")
+ endif()
+endif()
+
# For $CMAKE_INSTALL_{DATAROOT,MAN, ...}DIR
include(GNUInstallDirs)
diff --git a/cmake/RunTests.cmake b/cmake/RunTests.cmake
index bd7b630708..5f818cc9ad 100644
--- a/cmake/RunTests.cmake
+++ b/cmake/RunTests.cmake
@@ -3,6 +3,10 @@ set(ENV{NVIM_RPLUGIN_MANIFEST} ${WORKING_DIR}/Xtest_rplugin_manifest)
set(ENV{XDG_CONFIG_HOME} ${WORKING_DIR}/Xtest_xdg/config)
set(ENV{XDG_DATA_HOME} ${WORKING_DIR}/Xtest_xdg/share)
+if(NOT DEFINED ENV{NVIM_LOG_FILE})
+ set(ENV{NVIM_LOG_FILE} ${WORKING_DIR}/.nvimlog)
+endif()
+
if(NVIM_PRG)
set(ENV{NVIM_PRG} "${NVIM_PRG}")
endif()
diff --git a/contrib/local.mk.example b/contrib/local.mk.example
index 04f21131b8..cadb9cf4b2 100644
--- a/contrib/local.mk.example
+++ b/contrib/local.mk.example
@@ -31,9 +31,8 @@
#
# CMAKE_BUILD_TYPE := Debug
-# By default, nvim's log level is INFO (1) (unless CMAKE_BUILD_TYPE is
-# "Release", in which case logging is disabled).
-# The log level must be a number DEBUG (0), INFO (1), WARNING (2) or ERROR (3).
+# The default log level is 1 (INFO) (unless CMAKE_BUILD_TYPE is "Release").
+# Log levels: 0 (DEBUG), 1 (INFO), 2 (WARNING), 3 (ERROR)
# CMAKE_EXTRA_FLAGS += -DMIN_LOG_LEVEL=1
# By default, nvim uses bundled versions of its required third-party
diff --git a/runtime/autoload/health/provider.vim b/runtime/autoload/health/provider.vim
index 6183182b73..31a235a397 100644
--- a/runtime/autoload/health/provider.vim
+++ b/runtime/autoload/health/provider.vim
@@ -460,7 +460,7 @@ function! s:check_ruby() abort
\ 'Are you behind a firewall or proxy?'])
return
endif
- let latest_gem = get(split(latest_gem, ' (\|, \|)$' ), 1, 'not found')
+ let latest_gem = get(split(latest_gem, 'neovim (\|, \|)$' ), 1, 'not found')
let current_gem_cmd = host .' --version'
let current_gem = s:system(current_gem_cmd)
diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim
index 361ade59d3..dd71ede680 100644
--- a/runtime/autoload/man.vim
+++ b/runtime/autoload/man.vim
@@ -2,8 +2,17 @@
let s:find_arg = '-w'
let s:localfile_arg = v:true " Always use -l if possible. #6683
+let s:section_arg = '-s'
+
+function! s:init_section_flag()
+ call system(['env', 'MANPAGER=cat', 'man', s:section_arg, '1', 'man'])
+ if v:shell_error
+ let s:section_arg = '-S'
+ endif
+endfunction
function! s:init() abort
+ call s:init_section_flag()
" TODO(nhooyr): Does `man -l` on SunOS list searched directories?
try
if !has('win32') && $OSTYPE !~? 'cygwin\|linux' && system('uname -s') =~? 'SunOS' && system('uname -r') =~# '^5'
@@ -211,7 +220,7 @@ function! s:get_path(sect, name) abort
" - sections starting with '-'
" - 3pcap section (found on macOS)
" - commas between sections (for section priority)
- return s:system(['man', s:find_arg, '-s', a:sect, a:name])
+ return s:system(['man', s:find_arg, s:section_arg, a:sect, a:name])
endfunction
function! s:verify_exists(sect, name) abort
diff --git a/runtime/autoload/provider/clipboard.vim b/runtime/autoload/provider/clipboard.vim
index a3210046b1..e15aa1f2bd 100644
--- a/runtime/autoload/provider/clipboard.vim
+++ b/runtime/autoload/provider/clipboard.vim
@@ -84,6 +84,12 @@ function! provider#clipboard#Executable() abort
let s:copy['*'] = s:copy['+']
let s:paste['*'] = s:paste['+']
return 'win32yank'
+ elseif exists('$TMUX') && executable('tmux')
+ let s:copy['+'] = 'tmux load-buffer -'
+ let s:paste['+'] = 'tmux save-buffer -'
+ let s:copy['*'] = s:copy['+']
+ let s:paste['*'] = s:paste['+']
+ return 'tmux'
endif
let s:err = 'clipboard: No clipboard tool available. :help clipboard'
diff --git a/runtime/autoload/provider/ruby.vim b/runtime/autoload/provider/ruby.vim
index c8ede20a75..91b7fb9f2c 100644
--- a/runtime/autoload/provider/ruby.vim
+++ b/runtime/autoload/provider/ruby.vim
@@ -16,7 +16,11 @@ function! s:job_opts.on_stderr(chan_id, data, event)
endfunction
function! provider#ruby#Detect() abort
- return exepath('neovim-ruby-host')
+ if exists("g:ruby_host_prog")
+ return g:ruby_host_prog
+ else
+ return exepath('neovim-ruby-host')
+ end
endfunction
function! provider#ruby#Prog()
@@ -24,15 +28,15 @@ function! provider#ruby#Prog()
endfunction
function! provider#ruby#Require(host) abort
- let args = [provider#ruby#Prog()]
+ let prog = provider#ruby#Prog()
let ruby_plugins = remote#host#PluginsForHost(a:host.name)
for plugin in ruby_plugins
- call add(args, plugin.path)
+ let prog .= " " . shellescape(plugin.path)
endfor
try
- let channel_id = jobstart(args, s:job_opts)
+ let channel_id = jobstart(prog, s:job_opts)
if rpcrequest(channel_id, 'poll') ==# 'ok'
return channel_id
endif
diff --git a/runtime/autoload/shada.vim b/runtime/autoload/shada.vim
index cf27ee608a..87acc515ee 100644
--- a/runtime/autoload/shada.vim
+++ b/runtime/autoload/shada.vim
@@ -45,7 +45,7 @@ call map(copy(s:SHADA_ENTRY_NAMES),
let s:SHADA_MAP_ENTRIES = {
\'search_pattern': ['sp', 'sh', 'ss', 'sb', 'sm', 'sc', 'sl', 'se', 'so',
\ 'su'],
- \'register': ['n', 'rc', 'rw', 'rt'],
+ \'register': ['n', 'rc', 'rw', 'rt', 'ru'],
\'global_mark': ['n', 'f', 'l', 'c'],
\'local_mark': ['f', 'n', 'l', 'c'],
\'jump': ['f', 'l', 'c'],
@@ -139,6 +139,7 @@ let s:SHADA_STANDARD_KEYS = {
\'rt': ['type', 'regtype', s:SHADA_ENUMS.regtype.CHARACTERWISE],
\'rw': ['block width', 'uint', 0],
\'rc': ['contents', 'binarray', s:SHADA_REQUIRED],
+ \'ru': ['is_unnamed', 'boolean', g:msgpack#false],
\'n': ['name', 'intchar', char2nr('"')],
\'l': ['line number', 'uint', 1],
\'c': ['column', 'uint', 0],
diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt
index 44f2b3688c..2a73590c76 100644
--- a/runtime/doc/eval.txt
+++ b/runtime/doc/eval.txt
@@ -22,6 +22,8 @@ done, the features in this document are not available. See |+eval| and
There are six types of variables:
Number A 32 or 64 bit signed number. |expr-number| *Number*
+ 64-bit Number is available only when compiled with the
+ |+num64| feature.
Examples: -123 0x10 0177 0b1011
Float A floating point number. |floating-point-format| *Float*
@@ -887,6 +889,11 @@ When dividing a Number by zero the result depends on the value:
<0 / 0 = -0x7fffffff (like negative infinity)
(before Vim 7.2 it was always 0x7fffffff)
+When 64-bit Number support is enabled:
+ 0 / 0 = -0x8000000000000000 (like NaN for Float)
+ >0 / 0 = 0x7fffffffffffffff (like positive infinity)
+ <0 / 0 = -0x7fffffffffffffff (like negative infinity)
+
When the righthand side of '%' is zero, the result is 0.
None of these work for |Funcref|s.
@@ -1936,16 +1943,23 @@ argidx() Number current index in the argument list
arglistid([{winnr} [, {tabnr}]]) Number argument list id
argv({nr}) String {nr} entry of the argument list
argv() List the argument list
-assert_equal({exp}, {act} [, {msg}]) none assert {exp} is equal to {act}
-assert_exception( {error} [, {msg}]) none assert {error} is in v:exception
-assert_fails( {cmd} [, {error}]) none assert {cmd} fails
-assert_false({actual} [, {msg}]) none assert {actual} is false
+assert_equal({exp}, {act} [, {msg}])
+ none assert {exp} is equal to {act}
+assert_exception({error} [, {msg}])
+ none assert {error} is in v:exception
+assert_fails({cmd} [, {error}]) none assert {cmd} fails
+assert_false({actual} [, {msg}])
+ none assert {actual} is false
assert_inrange({lower}, {upper}, {actual} [, {msg}])
none assert {actual} is inside the range
-assert_match( {pat}, {text} [, {msg}]) none assert {pat} matches {text}
-assert_notequal( {exp}, {act} [, {msg}]) none assert {exp} is not equal {act}
-assert_notmatch( {pat}, {text} [, {msg}]) none assert {pat} not matches {text}
-assert_true({actual} [, {msg}]) none assert {actual} is true
+assert_match({pat}, {text} [, {msg}])
+ none assert {pat} matches {text}
+assert_notequal({exp}, {act} [, {msg}])
+ none assert {exp} is not equal {act}
+assert_notmatch({pat}, {text} [, {msg}])
+ none assert {pat} not matches {text}
+assert_report({msg}) none report a test failure
+assert_true({actual} [, {msg}]) none assert {actual} is true
asin({expr}) Float arc sine of {expr}
atan({expr}) Float arc tangent of {expr}
atan2({expr}, {expr}) Float arc tangent of {expr1} / {expr2}
@@ -2501,6 +2515,9 @@ assert_notmatch({pattern}, {actual} [, {msg}])
The opposite of `assert_match()`: add an error message to
|v:errors| when {pattern} matches {actual}.
+assert_report({msg}) *assert_report()*
+ Report a test failure directly, using {msg}.
+
assert_true({actual} [, {msg}]) *assert_true()*
When {actual} is not true an error message is added to
|v:errors|, like with |assert_equal()|.
@@ -2845,8 +2862,6 @@ confirm({msg} [, {choices} [, {default} [, {type}]]])
Confirm() offers the user a dialog, from which a choice can be
made. It returns the number of the choice. For the first
choice this is 1.
- Note: confirm() is only supported when compiled with dialog
- support, see |+dialog_con| and |+dialog_gui|.
{msg} is displayed in a |dialog| with {choices} as the
alternatives. When {choices} is missing or empty, "&OK" is
@@ -3538,17 +3553,19 @@ float2nr({expr}) *float2nr()*
decimal point.
{expr} must evaluate to a |Float| or a Number.
When the value of {expr} is out of range for a |Number| the
- result is truncated to 0x7fffffff or -0x7fffffff. NaN results
- in -0x80000000.
+ result is truncated to 0x7fffffff or -0x7fffffff (or when
+ 64-bit Number support is enabled, 0x7fffffffffffffff or
+ -0x7fffffffffffffff. NaN results in -0x80000000 (or when
+ 64-bit Number support is enabled, -0x8000000000000000).
Examples: >
echo float2nr(3.95)
< 3 >
echo float2nr(-23.45)
< -23 >
echo float2nr(1.0e100)
-< 2147483647 >
+< 2147483647 (or 9223372036854775807) >
echo float2nr(-1.0e150)
-< -2147483647 >
+< -2147483647 (or -9223372036854775807) >
echo float2nr(1.0e-100)
< 0
@@ -3634,11 +3651,14 @@ foldtext() Returns a String, to be displayed for a closed fold. This is
|v:foldstart|, |v:foldend| and |v:folddashes| variables.
The returned string looks like this: >
+-- 45 lines: abcdef
-< The number of dashes depends on the foldlevel. The "45" is
- the number of lines in the fold. "abcdef" is the text in the
- first non-blank line of the fold. Leading white space, "//"
- or "/*" and the text from the 'foldmarker' and 'commentstring'
- options is removed.
+< The number of leading dashes depends on the foldlevel. The
+ "45" is the number of lines in the fold. "abcdef" is the text
+ in the first non-blank line of the fold. Leading white space,
+ "//" or "/*" and the text from the 'foldmarker' and
+ 'commentstring' options is removed.
+ When used to draw the actual foldtext, the rest of the line
+ will be filled with the fold char from the 'fillchars'
+ setting.
{not available when compiled without the |+folding| feature}
foldtextresult({lnum}) *foldtextresult()*
@@ -4883,9 +4903,9 @@ jobstart({cmd}[, {opts}]) {Nvim} *jobstart()*
unless cmd[0] is some form of "cmd.exe".
{opts} is a dictionary with these keys:
- on_stdout: stdout event handler (function name or |Funcref|)
- on_stderr: stderr event handler (function name or |Funcref|)
- on_exit : exit event handler (function name or |Funcref|)
+ |on_stdout|: stdout event handler (function name or |Funcref|)
+ |on_stderr|: stderr event handler (function name or |Funcref|)
+ |on_exit| : exit event handler (function name or |Funcref|)
cwd : Working directory of the job; defaults to
|current-directory|.
rpc : If set, |msgpack-rpc| will be used to communicate
@@ -6462,11 +6482,20 @@ serverlist() *serverlist()*
nvim --cmd "echo serverlist()" --cmd "q"
<
serverstart([{address}]) *serverstart()*
- Opens a named pipe or TCP socket at {address} for clients to
- connect to and returns {address}. If no address is given, it
- is equivalent to: >
+ Opens a TCP socket (IPv4/IPv6), Unix domain socket (Unix),
+ or named pipe (Windows) at {address} for clients to connect
+ to and returns {address}.
+
+ If {address} contains `:`, a TCP socket is used. Everything in
+ front of the last occurrence of `:` is the IP or hostname,
+ everything after it the port. If the port is empty or `0`,
+ a random port will be assigned.
+
+ If no address is given, it is equivalent to: >
:call serverstart(tempname())
+
< |$NVIM_LISTEN_ADDRESS| is set to {address} if not already set.
+
*--servername*
The Vim command-line option `--servername` can be imitated: >
nvim --cmd "let g:server_addr = serverstart('foo')"
@@ -6712,6 +6741,8 @@ setreg({regname}, {value} [, {options}])
used as the width of the selection - if it is not specified
then the width of the block is set to the number of characters
in the longest line (counting a <Tab> as 1 character).
+ If {options} contains "u" or '"', then the unnamed register is
+ set to point to register {regname}.
If {options} contains no register settings, then the default
is to use character mode unless {value} ends in a <NL> for
@@ -6856,6 +6887,21 @@ sinh({expr}) *sinh()*
:echo sinh(-0.9)
< -1.026517
+sockconnect({mode}, {address}, {opts}) *sockconnect()*
+ Connect a socket to an address. If {mode} is "pipe" then
+ {address} should be the path of a named pipe. If {mode} is
+ "tcp" then {address} should be of the form "host:port" where
+ the host should be an ip adderess or host name, and port the
+ port number. Currently only rpc sockets are supported, so
+ {opts} must be passed with "rpc" set to |TRUE|.
+
+ {opts} is a dictionary with these keys:
+ rpc : If set, |msgpack-rpc| will be used to communicate
+ over the socket.
+ Returns:
+ - The channel ID on success, which is used by
+ |rpcnotify()| and |rpcrequest()| and |rpcstop()|.
+ - 0 on invalid arguments or connection failure.
sort({list} [, {func} [, {dict}]]) *sort()* *E702*
Sort the items in {list} in-place. Returns {list}.
@@ -7959,7 +8005,10 @@ winwidth({nr}) *winwidth()*
:if winwidth(0) <= 50
: exe "normal 50\<C-W>|"
:endif
-<
+< For getting the terminal or screen size, see the 'columns'
+ option.
+
+
wordcount() *wordcount()*
The result is a dictionary of byte/chars/word statistics for
the current buffer. This is the same info as provided by
@@ -8030,7 +8079,7 @@ There are four types of features:
:if has("cindent")
2. Features that are only supported when certain conditions have been met.
Example: >
- :if has("gui_running")
+ :if has("win32")
< *has-patch*
3. {Nvim} version. The "nvim-1.2.3" feature means that the Nvim version is
1.2.3 or later. Example: >
@@ -8065,17 +8114,14 @@ browse Compiled with |:browse| support, and browse() will
browsefilter Compiled with support for |browsefilter|.
byte_offset Compiled with support for 'o' in 'statusline'
cindent Compiled with 'cindent' support.
-clientserver Compiled with remote invocation support |clientserver|.
clipboard Compiled with 'clipboard' support.
cmdline_compl Compiled with |cmdline-completion| support.
cmdline_hist Compiled with |cmdline-history| support.
cmdline_info Compiled with 'showcmd' and 'ruler' support.
comments Compiled with |'comments'| support.
-compatible Compiled to be very Vi compatible.
cscope Compiled with |cscope| support.
debug Compiled with "DEBUG" defined.
dialog_con Compiled with console dialog support.
-dialog_gui Compiled with GUI dialog support.
digraphs Compiled with support for digraphs.
eval Compiled with expression evaluation support. Always
true, of course!
@@ -8093,9 +8139,6 @@ fname_case Case in file names matters (for Windows this is not
present).
folding Compiled with |folding| support.
gettext Compiled with message translation |multi-lang|
-gui Compiled with GUI enabled.
-gui_running Vim is running in the GUI, or it will start soon.
-gui_win32 Compiled with MS Windows Win32 GUI.
iconv Can use iconv() for conversion.
insert_expand Compiled with support for CTRL-X expansion commands in
Insert mode.
@@ -8110,8 +8153,7 @@ lispindent Compiled with support for lisp indenting.
listcmds Compiled with commands for the buffer list |:files|
and the argument list |arglist|.
localmap Compiled with local mappings and abbr. |:map-local|
-mac Macintosh version of Vim.
-macunix Macintosh version of Vim, using Unix files (OS-X).
+mac macOS version of Vim.
menu Compiled with support for |:menu|.
mksession Compiled with support for |:mksession|.
modify_fname Compiled with file name modifiers. |filename-modifiers|
@@ -8119,17 +8161,16 @@ mouse Compiled with support mouse.
mouseshape Compiled with support for 'mouseshape'.
multi_byte Compiled with support for 'encoding'
multi_byte_encoding 'encoding' is set to a multi-byte encoding.
-multi_byte_ime Compiled with support for IME input method.
multi_lang Compiled with support for multiple languages.
+num64 Compiled with 64-bit |Number| support.
nvim This is Nvim. |has-patch|
-ole Compiled with OLE automation support for Win32.
path_extra Compiled with up/downwards search in 'path' and 'tags'
persistent_undo Compiled with support for persistent undo history.
postscript Compiled with PostScript file printing.
printer Compiled with |:hardcopy| support.
profile Compiled with |:profile| support.
-python Compiled with Python 2.x interface. |has-python|
-python3 Compiled with Python 3.x interface. |has-python|
+python Legacy Vim Python 2.x API is available. |has-python|
+python3 Legacy Vim Python 3.x API is available. |has-python|
quickfix Compiled with |quickfix| support.
reltime Compiled with |reltime()| support.
rightleft Compiled with 'rightleft' support.
@@ -8152,14 +8193,10 @@ tag_old_static Compiled with support for old static tags
|tag-old-static|.
tag_any_white Compiled with support for any white characters in tags
files |tag-any-white|.
-terminfo Compiled with terminfo instead of termcap.
termresponse Compiled with support for |t_RV| and |v:termresponse|.
textobjects Compiled with support for |text-objects|.
-tgetent Compiled with tgetent support, able to use a termcap
- or terminfo file.
timers Compiled with |timer_start()| support.
title Compiled with window title support |'title'|.
-toolbar Compiled with support for |gui-toolbar|.
unix Unix version of Vim.
unnamedplus Compiled with support for "unnamedplus" in 'clipboard'
user_commands User-defined commands.
@@ -8174,17 +8211,9 @@ vreplace Compiled with |gR| and |gr| commands.
wildignore Compiled with 'wildignore' option.
wildmenu Compiled with 'wildmenu' option.
win32 Windows version of Vim (32 or 64 bit).
-win32unix Windows version of Vim, using Unix files (Cygwin).
-win64 Windows version of Vim (64 bit).
winaltkeys Compiled with 'winaltkeys' option.
windows Compiled with support for more than one window.
writebackup Compiled with 'writebackup' default on.
-xfontset Compiled with X fontset support |xfontset|.
-xim Compiled with X input method support |xim|.
-xpm Compiled with pixmap support.
-xpm_w32 Compiled with pixmap support for Win32. (Only for
- backward compatibility. Use "xpm" instead.)
-x11 Compiled with X11 support.
*string-match*
Matching a pattern in a String
diff --git a/runtime/doc/gui.txt b/runtime/doc/gui.txt
index 314799d083..0bd3a40a7c 100644
--- a/runtime/doc/gui.txt
+++ b/runtime/doc/gui.txt
@@ -854,30 +854,4 @@ This section describes other features which are related to the GUI.
- In the GUI, several normal keys may have modifiers in mappings etc, these
are <Space>, <Tab>, <NL>, <CR>, <Esc>.
-- To check in a Vim script if the GUI is being used, you can use something
- like this: >
-
- if has("gui_running")
- echo "yes, we have a GUI"
- else
- echo "Boring old console"
- endif
-< *setting-guifont*
-- When you use the same vimrc file on various systems, you can use something
- like this to set options specifically for each type of GUI: >
-
- if has("gui_running")
- if has("gui_gtk2")
- :set guifont=Luxi\ Mono\ 12
- elseif has("x11")
- " Also for GTK 1
- :set guifont=*-lucidatypewriter-medium-r-normal-*-*-180-*-*-m-*-*
- elseif has("gui_win32")
- :set guifont=Luxi_Mono:h12:cANSI
- endif
- endif
-
-A recommended Japanese font is MS Mincho. You can find info here:
-http://www.lexikan.com/mincho.htm
-
vim:tw=78:sw=4:ts=8:ft=help:norl:
diff --git a/runtime/doc/if_pyth.txt b/runtime/doc/if_pyth.txt
index 25da033190..8baa2d309b 100644
--- a/runtime/doc/if_pyth.txt
+++ b/runtime/doc/if_pyth.txt
@@ -679,7 +679,7 @@ vim.Function object *python-Function*
8. pyeval() and py3eval() Vim functions *python-pyeval*
To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
-functions to evaluate Python expressions and pass their values to VimL.
+functions to evaluate Python expressions and pass their values to Vim script.
==============================================================================
9. Python 3 *python3*
diff --git a/runtime/doc/intro.txt b/runtime/doc/intro.txt
index f9e97c4c38..c745d60ebc 100644
--- a/runtime/doc/intro.txt
+++ b/runtime/doc/intro.txt
@@ -489,7 +489,7 @@ examples and use them directly. Or type them literally, including the '<' and
==============================================================================
5. Modes, introduction *vim-modes-intro* *vim-modes*
-Vim has six BASIC modes:
+Vim has seven BASIC modes:
*Normal* *Normal-mode* *command-mode*
Normal mode In Normal mode you can enter all the normal editor
@@ -525,6 +525,13 @@ Ex mode Like Command-line mode, but after entering a command
you remain in Ex mode. Very limited editing of the
command line. |Ex-mode|
+ *Terminal-mode*
+Terminal mode In Terminal mode all input (except |c_CTRL-\_CTRL-N|)
+ is sent to the process running in the current
+ |terminal| buffer.
+ If the 'showmode' option is on "-- TERMINAL --" is shown
+ at the bottom of the window.
+
There are six ADDITIONAL modes. These are variants of the BASIC modes:
*Operator-pending* *Operator-pending-mode*
diff --git a/runtime/doc/job_control.txt b/runtime/doc/job_control.txt
index 5f9654d83c..da592d6eb0 100644
--- a/runtime/doc/job_control.txt
+++ b/runtime/doc/job_control.txt
@@ -75,6 +75,7 @@ Here's what is happening:
- The `JobHandler()` function is a callback passed to |jobstart()| to handle
various job events. It takes care of displaying stdout/stderr received from
the shells.
+ *on_stdout* *on_stderr* *on_exit*
- The arguments passed to `JobHandler()` are:
0: The job id
diff --git a/runtime/doc/nvim_terminal_emulator.txt b/runtime/doc/nvim_terminal_emulator.txt
index 129a2dfed3..801ff75647 100644
--- a/runtime/doc/nvim_terminal_emulator.txt
+++ b/runtime/doc/nvim_terminal_emulator.txt
@@ -4,7 +4,7 @@
NVIM REFERENCE MANUAL by Thiago de Arruda
-Terminal emulator *terminal-emulator*
+Terminal emulator *terminal* *terminal-emulator*
Nvim embeds a VT220/xterm terminal emulator based on libvterm. The terminal is
presented as a special buffer type, asynchronously updated from the virtual
@@ -43,7 +43,7 @@ restarting the {cmd} when the session is loaded.
==============================================================================
Input *terminal-emulator-input*
-To send input, enter terminal-mode using any command that would enter "insert
+To send input, enter |Terminal-mode| using any command that would enter "insert
mode" in a normal buffer, such as |i| or |:startinsert|. In this mode all keys
except <C-\><C-N> are sent to the underlying program. Use <C-\><C-N> to return
to normal-mode. |CTRL-\_CTRL-N|
@@ -89,6 +89,16 @@ Options: 'scrollback'
Events: |TermOpen|, |TermClose|
Highlight groups: |hl-TermCursor|, |hl-TermCursorNC|
+Terminal sets local defaults for some options, which may differ from your
+global configuration.
+
+- 'list' is disabled
+- 'wrap' is disabled
+- 'relativenumber' is disabled in |Terminal-mode| (and cannot be enabled)
+
+You can change the defaults with a TermOpen autocommand: >
+ au TermOpen * setlocal list
+
Terminal colors can be customized with these variables:
- `{g,b}:terminal_color_$NUM`: The terminal color palette, where `$NUM` is the
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt
index 8949d27dd6..bb5cfb4a80 100644
--- a/runtime/doc/options.txt
+++ b/runtime/doc/options.txt
@@ -4044,7 +4044,7 @@ A jump table for the options with a short description can be found at |Q_op|.
listing continues until finished.
*'mouse'* *E538*
-'mouse' string (default "a")
+'mouse' string (default "")
global
Enable the use of the mouse. Only works for certain terminals.
@@ -4368,7 +4368,8 @@ A jump table for the options with a short description can be found at |Q_op|.
Note that typing <F10> in paste mode inserts "<F10>", since in paste
mode everything is inserted literally, except the 'pastetoggle' key
sequence.
- When the value has several bytes 'ttimeoutlen' applies.
+ No timeout is used, this means that a multi-key 'pastetoggle' can not
+ be triggered manually.
*'pex'* *'patchexpr'*
'patchexpr' 'pex' string (default "")
@@ -6777,9 +6778,16 @@ A jump table for the options with a short description can be found at |Q_op|.
Window-local highlights. Comma-delimited list of |group-name| pairs
"{hl-builtin}:{hl-group},..." where each {hl-builtin} is a group (from
|highlight-groups|) to be overridden by {hl-group} in the window where
- this option was set.
- Currently |hl-Normal| and |hl-NormalNC| can be overridden.
- Useful for changing the background color. Example: >
+ this option was set. Only builting ui highlights are supported, not
+ syntax highlighting. For that purpose, use |:ownsyntax|.
+
+ Most highlights occuring within the frame of a window are supported.
+ Highlights of vertical separators are determined by the window to the
+ left of the separator. The highlight of a tabpage in |tabline| is
+ determined by the last focused window in the tabpage. Highlights of
+ the popupmenu are determined by the current window. Highlights in the
+ message area are not overridable. Example for overriding the
+ backgrond color: >
set winhighlight=Normal:MyNormal,NormalNC:MyNormalNC
<
*'winfixheight'* *'wfh'* *'nowinfixheight'* *'nowfh'*
diff --git a/runtime/doc/provider.txt b/runtime/doc/provider.txt
index 8d1dd0a6cd..435646bd1c 100644
--- a/runtime/doc/provider.txt
+++ b/runtime/doc/provider.txt
@@ -99,6 +99,19 @@ RUBY PROVIDER CONFIGURATION ~
*g:loaded_ruby_provider*
To disable Ruby support: >
let g:loaded_ruby_provider = 1
+<
+ *g:ruby_host_prog*
+Command to start the Ruby host. By default this is `neovim-ruby-host`. For users
+who use per-project Ruby versions with tools like RVM or rbenv, setting this can
+prevent the need to install the `neovim` gem in every project.
+
+To use an absolute path (e.g. to an rbenv installation): >
+ let g:ruby_host_prog = '~/.rbenv/versions/2.4.1/bin/neovim-ruby-host'
+<
+
+To use the RVM "system" Ruby installation: >
+ let g:ruby_host_prog = 'rvm system do neovim-ruby-host'
+<
==============================================================================
Clipboard integration *provider-clipboard* *clipboard*
diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt
index 477d927a12..8581bcfb72 100644
--- a/runtime/doc/starting.txt
+++ b/runtime/doc/starting.txt
@@ -1281,29 +1281,32 @@ exactly four MessagePack objects:
5 (Register) Map describing one register (|registers|). If key
value is equal to default then it is normally not
present. Keys:
- Key Type Def Description ~
- rt UInteger 0 Register type:
- No Description ~
- 0 |characterwise-register|
- 1 |linewise-register|
- 2 |blockwise-register|
- rw UInteger 0 Register width. Only valid
- for |blockwise-register|s.
- rc Array of binary N/A Register contents. Each
- entry in the array
- represents its own line.
- NUL characters inside the
- line should be represented
- as NL according to
- |NL-used-for-Nul|.
- n UInteger N/A Register name: character
- code in range [1, 255].
- Example: |quote0| register
- has name 48 (ASCII code for
- zero character).
- * any none Other keys are allowed
- for compatibility reasons,
- see |shada-compatibility|.
+ Key Type Def Description ~
+ rt UInteger 0 Register type:
+ No Description ~
+ 0 |characterwise-register|
+ 1 |linewise-register|
+ 2 |blockwise-register|
+ rw UInteger 0 Register width. Only valid
+ for |blockwise-register|s.
+ rc Array of binary N/A Register contents. Each
+ entry in the array
+ represents its own line.
+ NUL characters inside the
+ line should be represented
+ as NL according to
+ |NL-used-for-Nul|.
+ ru Boolean false Unnamed register. Whether
+ the unnamed register had
+ pointed to this register.
+ n UInteger N/A Register name: character
+ code in range [1, 255].
+ Example: |quote0| register
+ has name 48 (ASCII code for
+ zero character).
+ * any none Other keys are allowed
+ for compatibility reasons,
+ see |shada-compatibility|.
6 (Variable) Array containing two items: variable name (binary) and
variable value (any object). Values are converted
using the same code |msgpackparse()| uses when reading,
@@ -1363,39 +1366,38 @@ file when reading and include:
complete MessagePack object.
==============================================================================
-9. Base Directories *base-directories* *xdg*
+9. Standard Paths
-Nvim conforms to the XDG Base Directory Specification for application
-configuration and data file locations. This just means Nvim looks for some
-optional settings and uses them if they exist, otherwise defaults are chosen.
-https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
-
-CONFIGURATION DIRECTORY *$XDG_CONFIG_HOME*
-
- Base directory default:
- Unix: ~/.config
- Windows: ~/AppData/Local
-
- Nvim directory:
- Unix: ~/.config/nvim/
- Windows: ~/AppData/Local/nvim/
-
-DATA DIRECTORY *$XDG_DATA_HOME*
+Nvim stores configuration and data in standard locations. Plugins are strongly
+encouraged to follow this pattern also.
- Base directory default:
- Unix: ~/.local/share
- Windows: ~/AppData/Local
-
- Nvim directory:
- Unix: ~/.local/share/nvim/
- Windows: ~/AppData/Local/nvim-data/
-
-Note on Windows the configuration and data directory defaults are the same
-(for lack of an alternative), but the sub-directory for data is named
-"nvim-data" to separate it from the configuration sub-directory "nvim".
-
-Throughout other sections of the user manual, the defaults are used as generic
-placeholders, e.g. where "~/.config" is mentioned it should be understood to
-mean "$XDG_CONFIG_HOME or ~/.config".
+ *base-directories* *xdg*
+The "base" (root) directories conform to the XDG Base Directory Specification.
+https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+The $XDG_CONFIG_HOME and $XDG_DATA_HOME environment variables are used if they
+exist, otherwise default values (listed below) are used.
+
+Note: Throughout the user manual these defaults are used as placeholders, e.g.
+"~/.config" is understood to mean "$XDG_CONFIG_HOME or ~/.config".
+
+CONFIG DIRECTORY *$XDG_CONFIG_HOME*
+ Base Nvim ~
+Unix: ~/.config ~/.config/nvim
+Windows: ~/AppData/Local ~/AppData/Local/nvim
+
+DATA DIRECTORY *$XDG_DATA_HOME*
+ Base Nvim ~
+Unix: ~/.local/share ~/.local/share/nvim
+Windows: ~/AppData/Local ~/AppData/Local/nvim-data
+
+STANDARD PATHS *standard-path*
+
+ *$NVIM_LOG_FILE*
+Besides 'debug' and 'verbose', Nvim has a low-level "log of last resort" that
+is written directly to the filesystem. This log may also be used by plugins or
+RPC clients for debugging. $NVIM_LOG_FILE contains the log file path: >
+ :echo $NVIM_LOG_FILE
+Usually the file is ~/.local/share/nvim/log unless that path is inaccessible
+or if $NVIM_LOG_FILE was set before |startup|.
vim:tw=78:ts=8:ft=help:norl:
diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt
index d711aa6a29..07af856e6b 100644
--- a/runtime/doc/syntax.txt
+++ b/runtime/doc/syntax.txt
@@ -3285,8 +3285,8 @@ Some folding is now supported with syntax/vim.vim: >
g:vimsyn_folding =~ 'P' : fold python script
<
*g:vimsyn_noerror*
-Not all error highlighting that syntax/vim.vim does may be correct; VimL is a
-difficult language to highlight correctly. A way to suppress error
+Not all error highlighting that syntax/vim.vim does may be correct; Vim script
+is a difficult language to highlight correctly. A way to suppress error
highlighting is to put the following line in your |vimrc|: >
let g:vimsyn_noerror = 1
diff --git a/runtime/doc/usr_02.txt b/runtime/doc/usr_02.txt
index b32d84080c..b738cdc48b 100644
--- a/runtime/doc/usr_02.txt
+++ b/runtime/doc/usr_02.txt
@@ -578,7 +578,7 @@ Summary: *help-summary* >
register: >
:help quote:
-13) Vim Script (VimL) is available at >
+13) Vim Script is available at >
:help eval.txt
< Certain aspects of the language are available at :h expr-X where "X" is a
single letter. E.g. >
@@ -588,10 +588,10 @@ Summary: *help-summary* >
Also important is >
:help function-list
< to find a short description of all functions available. Help topics for
- VimL functions always include the "()", so: >
+ Vim script functions always include the "()", so: >
:help append()
-< talks about the append VimL function rather than how to append text in the
- current buffer.
+< talks about the append Vim script function rather than how to append text
+ in the current buffer.
14) Mappings are talked about in the help page :h |map.txt|. Use >
:help mapmode-i
diff --git a/runtime/doc/usr_05.txt b/runtime/doc/usr_05.txt
index 9e7f06ab63..cb7bf94ddc 100644
--- a/runtime/doc/usr_05.txt
+++ b/runtime/doc/usr_05.txt
@@ -140,15 +140,13 @@ quite complicated things. Still, it is just a sequence of commands that are
executed like you typed them.
>
- if &t_Co > 2 || has("gui_running")
- syntax on
- set hlsearch
- endif
-
-This switches on syntax highlighting, but only if colors are available. And
-the 'hlsearch' option tells Vim to highlight matches with the last used search
-pattern. The "if" command is very useful to set options only when some
-condition is met. More about that in |usr_41.txt|.
+ syntax on
+ set hlsearch
+
+This switches on syntax highlighting. And the 'hlsearch' option tells Vim to
+highlight matches with the last used search pattern. The "if" command is very
+useful to set options only when some condition is met. More about that in
+|usr_41.txt|.
*vimrc-filetype* >
filetype plugin indent on
diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt
index e8da7eeb89..8880b625e9 100644
--- a/runtime/doc/various.txt
+++ b/runtime/doc/various.txt
@@ -208,15 +208,20 @@ g8 Print the hex values of the bytes used in the
:sh[ell] Removed. |vim-differences| {Nvim}
*:terminal* *:te*
-:te[rminal][!] {cmd} Execute {cmd} with 'shell' in a |terminal-emulator|
- buffer. Equivalent to: >
+:te[rminal][!] [{cmd}] Execute {cmd} with 'shell' in a new |terminal| buffer.
+ Equivalent to: >
:enew
:call termopen('{cmd}')
:startinsert
<
- See |jobstart()|.
+ See |termopen()|.
- To enter terminal mode automatically: >
+ Without {cmd}, start an interactive shell.
+
+ Creating the terminal buffer fails when changes have been
+ made to the current buffer, unless 'hidden' is set.
+
+ To enter |Terminal-mode| automatically: >
autocmd BufEnter term://* startinsert
autocmd BufLeave term://* stopinsert
<
@@ -347,6 +352,7 @@ N *+mouseshape* |'mouseshape'|
N *+multi_byte* 16 and 32 bit characters |multibyte|
*+multi_byte_ime* Win32 input method for multibyte chars |multibyte-ime|
N *+multi_lang* non-English language support |multi-lang|
+ *+num64* 64-bit Number support |Number|
N *+path_extra* Up/downwards search in 'path' and 'tags'
N *+persistent_undo* Persistent undo |undo-persistence|
*+postscript* |:hardcopy| writes a PostScript file
diff --git a/scripts/genappimage.sh b/scripts/genappimage.sh
index fd7247b947..a73ccd86c7 100755
--- a/scripts/genappimage.sh
+++ b/scripts/genappimage.sh
@@ -18,23 +18,22 @@ ROOT_DIR="$(git rev-parse --show-toplevel)"
APP_BUILD_DIR="$ROOT_DIR/build"
APP_DIR="$APP.AppDir"
-# App version, used by generate_appimage.
-VERSION=$("$ROOT_DIR"/build/bin/nvim --version | head -n 1 | grep -o 'v.*')
-
########################################################################
# Compile nvim and install it into AppDir
########################################################################
# Build and install nvim into the AppImage
-make CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXTRA_FLAGS="-DCMAKE_INSTALL_PREFIX=${APP_DIR}/usr"
+make CMAKE_BUILD_TYPE=RelWithDebInfo CMAKE_EXTRA_FLAGS="-DCMAKE_INSTALL_PREFIX=${APP_DIR}/usr -DCMAKE_INSTALL_MANDIR=man"
make install
########################################################################
# Get helper functions and move to AppDir
########################################################################
+# App version, used by generate_appimage.
+VERSION=$("$ROOT_DIR"/build/bin/nvim --version | head -n 1 | grep -o 'v.*')
+
cd "$APP_BUILD_DIR"
-mkdir "$APP_DIR"
curl -Lo "$APP_BUILD_DIR"/appimage_functions.sh https://github.com/probonopd/AppImages/raw/master/functions.sh
. ./appimage_functions.sh
@@ -80,3 +79,5 @@ generate_appimage
mv "$ROOT_DIR"/out/*.AppImage "$ROOT_DIR"/build/bin
# Remove the (now empty) folder the AppImage was built in
rmdir "$ROOT_DIR"/out
+
+echo 'genappimage.sh: finished'
diff --git a/scripts/pvscheck.sh b/scripts/pvscheck.sh
index ca85b6be7f..dfdc539bf9 100755
--- a/scripts/pvscheck.sh
+++ b/scripts/pvscheck.sh
@@ -1,14 +1,20 @@
#!/bin/sh
+
+# Assume that "local" is available.
+# shellcheck disable=SC2039
+
set -e
# Note: -u causes problems with posh, it barks at “undefined” $@ when no
# arguments provided.
test -z "$POSH_VERSION" && set -u
get_jobs_num() {
- local num="$(cat /proc/cpuinfo | grep -c "^processor")"
- num="$(echo $(( num + 1 )))"
- num="${num:-1}"
- echo $num
+ if [ -n "${TRAVIS:-}" ] ; then
+ # HACK: /proc/cpuinfo on Travis CI is misleading, so hardcode 1.
+ echo 1
+ else
+ echo $(( $(grep -c "^processor" /proc/cpuinfo) + 1 ))
+ fi
}
help() {
@@ -21,7 +27,7 @@ help() {
echo ' --pvs: Use the specified URL as a path to pvs-studio archive.'
echo ' By default latest tested version is used.'
echo
- echo ' May use `--pvs detect` to try detecting latest version.'
+ echo ' May use "--pvs detect" to try detecting latest version.'
echo ' That assumes certain viva64.com site properties and'
echo ' may be broken by the site update.'
echo
@@ -261,15 +267,6 @@ install_pvs() {(
rmdir "$pvsdir"
)}
-adjust_path() {
- if test -d "$tgt/pvs-studio" ; then
- local saved_pwd="$PWD"
- cd "$tgt/pvs-studio"
- export PATH="$PWD/bin${PATH+:}${PATH}"
- cd "$saved_pwd"
- fi
-}
-
create_compile_commands() {(
local tgt="$1" ; shift
local deps="$1" ; shift
@@ -369,7 +366,7 @@ do_check() {
do_recheck() {
local tgt="$1" ; shift
- local deps="$2" ; shift
+ local deps="$1" ; shift
create_compile_commands "$tgt" "$deps"
@@ -379,7 +376,12 @@ do_recheck() {
do_analysis() {
local tgt="$1" ; shift
- adjust_path "$tgt"
+ if test -d "$tgt/pvs-studio" ; then
+ local saved_pwd="$PWD"
+ cd "$tgt/pvs-studio"
+ export PATH="$PWD/bin${PATH+:}${PATH}"
+ cd "$saved_pwd"
+ fi
run_analysis "$tgt"
}
diff --git a/scripts/vim-patch.sh b/scripts/vim-patch.sh
index 3b083e7b83..63665b9253 100755
--- a/scripts/vim-patch.sh
+++ b/scripts/vim-patch.sh
@@ -280,7 +280,7 @@ submit_pr() {
echo "Pushing to 'origin/${checked_out_branch}'."
output="$(git push origin "${checked_out_branch}" 2>&1)" &&
echo "✔ ${output}" ||
- (echo "✘ ${output}"; git reset --soft HEAD^1; false)
+ (echo "✘ ${output}"; false)
echo
fi
diff --git a/src/clint.py b/src/clint.py
index 3babb7772b..69a061d2ab 100755
--- a/src/clint.py
+++ b/src/clint.py
@@ -2529,6 +2529,8 @@ def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
r'(?<!\bklist_t)'
r'(?<!\bkliter_t)'
r'(?<!\bkhash_t)'
+ r'(?<!\bkbtree_t)'
+ r'(?<!\bkbitr_t)'
r'\((?:const )?(?:struct )?[a-zA-Z_]\w*(?: *\*(?:const)?)*\)'
r' +'
r'-?(?:\*+|&)?(?:\w+|\+\+|--|\()', cast_line)
@@ -2600,16 +2602,23 @@ def CheckBraces(filename, clean_lines, linenum, error):
else:
func_start_linenum = end_linenum + 1
while not clean_lines.lines[func_start_linenum] == '{':
- if not Match(r'^(?:\s*\b(?:FUNC_ATTR|REAL_FATTR)_\w+\b(?:\(\d+(, \d+)*\))?)+$',
- clean_lines.lines[func_start_linenum]):
+ attrline = Match(r'^((?!# *define).*?)(?:FUNC_ATTR|FUNC_API|REAL_FATTR)_\w+(?:\(\d+(, \d+)*\))?',
+ clean_lines.lines[func_start_linenum])
+ if attrline:
+ if len(attrline.group(1)) != 2:
+ error(filename, func_start_linenum,
+ 'whitespace/indent', 5,
+ 'Function attribute line should have 2-space '
+ 'indent')
+
+ func_start_linenum += 1
+ else:
if clean_lines.lines[func_start_linenum].endswith('{'):
error(filename, func_start_linenum,
'readability/braces', 5,
'Brace starting function body must be placed '
'after the function signature')
break
- else:
- func_start_linenum += 1
# An else clause should be on the same line as the preceding closing brace.
# If there is no preceding closing brace, there should be one.
diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c
index 0b8d39d0d2..82de8fd4a2 100644
--- a/src/nvim/api/buffer.c
+++ b/src/nvim/api/buffer.c
@@ -35,7 +35,7 @@
/// @param[out] err Error details, if any
/// @return Line count
Integer nvim_buf_line_count(Buffer buffer, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -157,7 +157,7 @@ ArrayOf(String) nvim_buf_get_lines(uint64_t channel_id,
Integer end,
Boolean strict_indexing,
Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -270,7 +270,7 @@ void nvim_buf_set_lines(uint64_t channel_id,
Boolean strict_indexing,
ArrayOf(String) replacement, // NOLINT
Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -330,7 +330,7 @@ void nvim_buf_set_lines(uint64_t channel_id,
}
try_start();
- bufref_T save_curbuf = { NULL, 0 };
+ bufref_T save_curbuf = { NULL, 0, 0 };
switch_to_win_for_buf(buf, &save_curwin, &save_curtab, &save_curbuf);
if (u_save((linenr_T)(start - 1), (linenr_T)end) == FAIL) {
@@ -399,7 +399,7 @@ void nvim_buf_set_lines(uint64_t channel_id,
// Only adjust marks if we managed to switch to a window that holds
// the buffer, otherwise line numbers will be invalid.
if (save_curbuf.br_buf == NULL) {
- mark_adjust((linenr_T)start, (linenr_T)(end - 1), MAXLNUM, extra);
+ mark_adjust((linenr_T)start, (linenr_T)(end - 1), MAXLNUM, extra, false);
}
changed_lines((linenr_T)start, 0, (linenr_T)end, (long)extra);
@@ -425,7 +425,7 @@ end:
/// @param[out] err Error details, if any
/// @return Variable value
Object nvim_buf_get_var(Buffer buffer, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -442,7 +442,7 @@ Object nvim_buf_get_var(Buffer buffer, String name, Error *err)
///
/// @return `b:changedtick` value.
Integer nvim_buf_get_changedtick(Buffer buffer, Error *err)
- FUNC_API_SINCE(2)
+ FUNC_API_SINCE(2)
{
const buf_T *const buf = find_buffer_by_handle(buffer, err);
@@ -453,6 +453,26 @@ Integer nvim_buf_get_changedtick(Buffer buffer, Error *err)
return buf->b_changedtick;
}
+/// Get a list of dictionaries describing buffer-local mappings
+/// Note that the buffer key in the dictionary will represent the buffer
+/// handle where the mapping is present
+///
+/// @param mode The abbreviation for the mode
+/// @param buffer_id Buffer handle
+/// @param[out] err Error details, if any
+/// @returns An array of maparg() like dictionaries describing mappings
+ArrayOf(Dictionary) nvim_buf_get_keymap(Buffer buffer, String mode, Error *err)
+ FUNC_API_SINCE(3)
+{
+ buf_T *buf = find_buffer_by_handle(buffer, err);
+
+ if (!buf) {
+ return (Array)ARRAY_DICT_INIT;
+ }
+
+ return keymap_array(mode, buf);
+}
+
/// Sets a buffer-scoped (b:) variable
///
/// @param buffer Buffer handle
@@ -460,7 +480,7 @@ Integer nvim_buf_get_changedtick(Buffer buffer, Error *err)
/// @param value Variable value
/// @param[out] err Error details, if any
void nvim_buf_set_var(Buffer buffer, String name, Object value, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -477,7 +497,7 @@ void nvim_buf_set_var(Buffer buffer, String name, Object value, Error *err)
/// @param name Variable name
/// @param[out] err Error details, if any
void nvim_buf_del_var(Buffer buffer, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -538,7 +558,7 @@ Object buffer_del_var(Buffer buffer, String name, Error *err)
/// @param[out] err Error details, if any
/// @return Option value
Object nvim_buf_get_option(Buffer buffer, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -557,7 +577,7 @@ Object nvim_buf_get_option(Buffer buffer, String name, Error *err)
/// @param value Option value
/// @param[out] err Error details, if any
void nvim_buf_set_option(Buffer buffer, String name, Object value, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -577,8 +597,8 @@ void nvim_buf_set_option(Buffer buffer, String name, Object value, Error *err)
/// @param[out] err Error details, if any
/// @return Buffer number
Integer nvim_buf_get_number(Buffer buffer, Error *err)
- FUNC_API_SINCE(1)
- FUNC_API_DEPRECATED_SINCE(2)
+ FUNC_API_SINCE(1)
+ FUNC_API_DEPRECATED_SINCE(2)
{
Integer rv = 0;
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -596,7 +616,7 @@ Integer nvim_buf_get_number(Buffer buffer, Error *err)
/// @param[out] err Error details, if any
/// @return Buffer name
String nvim_buf_get_name(Buffer buffer, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
String rv = STRING_INIT;
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -614,7 +634,7 @@ String nvim_buf_get_name(Buffer buffer, Error *err)
/// @param name Buffer name
/// @param[out] err Error details, if any
void nvim_buf_set_name(Buffer buffer, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -644,7 +664,7 @@ void nvim_buf_set_name(Buffer buffer, String name, Error *err)
/// @param buffer Buffer handle
/// @return true if the buffer is valid, false otherwise
Boolean nvim_buf_is_valid(Buffer buffer)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Error stub = ERROR_INIT;
Boolean ret = find_buffer_by_handle(buffer, &stub) != NULL;
@@ -678,7 +698,7 @@ void buffer_insert(Buffer buffer,
/// @param[out] err Error details, if any
/// @return (row, col) tuple
ArrayOf(Integer, 2) nvim_buf_get_mark(Buffer buffer, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -754,7 +774,7 @@ Integer nvim_buf_add_highlight(Buffer buffer,
Integer col_start,
Integer col_end,
Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
if (!buf) {
@@ -795,7 +815,7 @@ void nvim_buf_clear_highlight(Buffer buffer,
Integer line_start,
Integer line_end,
Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
if (!buf) {
diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c
index 1d7b305da3..d401ae52a0 100644
--- a/src/nvim/api/private/helpers.c
+++ b/src/nvim/api/private/helpers.c
@@ -24,6 +24,7 @@
#include "nvim/option_defs.h"
#include "nvim/version.h"
#include "nvim/lib/kvec.h"
+#include "nvim/getchar.h"
/// Helper structure for vim_to_object
typedef struct {
@@ -960,7 +961,7 @@ static void set_option_value_for(char *key,
{
win_T *save_curwin = NULL;
tabpage_T *save_curtab = NULL;
- bufref_T save_curbuf = { NULL, 0 };
+ bufref_T save_curbuf = { NULL, 0, 0 };
try_start();
switch (opt_type)
@@ -1034,3 +1035,41 @@ void api_set_error(Error *err, ErrorType errType, const char *format, ...)
err->type = errType;
}
+
+/// Get an array containing dictionaries describing mappings
+/// based on mode and buffer id
+///
+/// @param mode The abbreviation for the mode
+/// @param buf The buffer to get the mapping array. NULL for global
+/// @returns An array of maparg() like dictionaries describing mappings
+ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf)
+{
+ Array mappings = ARRAY_DICT_INIT;
+ dict_T *const dict = tv_dict_alloc();
+
+ // Convert the string mode to the integer mode
+ // that is stored within each mapblock
+ char_u *p = (char_u *)mode.data;
+ int int_mode = get_map_mode(&p, 0);
+
+ // Determine the desired buffer value
+ long buffer_value = (buf == NULL) ? 0 : buf->handle;
+
+ for (int i = 0; i < MAX_MAPHASH; i++) {
+ for (const mapblock_T *current_maphash = get_maphash(i, buf);
+ current_maphash;
+ current_maphash = current_maphash->m_next) {
+ // Check for correct mode
+ if (int_mode & current_maphash->m_mode) {
+ mapblock_fill_dict(dict, current_maphash, buffer_value, false);
+ ADD(mappings, vim_to_object(
+ (typval_T[]) { { .v_type = VAR_DICT, .vval.v_dict = dict } }));
+
+ tv_dict_clear(dict);
+ }
+ }
+ }
+ tv_dict_free(dict);
+
+ return mappings;
+}
diff --git a/src/nvim/api/tabpage.c b/src/nvim/api/tabpage.c
index 6f2f9e1d2a..b6830d9fcf 100644
--- a/src/nvim/api/tabpage.c
+++ b/src/nvim/api/tabpage.c
@@ -18,7 +18,7 @@
/// @param[out] err Error details, if any
/// @return List of windows in `tabpage`
ArrayOf(Window) nvim_tabpage_list_wins(Tabpage tabpage, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
tabpage_T *tab = find_tab_by_handle(tabpage, err);
@@ -48,7 +48,7 @@ ArrayOf(Window) nvim_tabpage_list_wins(Tabpage tabpage, Error *err)
/// @param[out] err Error details, if any
/// @return Variable value
Object nvim_tabpage_get_var(Tabpage tabpage, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
tabpage_T *tab = find_tab_by_handle(tabpage, err);
@@ -69,7 +69,7 @@ void nvim_tabpage_set_var(Tabpage tabpage,
String name,
Object value,
Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
tabpage_T *tab = find_tab_by_handle(tabpage, err);
@@ -86,7 +86,7 @@ void nvim_tabpage_set_var(Tabpage tabpage,
/// @param name Variable name
/// @param[out] err Error details, if any
void nvim_tabpage_del_var(Tabpage tabpage, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
tabpage_T *tab = find_tab_by_handle(tabpage, err);
@@ -145,7 +145,7 @@ Object tabpage_del_var(Tabpage tabpage, String name, Error *err)
/// @param[out] err Error details, if any
/// @return Window handle
Window nvim_tabpage_get_win(Tabpage tabpage, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Window rv = 0;
tabpage_T *tab = find_tab_by_handle(tabpage, err);
@@ -173,7 +173,7 @@ Window nvim_tabpage_get_win(Tabpage tabpage, Error *err)
/// @param[out] err Error details, if any
/// @return Tabpage number
Integer nvim_tabpage_get_number(Tabpage tabpage, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Integer rv = 0;
tabpage_T *tab = find_tab_by_handle(tabpage, err);
@@ -190,7 +190,7 @@ Integer nvim_tabpage_get_number(Tabpage tabpage, Error *err)
/// @param tabpage Tabpage handle
/// @return true if the tabpage is valid, false otherwise
Boolean nvim_tabpage_is_valid(Tabpage tabpage)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Error stub = ERROR_INIT;
Boolean ret = find_tab_by_handle(tabpage, &stub) != NULL;
diff --git a/src/nvim/api/ui.c b/src/nvim/api/ui.c
index 1b29f2fc78..573be23d8e 100644
--- a/src/nvim/api/ui.c
+++ b/src/nvim/api/ui.c
@@ -30,13 +30,13 @@ typedef struct {
static PMap(uint64_t) *connected_uis = NULL;
void remote_ui_init(void)
- FUNC_API_NOEXPORT
+ FUNC_API_NOEXPORT
{
connected_uis = pmap_new(uint64_t)();
}
void remote_ui_disconnect(uint64_t channel_id)
- FUNC_API_NOEXPORT
+ FUNC_API_NOEXPORT
{
UI *ui = pmap_get(uint64_t)(connected_uis, channel_id);
if (!ui) {
@@ -53,7 +53,7 @@ void remote_ui_disconnect(uint64_t channel_id)
void nvim_ui_attach(uint64_t channel_id, Integer width, Integer height,
Dictionary options, Error *err)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
if (pmap_has(uint64_t)(connected_uis, channel_id)) {
api_set_error(err, kErrorTypeException, "UI already attached for channel");
@@ -125,7 +125,7 @@ void ui_attach(uint64_t channel_id, Integer width, Integer height,
}
void nvim_ui_detach(uint64_t channel_id, Error *err)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
if (!pmap_has(uint64_t)(connected_uis, channel_id)) {
api_set_error(err, kErrorTypeException, "UI is not attached for channel");
@@ -137,7 +137,7 @@ void nvim_ui_detach(uint64_t channel_id, Error *err)
void nvim_ui_try_resize(uint64_t channel_id, Integer width,
Integer height, Error *err)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
if (!pmap_has(uint64_t)(connected_uis, channel_id)) {
api_set_error(err, kErrorTypeException, "UI is not attached for channel");
@@ -158,7 +158,7 @@ void nvim_ui_try_resize(uint64_t channel_id, Integer width,
void nvim_ui_set_option(uint64_t channel_id, String name,
Object value, Error *error)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
if (!pmap_has(uint64_t)(connected_uis, channel_id)) {
api_set_error(error, kErrorTypeException, "UI is not attached for channel");
diff --git a/src/nvim/api/ui_events.in.h b/src/nvim/api/ui_events.in.h
index 45d04335e4..1b5d17584f 100644
--- a/src/nvim/api/ui_events.in.h
+++ b/src/nvim/api/ui_events.in.h
@@ -11,61 +11,61 @@
#include "nvim/ui.h"
void resize(Integer rows, Integer columns)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void clear(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void eol_clear(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void cursor_goto(Integer row, Integer col)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void mode_info_set(Boolean enabled, Array cursor_styles)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void update_menu(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void busy_start(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void busy_stop(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void mouse_on(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void mouse_off(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void mode_change(String mode, Integer mode_idx)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void set_scroll_region(Integer top, Integer bot, Integer left, Integer right)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void scroll(Integer count)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void highlight_set(HlAttrs attrs)
- FUNC_API_SINCE(3) FUNC_API_REMOTE_IMPL FUNC_API_BRIDGE_IMPL;
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_IMPL FUNC_API_BRIDGE_IMPL;
void put(String str)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void bell(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void visual_bell(void)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void flush(void)
- FUNC_API_SINCE(3) FUNC_API_REMOTE_IMPL;
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_IMPL;
void update_fg(Integer fg)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void update_bg(Integer bg)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void update_sp(Integer sp)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void suspend(void)
- FUNC_API_SINCE(3) FUNC_API_BRIDGE_IMPL;
+ FUNC_API_SINCE(3) FUNC_API_BRIDGE_IMPL;
void set_title(String title)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void set_icon(String icon)
- FUNC_API_SINCE(3);
+ FUNC_API_SINCE(3);
void popupmenu_show(Array items, Integer selected, Integer row, Integer col)
- FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
void popupmenu_hide(void)
- FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
void popupmenu_select(Integer selected)
- FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
void tabline_update(Tabpage current, Array tabs)
- FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY;
#endif // NVIM_API_UI_EVENTS_IN_H
diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c
index de1d099c11..80efe86ea3 100644
--- a/src/nvim/api/vim.c
+++ b/src/nvim/api/vim.c
@@ -13,6 +13,7 @@
#include "nvim/ascii.h"
#include "nvim/api/private/helpers.h"
#include "nvim/api/private/defs.h"
+#include "nvim/api/private/dispatch.h"
#include "nvim/api/buffer.h"
#include "nvim/msgpack_rpc/channel.h"
#include "nvim/lua/executor.h"
@@ -45,7 +46,7 @@
/// @param command Ex-command string
/// @param[out] err Error details (including actual VimL error), if any
void nvim_command(String command, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
// Run the command
try_start();
@@ -63,7 +64,7 @@ void nvim_command(String command, Error *err)
/// @see feedkeys()
/// @see vim_strsave_escape_csi
void nvim_feedkeys(String keys, String mode, Boolean escape_csi)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
bool remap = true;
bool insert = false;
@@ -130,7 +131,7 @@ void nvim_feedkeys(String keys, String mode, Boolean escape_csi)
/// @return Number of bytes actually written (can be fewer than
/// requested if the buffer becomes full).
Integer nvim_input(String keys)
- FUNC_API_SINCE(1) FUNC_API_ASYNC
+ FUNC_API_SINCE(1) FUNC_API_ASYNC
{
return (Integer)input_enqueue(keys);
}
@@ -142,7 +143,7 @@ Integer nvim_input(String keys)
/// @see cpoptions
String nvim_replace_termcodes(String str, Boolean from_part, Boolean do_lt,
Boolean special)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
if (str.size == 0) {
// Empty string
@@ -162,7 +163,7 @@ String nvim_replace_termcodes(String str, Boolean from_part, Boolean do_lt,
}
String nvim_command_output(String str, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
do_cmdline_cmd("redir => v:command_output");
nvim_command(str, err);
@@ -183,7 +184,7 @@ String nvim_command_output(String str, Error *err)
/// @param[out] err Error details, if any
/// @return Evaluation result or expanded object
Object nvim_eval(String expr, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Object rv = OBJECT_INIT;
// Evaluate the expression
@@ -214,7 +215,7 @@ Object nvim_eval(String expr, Error *err)
/// @param[out] err Error details, if any
/// @return Result of the function call
Object nvim_call_function(String fname, Array args, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Object rv = OBJECT_INIT;
if (args.size > MAX_FUNC_ARGS) {
@@ -282,7 +283,7 @@ Object nvim_execute_lua(String code, Array args, Error *err)
/// @param[out] err Error details, if any
/// @return Number of cells
Integer nvim_strwidth(String str, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
if (str.size > INT_MAX) {
api_set_error(err, kErrorTypeValidation, "String length is too high");
@@ -296,7 +297,7 @@ Integer nvim_strwidth(String str, Error *err)
///
/// @return List of paths
ArrayOf(String) nvim_list_runtime_paths(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
char_u *rtp = p_rtp;
@@ -339,7 +340,7 @@ ArrayOf(String) nvim_list_runtime_paths(void)
/// @param dir Directory path
/// @param[out] err Error details, if any
void nvim_set_current_dir(String dir, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
if (dir.size >= MAXPATHL) {
api_set_error(err, kErrorTypeValidation, "Directory string is too long");
@@ -368,7 +369,7 @@ void nvim_set_current_dir(String dir, Error *err)
/// @param[out] err Error details, if any
/// @return Current line string
String nvim_get_current_line(Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return buffer_get_line(curbuf->handle, curwin->w_cursor.lnum - 1, err);
}
@@ -378,7 +379,7 @@ String nvim_get_current_line(Error *err)
/// @param line Line contents
/// @param[out] err Error details, if any
void nvim_set_current_line(String line, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buffer_set_line(curbuf->handle, curwin->w_cursor.lnum - 1, line, err);
}
@@ -387,7 +388,7 @@ void nvim_set_current_line(String line, Error *err)
///
/// @param[out] err Error details, if any
void nvim_del_current_line(Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buffer_del_line(curbuf->handle, curwin->w_cursor.lnum - 1, err);
}
@@ -398,7 +399,7 @@ void nvim_del_current_line(Error *err)
/// @param[out] err Error details, if any
/// @return Variable value
Object nvim_get_var(String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return dict_get_value(&globvardict, name, err);
}
@@ -409,7 +410,7 @@ Object nvim_get_var(String name, Error *err)
/// @param value Variable value
/// @param[out] err Error details, if any
void nvim_set_var(String name, Object value, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
dict_set_var(&globvardict, name, value, false, false, err);
}
@@ -419,7 +420,7 @@ void nvim_set_var(String name, Object value, Error *err)
/// @param name Variable name
/// @param[out] err Error details, if any
void nvim_del_var(String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
dict_set_var(&globvardict, name, NIL, true, false, err);
}
@@ -458,7 +459,7 @@ Object vim_del_var(String name, Error *err)
/// @param[out] err Error details, if any
/// @return Variable value
Object nvim_get_vvar(String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return dict_get_value(&vimvardict, name, err);
}
@@ -469,7 +470,7 @@ Object nvim_get_vvar(String name, Error *err)
/// @param[out] err Error details, if any
/// @return Option value (global)
Object nvim_get_option(String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return get_option_from(NULL, SREQ_GLOBAL, name, err);
}
@@ -480,7 +481,7 @@ Object nvim_get_option(String name, Error *err)
/// @param value New option value
/// @param[out] err Error details, if any
void nvim_set_option(String name, Object value, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
set_option_to(NULL, SREQ_GLOBAL, name, value, err);
}
@@ -489,7 +490,7 @@ void nvim_set_option(String name, Object value, Error *err)
///
/// @param str Message
void nvim_out_write(String str)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
write_msg(str, false);
}
@@ -498,7 +499,7 @@ void nvim_out_write(String str)
///
/// @param str Message
void nvim_err_write(String str)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
write_msg(str, true);
}
@@ -509,7 +510,7 @@ void nvim_err_write(String str)
/// @param str Message
/// @see nvim_err_write()
void nvim_err_writeln(String str)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
nvim_err_write(str);
nvim_err_write((String) { .data = "\n", .size = 1 });
@@ -519,7 +520,7 @@ void nvim_err_writeln(String str)
///
/// @return List of buffer handles
ArrayOf(Buffer) nvim_list_bufs(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
@@ -541,7 +542,7 @@ ArrayOf(Buffer) nvim_list_bufs(void)
///
/// @return Buffer handle
Buffer nvim_get_current_buf(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return curbuf->handle;
}
@@ -551,7 +552,7 @@ Buffer nvim_get_current_buf(void)
/// @param id Buffer handle
/// @param[out] err Error details, if any
void nvim_set_current_buf(Buffer buffer, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -573,7 +574,7 @@ void nvim_set_current_buf(Buffer buffer, Error *err)
///
/// @return List of window handles
ArrayOf(Window) nvim_list_wins(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
@@ -595,7 +596,7 @@ ArrayOf(Window) nvim_list_wins(void)
///
/// @return Window handle
Window nvim_get_current_win(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return curwin->handle;
}
@@ -604,7 +605,7 @@ Window nvim_get_current_win(void)
///
/// @param handle Window handle
void nvim_set_current_win(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -626,7 +627,7 @@ void nvim_set_current_win(Window window, Error *err)
///
/// @return List of tabpage handles
ArrayOf(Tabpage) nvim_list_tabpages(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
@@ -648,7 +649,7 @@ ArrayOf(Tabpage) nvim_list_tabpages(void)
///
/// @return Tabpage handle
Tabpage nvim_get_current_tabpage(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return curtab->handle;
}
@@ -658,7 +659,7 @@ Tabpage nvim_get_current_tabpage(void)
/// @param handle Tabpage handle
/// @param[out] err Error details, if any
void nvim_set_current_tabpage(Tabpage tabpage, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
tabpage_T *tp = find_tab_by_handle(tabpage, err);
@@ -681,7 +682,7 @@ void nvim_set_current_tabpage(Tabpage tabpage, Error *err)
/// @param channel_id Channel id (passed automatically by the dispatcher)
/// @param event Event type string
void nvim_subscribe(uint64_t channel_id, String event)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
size_t length = (event.size < METHOD_MAXLEN ? event.size : METHOD_MAXLEN);
char e[METHOD_MAXLEN + 1];
@@ -695,7 +696,7 @@ void nvim_subscribe(uint64_t channel_id, String event)
/// @param channel_id Channel id (passed automatically by the dispatcher)
/// @param event Event type string
void nvim_unsubscribe(uint64_t channel_id, String event)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
size_t length = (event.size < METHOD_MAXLEN ?
event.size :
@@ -707,13 +708,13 @@ void nvim_unsubscribe(uint64_t channel_id, String event)
}
Integer nvim_get_color_by_name(String name)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
return name_to_color((char_u *)name.data);
}
Dictionary nvim_get_color_map(void)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Dictionary colors = ARRAY_DICT_INIT;
@@ -743,8 +744,19 @@ Dictionary nvim_get_mode(void)
return rv;
}
+/// Get a list of dictionaries describing global (i.e. non-buffer) mappings
+/// Note that the "buffer" key will be 0 to represent false.
+///
+/// @param mode The abbreviation for the mode
+/// @returns An array of maparg() like dictionaries describing mappings
+ArrayOf(Dictionary) nvim_get_keymap(String mode)
+ FUNC_API_SINCE(3)
+{
+ return keymap_array(mode, NULL);
+}
+
Array nvim_get_api_info(uint64_t channel_id)
- FUNC_API_SINCE(1) FUNC_API_ASYNC FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_ASYNC FUNC_API_REMOTE_ONLY
{
Array rv = ARRAY_DICT_INIT;
@@ -777,7 +789,7 @@ Array nvim_get_api_info(uint64_t channel_id)
/// which resulted in an error, the error type and the error message. If an
/// error ocurred, the values from all preceding calls will still be returned.
Array nvim_call_atomic(uint64_t channel_id, Array calls, Error *err)
- FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
+ FUNC_API_SINCE(1) FUNC_API_REMOTE_ONLY
{
Array rv = ARRAY_DICT_INIT;
Array results = ARRAY_DICT_INIT;
diff --git a/src/nvim/api/window.c b/src/nvim/api/window.c
index 22902800ea..9bc91ef8fb 100644
--- a/src/nvim/api/window.c
+++ b/src/nvim/api/window.c
@@ -22,7 +22,7 @@
/// @param[out] err Error details, if any
/// @return Buffer handle
Buffer nvim_win_get_buf(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -39,7 +39,7 @@ Buffer nvim_win_get_buf(Window window, Error *err)
/// @param[out] err Error details, if any
/// @return (row, col) tuple
ArrayOf(Integer, 2) nvim_win_get_cursor(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
win_T *win = find_window_by_handle(window, err);
@@ -58,7 +58,7 @@ ArrayOf(Integer, 2) nvim_win_get_cursor(Window window, Error *err)
/// @param pos (row, col) tuple representing the new position
/// @param[out] err Error details, if any
void nvim_win_set_cursor(Window window, ArrayOf(Integer, 2) pos, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -105,7 +105,7 @@ void nvim_win_set_cursor(Window window, ArrayOf(Integer, 2) pos, Error *err)
/// @param[out] err Error details, if any
/// @return Height as a count of rows
Integer nvim_win_get_height(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -123,7 +123,7 @@ Integer nvim_win_get_height(Window window, Error *err)
/// @param height Height as a count of rows
/// @param[out] err Error details, if any
void nvim_win_set_height(Window window, Integer height, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -150,7 +150,7 @@ void nvim_win_set_height(Window window, Integer height, Error *err)
/// @param[out] err Error details, if any
/// @return Width as a count of columns
Integer nvim_win_get_width(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -168,7 +168,7 @@ Integer nvim_win_get_width(Window window, Error *err)
/// @param width Width as a count of columns
/// @param[out] err Error details, if any
void nvim_win_set_width(Window window, Integer width, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -196,7 +196,7 @@ void nvim_win_set_width(Window window, Integer width, Error *err)
/// @param[out] err Error details, if any
/// @return Variable value
Object nvim_win_get_var(Window window, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -214,7 +214,7 @@ Object nvim_win_get_var(Window window, String name, Error *err)
/// @param value Variable value
/// @param[out] err Error details, if any
void nvim_win_set_var(Window window, String name, Object value, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -231,7 +231,7 @@ void nvim_win_set_var(Window window, String name, Object value, Error *err)
/// @param name Variable name
/// @param[out] err Error details, if any
void nvim_win_del_var(Window window, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -291,7 +291,7 @@ Object window_del_var(Window window, String name, Error *err)
/// @param[out] err Error details, if any
/// @return Option value
Object nvim_win_get_option(Window window, String name, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -310,7 +310,7 @@ Object nvim_win_get_option(Window window, String name, Error *err)
/// @param value Option value
/// @param[out] err Error details, if any
void nvim_win_set_option(Window window, String name, Object value, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
win_T *win = find_window_by_handle(window, err);
@@ -327,7 +327,7 @@ void nvim_win_set_option(Window window, String name, Object value, Error *err)
/// @param[out] err Error details, if any
/// @return (row, col) tuple with the window position
ArrayOf(Integer, 2) nvim_win_get_position(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Array rv = ARRAY_DICT_INIT;
win_T *win = find_window_by_handle(window, err);
@@ -346,7 +346,7 @@ ArrayOf(Integer, 2) nvim_win_get_position(Window window, Error *err)
/// @param[out] err Error details, if any
/// @return Tabpage that contains the window
Tabpage nvim_win_get_tabpage(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Tabpage rv = 0;
win_T *win = find_window_by_handle(window, err);
@@ -364,7 +364,7 @@ Tabpage nvim_win_get_tabpage(Window window, Error *err)
/// @param[out] err Error details, if any
/// @return Window number
Integer nvim_win_get_number(Window window, Error *err)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
int rv = 0;
win_T *win = find_window_by_handle(window, err);
@@ -384,7 +384,7 @@ Integer nvim_win_get_number(Window window, Error *err)
/// @param window Window handle
/// @return true if the window is valid, false otherwise
Boolean nvim_win_is_valid(Window window)
- FUNC_API_SINCE(1)
+ FUNC_API_SINCE(1)
{
Error stub = ERROR_INIT;
Boolean ret = find_window_by_handle(window, &stub) != NULL;
diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c
index 6abd505ead..b5ca6543c5 100644
--- a/src/nvim/buffer.c
+++ b/src/nvim/buffer.c
@@ -74,6 +74,12 @@
#include "nvim/os/time.h"
#include "nvim/os/input.h"
+typedef enum {
+ kBLSUnchanged = 0,
+ kBLSChanged = 1,
+ kBLSDeleted = 2,
+} BufhlLineStatus;
+
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "buffer.c.generated.h"
#endif
@@ -281,19 +287,22 @@ open_buffer (
void set_bufref(bufref_T *bufref, buf_T *buf)
{
bufref->br_buf = buf;
+ bufref->br_fnum = buf->b_fnum;
bufref->br_buf_free_count = buf_free_count;
}
-/// Check if "bufref" points to a valid buffer.
-///
+/// Return true if "bufref->br_buf" points to the same buffer as when
+/// set_bufref() was called and it is a valid buffer.
/// Only goes through the buffer list if buf_free_count changed.
+/// Also checks if b_fnum is still the same, a :bwipe followed by :new might get
+/// the same allocated memory, but it's a different buffer.
///
/// @param bufref Buffer reference to check for.
bool bufref_valid(bufref_T *bufref)
{
return bufref->br_buf_free_count == buf_free_count
? true
- : buf_valid(bufref->br_buf);
+ : buf_valid(bufref->br_buf) && bufref->br_fnum == bufref->br_buf->b_fnum;
}
/// Check that "buf" points to a valid buffer in the buffer list.
@@ -1753,16 +1762,15 @@ void free_buf_options(buf_T *buf, int free_p_ff)
clear_string_option(&buf->b_p_bkc);
}
-/*
- * get alternate file n
- * set linenr to lnum or altfpos.lnum if lnum == 0
- * also set cursor column to altfpos.col if 'startofline' is not set.
- * if (options & GETF_SETMARK) call setpcmark()
- * if (options & GETF_ALT) we are jumping to an alternate file.
- * if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping
- *
- * return FAIL for failure, OK for success
- */
+
+/// Get alternate file "n".
+/// Set linenr to "lnum" or altfpos.lnum if "lnum" == 0.
+/// Also set cursor column to altfpos.col if 'startofline' is not set.
+/// if (options & GETF_SETMARK) call setpcmark()
+/// if (options & GETF_ALT) we are jumping to an alternate file.
+/// if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping
+///
+/// Return FAIL for failure, OK for success.
int buflist_getfile(int n, linenr_T lnum, int options, int forceit)
{
buf_T *buf;
@@ -5136,6 +5144,30 @@ void sign_mark_adjust(linenr_T line1, linenr_T line2, long amount, long amount_a
// bufhl: plugin highlights associated with a buffer
+/// Get reference to line in kbtree_t
+///
+/// @param b the three
+/// @param line the linenumber to lookup
+/// @param put if true, put a new line when not found
+/// if false, return NULL when not found
+BufhlLine *bufhl_tree_ref(BufhlInfo *b, linenr_T line, bool put)
+{
+ BufhlLine t = BUFHLLINE_INIT(line);
+
+ // kp_put() only works if key is absent, try get first
+ BufhlLine **pp = kb_get(bufhl, b, &t);
+ if (pp) {
+ return *pp;
+ } else if (!put) {
+ return NULL;
+ }
+
+ BufhlLine *p = xmalloc(sizeof(*p));
+ *p = (BufhlLine)BUFHLLINE_INIT(line);
+ kb_put(bufhl, b, p);
+ return p;
+}
+
/// Adds a highlight to buffer.
///
/// Unlike matchaddpos() highlights follow changes to line numbering (as lines
@@ -5173,13 +5205,10 @@ int bufhl_add_hl(buf_T *buf,
// no highlight group or invalid line, just return src_id
return src_id;
}
- if (!buf->b_bufhl_info) {
- buf->b_bufhl_info = map_new(linenr_T, bufhl_vec_T)();
- }
- bufhl_vec_T* lineinfo = map_ref(linenr_T, bufhl_vec_T)(buf->b_bufhl_info,
- lnum, true);
- bufhl_hl_item_T *hlentry = kv_pushp(*lineinfo);
+ BufhlLine *lineinfo = bufhl_tree_ref(&buf->b_bufhl_info, lnum, true);
+
+ BufhlItem *hlentry = kv_pushp(lineinfo->items);
hlentry->src_id = src_id;
hlentry->hl_id = hl_id;
hlentry->start = col_start;
@@ -5201,20 +5230,24 @@ int bufhl_add_hl(buf_T *buf,
void bufhl_clear_line_range(buf_T *buf,
int src_id,
linenr_T line_start,
- linenr_T line_end) {
- if (!buf->b_bufhl_info) {
- return;
- }
- linenr_T line;
+ linenr_T line_end)
+{
linenr_T first_changed = MAXLNUM, last_changed = -1;
- // In the case line_start - line_end << bufhl_info->size
- // it might be better to reverse this, i e loop over the lines
- // to clear on.
- bufhl_vec_T unused;
- map_foreach(buf->b_bufhl_info, line, unused, {
- (void)unused;
+
+ kbitr_t(bufhl) itr;
+ BufhlLine *l, t = BUFHLLINE_INIT(line_start);
+ if (!kb_itr_get(bufhl, &buf->b_bufhl_info, &t, &itr)) {
+ kb_itr_next(bufhl, &buf->b_bufhl_info, &itr);
+ }
+ for (; kb_itr_valid(&itr); kb_itr_next(bufhl, &buf->b_bufhl_info, &itr)) {
+ l = kb_itr_key(&itr);
+ linenr_T line = l->line;
+ if (line > line_end) {
+ break;
+ }
if (line_start <= line && line <= line_end) {
- if (bufhl_clear_line(buf->b_bufhl_info, src_id, line)) {
+ BufhlLineStatus status = bufhl_clear_line(l, src_id, line);
+ if (status != kBLSUnchanged) {
if (line > last_changed) {
last_changed = line;
}
@@ -5222,8 +5255,12 @@ void bufhl_clear_line_range(buf_T *buf,
first_changed = line;
}
}
+ if (status == kBLSDeleted) {
+ kb_del_itr(bufhl, &buf->b_bufhl_info, &itr);
+ xfree(l);
+ }
}
- })
+ }
if (last_changed != -1) {
changed_lines_buf(buf, first_changed, last_changed+1, 0);
@@ -5236,42 +5273,40 @@ void bufhl_clear_line_range(buf_T *buf,
/// @param bufhl_info The highlight info for the buffer
/// @param src_id Highlight source group to clear, or -1 to clear all groups.
/// @param lnum Linenr where the highlight should be cleared
-static bool bufhl_clear_line(bufhl_info_T *bufhl_info, int src_id,
- linenr_T lnum)
+static BufhlLineStatus bufhl_clear_line(BufhlLine *lineinfo, int src_id,
+ linenr_T lnum)
{
- bufhl_vec_T *lineinfo = map_ref(linenr_T, bufhl_vec_T)(bufhl_info,
- lnum, false);
- size_t oldsize = kv_size(*lineinfo);
+ size_t oldsize = kv_size(lineinfo->items);
if (src_id < 0) {
- kv_size(*lineinfo) = 0;
+ kv_size(lineinfo->items) = 0;
} else {
- size_t newind = 0;
- for (size_t i = 0; i < kv_size(*lineinfo); i++) {
- if (kv_A(*lineinfo, i).src_id != src_id) {
- if (i != newind) {
- kv_A(*lineinfo, newind) = kv_A(*lineinfo, i);
+ size_t newidx = 0;
+ for (size_t i = 0; i < kv_size(lineinfo->items); i++) {
+ if (kv_A(lineinfo->items, i).src_id != src_id) {
+ if (i != newidx) {
+ kv_A(lineinfo->items, newidx) = kv_A(lineinfo->items, i);
}
- newind++;
+ newidx++;
}
}
- kv_size(*lineinfo) = newind;
+ kv_size(lineinfo->items) = newidx;
}
- if (kv_size(*lineinfo) == 0) {
- kv_destroy(*lineinfo);
- map_del(linenr_T, bufhl_vec_T)(bufhl_info, lnum);
+ if (kv_size(lineinfo->items) == 0) {
+ kv_destroy(lineinfo->items);
+ return kBLSDeleted;
}
- return kv_size(*lineinfo) != oldsize;
+ return kv_size(lineinfo->items) != oldsize ? kBLSChanged : kBLSUnchanged;
}
/// Remove all highlights and free the highlight data
-void bufhl_clear_all(buf_T* buf) {
- if (!buf->b_bufhl_info) {
- return;
- }
+void bufhl_clear_all(buf_T *buf)
+{
bufhl_clear_line_range(buf, -1, 1, MAXLNUM);
- map_free(linenr_T, bufhl_vec_T)(buf->b_bufhl_info);
- buf->b_bufhl_info = NULL;
+ kb_destroy(bufhl, (&buf->b_bufhl_info));
+ kb_init(&buf->b_bufhl_info);
+ kv_destroy(buf->b_bufhl_move_space);
+ kv_init(buf->b_bufhl_move_space);
}
/// Adjust a placed highlight for inserted/deleted lines.
@@ -5279,29 +5314,49 @@ void bufhl_mark_adjust(buf_T* buf,
linenr_T line1,
linenr_T line2,
long amount,
- long amount_after) {
- if (!buf->b_bufhl_info) {
+ long amount_after,
+ bool end_temp)
+{
+ kbitr_t(bufhl) itr;
+ BufhlLine *l, t = BUFHLLINE_INIT(line1);
+ if (end_temp && amount < 0) {
+ // Move all items from b_bufhl_move_space to the btree.
+ for (size_t i = 0; i < kv_size(buf->b_bufhl_move_space); i++) {
+ l = kv_A(buf->b_bufhl_move_space, i);
+ l->line += amount;
+ kb_put(bufhl, &buf->b_bufhl_info, l);
+ }
+ kv_size(buf->b_bufhl_move_space) = 0;
return;
}
- bufhl_info_T *newmap = map_new(linenr_T, bufhl_vec_T)();
- linenr_T line;
- bufhl_vec_T lineinfo;
- map_foreach(buf->b_bufhl_info, line, lineinfo, {
- if (line >= line1 && line <= line2) {
+ if (!kb_itr_get(bufhl, &buf->b_bufhl_info, &t, &itr)) {
+ kb_itr_next(bufhl, &buf->b_bufhl_info, &itr);
+ }
+ for (; kb_itr_valid(&itr); kb_itr_next(bufhl, &buf->b_bufhl_info, &itr)) {
+ l = kb_itr_key(&itr);
+ if (l->line >= line1 && l->line <= line2) {
+ if (end_temp && amount > 0) {
+ kb_del_itr(bufhl, &buf->b_bufhl_info, &itr);
+ kv_push(buf->b_bufhl_move_space, l);
+ }
if (amount == MAXLNUM) {
- bufhl_clear_line(buf->b_bufhl_info, -1, line);
- continue;
+ if (bufhl_clear_line(l, -1, l->line) == kBLSDeleted) {
+ kb_del_itr(bufhl, &buf->b_bufhl_info, &itr);
+ xfree(l);
+ } else {
+ assert(false);
+ }
} else {
- line += amount;
+ l->line += amount;
+ }
+ } else if (l->line > line2) {
+ if (amount_after == 0) {
+ break;
}
- } else if (line > line2) {
- line += amount_after;
+ l->line += amount_after;
}
- map_put(linenr_T, bufhl_vec_T)(newmap, line, lineinfo);
- });
- map_free(linenr_T, bufhl_vec_T)(buf->b_bufhl_info);
- buf->b_bufhl_info = newmap;
+ }
}
@@ -5311,13 +5366,14 @@ void bufhl_mark_adjust(buf_T* buf,
/// @param lnum The line number
/// @param[out] info The highligts for the line
/// @return true if there was highlights to display
-bool bufhl_start_line(buf_T *buf, linenr_T lnum, bufhl_lineinfo_T *info) {
- if (!buf->b_bufhl_info) {
+bool bufhl_start_line(buf_T *buf, linenr_T lnum, BufhlLineInfo *info)
+{
+ BufhlLine *lineinfo = bufhl_tree_ref(&buf->b_bufhl_info, lnum, false);
+ if (!lineinfo) {
return false;
}
-
info->valid_to = -1;
- info->entries = map_get(linenr_T, bufhl_vec_T)(buf->b_bufhl_info, lnum);
+ info->entries = lineinfo->items;
return kv_size(info->entries) > 0;
}
@@ -5331,14 +5387,15 @@ bool bufhl_start_line(buf_T *buf, linenr_T lnum, bufhl_lineinfo_T *info) {
/// @param info The info returned by bufhl_start_line
/// @param col The column to get the attr for
/// @return The highilight attr to display at the column
-int bufhl_get_attr(bufhl_lineinfo_T *info, colnr_T col) {
+int bufhl_get_attr(BufhlLineInfo *info, colnr_T col)
+{
if (col <= info->valid_to) {
return info->current;
}
int attr = 0;
info->valid_to = MAXCOL;
for (size_t i = 0; i < kv_size(info->entries); i++) {
- bufhl_hl_item_T entry = kv_A(info->entries, i);
+ BufhlItem entry = kv_A(info->entries, i);
if (entry.start <= col && col <= entry.stop) {
int entry_attr = syn_id2attr(entry.hl_id);
attr = hl_combine_attr(attr, entry_attr);
diff --git a/src/nvim/buffer.h b/src/nvim/buffer.h
index 39b9faf8b1..faeeed121c 100644
--- a/src/nvim/buffer.h
+++ b/src/nvim/buffer.h
@@ -83,14 +83,16 @@ static inline void restore_win_for_buf(win_T *save_curwin,
}
}
-static inline void buf_set_changedtick(buf_T *const buf, const int changedtick)
+static inline void buf_set_changedtick(buf_T *const buf,
+ const varnumber_T changedtick)
REAL_FATTR_NONNULL_ALL REAL_FATTR_ALWAYS_INLINE;
/// Set b_changedtick and corresponding variable
///
/// @param[out] buf Buffer to set changedtick in.
/// @param[in] changedtick New value.
-static inline void buf_set_changedtick(buf_T *const buf, const int changedtick)
+static inline void buf_set_changedtick(buf_T *const buf,
+ const varnumber_T changedtick)
{
#ifndef NDEBUG
dictitem_T *const changedtick_di = tv_dict_find(
@@ -113,7 +115,7 @@ static inline void buf_set_changedtick(buf_T *const buf, const int changedtick)
do { \
win_T *save_curwin = NULL; \
tabpage_T *save_curtab = NULL; \
- bufref_T save_curbuf = { NULL, 0 }; \
+ bufref_T save_curbuf = { NULL, 0, 0 }; \
switch_to_win_for_buf(b, &save_curwin, &save_curtab, &save_curbuf); \
code; \
restore_win_for_buf(save_curwin, save_curtab, &save_curbuf); \
diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h
index 88fa9726a4..559dffb945 100644
--- a/src/nvim/buffer_defs.h
+++ b/src/nvim/buffer_defs.h
@@ -12,11 +12,14 @@ typedef struct file_buffer buf_T; // Forward declaration
// bufref_valid() only needs to check "buf" when the count differs.
typedef struct {
buf_T *br_buf;
+ int br_fnum;
int br_buf_free_count;
} bufref_T;
// for garray_T
#include "nvim/garray.h"
+// for HLF_COUNT
+#include "nvim/highlight_defs.h"
// for pos_T, lpos_T and linenr_T
#include "nvim/pos.h"
// for the number window-local and buffer-local options
@@ -103,8 +106,6 @@ typedef struct frame_S frame_T;
// for bufhl_*_T
#include "nvim/bufhl_defs.h"
-typedef Map(linenr_T, bufhl_vec_T) bufhl_info_T;
-
#include "nvim/os/fs_defs.h" // for FileID
#include "nvim/terminal.h" // for Terminal
@@ -438,6 +439,9 @@ typedef TV_DICTITEM_STRUCT(sizeof("changedtick")) ChangedtickDictItem;
#define BUF_HAS_QF_ENTRY 1
#define BUF_HAS_LL_ENTRY 2
+// Maximum number of maphash blocks we will have
+#define MAX_MAPHASH 256
+
/*
* buffer: structure that holds information about one file
*
@@ -526,8 +530,8 @@ struct file_buffer {
*/
uint64_t b_chartab[4];
- /* Table used for mappings local to a buffer. */
- mapblock_T *(b_maphash[256]);
+ // Table used for mappings local to a buffer.
+ mapblock_T *(b_maphash[MAX_MAPHASH]);
/* First abbreviation local to a buffer. */
mapblock_T *b_first_abbr;
@@ -756,7 +760,9 @@ struct file_buffer {
int b_mapped_ctrl_c; // modes where CTRL-C is mapped
- bufhl_info_T *b_bufhl_info; // buffer stored highlights
+ BufhlInfo b_bufhl_info; // buffer stored highlights
+
+ kvec_t(BufhlLine *) b_bufhl_move_space; // temporary space for highlights
};
/*
@@ -932,9 +938,13 @@ struct window_S {
synblock_T *w_s; /* for :ownsyntax */
- int w_hl_id; ///< 'winhighlight' id
- int w_hl_id_inactive; ///< 'winhighlight' id for inactive window
- int w_hl_attr; ///< 'winhighlight' final attrs
+ int w_hl_id_normal; ///< 'winhighlight' normal id
+ int w_hl_attr_normal; ///< 'winhighlight' normal final attrs
+
+ int w_hl_ids[HLF_COUNT]; ///< 'winhighlight' id
+ int w_hl_attrs[HLF_COUNT]; ///< 'winhighlight' final attrs
+
+ int w_hl_needs_update; ///< attrs need to be recalculated
win_T *w_prev; /* link to previous window */
win_T *w_next; /* link to next window */
@@ -1165,4 +1175,9 @@ struct window_S {
qf_info_T *w_llist_ref;
};
+static inline int win_hl_attr(win_T *wp, int hlf)
+{
+ return wp->w_hl_attrs[hlf];
+}
+
#endif // NVIM_BUFFER_DEFS_H
diff --git a/src/nvim/bufhl_defs.h b/src/nvim/bufhl_defs.h
index e47bb2a238..24bd6b7f29 100644
--- a/src/nvim/bufhl_defs.h
+++ b/src/nvim/bufhl_defs.h
@@ -3,23 +3,32 @@
#include "nvim/pos.h"
#include "nvim/lib/kvec.h"
+#include "nvim/lib/kbtree.h"
+
// bufhl: buffer specific highlighting
-struct bufhl_hl_item
-{
+typedef struct {
int src_id;
int hl_id; // highlight group
colnr_T start; // first column to highlight
colnr_T stop; // last column to highlight
-};
-typedef struct bufhl_hl_item bufhl_hl_item_T;
+} BufhlItem;
-typedef kvec_t(struct bufhl_hl_item) bufhl_vec_T;
+typedef kvec_t(BufhlItem) BufhlItemVec;
+
+typedef struct {
+ linenr_T line;
+ BufhlItemVec items;
+} BufhlLine;
+#define BUFHLLINE_INIT(l) { l, KV_INITIAL_VALUE }
typedef struct {
- bufhl_vec_T entries;
+ BufhlItemVec entries;
int current;
colnr_T valid_to;
-} bufhl_lineinfo_T;
+} BufhlLineInfo;
+#define BUFHL_CMP(a, b) ((int)(((a)->line - (b)->line)))
+KBTREE_INIT(bufhl, BufhlLine *, BUFHL_CMP, 10)
+typedef kbtree_t(bufhl) BufhlInfo;
#endif // NVIM_BUFHL_DEFS_H
diff --git a/src/nvim/charset.c b/src/nvim/charset.c
index 5a0590d075..48db1030a6 100644
--- a/src/nvim/charset.c
+++ b/src/nvim/charset.c
@@ -1621,13 +1621,13 @@ bool vim_isblankline(char_u *lbuf)
/// @param unptr Returns the unsigned result.
/// @param maxlen Max length of string to check.
void vim_str2nr(const char_u *const start, int *const prep, int *const len,
- const int what, long *const nptr, unsigned long *const unptr,
- const int maxlen)
+ const int what, varnumber_T *const nptr,
+ uvarnumber_T *const unptr, const int maxlen)
{
const char_u *ptr = start;
int pre = 0; // default is decimal
bool negative = false;
- unsigned long un = 0;
+ uvarnumber_T un = 0;
if (ptr[0] == '-') {
negative = true;
@@ -1683,7 +1683,12 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len,
n += 2; // skip over "0b"
}
while ('0' <= *ptr && *ptr <= '1') {
- un = 2 * un + (unsigned long)(*ptr - '0');
+ // avoid ubsan error for overflow
+ if (un < UVARNUMBER_MAX / 2) {
+ un = 2 * un + (uvarnumber_T)(*ptr - '0');
+ } else {
+ un = UVARNUMBER_MAX;
+ }
ptr++;
if (n++ == maxlen) {
break;
@@ -1692,7 +1697,12 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len,
} else if ((pre == '0') || what == STR2NR_OCT + STR2NR_FORCE) {
// octal
while ('0' <= *ptr && *ptr <= '7') {
- un = 8 * un + (unsigned long)(*ptr - '0');
+ // avoid ubsan error for overflow
+ if (un < UVARNUMBER_MAX / 8) {
+ un = 8 * un + (uvarnumber_T)(*ptr - '0');
+ } else {
+ un = UVARNUMBER_MAX;
+ }
ptr++;
if (n++ == maxlen) {
break;
@@ -1705,7 +1715,12 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len,
n += 2; // skip over "0x"
}
while (ascii_isxdigit(*ptr)) {
- un = 16 * un + (unsigned long)hex2nr(*ptr);
+ // avoid ubsan error for overflow
+ if (un < UVARNUMBER_MAX / 16) {
+ un = 16 * un + (uvarnumber_T)hex2nr(*ptr);
+ } else {
+ un = UVARNUMBER_MAX;
+ }
ptr++;
if (n++ == maxlen) {
break;
@@ -1714,7 +1729,12 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len,
} else {
// decimal
while (ascii_isdigit(*ptr)) {
- un = 10 * un + (unsigned long)(*ptr - '0');
+ // avoid ubsan error for overflow
+ if (un < UVARNUMBER_MAX / 10) {
+ un = 10 * un + (uvarnumber_T)(*ptr - '0');
+ } else {
+ un = UVARNUMBER_MAX;
+ }
ptr++;
if (n++ == maxlen) {
break;
@@ -1731,11 +1751,18 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len,
}
if (nptr != NULL) {
- if (negative) {
- // account for leading '-' for decimal numbers
- *nptr = -(long)un;
+ if (negative) { // account for leading '-' for decimal numbers
+ // avoid ubsan error for overflow
+ if (un > VARNUMBER_MAX) {
+ *nptr = VARNUMBER_MIN;
+ } else {
+ *nptr = -(varnumber_T)un;
+ }
} else {
- *nptr = (long)un;
+ if (un > VARNUMBER_MAX) {
+ un = VARNUMBER_MAX;
+ }
+ *nptr = (varnumber_T)un;
}
}
diff --git a/src/nvim/cursor_shape.c b/src/nvim/cursor_shape.c
index e302d5aa4c..97fc3a3ca3 100644
--- a/src/nvim/cursor_shape.c
+++ b/src/nvim/cursor_shape.c
@@ -260,7 +260,7 @@ int cursor_mode_str2int(const char *mode)
return current_mode;
}
}
- ELOG("Unknown mode %s", mode);
+ WLOG("Unknown mode %s", mode);
return -1;
}
diff --git a/src/nvim/diff.c b/src/nvim/diff.c
index 0bd3f59cf2..7da6665cb7 100644
--- a/src/nvim/diff.c
+++ b/src/nvim/diff.c
@@ -2311,7 +2311,7 @@ void ex_diffgetput(exarg_T *eap)
// Adjust marks. This will change the following entries!
if (added != 0) {
- mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added);
+ mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added, false);
if (curwin->w_cursor.lnum >= lnum) {
// Adjust the cursor position if it's in/after the changed
// lines.
diff --git a/src/nvim/eval.c b/src/nvim/eval.c
index e4b3128930..18aa5bf763 100644
--- a/src/nvim/eval.c
+++ b/src/nvim/eval.c
@@ -6,6 +6,7 @@
*/
#include <assert.h>
+#include <float.h>
#include <inttypes.h>
#include <stdarg.h>
#include <string.h>
@@ -446,7 +447,7 @@ typedef struct {
bool rpc;
int refcount;
Callback on_stdout, on_stderr, on_exit;
- int *status_ptr;
+ varnumber_T *status_ptr;
uint64_t id;
MultiQueue *events;
} TerminalJobData;
@@ -1081,10 +1082,10 @@ char_u *eval_to_string_safe(char_u *arg, char_u **nextcmd, int use_sandbox)
* Evaluates "expr" silently.
* Returns -1 for an error.
*/
-int eval_to_number(char_u *expr)
+varnumber_T eval_to_number(char_u *expr)
{
typval_T rettv;
- int retval;
+ varnumber_T retval;
char_u *p = skipwhite(expr);
++emsg_off;
@@ -1189,7 +1190,7 @@ int get_spellword(list_T *list, const char **pp)
}
-// Call some vimL function and return the result in "*rettv".
+// Call some vim script function and return the result in "*rettv".
// Uses argv[argc] for the function arguments. Only Number and String
// arguments are currently supported.
//
@@ -1203,7 +1204,7 @@ int call_vim_function(
typval_T *rettv
)
{
- long n;
+ varnumber_T n;
int len;
int doesrange;
void *save_funccalp = NULL;
@@ -1256,21 +1257,19 @@ int call_vim_function(
return ret;
}
-/*
- * Call vimL function "func" and return the result as a number.
- * Returns -1 when calling the function fails.
- * Uses argv[argc] for the function arguments.
- */
-long
-call_func_retnr (
- char_u *func,
- int argc,
- const char_u *const *const argv,
- int safe // use the sandbox
-)
+/// Call Vim script function and return the result as a number
+///
+/// @param[in] func Function name.
+/// @param[in] argc Number of arguments.
+/// @param[in] argv Array with string arguments.
+/// @param[in] safe Use with sandbox.
+///
+/// @return -1 when calling function fails, result of function otherwise.
+varnumber_T call_func_retnr(char_u *func, int argc,
+ const char_u *const *const argv, int safe)
{
typval_T rettv;
- long retval;
+ varnumber_T retval;
/* All arguments are passed as strings, no conversion to number. */
if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
@@ -1281,14 +1280,14 @@ call_func_retnr (
return retval;
}
-/// Call VimL function and return the result as a string
+/// Call Vim script function and return the result as a string
///
/// @param[in] func Function name.
/// @param[in] argc Number of arguments.
/// @param[in] argv Array with string arguments.
/// @param[in] safe Use the sandbox.
///
-/// @return [allocated] NULL when calling function failes, allocated string
+/// @return [allocated] NULL when calling function fails, allocated string
/// otherwise.
char *call_func_retstr(const char *const func, const int argc,
const char_u *const *const argv,
@@ -1307,18 +1306,17 @@ char *call_func_retstr(const char *const func, const int argc,
return retval;
}
-/*
- * Call vimL function "func" and return the result as a List.
- * Uses argv[argc] for the function arguments.
- * Returns NULL when there is something wrong.
- */
-void *
-call_func_retlist (
- char_u *func,
- int argc,
- const char_u *const *const argv,
- int safe // use the sandbox
-)
+/// Call Vim script function and return the result as a List
+///
+/// @param[in] func Function name.
+/// @param[in] argc Number of arguments.
+/// @param[in] argv Array with string arguments.
+/// @param[in] safe Use the sandbox.
+///
+/// @return [allocated] NULL when calling function fails or return tv is not a
+/// List, allocated List otherwise.
+void *call_func_retlist(char_u *func, int argc, const char_u *const *const argv,
+ int safe)
{
typval_T rettv;
@@ -1399,7 +1397,7 @@ void prof_child_exit(proftime_T *tm /* where waittime was stored */
int eval_foldexpr(char_u *arg, int *cp)
{
typval_T tv;
- int retval;
+ varnumber_T retval;
char_u *s;
int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
OPT_LOCAL);
@@ -1432,7 +1430,7 @@ int eval_foldexpr(char_u *arg, int *cp)
--sandbox;
--textlock;
- return retval;
+ return (int)retval;
}
/*
@@ -2286,7 +2284,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
if (empty1) {
lp->ll_n1 = 0;
} else {
- lp->ll_n1 = tv_get_number(&var1); // Is number or string.
+ lp->ll_n1 = (long)tv_get_number(&var1); // Is number or string.
tv_clear(&var1);
}
lp->ll_dict = NULL;
@@ -2315,7 +2313,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
* Otherwise "lp->ll_n2" is set to the second index.
*/
if (lp->ll_range && !lp->ll_empty2) {
- lp->ll_n2 = tv_get_number(&var2); // Is number or string.
+ lp->ll_n2 = (long)tv_get_number(&var2); // Is number or string.
tv_clear(&var2);
if (lp->ll_n2 < 0) {
ni = tv_list_find(lp->ll_list, lp->ll_n2);
@@ -3525,7 +3523,7 @@ static int eval4(char_u **arg, typval_T *rettv, int evaluate)
exptype_T type = TYPE_UNKNOWN;
int type_is = FALSE; /* TRUE for "is" and "isnot" */
int len = 2;
- long n1, n2;
+ varnumber_T n1, n2;
int ic;
/*
@@ -3787,7 +3785,7 @@ static int eval5(char_u **arg, typval_T *rettv, int evaluate)
typval_T var2;
typval_T var3;
int op;
- long n1, n2;
+ varnumber_T n1, n2;
float_T f1 = 0, f2 = 0;
char_u *p;
@@ -3917,29 +3915,26 @@ static int eval5(char_u **arg, typval_T *rettv, int evaluate)
// TODO(ZyX-I): move to eval/expressions
-/*
- * Handle fifth level expression:
- * * number multiplication
- * / number division
- * % number modulo
- *
- * "arg" must point to the first non-white of the expression.
- * "arg" is advanced to the next non-white after the recognized expression.
- *
- * Return OK or FAIL.
- */
-static int
-eval6 (
- char_u **arg,
- typval_T *rettv,
- int evaluate,
- int want_string /* after "." operator */
-)
+/// Handle fifth level expression:
+/// - * number multiplication
+/// - / number division
+/// - % number modulo
+///
+/// @param[in,out] arg Points to the first non-whitespace character of the
+/// expression. Is advanced to the next non-whitespace
+/// character after the recognized expression.
+/// @param[out] rettv Location where result is saved.
+/// @param[in] evaluate If not true, rettv is not populated.
+/// @param[in] want_string True if "." is string_concatenation, otherwise
+/// float
+/// @return OK or FAIL.
+static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string)
+ FUNC_ATTR_NO_SANITIZE_UNDEFINED
{
typval_T var2;
int op;
- long n1, n2;
- int use_float = FALSE;
+ varnumber_T n1, n2;
+ bool use_float = false;
float_T f1 = 0, f2;
bool error = false;
@@ -3960,7 +3955,7 @@ eval6 (
if (evaluate) {
if (rettv->v_type == VAR_FLOAT) {
f1 = rettv->vval.v_float;
- use_float = TRUE;
+ use_float = true;
n1 = 0;
} else {
n1 = tv_get_number_chk(rettv, &error);
@@ -3984,7 +3979,7 @@ eval6 (
if (var2.v_type == VAR_FLOAT) {
if (!use_float) {
f1 = n1;
- use_float = TRUE;
+ use_float = true;
}
f2 = var2.vval.v_float;
n2 = 0;
@@ -4027,18 +4022,20 @@ eval6 (
rettv->v_type = VAR_FLOAT;
rettv->vval.v_float = f1;
} else {
- if (op == '*')
+ if (op == '*') {
n1 = n1 * n2;
- else if (op == '/') {
- if (n2 == 0) { /* give an error message? */
- if (n1 == 0)
- n1 = -0x7fffffffL - 1L; /* similar to NaN */
- else if (n1 < 0)
- n1 = -0x7fffffffL;
- else
- n1 = 0x7fffffffL;
- } else
+ } else if (op == '/') {
+ if (n2 == 0) { // give an error message?
+ if (n1 == 0) {
+ n1 = VARNUMBER_MIN; // similar to NaN
+ } else if (n1 < 0) {
+ n1 = -VARNUMBER_MAX;
+ } else {
+ n1 = VARNUMBER_MAX;
+ }
+ } else {
n1 = n1 / n2;
+ }
} else {
if (n2 == 0) /* give an error message? */
n1 = 0;
@@ -4087,7 +4084,7 @@ static int eval7(
int want_string // after "." operator
)
{
- long n;
+ varnumber_T n;
int len;
char_u *s;
char_u *start_leader, *end_leader;
@@ -4285,7 +4282,7 @@ static int eval7(
// Apply logical NOT and unary '-', from right to left, ignore '+'.
if (ret == OK && evaluate && end_leader > start_leader) {
bool error = false;
- int val = 0;
+ varnumber_T val = 0;
float_T f = 0.0;
if (rettv->v_type == VAR_FLOAT) {
@@ -5100,7 +5097,8 @@ bool garbage_collect(bool testing)
do {
yankreg_T reg;
char name = NUL;
- reg_iter = op_register_iter(reg_iter, &name, &reg);
+ bool is_unnamed = false;
+ reg_iter = op_register_iter(reg_iter, &name, &reg, &is_unnamed);
if (name != NUL) {
ABORTING(set_ref_dict)(reg.additional_data, copyID);
}
@@ -5897,6 +5895,19 @@ size_t string2float(const char *const text, float_T *const ret_value)
{
char *s = NULL;
+ // MS-Windows does not deal with "inf" and "nan" properly
+ if (STRNICMP(text, "inf", 3) == 0) {
+ *ret_value = INFINITY;
+ return 3;
+ }
+ if (STRNICMP(text, "-inf", 3) == 0) {
+ *ret_value = -INFINITY;
+ return 4;
+ }
+ if (STRNICMP(text, "nan", 3) == 0) {
+ *ret_value = NAN;
+ return 3;
+ }
*ret_value = strtod(text, &s);
return (size_t) (s - text);
}
@@ -6677,7 +6688,7 @@ static void f_argv(typval_T *argvars, typval_T *rettv, FunPtr fptr)
int idx;
if (argvars[0].v_type != VAR_UNKNOWN) {
- idx = tv_get_number_chk(&argvars[0], NULL);
+ idx = (int)tv_get_number_chk(&argvars[0], NULL);
if (idx >= 0 && idx < ARGCOUNT) {
rettv->vval.v_string = (char_u *)xstrdup(
(const char *)alist_name(&ARGLIST[idx]));
@@ -6793,6 +6804,17 @@ static void f_assert_notequal(typval_T *argvars, typval_T *rettv, FunPtr fptr)
assert_equal_common(argvars, ASSERT_NOTEQUAL);
}
+/// "assert_report(msg)
+static void f_assert_report(typval_T *argvars, typval_T *rettv, FunPtr fptr)
+{
+ garray_T ga;
+
+ prepare_assert_error(&ga);
+ ga_concat(&ga, (const char_u *)tv_get_string(&argvars[0]));
+ assert_error(&ga);
+ ga_clear(&ga);
+}
+
/// "assert_exception(string[, msg])" function
static void f_assert_exception(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
@@ -7402,7 +7424,7 @@ static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
return;
}
- const int startcol = tv_get_number_chk(&argvars[0], NULL);
+ const colnr_T startcol = tv_get_number_chk(&argvars[0], NULL);
if (startcol <= 0) {
return;
}
@@ -7613,9 +7635,9 @@ static void f_cursor(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
} else {
line = tv_get_lnum(argvars);
- col = tv_get_number_chk(&argvars[1], NULL);
+ col = (long)tv_get_number_chk(&argvars[1], NULL);
if (argvars[2].v_type != VAR_UNKNOWN) {
- coladd = tv_get_number_chk(&argvars[2], NULL);
+ coladd = (long)tv_get_number_chk(&argvars[2], NULL);
}
}
if (line < 0 || col < 0
@@ -8169,7 +8191,7 @@ static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
} else if (!tv_check_lock(l1->lv_lock, arg_errmsg, TV_TRANSLATE)) {
listitem_T *item;
if (argvars[2].v_type != VAR_UNKNOWN) {
- before = tv_get_number_chk(&argvars[2], &error);
+ before = (long)tv_get_number_chk(&argvars[2], &error);
if (error) {
return; // Type error; errmsg already given.
}
@@ -8538,9 +8560,9 @@ static void f_float2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
float_T f;
if (tv_get_float_chk(argvars, &f)) {
- if (f < VARNUMBER_MIN) {
- rettv->vval.v_number = VARNUMBER_MIN;
- } else if (f > VARNUMBER_MAX) {
+ if (f <= -VARNUMBER_MAX + DBL_EPSILON) {
+ rettv->vval.v_number = -VARNUMBER_MAX;
+ } else if (f >= VARNUMBER_MAX - DBL_EPSILON) {
rettv->vval.v_number = VARNUMBER_MAX;
} else {
rettv->vval.v_number = (varnumber_T)f;
@@ -10515,6 +10537,7 @@ static void f_has(typval_T *argvars, typval_T *rettv, FunPtr fptr)
"mouse",
"multi_byte",
"multi_lang",
+ "num64",
"packages",
"path_extra",
"persistent_undo",
@@ -12102,22 +12125,7 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact)
tv_dict_alloc_ret(rettv);
if (rhs != NULL) {
// Return a dictionary.
- char_u *lhs = str2special_save(mp->m_keys, true);
- char *const mapmode = map_mode_to_chars(mp->m_mode);
- dict_T *dict = rettv->vval.v_dict;
-
- tv_dict_add_str(dict, S_LEN("lhs"), (const char *)lhs);
- tv_dict_add_str(dict, S_LEN("rhs"), (const char *)mp->m_orig_str);
- tv_dict_add_nr(dict, S_LEN("noremap"), mp->m_noremap ? 1 : 0);
- tv_dict_add_nr(dict, S_LEN("expr"), mp->m_expr ? 1 : 0);
- tv_dict_add_nr(dict, S_LEN("silent"), mp->m_silent ? 1 : 0);
- tv_dict_add_nr(dict, S_LEN("sid"), (varnumber_T)mp->m_script_ID);
- tv_dict_add_nr(dict, S_LEN("buffer"), (varnumber_T)buffer_local);
- tv_dict_add_nr(dict, S_LEN("nowait"), mp->m_nowait ? 1 : 0);
- tv_dict_add_str(dict, S_LEN("mode"), mapmode);
-
- xfree(lhs);
- xfree(mapmode);
+ mapblock_fill_dict(rettv->vval.v_dict, mp, buffer_local, true);
}
}
}
@@ -12134,6 +12142,46 @@ static void f_luaeval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
executor_eval_lua(cstr_as_string((char *)str), &argvars[1], rettv);
}
+/// Fill a dictionary with all applicable maparg() like dictionaries
+///
+/// @param dict The dictionary to be filled
+/// @param mp The maphash that contains the mapping information
+/// @param buffer_value The "buffer" value
+/// @param compatible True for compatible with old maparg() dict
+void mapblock_fill_dict(dict_T *const dict,
+ const mapblock_T *const mp,
+ long buffer_value,
+ bool compatible)
+ FUNC_ATTR_NONNULL_ALL
+{
+ char_u *lhs = str2special_save(mp->m_keys, true);
+ char *const mapmode = map_mode_to_chars(mp->m_mode);
+ varnumber_T noremap_value;
+
+ if (compatible) {
+ // Keep old compatible behavior
+ // This is unable to determine whether a mapping is a <script> mapping
+ noremap_value = !!mp->m_noremap;
+ } else {
+ // Distinguish between <script> mapping
+ // If it's not a <script> mapping, check if it's a noremap
+ noremap_value = mp->m_noremap == REMAP_SCRIPT ? 2 : !!mp->m_noremap;
+ }
+
+ tv_dict_add_str(dict, S_LEN("lhs"), (const char *)lhs);
+ tv_dict_add_str(dict, S_LEN("rhs"), (const char *)mp->m_orig_str);
+ tv_dict_add_nr(dict, S_LEN("noremap"), noremap_value);
+ tv_dict_add_nr(dict, S_LEN("expr"), mp->m_expr ? 1 : 0);
+ tv_dict_add_nr(dict, S_LEN("silent"), mp->m_silent ? 1 : 0);
+ tv_dict_add_nr(dict, S_LEN("sid"), (varnumber_T)mp->m_script_ID);
+ tv_dict_add_nr(dict, S_LEN("buffer"), (varnumber_T)buffer_value);
+ tv_dict_add_nr(dict, S_LEN("nowait"), mp->m_nowait ? 1 : 0);
+ tv_dict_add_str(dict, S_LEN("mode"), mapmode);
+
+ xfree(lhs);
+ xfree(mapmode);
+}
+
/*
* "map()" function
*/
@@ -12919,7 +12967,7 @@ static void f_range(typval_T *argvars, typval_T *rettv, FunPtr fptr)
varnumber_T start;
varnumber_T end;
varnumber_T stride = 1;
- long i;
+ varnumber_T i;
bool error = false;
start = tv_get_number_chk(&argvars[0], &error);
@@ -13137,7 +13185,7 @@ static int list2proftime(typval_T *arg, proftime_T *tm) FUNC_ATTR_NONNULL_ALL
// in f_reltime() we split up the 64-bit proftime_T into two 32-bit
// values, now we combine them again.
union {
- struct { varnumber_T low, high; } split;
+ struct { int32_t low, high; } split;
proftime_T prof;
} u = { .split.high = n1, .split.low = n2 };
@@ -13178,7 +13226,7 @@ static void f_reltime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
// (varnumber_T is defined as int). For all our supported platforms, int's
// are at least 32-bits wide. So we'll use two 32-bit values to store it.
union {
- struct { varnumber_T low, high; } split;
+ struct { int32_t low, high; } split;
proftime_T prof;
} u = { .prof = res };
@@ -14296,22 +14344,39 @@ static void f_serverstart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
return;
}
+ char *address;
// If the user supplied an address, use it, otherwise use a temp.
if (argvars[0].v_type != VAR_UNKNOWN) {
if (argvars[0].v_type != VAR_STRING) {
EMSG(_(e_invarg));
return;
} else {
- rettv->vval.v_string = (char_u *)xstrdup(tv_get_string(argvars));
+ address = xstrdup(tv_get_string(argvars));
}
} else {
- rettv->vval.v_string = (char_u *)server_address_new();
+ address = server_address_new();
}
- int result = server_start((char *) rettv->vval.v_string);
+ int result = server_start(address);
+ xfree(address);
+
if (result != 0) {
- EMSG2("Failed to start server: %s", uv_strerror(result));
+ EMSG2("Failed to start server: %s",
+ result > 0 ? "Unknown system error" : uv_strerror(result));
+ return;
+ }
+
+ // Since it's possible server_start adjusted the given {address} (e.g.,
+ // "localhost:" will now have a port), return the final value to the user.
+ size_t n;
+ char **addrs = server_address_list(&n);
+ rettv->vval.v_string = (char_u *)addrs[n - 1];
+
+ n--;
+ for (size_t i = 0; i < n; i++) {
+ xfree(addrs[i]);
}
+ xfree(addrs);
}
/// "serverstop()" function
@@ -14792,6 +14857,7 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
regname = '"';
}
+ bool set_unnamed = false;
if (argvars[2].v_type != VAR_UNKNOWN) {
const char *stropt = tv_get_string_chk(&argvars[2]);
if (stropt == NULL) {
@@ -14820,6 +14886,10 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
break;
}
+ case 'u': case '"': { // unnamed register
+ set_unnamed = true;
+ break;
+ }
}
}
}
@@ -14872,6 +14942,11 @@ free_lstval:
append, yank_type, block_len);
}
rettv->vval.v_number = 0;
+
+ if (set_unnamed) {
+ // Discard the result. We already handle the error case.
+ if (op_register_set_previous(regname)) { }
+ }
}
/*
@@ -15016,6 +15091,54 @@ static void f_simplify(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_STRING;
}
+/// "sockconnect()" function
+static void f_sockconnect(typval_T *argvars, typval_T *rettv, FunPtr fptr)
+{
+ if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) {
+ EMSG(_(e_invarg));
+ return;
+ }
+ if (argvars[2].v_type != VAR_DICT && argvars[2].v_type != VAR_UNKNOWN) {
+ // Wrong argument types
+ EMSG2(_(e_invarg2), "expected dictionary");
+ return;
+ }
+
+ const char *mode = tv_get_string(&argvars[0]);
+ const char *address = tv_get_string(&argvars[1]);
+
+ bool tcp;
+ if (strcmp(mode, "tcp") == 0) {
+ tcp = true;
+ } else if (strcmp(mode, "pipe") == 0) {
+ tcp = false;
+ } else {
+ EMSG2(_(e_invarg2), "invalid mode");
+ return;
+ }
+
+ bool rpc = false;
+ if (argvars[2].v_type == VAR_DICT) {
+ dict_T *opts = argvars[2].vval.v_dict;
+ rpc = tv_dict_get_number(opts, "rpc") != 0;
+ }
+
+ if (!rpc) {
+ EMSG2(_(e_invarg2), "rpc option must be true");
+ return;
+ }
+
+ const char *error = NULL;
+ uint64_t id = channel_connect(tcp, address, 50, &error);
+
+ if (error) {
+ EMSG2(_("connection failed: %s"), error);
+ }
+
+ rettv->vval.v_number = (varnumber_T)id;
+ rettv->v_type = VAR_NUMBER;
+}
+
/// struct used in the array that's given to qsort()
typedef struct {
listitem_T *item;
@@ -15051,8 +15174,8 @@ static int item_compare(const void *s1, const void *s2, bool keep_zero)
int res;
if (sortinfo->item_compare_numbers) {
- const long v1 = tv_get_number(tv1);
- const long v2 = tv_get_number(tv2);
+ const varnumber_T v1 = tv_get_number(tv1);
+ const varnumber_T v2 = tv_get_number(tv2);
res = v1 == v2 ? 0 : v1 > v2 ? 1 : -1;
goto item_compare_end;
@@ -15584,11 +15707,15 @@ static void f_split(typval_T *argvars, typval_T *rettv, FunPtr fptr)
static void f_str2float(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *p = skipwhite((const char_u *)tv_get_string(&argvars[0]));
+ bool isneg = (*p == '-');
- if (*p == '+') {
+ if (*p == '+' || *p == '-') {
p = skipwhite(p + 1);
}
(void)string2float((char *)p, &rettv->vval.v_float);
+ if (isneg) {
+ rettv->vval.v_float *= -1;
+ }
rettv->v_type = VAR_FLOAT;
}
@@ -15596,7 +15723,7 @@ static void f_str2float(typval_T *argvars, typval_T *rettv, FunPtr fptr)
static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int base = 10;
- long n;
+ varnumber_T n;
int what;
if (argvars[1].v_type != VAR_UNKNOWN) {
@@ -15608,7 +15735,8 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
char_u *p = skipwhite((const char_u *)tv_get_string(&argvars[0]));
- if (*p == '+') {
+ bool isneg = (*p == '-');
+ if (*p == '+' || *p == '-') {
p = skipwhite(p + 1);
}
switch (base) {
@@ -15629,7 +15757,11 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
vim_str2nr(p, NULL, NULL, what, &n, NULL, 0);
- rettv->vval.v_number = n;
+ if (isneg) {
+ rettv->vval.v_number = -n;
+ } else {
+ rettv->vval.v_number = n;
+ }
}
/*
@@ -18007,7 +18139,7 @@ static int eval_isnamec1(int c)
/*
* Get number v: variable value.
*/
-long get_vim_var_nr(int idx) FUNC_ATTR_PURE
+varnumber_T get_vim_var_nr(int idx) FUNC_ATTR_PURE
{
return vimvars[idx].vv_nr;
}
@@ -19633,10 +19765,12 @@ void ex_function(exarg_T *eap)
/* When there is a line break use what follows for the function body.
* Makes 'exe "func Test()\n...\nendfunc"' work. */
- if (*p == '\n')
+ const char *const end = (const char *)p + STRLEN(p);
+ if (*p == '\n') {
line_arg = p + 1;
- else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
- EMSG(_(e_trailing));
+ } else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) {
+ emsgf(_(e_trailing));
+ }
/*
* Read the body of the function, until ":endfunction" is found.
@@ -19710,8 +19844,30 @@ void ex_function(exarg_T *eap)
/* Check for "endfunction". */
if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0) {
- if (line_arg == NULL)
+ if (*p == '!') {
+ p++;
+ }
+ const char *const comment_start = strchr((const char *)p, '"');
+ const char *const endfunc_end = (comment_start
+ ? strchr(comment_start, '\n')
+ : strpbrk((const char *)p, "\n|"));
+ p = (endfunc_end
+ ? (char_u *)endfunc_end
+ : p + STRLEN(p));
+ if (*p == '|') {
+ emsgf(_(e_trailing2), p);
+ if (line_arg == NULL) {
+ xfree(theline);
+ }
+ goto erret;
+ }
+ if (line_arg == NULL) {
xfree(theline);
+ } else {
+ if ((const char *)p < end) {
+ eap->nextcmd = p + 1;
+ }
+ }
break;
}
@@ -19738,9 +19894,15 @@ void ex_function(exarg_T *eap)
}
}
- /* Check for ":append" or ":insert". */
+ // Check for ":append", ":change", ":insert".
p = skip_range(p, NULL);
if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
+ || (p[0] == 'c'
+ && (!ASCII_ISALPHA(p[1])
+ || (p[1] == 'h' && (!ASCII_ISALPHA(p[2])
+ || (p[2] == 'a'
+ && (STRNCMP(&p[3], "nge", 3) != 0
+ || !ASCII_ISALPHA(p[6])))))))
|| (p[0] == 'i'
&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
&& (!ASCII_ISALPHA(p[2])
diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua
index 533403b2b0..30766a0734 100644
--- a/src/nvim/eval.lua
+++ b/src/nvim/eval.lua
@@ -33,6 +33,7 @@ return {
assert_match={args={2, 3}},
assert_notequal={args={2, 3}},
assert_notmatch={args={2, 3}},
+ assert_report={args=1},
assert_true={args={1, 2}},
atan={args=1, func="float_op_wrapper", data="&atan"},
atan2={args=2},
@@ -268,6 +269,7 @@ return {
simplify={args=1},
sin={args=1, func="float_op_wrapper", data="&sin"},
sinh={args=1, func="float_op_wrapper", data="&sinh"},
+ sockconnect={args={2,3}},
sort={args={1, 3}},
soundfold={args=1},
spellbadword={args={0, 1}},
diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c
index 935c98fb84..9c9c2c2dc8 100644
--- a/src/nvim/eval/decode.c
+++ b/src/nvim/eval/decode.c
@@ -435,8 +435,8 @@ static inline int parse_json_string(const char *const buf, const size_t buf_len,
case 'u': {
const char ubuf[] = { t[1], t[2], t[3], t[4] };
t += 4;
- unsigned long ch;
- vim_str2nr((char_u *) ubuf, NULL, NULL,
+ uvarnumber_T ch;
+ vim_str2nr((char_u *)ubuf, NULL, NULL,
STR2NR_HEX | STR2NR_FORCE, NULL, &ch, 4);
if (ch == 0) {
hasnul = true;
@@ -609,7 +609,7 @@ parse_json_number_check:
tv.v_type = VAR_FLOAT;
} else {
// Convert integer
- long nr;
+ varnumber_T nr;
int num_len;
vim_str2nr((char_u *) s, NULL, &num_len, 0, &nr, NULL, (int) (p - s));
if ((int) exp_num_len != num_len) {
@@ -617,7 +617,7 @@ parse_json_number_check:
"to integer vim_str2nr consumed %i bytes in place of %zu"),
(int) exp_num_len, s, num_len, exp_num_len);
}
- tv.vval.v_number = (varnumber_T) nr;
+ tv.vval.v_number = nr;
}
if (json_decoder_pop(OBJ(tv, false, *didcomma, *didcolon),
stack, container_stack,
diff --git a/src/nvim/eval/executor.c b/src/nvim/eval/executor.c
index 91bb61323f..99298cbbcf 100644
--- a/src/nvim/eval/executor.c
+++ b/src/nvim/eval/executor.c
@@ -25,7 +25,7 @@ char *e_listidx = N_("E684: list index out of range: %" PRId64);
/// @return OK or FAIL.
int eexe_mod_op(typval_T *const tv1, const typval_T *const tv2,
const char *const op)
- FUNC_ATTR_NONNULL_ALL
+ FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NO_SANITIZE_UNDEFINED
{
// Can't do anything with a Funcref, a Dict or special value on the right.
if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT) {
@@ -55,7 +55,7 @@ int eexe_mod_op(typval_T *const tv1, const typval_T *const tv2,
// nr += nr or nr -= nr
varnumber_T n = tv_get_number(tv1);
if (tv2->v_type == VAR_FLOAT) {
- float_T f = n;
+ float_T f = (float_T)n;
if (*op == '+') {
f += tv2->vval.v_float;
@@ -99,7 +99,7 @@ int eexe_mod_op(typval_T *const tv1, const typval_T *const tv2,
}
const float_T f = (tv2->v_type == VAR_FLOAT
? tv2->vval.v_float
- : tv_get_number(tv2));
+ : (float_T)tv_get_number(tv2));
if (*op == '+') {
tv1->vval.v_float += f;
} else {
diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c
index f017f57b12..4521085519 100644
--- a/src/nvim/eval/typval.c
+++ b/src/nvim/eval/typval.c
@@ -2405,9 +2405,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) {
- long nr;
- vim_str2nr(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &nr, NULL, 0);
- n = (varnumber_T)nr;
+ vim_str2nr(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0);
}
return n;
}
@@ -2444,7 +2442,7 @@ varnumber_T tv_get_number_chk(const typval_T *const tv, bool *const ret_error)
linenr_T tv_get_lnum(const typval_T *const tv)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
- linenr_T lnum = tv_get_number_chk(tv, NULL);
+ linenr_T lnum = (linenr_T)tv_get_number_chk(tv, NULL);
if (lnum == 0) { // No valid number, try using same function as line() does.
int fnum;
pos_T *const fp = var2fpos(tv, true, &fnum);
diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h
index 0f659727ee..3f8ed3b3f9 100644
--- a/src/nvim/eval/typval.h
+++ b/src/nvim/eval/typval.h
@@ -1,7 +1,7 @@
#ifndef NVIM_EVAL_TYPVAL_H
#define NVIM_EVAL_TYPVAL_H
-#include <limits.h>
+#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
@@ -20,20 +20,21 @@
#include "nvim/macros.h"
/// Type used for VimL VAR_NUMBER values
-typedef int varnumber_T;
+typedef int64_t varnumber_T;
+typedef uint64_t uvarnumber_T;
/// Type used for VimL VAR_FLOAT values
typedef double float_T;
/// Maximal possible value of varnumber_T variable
-#define VARNUMBER_MAX INT_MAX
+#define VARNUMBER_MAX INT64_MAX
+#define UVARNUMBER_MAX UINT64_MAX
/// Mimimal possible value of varnumber_T variable
-#define VARNUMBER_MIN INT_MIN
-#define PRIdVARNUMBER "d"
+#define VARNUMBER_MIN INT64_MIN
/// %d printf format specifier for varnumber_T
-#define PRIdVARNUMBER "d"
+#define PRIdVARNUMBER PRId64
typedef struct listvar_S list_T;
typedef struct dictvar_S dict_T;
diff --git a/src/nvim/event/loop.c b/src/nvim/event/loop.c
index c709ce9a1c..25701a1621 100644
--- a/src/nvim/event/loop.c
+++ b/src/nvim/event/loop.c
@@ -8,6 +8,7 @@
#include "nvim/event/loop.h"
#include "nvim/event/process.h"
+#include "nvim/log.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "event/loop.c.generated.h"
@@ -78,20 +79,34 @@ void loop_on_put(MultiQueue *queue, void *data)
uv_stop(&loop->uv);
}
-void loop_close(Loop *loop, bool wait)
+/// @returns false if the loop could not be closed gracefully
+bool loop_close(Loop *loop, bool wait)
{
+ bool rv = true;
uv_mutex_destroy(&loop->mutex);
uv_close((uv_handle_t *)&loop->children_watcher, NULL);
uv_close((uv_handle_t *)&loop->children_kill_timer, NULL);
uv_close((uv_handle_t *)&loop->poll_timer, NULL);
uv_close((uv_handle_t *)&loop->async, NULL);
- do {
+ uint64_t start = wait ? os_hrtime() : 0;
+ while (true) {
uv_run(&loop->uv, wait ? UV_RUN_DEFAULT : UV_RUN_NOWAIT);
- } while (uv_loop_close(&loop->uv) && wait);
+ if (!uv_loop_close(&loop->uv) || !wait) {
+ break;
+ }
+ if (os_hrtime() - start >= 2 * 1000000000) {
+ // Some libuv resource was not correctly deref'd. Log and bail.
+ rv = false;
+ ELOG("uv_loop_close() hang?");
+ log_uv_handles(&loop->uv);
+ break;
+ }
+ }
multiqueue_free(loop->fast_events);
multiqueue_free(loop->thread_events);
multiqueue_free(loop->events);
kl_destroy(WatcherPtr, loop->children);
+ return rv;
}
void loop_purge(Loop *loop)
diff --git a/src/nvim/event/socket.c b/src/nvim/event/socket.c
index 922e9c8be8..a796f303ab 100644
--- a/src/nvim/event/socket.c
+++ b/src/nvim/event/socket.c
@@ -15,63 +15,58 @@
#include "nvim/vim.h"
#include "nvim/strings.h"
#include "nvim/path.h"
+#include "nvim/main.h"
#include "nvim/memory.h"
#include "nvim/macros.h"
+#include "nvim/charset.h"
+#include "nvim/log.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "event/socket.c.generated.h"
#endif
-#define NVIM_DEFAULT_TCP_PORT 7450
-
-void socket_watcher_init(Loop *loop, SocketWatcher *watcher,
- const char *endpoint, void *data)
- FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_NONNULL_ARG(2) FUNC_ATTR_NONNULL_ARG(3)
+int socket_watcher_init(Loop *loop, SocketWatcher *watcher,
+ const char *endpoint)
+ FUNC_ATTR_NONNULL_ALL
{
- // Trim to `ADDRESS_MAX_SIZE`
- if (xstrlcpy(watcher->addr, endpoint, sizeof(watcher->addr))
- >= sizeof(watcher->addr)) {
- // TODO(aktau): since this is not what the user wanted, perhaps we
- // should return an error here
- WLOG("Address was too long, truncated to %s", watcher->addr);
- }
+ xstrlcpy(watcher->addr, endpoint, sizeof(watcher->addr));
+ char *addr = watcher->addr;
+ char *host_end = strrchr(addr, ':');
- bool tcp = true;
- char ip[16], *ip_end = xstrchrnul(watcher->addr, ':');
+ if (host_end && addr != host_end) {
+ // Split user specified address into two strings, addr(hostname) and port.
+ // The port part in watcher->addr will be updated later.
+ *host_end = '\0';
+ char *port = host_end + 1;
+ intmax_t iport;
- // (ip_end - addr) is always > 0, so convert to size_t
- size_t addr_len = (size_t)(ip_end - watcher->addr);
-
- if (addr_len > sizeof(ip) - 1) {
- // Maximum length of an IPv4 address buffer is 15 (eg: 255.255.255.255)
- addr_len = sizeof(ip) - 1;
- }
+ int ret = getdigits_safe(&(char_u *){ (char_u *)port }, &iport);
+ if (ret == FAIL || iport < 0 || iport > UINT16_MAX) {
+ ELOG("Invalid port: %s", port);
+ return UV_EINVAL;
+ }
- // Extract the address part
- xstrlcpy(ip, watcher->addr, addr_len + 1);
- int port = NVIM_DEFAULT_TCP_PORT;
-
- if (*ip_end == ':') {
- // Extract the port
- long lport = strtol(ip_end + 1, NULL, 10); // NOLINT
- if (lport <= 0 || lport > 0xffff) {
- // Invalid port, treat as named pipe or unix socket
- tcp = false;
- } else {
- port = (int) lport;
+ if (*port == NUL) {
+ // When no port is given, (uv_)getaddrinfo expects NULL otherwise the
+ // implementation may attempt to lookup the service by name (and fail)
+ port = NULL;
}
- }
- if (tcp) {
- // Try to parse ip address
- if (uv_ip4_addr(ip, port, &watcher->uv.tcp.addr)) {
- // Invalid address, treat as named pipe or unix socket
- tcp = false;
+ uv_getaddrinfo_t request;
+
+ int retval = uv_getaddrinfo(&loop->uv, &request, NULL, addr, port,
+ &(struct addrinfo){
+ .ai_family = AF_UNSPEC,
+ .ai_socktype = SOCK_STREAM,
+ });
+ if (retval != 0) {
+ ELOG("Host lookup failed: %s", endpoint);
+ return retval;
}
- }
+ watcher->uv.tcp.addrinfo = request.addrinfo;
- if (tcp) {
uv_tcp_init(&loop->uv, &watcher->uv.tcp.handle);
+ uv_tcp_nodelay(&watcher->uv.tcp.handle, true);
watcher->stream = STRUCT_CAST(uv_stream_t, &watcher->uv.tcp.handle);
} else {
uv_pipe_init(&loop->uv, &watcher->uv.pipe.handle, 0);
@@ -82,33 +77,60 @@ void socket_watcher_init(Loop *loop, SocketWatcher *watcher,
watcher->cb = NULL;
watcher->close_cb = NULL;
watcher->events = NULL;
+ watcher->data = NULL;
+
+ return 0;
}
int socket_watcher_start(SocketWatcher *watcher, int backlog, socket_cb cb)
FUNC_ATTR_NONNULL_ALL
{
watcher->cb = cb;
- int result;
+ int result = UV_EINVAL;
if (watcher->stream->type == UV_TCP) {
- result = uv_tcp_bind(&watcher->uv.tcp.handle,
- (const struct sockaddr *)&watcher->uv.tcp.addr, 0);
+ struct addrinfo *ai = watcher->uv.tcp.addrinfo;
+
+ for (; ai; ai = ai->ai_next) {
+ result = uv_tcp_bind(&watcher->uv.tcp.handle, ai->ai_addr, 0);
+ if (result != 0) {
+ continue;
+ }
+ result = uv_listen(watcher->stream, backlog, connection_cb);
+ if (result == 0) {
+ struct sockaddr_storage sas;
+
+ // When the endpoint in socket_watcher_init() didn't specify a port
+ // number, a free random port number will be assigned. sin_port will
+ // contain 0 in this case, unless uv_tcp_getsockname() is used first.
+ uv_tcp_getsockname(&watcher->uv.tcp.handle, (struct sockaddr *)&sas,
+ &(int){ sizeof(sas) });
+ uint16_t port = (uint16_t)((sas.ss_family == AF_INET)
+ ? ((struct sockaddr_in *)&sas)->sin_port
+ : ((struct sockaddr_in6 *)&sas)->sin6_port);
+ // v:servername uses the string from watcher->addr
+ size_t len = strlen(watcher->addr);
+ snprintf(watcher->addr+len, sizeof(watcher->addr)-len, ":%" PRIu16,
+ ntohs(port));
+ break;
+ }
+ }
+ uv_freeaddrinfo(watcher->uv.tcp.addrinfo);
} else {
result = uv_pipe_bind(&watcher->uv.pipe.handle, watcher->addr);
- }
-
- if (result == 0) {
- result = uv_listen(watcher->stream, backlog, connection_cb);
+ if (result == 0) {
+ result = uv_listen(watcher->stream, backlog, connection_cb);
+ }
}
assert(result <= 0); // libuv should return negative error code or zero.
if (result < 0) {
- if (result == -EACCES) {
+ if (result == UV_EACCES) {
// Libuv converts ENOENT to EACCES for Windows compatibility, but if
// the parent directory does not exist, ENOENT would be more accurate.
*path_tail((char_u *)watcher->addr) = NUL;
if (!os_path_exists((char_u *)watcher->addr)) {
- result = -ENOENT;
+ result = UV_ENOENT;
}
}
return result;
@@ -125,6 +147,7 @@ int socket_watcher_accept(SocketWatcher *watcher, Stream *stream)
if (watcher->stream->type == UV_TCP) {
client = STRUCT_CAST(uv_stream_t, &stream->uv.tcp);
uv_tcp_init(watcher->uv.tcp.handle.loop, (uv_tcp_t *)client);
+ uv_tcp_nodelay((uv_tcp_t *)client, true);
} else {
client = STRUCT_CAST(uv_stream_t, &stream->uv.pipe);
uv_pipe_init(watcher->uv.pipe.handle.loop, (uv_pipe_t *)client, 0);
@@ -169,3 +192,77 @@ static void close_cb(uv_handle_t *handle)
watcher->close_cb(watcher, watcher->data);
}
}
+
+static void connect_cb(uv_connect_t *req, int status)
+{
+ int *ret_status = req->data;
+ *ret_status = status;
+ if (status != 0) {
+ uv_close((uv_handle_t *)req->handle, NULL);
+ }
+}
+
+bool socket_connect(Loop *loop, Stream *stream,
+ bool is_tcp, const char *address,
+ int timeout, const char **error)
+{
+ bool success = false;
+ int status;
+ uv_connect_t req;
+ req.data = &status;
+ uv_stream_t *uv_stream;
+
+ uv_tcp_t *tcp = &stream->uv.tcp;
+ uv_getaddrinfo_t addr_req;
+ addr_req.addrinfo = NULL;
+ const struct addrinfo *addrinfo = NULL;
+ char *addr = NULL;
+ if (is_tcp) {
+ addr = xstrdup(address);
+ char *host_end = strrchr(addr, ':');
+ if (!host_end) {
+ *error = _("tcp address must be host:port");
+ goto cleanup;
+ }
+ *host_end = NUL;
+
+ const struct addrinfo hints = { .ai_family = AF_UNSPEC,
+ .ai_socktype = SOCK_STREAM,
+ .ai_flags = AI_NUMERICSERV };
+ int retval = uv_getaddrinfo(&loop->uv, &addr_req, NULL,
+ addr, host_end+1, &hints);
+ if (retval != 0) {
+ *error = _("failed to lookup host or port");
+ goto cleanup;
+ }
+ addrinfo = addr_req.addrinfo;
+
+tcp_retry:
+ uv_tcp_init(&loop->uv, tcp);
+ uv_tcp_nodelay(tcp, true);
+ uv_tcp_connect(&req, tcp, addrinfo->ai_addr, connect_cb);
+ uv_stream = (uv_stream_t *)tcp;
+
+ } else {
+ uv_pipe_t *pipe = &stream->uv.pipe;
+ uv_pipe_init(&loop->uv, pipe, 0);
+ uv_pipe_connect(&req, pipe, address, connect_cb);
+ uv_stream = (uv_stream_t *)pipe;
+ }
+ status = 1;
+ LOOP_PROCESS_EVENTS_UNTIL(&main_loop, NULL, timeout, status != 1);
+ if (status == 0) {
+ stream_init(NULL, stream, -1, uv_stream);
+ success = true;
+ } else if (is_tcp && addrinfo->ai_next) {
+ addrinfo = addrinfo->ai_next;
+ goto tcp_retry;
+ } else {
+ *error = _("connection refused");
+ }
+
+cleanup:
+ xfree(addr);
+ uv_freeaddrinfo(addr_req.addrinfo);
+ return success;
+}
diff --git a/src/nvim/event/socket.h b/src/nvim/event/socket.h
index eb0823c76d..d30ae45502 100644
--- a/src/nvim/event/socket.h
+++ b/src/nvim/event/socket.h
@@ -20,7 +20,7 @@ struct socket_watcher {
union {
struct {
uv_tcp_t handle;
- struct sockaddr_in addr;
+ struct addrinfo *addrinfo;
} tcp;
struct {
uv_pipe_t handle;
diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c
index a528a65abb..8dcb3ac449 100644
--- a/src/nvim/ex_cmds.c
+++ b/src/nvim/ex_cmds.c
@@ -318,14 +318,12 @@ static int sort_abort; ///< flag to indicate if sorting has been interrupted
/// Struct to store info to be sorted.
typedef struct {
linenr_T lnum; ///< line number
- long start_col_nr; ///< starting column number or number
- long end_col_nr; ///< ending column number
union {
struct {
- long start_col_nr; ///< starting column number
- long end_col_nr; ///< ending column number
+ varnumber_T start_col_nr; ///< starting column number
+ varnumber_T end_col_nr; ///< ending column number
} line;
- long value; ///< value if sorting by integer
+ varnumber_T value; ///< value if sorting by integer
float_T value_flt; ///< value if sorting by float
} st_u;
} sorti_T;
@@ -599,9 +597,10 @@ void ex_sort(exarg_T *eap)
// Adjust marks for deleted (or added) lines and prepare for displaying.
deleted = (long)(count - (lnum - eap->line2));
if (deleted > 0) {
- mark_adjust(eap->line2 - deleted, eap->line2, (long)MAXLNUM, -deleted);
+ mark_adjust(eap->line2 - deleted, eap->line2, (long)MAXLNUM, -deleted,
+ false);
} else if (deleted < 0) {
- mark_adjust(eap->line2, MAXLNUM, -deleted, 0L);
+ mark_adjust(eap->line2, MAXLNUM, -deleted, 0L, false);
}
changed_lines(eap->line1, 0, eap->line2 + 1, -deleted);
@@ -796,9 +795,9 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
* 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);
+ mark_adjust_nofold(line1, line2, last_line - line2, 0L, true);
if (dest >= line2) {
- mark_adjust_nofold(line2 + 1, dest, -num_lines, 0L);
+ mark_adjust_nofold(line2 + 1, dest, -num_lines, 0L, false);
FOR_ALL_TAB_WINDOWS(tab, win) {
if (win->w_buffer == curbuf) {
foldMoveRange(&win->w_folds, line1, line2, dest);
@@ -807,7 +806,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
curbuf->b_op_start.lnum = dest - num_lines + 1;
curbuf->b_op_end.lnum = dest;
} else {
- mark_adjust_nofold(dest + 1, line1 - 1, num_lines, 0L);
+ mark_adjust_nofold(dest + 1, line1 - 1, num_lines, 0L, false);
FOR_ALL_TAB_WINDOWS(tab, win) {
if (win->w_buffer == curbuf) {
foldMoveRange(&win->w_folds, dest + 1, line1 - 1, line2);
@@ -818,7 +817,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
}
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
mark_adjust_nofold(last_line - num_lines + 1, last_line,
- -(last_line - dest - extra), 0L);
+ -(last_line - dest - extra), 0L, true);
/*
* Now we delete the original text -- webb
@@ -1214,15 +1213,14 @@ static void do_filter(
if (do_in) {
if (cmdmod.keepmarks || vim_strchr(p_cpo, CPO_REMMARK) == NULL) {
- if (read_linecount >= linecount)
- /* move all marks from old lines to new lines */
- mark_adjust(line1, line2, linecount, 0L);
- else {
- /* move marks from old lines to new lines, delete marks
- * that are in deleted lines */
- mark_adjust(line1, line1 + read_linecount - 1,
- linecount, 0L);
- mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0L);
+ if (read_linecount >= linecount) {
+ // move all marks from old lines to new lines
+ mark_adjust(line1, line2, linecount, 0L, false);
+ } else {
+ // move marks from old lines to new lines, delete marks
+ // that are in deleted lines
+ mark_adjust(line1, line1 + read_linecount - 1, linecount, 0L, false);
+ mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0L, false);
}
}
@@ -3760,7 +3758,7 @@ static buf_T *do_sub(exarg_T *eap, proftime_T timeout)
*p1 = NUL; // truncate up to the CR
ml_append(lnum - 1, new_start,
(colnr_T)(p1 - new_start + 1), false);
- mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
+ mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L, false);
if (subflags.do_ask) {
appended_lines(lnum - 1, 1L);
} else {
@@ -3849,7 +3847,7 @@ skip:
for (i = 0; i < nmatch_tl; ++i)
ml_delete(lnum, (int)FALSE);
mark_adjust(lnum, lnum + nmatch_tl - 1,
- (long)MAXLNUM, -nmatch_tl);
+ (long)MAXLNUM, -nmatch_tl, false);
if (subflags.do_ask) {
deleted_lines(lnum, nmatch_tl);
}
diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c
index a0406cf418..af8845de87 100644
--- a/src/nvim/ex_docmd.c
+++ b/src/nvim/ex_docmd.c
@@ -8847,15 +8847,16 @@ makeopens (
*/
tab_firstwin = firstwin; /* first window in tab page "tabnr" */
tab_topframe = topframe;
- for (tabnr = 1;; ++tabnr) {
+ for (tabnr = 1;; tabnr++) {
+ tabpage_T *tp = find_tabpage(tabnr);
+ if (tp == NULL) {
+ break; // done all tab pages
+ }
+
int need_tabnew = false;
int cnr = 1;
if ((ssop_flags & SSOP_TABPAGES)) {
- tabpage_T *tp = find_tabpage(tabnr);
-
- if (tp == NULL)
- break; /* done all tab pages */
if (tp == curtab) {
tab_firstwin = firstwin;
tab_topframe = topframe;
@@ -8968,6 +8969,16 @@ makeopens (
if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
return FAIL;
+ // Take care of tab-local working directories if applicable
+ if (tp->tp_localdir) {
+ if (fputs("if has('nvim') | tcd ", fd) < 0
+ || ses_put_fname(fd, tp->tp_localdir, &ssop_flags) == FAIL
+ || fputs(" | endif", fd) < 0
+ || put_eol(fd) == FAIL) {
+ return FAIL;
+ }
+ }
+
/* Don't continue in another tab page when doing only the current one
* or when at the last tab page. */
if (!(ssop_flags & SSOP_TABPAGES))
diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c
index 0c14bf4255..858374c68e 100644
--- a/src/nvim/ex_getln.c
+++ b/src/nvim/ex_getln.c
@@ -4073,7 +4073,7 @@ void ExpandGeneric(
/// @param flagsarg is a combination of EW_* flags.
static void expand_shellcmd(char_u *filepat, int *num_file, char_u ***file,
int flagsarg)
- FUNC_ATTR_NONNULL_ALL
+ FUNC_ATTR_NONNULL_ALL
{
char_u *pat;
int i;
@@ -4174,10 +4174,8 @@ static void expand_shellcmd(char_u *filepat, int *num_file, char_u ***file,
}
}
-/*
- * Call "user_expand_func()" to invoke a user defined VimL function and return
- * the result (either a string or a List).
- */
+/// Call "user_expand_func()" to invoke a user defined Vim script function and
+/// return the result (either a string or a List).
static void * call_user_expand_func(user_expand_func_T user_expand_func,
expand_T *xp, int *num_file, char_u ***file)
{
@@ -5004,7 +5002,7 @@ int get_list_range(char_u **str, int *num1, int *num2)
{
int len;
int first = false;
- long num;
+ varnumber_T num;
*str = skipwhite(*str);
if (**str == '-' || ascii_isdigit(**str)) { // parse "from" part of range
diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c
index 4063277403..be4188c4df 100644
--- a/src/nvim/fileio.c
+++ b/src/nvim/fileio.c
@@ -281,8 +281,8 @@ readfile (
colnr_T len;
long size = 0;
char_u *p = NULL;
- off_t filesize = 0;
- int skip_read = FALSE;
+ off_T filesize = 0;
+ int skip_read = false;
context_sha256_T sha_ctx;
int read_undo_file = FALSE;
int split = 0; /* number of split lines */
@@ -777,9 +777,9 @@ retry:
if (read_buffer) {
read_buf_lnum = 1;
read_buf_col = 0;
- } else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0) {
- /* Can't rewind the file, give up. */
- error = TRUE;
+ } else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0) {
+ // Can't rewind the file, give up.
+ error = true;
goto failed;
}
/* Delete the previously read lines. */
@@ -1614,19 +1614,16 @@ rewind_retry:
if (fileformat == EOL_DOS) {
if (ptr[-1] == CAR) { /* remove CR */
ptr[-1] = NUL;
- --len;
- }
- /*
- * Reading in Dos format, but no CR-LF found!
- * When 'fileformats' includes "unix", delete all
- * the lines read so far and start all over again.
- * Otherwise give an error message later.
- */
- else if (ff_error != EOL_DOS) {
- if ( try_unix
- && !read_stdin
- && (read_buffer
- || lseek(fd, (off_t)0L, SEEK_SET) == 0)) {
+ len--;
+ } else if (ff_error != EOL_DOS) {
+ // Reading in Dos format, but no CR-LF found!
+ // When 'fileformats' includes "unix", delete all
+ // the lines read so far and start all over again.
+ // Otherwise give an error message later.
+ if (try_unix
+ && !read_stdin
+ && (read_buffer
+ || vim_lseek(fd, (off_T)0L, SEEK_SET) == 0)) {
fileformat = EOL_UNIX;
if (set_options)
set_fileformat(EOL_UNIX, OPT_LOCAL);
@@ -3833,7 +3830,7 @@ static bool msg_add_fileformat(int eol_type)
/*
* Append line and character count to IObuff.
*/
-void msg_add_lines(int insert_space, long lnum, off_t nchars)
+void msg_add_lines(int insert_space, long lnum, off_T nchars)
{
char_u *p;
@@ -6870,8 +6867,8 @@ static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io,
patcmd.next = active_apc_list;
active_apc_list = &patcmd;
- /* set v:cmdarg (only when there is a matching pattern) */
- save_cmdbang = get_vim_var_nr(VV_CMDBANG);
+ // set v:cmdarg (only when there is a matching pattern)
+ save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
if (eap != NULL) {
save_cmdarg = set_cmdarg(eap, NULL);
set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
diff --git a/src/nvim/fold.c b/src/nvim/fold.c
index 9c44e89eed..db88791967 100644
--- a/src/nvim/fold.c
+++ b/src/nvim/fold.c
@@ -2894,7 +2894,7 @@ static void foldlevelExpr(fline_T *flp)
/* KeyTyped may be reset to 0 when calling a function which invokes
* do_cmdline(). To make 'foldopen' work correctly restore KeyTyped. */
save_keytyped = KeyTyped;
- n = eval_foldexpr(flp->wp->w_p_fde, &c);
+ n = (int)eval_foldexpr(flp->wp->w_p_fde, &c);
KeyTyped = save_keytyped;
switch (c) {
diff --git a/src/nvim/func_attr.h b/src/nvim/func_attr.h
index f1a1d9a563..bd26205d6d 100644
--- a/src/nvim/func_attr.h
+++ b/src/nvim/func_attr.h
@@ -95,6 +95,10 @@
# undef FUNC_ATTR_NORETURN
#endif
+#ifdef FUNC_ATTR_NO_SANITIZE_UNDEFINED
+# undef FUNC_ATTR_NO_SANITIZE_UNDEFINED
+#endif
+
#ifndef DID_REAL_ATTR
# define DID_REAL_ATTR
# ifdef __GNUC__
@@ -122,6 +126,14 @@
# define REAL_FATTR_ALLOC_SIZE(x) __attribute__((alloc_size(x)))
# define REAL_FATTR_ALLOC_SIZE_PROD(x, y) __attribute__((alloc_size(x, y)))
# endif
+
+# if NVIM_HAS_ATTRIBUTE(no_sanitize_undefined)
+# define REAL_FATTR_NO_SANITIZE_UNDEFINED \
+ __attribute__((no_sanitize_undefined))
+# elif NVIM_HAS_ATTRIBUTE(no_sanitize)
+# define REAL_FATTR_NO_SANITIZE_UNDEFINED \
+ __attribute__((no_sanitize("undefined")))
+# endif
# endif
// Define attributes that are not defined for this compiler.
@@ -177,6 +189,10 @@
# ifndef REAL_FATTR_NORETURN
# define REAL_FATTR_NORETURN
# endif
+
+# ifndef REAL_FATTR_NO_SANITIZE_UNDEFINED
+# define REAL_FATTR_NO_SANITIZE_UNDEFINED
+# endif
#endif
#ifdef DEFINE_FUNC_ATTRIBUTES
@@ -198,6 +214,7 @@
# define FUNC_ATTR_NONNULL_ARG(...) REAL_FATTR_NONNULL_ARG(__VA_ARGS__)
# define FUNC_ATTR_NONNULL_RET REAL_FATTR_NONNULL_RET
# define FUNC_ATTR_NORETURN REAL_FATTR_NORETURN
+# define FUNC_ATTR_NO_SANITIZE_UNDEFINED REAL_FATTR_NO_SANITIZE_UNDEFINED
#elif !defined(DO_NOT_DEFINE_EMPTY_ATTRIBUTES)
# define FUNC_ATTR_MALLOC
# define FUNC_ATTR_ALLOC_SIZE(x)
@@ -212,4 +229,5 @@
# define FUNC_ATTR_NONNULL_ARG(...)
# define FUNC_ATTR_NONNULL_RET
# define FUNC_ATTR_NORETURN
+# define FUNC_ATTR_NO_SANITIZE_UNDEFINED
#endif
diff --git a/src/nvim/garray.h b/src/nvim/garray.h
index 5d7806bbfa..94e1b61671 100644
--- a/src/nvim/garray.h
+++ b/src/nvim/garray.h
@@ -37,7 +37,7 @@ typedef struct growarray {
static inline void *ga_append_via_ptr(garray_T *gap, size_t item_size)
{
if ((int)item_size != gap->ga_itemsize) {
- ELOG("wrong item size in garray(%d), should be %d", item_size);
+ WLOG("wrong item size (%d), should be %d", item_size, gap->ga_itemsize);
}
ga_grow(gap, 1);
return ((char *)gap->ga_data) + (item_size * (size_t)gap->ga_len++);
diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c
index c3c393f1ec..4e42042959 100644
--- a/src/nvim/getchar.c
+++ b/src/nvim/getchar.c
@@ -18,6 +18,7 @@
#include "nvim/vim.h"
#include "nvim/ascii.h"
#include "nvim/getchar.h"
+#include "nvim/buffer_defs.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/edit.h"
@@ -47,6 +48,7 @@
#include "nvim/event/loop.h"
#include "nvim/os/input.h"
#include "nvim/os/os.h"
+#include "nvim/api/private/handle.h"
/*
* These buffers are used for storing:
@@ -102,11 +104,10 @@ static int block_redo = FALSE;
(NORMAL + VISUAL + SELECTMODE + \
OP_PENDING)) ? (c1) : ((c1) ^ 0x80))
-/*
- * Each mapping is put in one of the 256 hash lists, to speed up finding it.
- */
-static mapblock_T *(maphash[256]);
-static int maphash_valid = FALSE;
+// Each mapping is put in one of the MAX_MAPHASH hash lists,
+// to speed up finding it.
+static mapblock_T *(maphash[MAX_MAPHASH]);
+static bool maphash_valid = false;
/*
* List used for abbreviations.
@@ -1907,7 +1908,7 @@ static int vgetorpeek(int advance)
}
if ((mp == NULL || max_mlen >= mp_match_len)
- && keylen != KEYLEN_PART_MAP && keylen != KEYLEN_PART_KEY) {
+ && keylen != KEYLEN_PART_MAP) {
// No matching mapping found or found a non-matching mapping that
// matches at least what the matching mapping matched
keylen = 0;
@@ -4237,3 +4238,17 @@ static bool typebuf_match_len(const uint8_t *str, int *mlen)
*mlen = i;
return str[i] == NUL; // matched the whole string
}
+
+/// Retrieve the mapblock at the index either globally or for a certain buffer
+///
+/// @param index The index in the maphash[]
+/// @param buf The buffer to get the maphash from. NULL for global
+mapblock_T *get_maphash(int index, buf_T *buf)
+ FUNC_ATTR_PURE
+{
+ if (index > MAX_MAPHASH) {
+ return NULL;
+ }
+
+ return (buf == NULL) ? maphash[index] : buf->b_maphash[index];
+}
diff --git a/src/nvim/globals.h b/src/nvim/globals.h
index a3657f2122..6d1bd1de12 100644
--- a/src/nvim/globals.h
+++ b/src/nvim/globals.h
@@ -97,6 +97,34 @@ typedef enum {
EXTERN long Rows INIT(= DFLT_ROWS); // nr of rows in the screen
EXTERN long Columns INIT(= DFLT_COLS); // nr of columns in the screen
+// We use 64-bit file functions here, if available. E.g. ftello() returns
+// off_t instead of long, which helps if long is 32 bit and off_t is 64 bit.
+// We assume that when fseeko() is available then ftello() is too.
+// Note that Windows has different function names.
+#if (defined(_MSC_VER) && (_MSC_VER >= 1300)) || defined(__MINGW32__)
+typedef __int64 off_T;
+# ifdef __MINGW32__
+# define vim_lseek lseek64
+# define vim_fseek fseeko64
+# define vim_ftell ftello64
+# else
+# define vim_lseek _lseeki64
+# define vim_fseek _fseeki64
+# define vim_ftell _ftelli64
+# endif
+#else
+typedef off_t off_T;
+# ifdef HAVE_FSEEKO
+# define vim_lseek lseek
+# define vim_ftell ftello
+# define vim_fseek fseeko
+# else
+# define vim_lseek lseek
+# define vim_ftell ftell
+# define vim_fseek(a, b, c) fseek(a, (long)b, c)
+# endif
+#endif
+
/*
* The characters and attributes cached for the screen.
*/
@@ -411,124 +439,6 @@ EXTERN int did_check_timestamps INIT(= FALSE); /* did check timestamps
recently */
EXTERN int no_check_timestamps INIT(= 0); /* Don't check timestamps */
-/*
- * Values for index in highlight_attr[].
- * When making changes, also update hlf_names below!
- */
-typedef enum {
- HLF_8 = 0 /* Meta & special keys listed with ":map", text that is
- displayed different from what it is */
- , HLF_EOB // after the last line in the buffer
- , HLF_TERM // terminal cursor focused
- , HLF_TERMNC // terminal cursor unfocused
- , HLF_AT // @ characters at end of screen, characters that
- // don't really exist in the text
- , HLF_D // directories in CTRL-D listing
- , HLF_E // error messages
- , HLF_I // incremental search
- , HLF_L // last search string
- , HLF_M // "--More--" message
- , HLF_CM // Mode (e.g., "-- INSERT --")
- , HLF_N // line number for ":number" and ":#" commands
- , HLF_CLN // current line number
- , HLF_R // return to continue message and yes/no questions
- , HLF_S // status lines
- , HLF_SNC // status lines of not-current windows
- , HLF_C // column to separate vertically split windows
- , HLF_T // Titles for output from ":set all", ":autocmd" etc.
- , HLF_V // Visual mode
- , HLF_VNC // Visual mode, autoselecting and not clipboard owner
- , HLF_W // warning messages
- , HLF_WM // Wildmenu highlight
- , HLF_FL // Folded line
- , HLF_FC // Fold column
- , HLF_ADD // Added diff line
- , HLF_CHD // Changed diff line
- , HLF_DED // Deleted diff line
- , HLF_TXD // Text Changed in diff line
- , HLF_SC // Sign column
- , HLF_CONCEAL // Concealed text
- , HLF_SPB // SpellBad
- , HLF_SPC // SpellCap
- , HLF_SPR // SpellRare
- , HLF_SPL // SpellLocal
- , HLF_PNI // popup menu normal item
- , HLF_PSI // popup menu selected item
- , HLF_PSB // popup menu scrollbar
- , HLF_PST // popup menu scrollbar thumb
- , HLF_TP // tabpage line
- , HLF_TPS // tabpage line selected
- , HLF_TPF // tabpage line filler
- , HLF_CUC // 'cursurcolumn'
- , HLF_CUL // 'cursurline'
- , HLF_MC // 'colorcolumn'
- , HLF_QFL // selected quickfix line
- , HLF_0 // Whitespace
- , HLF_INACTIVE // NormalNC: Normal text in non-current windows
- , HLF_COUNT // MUST be the last one
-} hlf_T;
-
-EXTERN const char *hlf_names[] INIT(= {
- [HLF_8] = "SpecialKey",
- [HLF_EOB] = "EndOfBuffer",
- [HLF_TERM] = "TermCursor",
- [HLF_TERMNC] = "TermCursorNC",
- [HLF_AT] = "NonText",
- [HLF_D] = "Directory",
- [HLF_E] = "ErrorMsg",
- [HLF_I] = "IncSearch",
- [HLF_L] = "Search",
- [HLF_M] = "MoreMsg",
- [HLF_CM] = "ModeMsg",
- [HLF_N] = "LineNr",
- [HLF_CLN] = "CursorLineNr",
- [HLF_R] = "Question",
- [HLF_S] = "StatusLine",
- [HLF_SNC] = "StatusLineNC",
- [HLF_C] = "VertSplit",
- [HLF_T] = "Title",
- [HLF_V] = "Visual",
- [HLF_VNC] = "VisualNOS",
- [HLF_W] = "WarningMsg",
- [HLF_WM] = "WildMenu",
- [HLF_FL] = "Folded",
- [HLF_FC] = "FoldColumn",
- [HLF_ADD] = "DiffAdd",
- [HLF_CHD] = "DiffChange",
- [HLF_DED] = "DiffDelete",
- [HLF_TXD] = "DiffText",
- [HLF_SC] = "SignColumn",
- [HLF_CONCEAL] = "Conceal",
- [HLF_SPB] = "SpellBad",
- [HLF_SPC] = "SpellCap",
- [HLF_SPR] = "SpellRare",
- [HLF_SPL] = "SpellLocal",
- [HLF_PNI] = "Pmenu",
- [HLF_PSI] = "PmenuSel",
- [HLF_PSB] = "PmenuSbar",
- [HLF_PST] = "PmenuThumb",
- [HLF_TP] = "TabLine",
- [HLF_TPS] = "TabLineSel",
- [HLF_TPF] = "TabLineFill",
- [HLF_CUC] = "CursorColumn",
- [HLF_CUL] = "CursorLine",
- [HLF_MC] = "ColorColumn",
- [HLF_QFL] = "QuickFixLine",
- [HLF_0] = "Whitespace",
- [HLF_INACTIVE] = "NormalNC",
-});
-
-
-EXTERN int highlight_attr[HLF_COUNT]; /* Highl. attr for each context. */
-EXTERN int highlight_user[9]; /* User[1-9] attributes */
-EXTERN int highlight_stlnc[9]; /* On top of user */
-EXTERN int cterm_normal_fg_color INIT(= 0);
-EXTERN int cterm_normal_fg_bold INIT(= 0);
-EXTERN int cterm_normal_bg_color INIT(= 0);
-EXTERN RgbValue normal_fg INIT(= -1);
-EXTERN RgbValue normal_bg INIT(= -1);
-EXTERN RgbValue normal_sp INIT(= -1);
-
EXTERN int autocmd_busy INIT(= FALSE); /* Is apply_autocmds() busy? */
EXTERN int autocmd_no_enter INIT(= FALSE); /* *Enter autocmds disabled */
EXTERN int autocmd_no_leave INIT(= FALSE); /* *Leave autocmds disabled */
@@ -540,7 +450,7 @@ EXTERN int keep_filetype INIT(= FALSE); /* value for did_filetype when
// When deleting the current buffer, another one must be loaded.
// If we know which one is preferred, au_new_curbuf is set to it.
-EXTERN bufref_T au_new_curbuf INIT(= { NULL, 0 });
+EXTERN bufref_T au_new_curbuf INIT(= { NULL, 0, 0 });
// When deleting a buffer/window and autocmd_busy is TRUE, do not free the
// buffer/window. but link it in the list starting with
@@ -987,7 +897,7 @@ EXTERN int did_cursorhold INIT(= false); // set when CursorHold t'gerd
// for CursorMoved event
EXTERN pos_T last_cursormoved INIT(= INIT_POS_T(0, 0, 0));
-EXTERN int last_changedtick INIT(= 0); // for TextChanged event
+EXTERN varnumber_T last_changedtick INIT(= 0); // for TextChanged event
EXTERN buf_T *last_changedtick_buf INIT(= NULL);
EXTERN int postponed_split INIT(= 0); /* for CTRL-W CTRL-] command */
@@ -1221,6 +1131,7 @@ EXTERN char_u e_longname[] INIT(= N_("E75: Name too long"));
EXTERN char_u e_toomsbra[] INIT(= N_("E76: Too many ["));
EXTERN char_u e_toomany[] INIT(= N_("E77: Too many file names"));
EXTERN char_u e_trailing[] INIT(= N_("E488: Trailing characters"));
+EXTERN char_u e_trailing2[] INIT(= N_("E488: Trailing characters: %s"));
EXTERN char_u e_umark[] INIT(= N_("E78: Unknown mark"));
EXTERN char_u e_wildexpand[] INIT(= N_("E79: Cannot expand wildcards"));
EXTERN char_u e_winheight[] INIT(= N_(
diff --git a/src/nvim/highlight_defs.h b/src/nvim/highlight_defs.h
new file mode 100644
index 0000000000..927fc94bbe
--- /dev/null
+++ b/src/nvim/highlight_defs.h
@@ -0,0 +1,126 @@
+#ifndef NVIM_HIGHLIGHT_DEFS_H
+#define NVIM_HIGHLIGHT_DEFS_H
+
+#include <inttypes.h>
+
+#include "nvim/macros.h"
+
+typedef int32_t RgbValue;
+
+/// Values for index in highlight_attr[].
+/// When making changes, also update hlf_names below!
+typedef enum {
+ HLF_8 = 0 // Meta & special keys listed with ":map", text that is
+ // displayed different from what it is
+ , HLF_EOB // after the last line in the buffer
+ , HLF_TERM // terminal cursor focused
+ , HLF_TERMNC // terminal cursor unfocused
+ , HLF_AT // @ characters at end of screen, characters that
+ // don't really exist in the text
+ , HLF_D // directories in CTRL-D listing
+ , HLF_E // error messages
+ , HLF_I // incremental search
+ , HLF_L // last search string
+ , HLF_M // "--More--" message
+ , HLF_CM // Mode (e.g., "-- INSERT --")
+ , HLF_N // line number for ":number" and ":#" commands
+ , HLF_CLN // current line number
+ , HLF_R // return to continue message and yes/no questions
+ , HLF_S // status lines
+ , HLF_SNC // status lines of not-current windows
+ , HLF_C // column to separate vertically split windows
+ , HLF_T // Titles for output from ":set all", ":autocmd" etc.
+ , HLF_V // Visual mode
+ , HLF_VNC // Visual mode, autoselecting and not clipboard owner
+ , HLF_W // warning messages
+ , HLF_WM // Wildmenu highlight
+ , HLF_FL // Folded line
+ , HLF_FC // Fold column
+ , HLF_ADD // Added diff line
+ , HLF_CHD // Changed diff line
+ , HLF_DED // Deleted diff line
+ , HLF_TXD // Text Changed in diff line
+ , HLF_SC // Sign column
+ , HLF_CONCEAL // Concealed text
+ , HLF_SPB // SpellBad
+ , HLF_SPC // SpellCap
+ , HLF_SPR // SpellRare
+ , HLF_SPL // SpellLocal
+ , HLF_PNI // popup menu normal item
+ , HLF_PSI // popup menu selected item
+ , HLF_PSB // popup menu scrollbar
+ , HLF_PST // popup menu scrollbar thumb
+ , HLF_TP // tabpage line
+ , HLF_TPS // tabpage line selected
+ , HLF_TPF // tabpage line filler
+ , HLF_CUC // 'cursurcolumn'
+ , HLF_CUL // 'cursurline'
+ , HLF_MC // 'colorcolumn'
+ , HLF_QFL // selected quickfix line
+ , HLF_0 // Whitespace
+ , HLF_INACTIVE // NormalNC: Normal text in non-current windows
+ , HLF_COUNT // MUST be the last one
+} hlf_T;
+
+EXTERN const char *hlf_names[] INIT(= {
+ [HLF_8] = "SpecialKey",
+ [HLF_EOB] = "EndOfBuffer",
+ [HLF_TERM] = "TermCursor",
+ [HLF_TERMNC] = "TermCursorNC",
+ [HLF_AT] = "NonText",
+ [HLF_D] = "Directory",
+ [HLF_E] = "ErrorMsg",
+ [HLF_I] = "IncSearch",
+ [HLF_L] = "Search",
+ [HLF_M] = "MoreMsg",
+ [HLF_CM] = "ModeMsg",
+ [HLF_N] = "LineNr",
+ [HLF_CLN] = "CursorLineNr",
+ [HLF_R] = "Question",
+ [HLF_S] = "StatusLine",
+ [HLF_SNC] = "StatusLineNC",
+ [HLF_C] = "VertSplit",
+ [HLF_T] = "Title",
+ [HLF_V] = "Visual",
+ [HLF_VNC] = "VisualNC",
+ [HLF_W] = "WarningMsg",
+ [HLF_WM] = "WildMenu",
+ [HLF_FL] = "Folded",
+ [HLF_FC] = "FoldColumn",
+ [HLF_ADD] = "DiffAdd",
+ [HLF_CHD] = "DiffChange",
+ [HLF_DED] = "DiffDelete",
+ [HLF_TXD] = "DiffText",
+ [HLF_SC] = "SignColumn",
+ [HLF_CONCEAL] = "Conceal",
+ [HLF_SPB] = "SpellBad",
+ [HLF_SPC] = "SpellCap",
+ [HLF_SPR] = "SpellRare",
+ [HLF_SPL] = "SpellLocal",
+ [HLF_PNI] = "Pmenu",
+ [HLF_PSI] = "PmenuSel",
+ [HLF_PSB] = "PmenuSbar",
+ [HLF_PST] = "PmenuThumb",
+ [HLF_TP] = "TabLine",
+ [HLF_TPS] = "TabLineSel",
+ [HLF_TPF] = "TabLineFill",
+ [HLF_CUC] = "CursorColumn",
+ [HLF_CUL] = "CursorLine",
+ [HLF_MC] = "ColorColumn",
+ [HLF_QFL] = "QuickFixLine",
+ [HLF_0] = "Whitespace",
+ [HLF_INACTIVE] = "NormalNC"
+});
+
+
+EXTERN int highlight_attr[HLF_COUNT]; // Highl. attr for each context.
+EXTERN int highlight_user[9]; // User[1-9] attributes
+EXTERN int highlight_stlnc[9]; // On top of user
+EXTERN int cterm_normal_fg_color INIT(= 0);
+EXTERN int cterm_normal_fg_bold INIT(= 0);
+EXTERN int cterm_normal_bg_color INIT(= 0);
+EXTERN RgbValue normal_fg INIT(= -1);
+EXTERN RgbValue normal_bg INIT(= -1);
+EXTERN RgbValue normal_sp INIT(= -1);
+
+#endif // NVIM_HIGHLIGHT_DEFS_H
diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c
index e1c7df9175..f7706f5a0d 100644
--- a/src/nvim/if_cscope.c
+++ b/src/nvim/if_cscope.c
@@ -1972,7 +1972,7 @@ static void cs_release_csp(size_t i, int freefnpp)
static int cs_reset(exarg_T *eap)
{
char **dblist = NULL, **pplist = NULL, **fllist = NULL;
- char buf[20]; /* for snprintf " (#%zu)" */
+ char buf[25]; // for snprintf " (#%zu)"
if (csinfo_size == 0)
return CSCOPE_SUCCESS;
diff --git a/src/nvim/indent.c b/src/nvim/indent.c
index 5471b41b2c..efca739c2d 100644
--- a/src/nvim/indent.c
+++ b/src/nvim/indent.c
@@ -471,7 +471,7 @@ int get_breakindent_win(win_T *wp, char_u *line) {
|| prev_tick != wp->w_buffer->b_changedtick) {
prev_line = line;
prev_ts = wp->w_buffer->b_p_ts;
- prev_tick = wp->w_buffer->b_changedtick;
+ prev_tick = (int)wp->w_buffer->b_changedtick;
prev_indent = get_indent_str(line,
(int)wp->w_buffer->b_p_ts, wp->w_p_list);
}
@@ -538,7 +538,7 @@ int get_expr_indent(void)
sandbox++;
}
textlock++;
- indent = eval_to_number(curbuf->b_p_inde);
+ indent = (int)eval_to_number(curbuf->b_p_inde);
if (use_sandbox) {
sandbox--;
diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c
index 4806f46705..fd194a4080 100644
--- a/src/nvim/indent_c.c
+++ b/src/nvim/indent_c.c
@@ -822,21 +822,22 @@ cin_isterminated (
return found_start;
}
-/*
- * Recognize the basic picture of a function declaration -- it needs to
- * have an open paren somewhere and a close paren at the end of the line and
- * no semicolons anywhere.
- * When a line ends in a comma we continue looking in the next line.
- * "sp" points to a string with the line. When looking at other lines it must
- * be restored to the line. When it's NULL fetch lines here.
- * "lnum" is where we start looking.
- * "min_lnum" is the line before which we will not be looking.
- */
+/// Recognizes the basic picture of a function declaration -- it needs to
+/// have an open paren somewhere and a close paren at the end of the line and
+/// no semicolons anywhere.
+/// When a line ends in a comma we continue looking in the next line.
+///
+/// @param[in] sp Points to a string with the line. When looking at other
+/// lines it must be restored to the line. When it's NULL fetch
+/// lines here.
+/// @param[in] first_lnum Where to start looking.
+/// @param[in] min_lnum The line before which we will not be looking.
static int cin_isfuncdecl(char_u **sp, linenr_T first_lnum, linenr_T min_lnum)
{
char_u *s;
linenr_T lnum = first_lnum;
- int retval = FALSE;
+ linenr_T save_lnum = curwin->w_cursor.lnum;
+ int retval = false;
pos_T *trypos;
int just_started = TRUE;
@@ -845,18 +846,22 @@ static int cin_isfuncdecl(char_u **sp, linenr_T first_lnum, linenr_T min_lnum)
else
s = *sp;
+ curwin->w_cursor.lnum = lnum;
if (find_last_paren(s, '(', ')')
&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
lnum = trypos->lnum;
- if (lnum < min_lnum)
- return FALSE;
-
+ if (lnum < min_lnum) {
+ curwin->w_cursor.lnum = save_lnum;
+ return false;
+ }
s = ml_get(lnum);
}
- /* Ignore line starting with #. */
- if (cin_ispreproc(s))
- return FALSE;
+ curwin->w_cursor.lnum = save_lnum;
+ // Ignore line starting with #.
+ if (cin_ispreproc(s)) {
+ return false;
+ }
while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"') {
// ignore comments
diff --git a/src/nvim/keymap.c b/src/nvim/keymap.c
index 9c5fe78c7c..ee67b4c19d 100644
--- a/src/nvim/keymap.c
+++ b/src/nvim/keymap.c
@@ -557,7 +557,7 @@ int find_special_key(const char_u **srcp, const size_t src_len, int *const modp,
int modifiers;
int bit;
int key;
- unsigned long n;
+ uvarnumber_T n;
int l;
if (src_len == 0) {
diff --git a/src/nvim/lib/kbtree.h b/src/nvim/lib/kbtree.h
new file mode 100644
index 0000000000..a3943054e6
--- /dev/null
+++ b/src/nvim/lib/kbtree.h
@@ -0,0 +1,451 @@
+/*-
+ * Copyright 1997-1999, 2001, John-Mark Gurney.
+ * 2008-2009, Attractive Chaos <attractor@live.co.uk>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef NVIM_LIB_KBTREE_H
+#define NVIM_LIB_KBTREE_H
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "nvim/memory.h"
+
+#define KB_MAX_DEPTH 64
+
+#define __KB_KEY(type, x) (x->key)
+#define __KB_PTR(btr, x) (x->ptr)
+
+#define __KB_TREE_T(name,key_t,T) \
+ typedef struct kbnode_##name##_s kbnode_##name##_t; \
+ struct kbnode_##name##_s { \
+ int32_t n; \
+ bool is_internal; \
+ key_t key[2*T-1]; \
+ kbnode_##name##_t *ptr[]; \
+ } ; \
+ \
+ typedef struct { \
+ kbnode_##name##_t *root; \
+ int n_keys, n_nodes; \
+ } kbtree_##name##_t; \
+ \
+ typedef struct { \
+ kbnode_##name##_t *x; \
+ int i; \
+ } kbpos_##name##_t; \
+ typedef struct { \
+ kbpos_##name##_t stack[KB_MAX_DEPTH], *p; \
+ } kbitr_##name##_t; \
+
+
+#define __kb_destroy(kbnode_t,b) do { \
+ int i; \
+ unsigned int max = 8; \
+ kbnode_t *x, **top, **stack = 0; \
+ if (b->root) { \
+ top = stack = (kbnode_t**)xcalloc(max, sizeof(kbnode_t*)); \
+ *top++ = (b)->root; \
+ while (top != stack) { \
+ x = *--top; \
+ if (x->is_internal == 0) { xfree(x); continue; } \
+ for (i = 0; i <= x->n; ++i) \
+ if (__KB_PTR(b, x)[i]) { \
+ if (top - stack == (int)max) { \
+ max <<= 1; \
+ stack = (kbnode_t**)xrealloc(stack, max * sizeof(kbnode_t*)); \
+ top = stack + (max>>1); \
+ } \
+ *top++ = __KB_PTR(b, x)[i]; \
+ } \
+ xfree(x); \
+ } \
+ } \
+ xfree(stack); \
+ } while (0)
+
+#define __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \
+ static inline int __kb_getp_aux_##name(const kbnode_t * __restrict x, key_t * __restrict k, int *r) \
+ { \
+ int tr, *rr, begin = 0, end = x->n; \
+ if (x->n == 0) return -1; \
+ rr = r? r : &tr; \
+ while (begin < end) { \
+ int mid = (begin + end) >> 1; \
+ if (__cmp(__KB_KEY(key_t, x)[mid], *k) < 0) begin = mid + 1; \
+ else end = mid; \
+ } \
+ if (begin == x->n) { *rr = 1; return x->n - 1; } \
+ if ((*rr = __cmp(*k, __KB_KEY(key_t, x)[begin])) < 0) --begin; \
+ return begin; \
+ }
+
+#define __KB_GET(name, key_t, kbnode_t) \
+ static key_t *kb_getp_##name(kbtree_##name##_t *b, key_t * __restrict k) \
+ { \
+ if (!b->root) { \
+ return 0; \
+ } \
+ int i, r = 0; \
+ kbnode_t *x = b->root; \
+ while (x) { \
+ i = __kb_getp_aux_##name(x, k, &r); \
+ if (i >= 0 && r == 0) return &__KB_KEY(key_t, x)[i]; \
+ if (x->is_internal == 0) return 0; \
+ x = __KB_PTR(b, x)[i + 1]; \
+ } \
+ return 0; \
+ } \
+ static inline key_t *kb_get_##name(kbtree_##name##_t *b, key_t k) \
+ { \
+ return kb_getp_##name(b, &k); \
+ }
+
+#define __KB_INTERVAL(name, key_t, kbnode_t) \
+ static inline void kb_intervalp_##name(kbtree_##name##_t *b, key_t * __restrict k, key_t **lower, key_t **upper) \
+ { \
+ if (!b->root) { \
+ return; \
+ } \
+ int i, r = 0; \
+ kbnode_t *x = b->root; \
+ *lower = *upper = 0; \
+ while (x) { \
+ i = __kb_getp_aux_##name(x, k, &r); \
+ if (i >= 0 && r == 0) { \
+ *lower = *upper = &__KB_KEY(key_t, x)[i]; \
+ return; \
+ } \
+ if (i >= 0) *lower = &__KB_KEY(key_t, x)[i]; \
+ if (i < x->n - 1) *upper = &__KB_KEY(key_t, x)[i + 1]; \
+ if (x->is_internal == 0) return; \
+ x = __KB_PTR(b, x)[i + 1]; \
+ } \
+ } \
+ static inline void kb_interval_##name(kbtree_##name##_t *b, key_t k, key_t **lower, key_t **upper) \
+ { \
+ kb_intervalp_##name(b, &k, lower, upper); \
+ }
+
+#define __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \
+ /* x must be an internal node */ \
+ static inline void __kb_split_##name(kbtree_##name##_t *b, kbnode_t *x, int i, kbnode_t *y) \
+ { \
+ kbnode_t *z; \
+ z = (kbnode_t*)xcalloc(1, y->is_internal? ILEN : sizeof(kbnode_##name##_t)); \
+ ++b->n_nodes; \
+ z->is_internal = y->is_internal; \
+ z->n = T - 1; \
+ memcpy(__KB_KEY(key_t, z), &__KB_KEY(key_t, y)[T], sizeof(key_t) * (T - 1)); \
+ if (y->is_internal) memcpy(__KB_PTR(b, z), &__KB_PTR(b, y)[T], sizeof(void*) * T); \
+ y->n = T - 1; \
+ memmove(&__KB_PTR(b, x)[i + 2], &__KB_PTR(b, x)[i + 1], sizeof(void*) * (unsigned int)(x->n - i)); \
+ __KB_PTR(b, x)[i + 1] = z; \
+ memmove(&__KB_KEY(key_t, x)[i + 1], &__KB_KEY(key_t, x)[i], sizeof(key_t) * (unsigned int)(x->n - i)); \
+ __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[T - 1]; \
+ ++x->n; \
+ } \
+ static inline key_t *__kb_putp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k) \
+ { \
+ int i = x->n - 1; \
+ key_t *ret; \
+ if (x->is_internal == 0) { \
+ i = __kb_getp_aux_##name(x, k, 0); \
+ if (i != x->n - 1) \
+ memmove(&__KB_KEY(key_t, x)[i + 2], &__KB_KEY(key_t, x)[i + 1], (unsigned int)(x->n - i - 1) * sizeof(key_t)); \
+ ret = &__KB_KEY(key_t, x)[i + 1]; \
+ *ret = *k; \
+ ++x->n; \
+ } else { \
+ i = __kb_getp_aux_##name(x, k, 0) + 1; \
+ if (__KB_PTR(b, x)[i]->n == 2 * T - 1) { \
+ __kb_split_##name(b, x, i, __KB_PTR(b, x)[i]); \
+ if (__cmp(*k, __KB_KEY(key_t, x)[i]) > 0) ++i; \
+ } \
+ ret = __kb_putp_aux_##name(b, __KB_PTR(b, x)[i], k); \
+ } \
+ return ret; \
+ } \
+ static inline key_t *kb_putp_##name(kbtree_##name##_t *b, key_t * __restrict k) \
+ { \
+ if (!b->root) { \
+ b->root = (kbnode_t*)xcalloc(1, ILEN); \
+ ++b->n_nodes; \
+ } \
+ kbnode_t *r, *s; \
+ ++b->n_keys; \
+ r = b->root; \
+ if (r->n == 2 * T - 1) { \
+ ++b->n_nodes; \
+ s = (kbnode_t*)xcalloc(1, ILEN); \
+ b->root = s; s->is_internal = 1; s->n = 0; \
+ __KB_PTR(b, s)[0] = r; \
+ __kb_split_##name(b, s, 0, r); \
+ r = s; \
+ } \
+ return __kb_putp_aux_##name(b, r, k); \
+ } \
+ static inline void kb_put_##name(kbtree_##name##_t *b, key_t k) \
+ { \
+ kb_putp_##name(b, &k); \
+ }
+
+
+#define __KB_DEL(name, key_t, kbnode_t, T) \
+ static inline key_t __kb_delp_aux_##name(kbtree_##name##_t *b, kbnode_t *x, key_t * __restrict k, int s) \
+ { \
+ int yn, zn, i, r = 0; \
+ kbnode_t *xp, *y, *z; \
+ key_t kp; \
+ if (x == 0) return *k; \
+ if (s) { /* s can only be 0, 1 or 2 */ \
+ r = x->is_internal == 0? 0 : s == 1? 1 : -1; \
+ i = s == 1? x->n - 1 : -1; \
+ } else i = __kb_getp_aux_##name(x, k, &r); \
+ if (x->is_internal == 0) { \
+ if (s == 2) ++i; \
+ kp = __KB_KEY(key_t, x)[i]; \
+ memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, x)[i + 1], (unsigned int)(x->n - i - 1) * sizeof(key_t)); \
+ --x->n; \
+ return kp; \
+ } \
+ if (r == 0) { \
+ if ((yn = __KB_PTR(b, x)[i]->n) >= T) { \
+ xp = __KB_PTR(b, x)[i]; \
+ kp = __KB_KEY(key_t, x)[i]; \
+ __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 1); \
+ return kp; \
+ } else if ((zn = __KB_PTR(b, x)[i + 1]->n) >= T) { \
+ xp = __KB_PTR(b, x)[i + 1]; \
+ kp = __KB_KEY(key_t, x)[i]; \
+ __KB_KEY(key_t, x)[i] = __kb_delp_aux_##name(b, xp, 0, 2); \
+ return kp; \
+ } else if (yn == T - 1 && zn == T - 1) { \
+ y = __KB_PTR(b, x)[i]; z = __KB_PTR(b, x)[i + 1]; \
+ __KB_KEY(key_t, y)[y->n++] = *k; \
+ memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, z), (unsigned int)z->n * sizeof(key_t)); \
+ if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, z), (unsigned int)(z->n + 1) * sizeof(void*)); \
+ y->n += z->n; \
+ memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, x)[i + 1], (unsigned int)(x->n - i - 1) * sizeof(key_t)); \
+ memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, x)[i + 2], (unsigned int)(x->n - i - 1) * sizeof(void*)); \
+ --x->n; \
+ xfree(z); \
+ return __kb_delp_aux_##name(b, y, k, s); \
+ } \
+ } \
+ ++i; \
+ if ((xp = __KB_PTR(b, x)[i])->n == T - 1) { \
+ if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n >= T) { \
+ memmove(&__KB_KEY(key_t, xp)[1], __KB_KEY(key_t, xp), (unsigned int)xp->n * sizeof(key_t)); \
+ if (xp->is_internal) memmove(&__KB_PTR(b, xp)[1], __KB_PTR(b, xp), (unsigned int)(xp->n + 1) * sizeof(void*)); \
+ __KB_KEY(key_t, xp)[0] = __KB_KEY(key_t, x)[i - 1]; \
+ __KB_KEY(key_t, x)[i - 1] = __KB_KEY(key_t, y)[y->n - 1]; \
+ if (xp->is_internal) __KB_PTR(b, xp)[0] = __KB_PTR(b, y)[y->n]; \
+ --y->n; ++xp->n; \
+ } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n >= T) { \
+ __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \
+ __KB_KEY(key_t, x)[i] = __KB_KEY(key_t, y)[0]; \
+ if (xp->is_internal) __KB_PTR(b, xp)[xp->n] = __KB_PTR(b, y)[0]; \
+ --y->n; \
+ memmove(__KB_KEY(key_t, y), &__KB_KEY(key_t, y)[1], (unsigned int)y->n * sizeof(key_t)); \
+ if (y->is_internal) memmove(__KB_PTR(b, y), &__KB_PTR(b, y)[1], (unsigned int)(y->n + 1) * sizeof(void*)); \
+ } else if (i > 0 && (y = __KB_PTR(b, x)[i - 1])->n == T - 1) { \
+ __KB_KEY(key_t, y)[y->n++] = __KB_KEY(key_t, x)[i - 1]; \
+ memmove(&__KB_KEY(key_t, y)[y->n], __KB_KEY(key_t, xp), (unsigned int)xp->n * sizeof(key_t)); \
+ if (y->is_internal) memmove(&__KB_PTR(b, y)[y->n], __KB_PTR(b, xp), (unsigned int)(xp->n + 1) * sizeof(void*)); \
+ y->n += xp->n; \
+ memmove(&__KB_KEY(key_t, x)[i - 1], &__KB_KEY(key_t, x)[i], (unsigned int)(x->n - i) * sizeof(key_t)); \
+ memmove(&__KB_PTR(b, x)[i], &__KB_PTR(b, x)[i + 1], (unsigned int)(x->n - i) * sizeof(void*)); \
+ --x->n; \
+ xfree(xp); \
+ xp = y; \
+ } else if (i < x->n && (y = __KB_PTR(b, x)[i + 1])->n == T - 1) { \
+ __KB_KEY(key_t, xp)[xp->n++] = __KB_KEY(key_t, x)[i]; \
+ memmove(&__KB_KEY(key_t, xp)[xp->n], __KB_KEY(key_t, y), (unsigned int)y->n * sizeof(key_t)); \
+ if (xp->is_internal) memmove(&__KB_PTR(b, xp)[xp->n], __KB_PTR(b, y), (unsigned int)(y->n + 1) * sizeof(void*)); \
+ xp->n += y->n; \
+ memmove(&__KB_KEY(key_t, x)[i], &__KB_KEY(key_t, x)[i + 1], (unsigned int)(x->n - i - 1) * sizeof(key_t)); \
+ memmove(&__KB_PTR(b, x)[i + 1], &__KB_PTR(b, x)[i + 2], (unsigned int)(x->n - i - 1) * sizeof(void*)); \
+ --x->n; \
+ xfree(y); \
+ } \
+ } \
+ return __kb_delp_aux_##name(b, xp, k, s); \
+ } \
+ static inline key_t kb_delp_##name(kbtree_##name##_t *b, key_t * __restrict k) \
+ { \
+ kbnode_t *x; \
+ key_t ret; \
+ ret = __kb_delp_aux_##name(b, b->root, k, 0); \
+ --b->n_keys; \
+ if (b->root->n == 0 && b->root->is_internal) { \
+ --b->n_nodes; \
+ x = b->root; \
+ b->root = __KB_PTR(b, x)[0]; \
+ xfree(x); \
+ } \
+ return ret; \
+ } \
+ static inline key_t kb_del_##name(kbtree_##name##_t *b, key_t k) \
+ { \
+ return kb_delp_##name(b, &k); \
+ }
+
+#define __KB_ITR(name, key_t, kbnode_t) \
+ static inline void kb_itr_first_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \
+ { \
+ itr->p = 0; \
+ if (b->n_keys == 0) return; \
+ itr->p = itr->stack; \
+ itr->p->x = b->root; itr->p->i = 0; \
+ while (itr->p->x->is_internal && __KB_PTR(b, itr->p->x)[0] != 0) { \
+ kbnode_t *x = itr->p->x; \
+ ++itr->p; \
+ itr->p->x = __KB_PTR(b, x)[0]; itr->p->i = 0; \
+ } \
+ } \
+ static inline int kb_itr_next_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \
+ { \
+ if (itr->p < itr->stack) return 0; \
+ for (;;) { \
+ ++itr->p->i; \
+ while (itr->p->x && itr->p->i <= itr->p->x->n) { \
+ itr->p[1].i = 0; \
+ itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[itr->p->i] : 0; \
+ ++itr->p; \
+ } \
+ --itr->p; \
+ if (itr->p < itr->stack) return 0; \
+ if (itr->p->x && itr->p->i < itr->p->x->n) return 1; \
+ } \
+ } \
+ static inline int kb_itr_prev_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \
+ { \
+ if (itr->p < itr->stack) return 0; \
+ for (;;) { \
+ while (itr->p->x && itr->p->i >= 0) { \
+ itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[itr->p->i] : 0; \
+ itr->p[1].i = itr->p[1].x ? itr->p[1].x->n : -1; \
+ ++itr->p; \
+ } \
+ --itr->p; \
+ if (itr->p < itr->stack) return 0; \
+ --itr->p->i; \
+ if (itr->p->x && itr->p->i >= 0) return 1; \
+ } \
+ } \
+ static inline int kb_itr_getp_##name(kbtree_##name##_t *b, key_t * __restrict k, kbitr_##name##_t *itr) \
+ { \
+ if (b->n_keys == 0) { \
+ itr->p = NULL; \
+ return 0; \
+ } \
+ int i, r = 0; \
+ itr->p = itr->stack; \
+ itr->p->x = b->root; \
+ while (itr->p->x) { \
+ i = __kb_getp_aux_##name(itr->p->x, k, &r); \
+ itr->p->i = i; \
+ if (i >= 0 && r == 0) return 1; \
+ ++itr->p->i; \
+ itr->p[1].x = itr->p->x->is_internal? __KB_PTR(b, itr->p->x)[i + 1] : 0; \
+ ++itr->p; \
+ } \
+ return 0; \
+ } \
+ static inline int kb_itr_get_##name(kbtree_##name##_t *b, key_t k, kbitr_##name##_t *itr) \
+ { \
+ return kb_itr_getp_##name(b,&k,itr); \
+ } \
+ static inline void kb_del_itr_##name(kbtree_##name##_t *b, kbitr_##name##_t *itr) \
+ { \
+ key_t k = kb_itr_key(itr); \
+ kb_delp_##name(b, &k); \
+ kb_itr_getp_##name(b, &k, itr); \
+ }
+
+#define KBTREE_INIT(name, key_t, __cmp, T) \
+ KBTREE_INIT_IMPL(name, key_t, kbnode_##name##_t, __cmp, T, (sizeof(kbnode_##name##_t)+(2*T)*sizeof(void *)))
+
+#if (!defined(__clang__) && !defined(__INTEL_COMPILER)) && (__GNUC__ > 4 )
+
+// The index trickery shouldn't be UB anymore,
+// still it is to much for gcc:s -Werror=array-bounds
+# define __KB_PRAGMA_START \
+ _Pragma("GCC diagnostic push") \
+ _Pragma("GCC diagnostic ignored \"-Warray-bounds\"")
+
+# define __KB_PRAGMA_END \
+ _Pragma("GCC diagnostic pop") \
+
+#else
+
+# define __KB_PRAGMA_START
+# define __KB_PRAGMA_END
+
+#endif
+
+#define KBTREE_INIT_IMPL(name, key_t, kbnode_t, __cmp, T, ILEN) \
+ __KB_PRAGMA_START \
+ __KB_TREE_T(name, key_t, T) \
+ __KB_GET_AUX1(name, key_t, kbnode_t, __cmp) \
+ __KB_GET(name, key_t, kbnode_t) \
+ __KB_INTERVAL(name, key_t, kbnode_t) \
+ __KB_PUT(name, key_t, kbnode_t, __cmp, T, ILEN) \
+ __KB_DEL(name, key_t, kbnode_t, T) \
+ __KB_ITR(name, key_t, kbnode_t) \
+ __KB_PRAGMA_END
+
+#define KB_DEFAULT_SIZE 512
+
+#define kbtree_t(name) kbtree_##name##_t
+#define kbitr_t(name) kbitr_##name##_t
+#define kb_init(b) ((b)->n_keys = (b)->n_nodes = 0, (b)->root = 0)
+#define kb_destroy(name, b) __kb_destroy(kbnode_##name##_t, b)
+#define kb_get(name, b, k) kb_get_##name(b, k)
+#define kb_put(name, b, k) kb_put_##name(b, k)
+#define kb_del(name, b, k) kb_del_##name(b, k)
+#define kb_interval(name, b, k, l, u) kb_interval_##name(b, k, l, u)
+#define kb_getp(name, b, k) kb_getp_##name(b, k)
+#define kb_putp(name, b, k) kb_putp_##name(b, k)
+#define kb_delp(name, b, k) kb_delp_##name(b, k)
+#define kb_intervalp(name, b, k, l, u) kb_intervalp_##name(b, k, l, u)
+
+#define kb_itr_first(name, b, i) kb_itr_first_##name(b, i)
+#define kb_itr_get(name, b, k, i) kb_itr_get_##name(b, k, i)
+#define kb_itr_getp(name, b, k, i) kb_itr_getp_##name(b, k, i)
+#define kb_itr_next(name, b, i) kb_itr_next_##name(b, i)
+#define kb_itr_prev(name, b, i) kb_itr_prev_##name(b, i)
+#define kb_del_itr(name, b, i) kb_del_itr_##name(b, i)
+#define kb_itr_key(itr) __KB_KEY(dummy, (itr)->p->x)[(itr)->p->i]
+#define kb_itr_valid(itr) ((itr)->p >= (itr)->stack)
+
+#define kb_size(b) ((b)->n_keys)
+
+#define kb_generic_cmp(a, b) (((b) < (a)) - ((a) < (b)))
+#define kb_str_cmp(a, b) strcmp(a, b)
+
+#endif // NVIM_LIB_KBTREE_H
diff --git a/src/nvim/log.c b/src/nvim/log.c
index d059e28d5d..f1dbe61dda 100644
--- a/src/nvim/log.c
+++ b/src/nvim/log.c
@@ -7,20 +7,17 @@
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
+#include <uv.h>
#include "nvim/log.h"
#include "nvim/types.h"
#include "nvim/os/os.h"
#include "nvim/os/time.h"
-/// First location of the log file used by log_path_init()
-#define USR_LOG_FILE "$NVIM_LOG_FILE"
+#define LOG_FILE_ENV "NVIM_LOG_FILE"
-/// Fall back location of the log file used by log_path_init()
-#define USR_LOG_FILE_2 "$HOME" _PATHSEPSTR ".nvimlog"
-
-/// Cached location of the log file set by log_path_init()
-static char expanded_log_file_path[MAXPATHL + 1] = { 0 };
+/// Cached location of the expanded log file path decided by log_path_init().
+static char log_file_path[MAXPATHL + 1] = { 0 };
static uv_mutex_t mutex;
@@ -28,31 +25,53 @@ static uv_mutex_t mutex;
# include "log.c.generated.h"
#endif
-/// Initialize path to log file
+static bool log_try_create(char *fname)
+{
+ if (fname == NULL || fname[0] == '\0') {
+ return false;
+ }
+ FILE *log_file = fopen(fname, "a");
+ if (log_file == NULL) {
+ return false;
+ }
+ fclose(log_file);
+ return true;
+}
+
+/// Initializes path to log file. Sets $NVIM_LOG_FILE if empty.
///
-/// Tries to use #USR_LOG_FILE, then falls back #USR_LOG_FILE_2. Path to log
+/// Tries $NVIM_LOG_FILE, or falls back to $XDG_DATA_HOME/nvim/log. Path to log
/// file is cached, so only the first call has effect, unless first call was not
-/// successful. To make initialization not succeed either a bug in expand_env()
-/// is needed or both `$NVIM_LOG_FILE` and `$HOME` environment variables
-/// undefined.
+/// successful. Failed initialization indicates either a bug in expand_env()
+/// or both $NVIM_LOG_FILE and $HOME environment variables are undefined.
///
/// @return true if path was initialized, false otherwise.
static bool log_path_init(void)
{
- if (expanded_log_file_path[0]) {
+ if (log_file_path[0]) {
return true;
}
- expand_env((char_u *)USR_LOG_FILE, (char_u *)expanded_log_file_path,
- sizeof(expanded_log_file_path) - 1);
- // if the log file path expansion failed then fall back to stderr
- if (strcmp(USR_LOG_FILE, expanded_log_file_path) == 0) {
- memset(expanded_log_file_path, 0, sizeof(expanded_log_file_path));
- expand_env((char_u *)USR_LOG_FILE_2, (char_u *)expanded_log_file_path,
- sizeof(expanded_log_file_path) - 1);
- if (strcmp(USR_LOG_FILE_2, expanded_log_file_path) == 0) {
- memset(expanded_log_file_path, 0, sizeof(expanded_log_file_path));
+ size_t size = sizeof(log_file_path);
+ expand_env((char_u *)"$" LOG_FILE_ENV, (char_u *)log_file_path,
+ (int)size - 1);
+ if (strequal("$" LOG_FILE_ENV, log_file_path)
+ || log_file_path[0] == '\0'
+ || os_isdir((char_u *)log_file_path)
+ || !log_try_create(log_file_path)) {
+ // Invalid $NVIM_LOG_FILE or failed to expand; fall back to default.
+ char *defaultpath = stdpaths_user_data_subpath("log", 0, true);
+ size_t len = xstrlcpy(log_file_path, defaultpath, size);
+ xfree(defaultpath);
+ // Fall back to .nvimlog
+ if (len >= size || !log_try_create(log_file_path)) {
+ len = xstrlcpy(log_file_path, ".nvimlog", size);
+ }
+ // Fall back to stderr
+ if (len >= size || !log_try_create(log_file_path)) {
+ log_file_path[0] = '\0';
return false;
}
+ os_setenv(LOG_FILE_ENV, log_file_path, true);
}
return true;
}
@@ -75,6 +94,10 @@ void log_unlock(void)
bool do_log(int log_level, const char *func_name, int line_num, bool eol,
const char* fmt, ...) FUNC_ATTR_UNUSED
{
+ if (log_level < MIN_LOG_LEVEL) {
+ return false;
+ }
+
log_lock();
bool ret = false;
FILE *log_file = open_log_file();
@@ -97,26 +120,42 @@ end:
return ret;
}
+void log_uv_handles(void *loop)
+{
+ uv_loop_t *l = loop;
+ log_lock();
+ FILE *log_file = open_log_file();
+
+ if (log_file == NULL) {
+ goto end;
+ }
+
+ uv_print_all_handles(l, log_file);
+
+ if (log_file != stderr && log_file != stdout) {
+ fclose(log_file);
+ }
+end:
+ log_unlock();
+}
+
/// Open the log file for appending.
///
-/// @return The FILE* specified by the USR_LOG_FILE path or stderr in case of
-/// error
+/// @return FILE* decided by log_path_init() or stderr in case of error
FILE *open_log_file(void)
{
static bool opening_log_file = false;
-
// check if it's a recursive call
if (opening_log_file) {
do_log_to_file(stderr, ERROR_LOG_LEVEL, __func__, __LINE__, true,
- "Trying to LOG() recursively! Please fix it.");
+ "Cannot LOG() recursively.");
return stderr;
}
- // expand USR_LOG_FILE if needed and open the file
FILE *log_file = NULL;
opening_log_file = true;
if (log_path_init()) {
- log_file = fopen(expanded_log_file_path, "a");
+ log_file = fopen(log_file_path, "a");
}
opening_log_file = false;
@@ -124,10 +163,13 @@ FILE *open_log_file(void)
return log_file;
}
+ // May happen if:
+ // - LOG() is called before early_init()
+ // - Directory does not exist
+ // - File is not writable
do_log_to_file(stderr, ERROR_LOG_LEVEL, __func__, __LINE__, true,
- "Couldn't open USR_LOG_FILE, logging to stderr! This may be "
- "caused by attempting to LOG() before initialization "
- "functions are called (e.g. init_homedir()).");
+ "Logging to stderr, failed to open $" LOG_FILE_ENV ": %s",
+ log_file_path);
return stderr;
}
@@ -152,7 +194,7 @@ static bool v_do_log_to_file(FILE *log_file, int log_level,
[DEBUG_LOG_LEVEL] = "DEBUG",
[INFO_LOG_LEVEL] = "INFO ",
[WARNING_LOG_LEVEL] = "WARN ",
- [ERROR_LOG_LEVEL] = "ERROR"
+ [ERROR_LOG_LEVEL] = "ERROR",
};
assert(log_level >= DEBUG_LOG_LEVEL && log_level <= ERROR_LOG_LEVEL);
diff --git a/src/nvim/log.h b/src/nvim/log.h
index 32b7276f14..221f0bbaf6 100644
--- a/src/nvim/log.h
+++ b/src/nvim/log.h
@@ -18,55 +18,47 @@
#define ELOG(...)
#define ELOGN(...)
-// Logging is disabled if NDEBUG or DISABLE_LOG is defined.
-#if !defined(DISABLE_LOG) && defined(NDEBUG)
-# define DISABLE_LOG
-#endif
-
-// MIN_LOG_LEVEL can be defined during compilation to adjust the desired level
-// of logging. INFO_LOG_LEVEL is used by default.
#ifndef MIN_LOG_LEVEL
# define MIN_LOG_LEVEL INFO_LOG_LEVEL
#endif
-#ifndef DISABLE_LOG
-
-# if MIN_LOG_LEVEL <= DEBUG_LOG_LEVEL
-# undef DLOG
-# undef DLOGN
-# define DLOG(...) do_log(DEBUG_LOG_LEVEL, __func__, __LINE__, true, \
- __VA_ARGS__)
-# define DLOGN(...) do_log(DEBUG_LOG_LEVEL, __func__, __LINE__, false, \
- __VA_ARGS__)
-# endif
+#define LOG(level, ...) do_log((level), __func__, __LINE__, true, \
+ __VA_ARGS__)
-# if MIN_LOG_LEVEL <= INFO_LOG_LEVEL
-# undef ILOG
-# undef ILOGN
-# define ILOG(...) do_log(INFO_LOG_LEVEL, __func__, __LINE__, true, \
- __VA_ARGS__)
-# define ILOGN(...) do_log(INFO_LOG_LEVEL, __func__, __LINE__, false, \
- __VA_ARGS__)
-# endif
+#if MIN_LOG_LEVEL <= DEBUG_LOG_LEVEL
+# undef DLOG
+# undef DLOGN
+# define DLOG(...) do_log(DEBUG_LOG_LEVEL, __func__, __LINE__, true, \
+ __VA_ARGS__)
+# define DLOGN(...) do_log(DEBUG_LOG_LEVEL, __func__, __LINE__, false, \
+ __VA_ARGS__)
+#endif
-# if MIN_LOG_LEVEL <= WARNING_LOG_LEVEL
-# undef WLOG
-# undef WLOGN
-# define WLOG(...) do_log(WARNING_LOG_LEVEL, __func__, __LINE__, true, \
- __VA_ARGS__)
-# define WLOGN(...) do_log(WARNING_LOG_LEVEL, __func__, __LINE__, false, \
- __VA_ARGS__)
-# endif
+#if MIN_LOG_LEVEL <= INFO_LOG_LEVEL
+# undef ILOG
+# undef ILOGN
+# define ILOG(...) do_log(INFO_LOG_LEVEL, __func__, __LINE__, true, \
+ __VA_ARGS__)
+# define ILOGN(...) do_log(INFO_LOG_LEVEL, __func__, __LINE__, false, \
+ __VA_ARGS__)
+#endif
-# if MIN_LOG_LEVEL <= ERROR_LOG_LEVEL
-# undef ELOG
-# undef ELOGN
-# define ELOG(...) do_log(ERROR_LOG_LEVEL, __func__, __LINE__, true, \
- __VA_ARGS__)
-# define ELOGN(...) do_log(ERROR_LOG_LEVEL, __func__, __LINE__, false, \
- __VA_ARGS__)
-# endif
+#if MIN_LOG_LEVEL <= WARNING_LOG_LEVEL
+# undef WLOG
+# undef WLOGN
+# define WLOG(...) do_log(WARNING_LOG_LEVEL, __func__, __LINE__, true, \
+ __VA_ARGS__)
+# define WLOGN(...) do_log(WARNING_LOG_LEVEL, __func__, __LINE__, false, \
+ __VA_ARGS__)
+#endif
+#if MIN_LOG_LEVEL <= ERROR_LOG_LEVEL
+# undef ELOG
+# undef ELOGN
+# define ELOG(...) do_log(ERROR_LOG_LEVEL, __func__, __LINE__, true, \
+ __VA_ARGS__)
+# define ELOGN(...) do_log(ERROR_LOG_LEVEL, __func__, __LINE__, false, \
+ __VA_ARGS__)
#endif
#ifdef INCLUDE_GENERATED_DECLARATIONS
diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c
index 531cc42862..9ec5bfb8ad 100644
--- a/src/nvim/lua/executor.c
+++ b/src/nvim/lua/executor.c
@@ -417,7 +417,7 @@ static int nlua_eval_lua_string(lua_State *const lstate)
/// and locations where result and error are saved, respectively. Always
/// returns nothing (from the lua point of view).
static int nlua_exec_lua_string_api(lua_State *const lstate)
- FUNC_ATTR_NONNULL_ALL
+ FUNC_ATTR_NONNULL_ALL
{
const String *str = (const String *)lua_touserdata(lstate, 1);
const Array *args = (const Array *)lua_touserdata(lstate, 2);
diff --git a/src/nvim/main.c b/src/nvim/main.c
index 46607da6ea..19a661d7db 100644
--- a/src/nvim/main.c
+++ b/src/nvim/main.c
@@ -153,10 +153,11 @@ void event_init(void)
terminal_init();
}
-void event_teardown(void)
+/// @returns false if main_loop could not be closed gracefully
+bool event_teardown(void)
{
if (!main_loop.events) {
- return;
+ return true;
}
multiqueue_process_events(main_loop.events);
@@ -168,7 +169,7 @@ void event_teardown(void)
signal_teardown();
terminal_teardown();
- loop_close(&main_loop, true);
+ return loop_close(&main_loop, true);
}
/// Performs early initialization.
diff --git a/src/nvim/map.c b/src/nvim/map.c
index 366b286d14..537b6751e2 100644
--- a/src/nvim/map.c
+++ b/src/nvim/map.c
@@ -149,4 +149,3 @@ MAP_IMPL(handle_T, ptr_t, DEFAULT_INITIALIZER)
#define MSGPACK_HANDLER_INITIALIZER { .fn = NULL, .async = false }
MAP_IMPL(String, MsgpackRpcRequestHandler, MSGPACK_HANDLER_INITIALIZER)
#define KVEC_INITIALIZER { .size = 0, .capacity = 0, .items = NULL }
-MAP_IMPL(linenr_T, bufhl_vec_T, KVEC_INITIALIZER)
diff --git a/src/nvim/map.h b/src/nvim/map.h
index a4fccf47f9..047aa163ce 100644
--- a/src/nvim/map.h
+++ b/src/nvim/map.h
@@ -30,7 +30,6 @@ MAP_DECLS(ptr_t, ptr_t)
MAP_DECLS(uint64_t, ptr_t)
MAP_DECLS(handle_T, ptr_t)
MAP_DECLS(String, MsgpackRpcRequestHandler)
-MAP_DECLS(linenr_T, bufhl_vec_T)
#define map_new(T, U) map_##T##_##U##_new
#define map_free(T, U) map_##T##_##U##_free
diff --git a/src/nvim/mark.c b/src/nvim/mark.c
index 675fe4d57f..7889fabd45 100644
--- a/src/nvim/mark.c
+++ b/src/nvim/mark.c
@@ -888,9 +888,13 @@ void ex_changes(exarg_T *eap)
* 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, long amount, long amount_after)
+void mark_adjust(linenr_T line1,
+ linenr_T line2,
+ long amount,
+ long amount_after,
+ bool end_temp)
{
- mark_adjust_internal(line1, line2, amount, amount_after, true);
+ mark_adjust_internal(line1, line2, amount, amount_after, true, end_temp);
}
// mark_adjust_nofold() does the same as mark_adjust() but without adjusting
@@ -899,13 +903,14 @@ void mark_adjust(linenr_T line1, linenr_T line2, long amount, long amount_after)
// calling foldMarkAdjust() with arguments line1, line2, amount, amount_after,
// for an example of why this may be necessary, see do_move().
void mark_adjust_nofold(linenr_T line1, linenr_T line2, long amount,
- long amount_after)
+ long amount_after, bool end_temp)
{
- mark_adjust_internal(line1, line2, amount, amount_after, false);
+ mark_adjust_internal(line1, line2, amount, amount_after, false, end_temp);
}
-static void mark_adjust_internal(linenr_T line1, linenr_T line2, long amount,
- long amount_after, bool adjust_folds)
+static void mark_adjust_internal(linenr_T line1, linenr_T line2,
+ long amount, long amount_after,
+ bool adjust_folds, bool end_temp)
{
int i;
int fnum = curbuf->b_fnum;
@@ -954,7 +959,7 @@ static void mark_adjust_internal(linenr_T line1, linenr_T line2, long amount,
}
sign_mark_adjust(line1, line2, amount, amount_after);
- bufhl_mark_adjust(curbuf, line1, line2, amount, amount_after);
+ bufhl_mark_adjust(curbuf, line1, line2, amount, amount_after, end_temp);
}
/* previous context mark */
diff --git a/src/nvim/mark.h b/src/nvim/mark.h
index a356c1f398..ed4e47907b 100644
--- a/src/nvim/mark.h
+++ b/src/nvim/mark.h
@@ -81,7 +81,8 @@ static inline bool equalpos(pos_T, pos_T)
REAL_FATTR_CONST REAL_FATTR_ALWAYS_INLINE;
static inline bool ltoreq(pos_T, pos_T)
REAL_FATTR_CONST REAL_FATTR_ALWAYS_INLINE;
-static inline void clearpos(pos_T *) REAL_FATTR_ALWAYS_INLINE;
+static inline void clearpos(pos_T *)
+ REAL_FATTR_ALWAYS_INLINE;
/// Return true if position a is before (less than) position b.
static inline bool lt(pos_T a, pos_T b)
diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c
index 1abc69727c..9429703620 100644
--- a/src/nvim/memfile.c
+++ b/src/nvim/memfile.c
@@ -115,18 +115,18 @@ memfile_T *mf_open(char_u *fname, int flags)
}
}
- off_t size;
+ off_T size;
// When recovering, the actual block size will be retrieved from block 0
// in ml_recover(). The size used here may be wrong, therefore mf_blocknr_max
// must be rounded up.
if (mfp->mf_fd < 0
|| (flags & (O_TRUNC|O_EXCL))
- || (size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0) {
+ || (size = vim_lseek(mfp->mf_fd, 0L, SEEK_END)) <= 0) {
// no file or empty file
mfp->mf_blocknr_max = 0;
} else {
- assert(sizeof(off_t) <= sizeof(blocknr_T)
+ assert(sizeof(off_T) <= sizeof(blocknr_T)
&& mfp->mf_page_size > 0
&& mfp->mf_page_size - 1 <= INT64_MAX - size);
mfp->mf_blocknr_max = (((blocknr_T)size + mfp->mf_page_size - 1)
@@ -689,9 +689,9 @@ static int mf_read(memfile_T *mfp, bhdr_T *hp)
return FAIL;
unsigned page_size = mfp->mf_page_size;
- // TODO(elmart): Check (page_size * hp->bh_bnum) within off_t bounds.
- off_t offset = (off_t)(page_size * hp->bh_bnum);
- if (lseek(mfp->mf_fd, offset, SEEK_SET) != offset) {
+ // TODO(elmart): Check (page_size * hp->bh_bnum) within off_T bounds.
+ off_T offset = (off_T)(page_size * hp->bh_bnum);
+ if (vim_lseek(mfp->mf_fd, offset, SEEK_SET) != offset) {
PERROR(_("E294: Seek error in swap file read"));
return FAIL;
}
@@ -716,7 +716,7 @@ static int mf_read(memfile_T *mfp, bhdr_T *hp)
/// - Write error in swap file.
static int mf_write(memfile_T *mfp, bhdr_T *hp)
{
- off_t offset; // offset in the file
+ off_T offset; // offset in the file
blocknr_T nr; // block nr which is being written
bhdr_T *hp2;
unsigned page_size; // number of bytes in a page
@@ -745,9 +745,9 @@ static int mf_write(memfile_T *mfp, bhdr_T *hp)
hp2 = hp;
}
- // TODO(elmart): Check (page_size * nr) within off_t bounds.
- offset = (off_t)(page_size * nr);
- if (lseek(mfp->mf_fd, offset, SEEK_SET) != offset) {
+ // TODO(elmart): Check (page_size * nr) within off_T bounds.
+ offset = (off_T)(page_size * nr);
+ if (vim_lseek(mfp->mf_fd, offset, SEEK_SET) != offset) {
PERROR(_("E296: Seek error in swap file write"));
return FAIL;
}
diff --git a/src/nvim/memline.c b/src/nvim/memline.c
index 40a6761225..55e7e01825 100644
--- a/src/nvim/memline.c
+++ b/src/nvim/memline.c
@@ -763,7 +763,7 @@ void ml_recover(void)
int idx;
int top;
int txt_start;
- off_t size;
+ off_T size;
int called_from_main;
int serious_error = TRUE;
long mtime;
@@ -914,10 +914,11 @@ void ml_recover(void)
msg_end();
goto theend;
}
- if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
- mfp->mf_blocknr_max = 0; /* no file or empty file */
- else
+ if ((size = vim_lseek(mfp->mf_fd, (off_T)0L, SEEK_END)) <= 0) {
+ mfp->mf_blocknr_max = 0; // no file or empty file
+ } else {
mfp->mf_blocknr_max = size / mfp->mf_page_size;
+ }
mfp->mf_infile_count = mfp->mf_blocknr_max;
/* need to reallocate the memory used to store the data */
diff --git a/src/nvim/misc1.c b/src/nvim/misc1.c
index 9630656f3f..835b9c7b20 100644
--- a/src/nvim/misc1.c
+++ b/src/nvim/misc1.c
@@ -751,7 +751,7 @@ open_line (
// Skip mark_adjust when adding a line after the last one, there can't
// be marks there.
if (curwin->w_cursor.lnum + 1 < curbuf->b_ml.ml_line_count) {
- mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
+ mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L, false);
}
did_append = true;
} else {
@@ -1866,7 +1866,7 @@ void appended_lines_mark(linenr_T lnum, long count)
// Skip mark_adjust when adding a line after the last one, there can't
// be marks there.
if (lnum + count < curbuf->b_ml.ml_line_count) {
- mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
+ mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L, false);
}
changed_lines(lnum + 1, 0, lnum + 1, count);
}
@@ -1888,7 +1888,7 @@ void deleted_lines(linenr_T lnum, long count)
*/
void deleted_lines_mark(linenr_T lnum, long count)
{
- mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
+ mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count, false);
changed_lines(lnum, 0, lnum + count, -count);
}
diff --git a/src/nvim/msgpack_rpc/channel.c b/src/nvim/msgpack_rpc/channel.c
index cd64e14976..68ac35bc4e 100644
--- a/src/nvim/msgpack_rpc/channel.c
+++ b/src/nvim/msgpack_rpc/channel.c
@@ -12,6 +12,7 @@
#include "nvim/api/vim.h"
#include "nvim/api/ui.h"
#include "nvim/msgpack_rpc/channel.h"
+#include "nvim/msgpack_rpc/server.h"
#include "nvim/event/loop.h"
#include "nvim/event/libuv_process.h"
#include "nvim/event/rstream.h"
@@ -28,6 +29,7 @@
#include "nvim/map.h"
#include "nvim/log.h"
#include "nvim/misc1.h"
+#include "nvim/path.h"
#include "nvim/lib/kvec.h"
#include "nvim/os/input.h"
@@ -41,7 +43,8 @@
typedef enum {
kChannelTypeSocket,
kChannelTypeProc,
- kChannelTypeStdio
+ kChannelTypeStdio,
+ kChannelTypeInternal
} ChannelType;
typedef struct {
@@ -125,7 +128,7 @@ uint64_t channel_from_process(Process *proc, uint64_t id)
wstream_init(proc->in, 0);
rstream_init(proc->out, 0);
- rstream_start(proc->out, parse_msgpack, channel);
+ rstream_start(proc->out, receive_msgpack, channel);
return channel->id;
}
@@ -142,7 +145,36 @@ void channel_from_connection(SocketWatcher *watcher)
channel->data.stream.internal_data = channel;
wstream_init(&channel->data.stream, 0);
rstream_init(&channel->data.stream, CHANNEL_BUFFER_SIZE);
- rstream_start(&channel->data.stream, parse_msgpack, channel);
+ rstream_start(&channel->data.stream, receive_msgpack, channel);
+}
+
+uint64_t channel_connect(bool tcp, const char *address,
+ int timeout, const char **error)
+{
+ if (!tcp) {
+ char *path = fix_fname(address);
+ if (server_owns_pipe_address(path)) {
+ // avoid deadlock
+ xfree(path);
+ return channel_create_internal();
+ }
+ xfree(path);
+ }
+
+ Channel *channel = register_channel(kChannelTypeSocket, 0, NULL);
+ if (!socket_connect(&main_loop, &channel->data.stream,
+ tcp, address, timeout, error)) {
+ decref(channel);
+ return 0;
+ }
+
+ incref(channel); // close channel only after the stream is closed
+ channel->data.stream.internal_close_cb = close_cb;
+ channel->data.stream.internal_data = channel;
+ wstream_init(&channel->data.stream, 0);
+ rstream_init(&channel->data.stream, CHANNEL_BUFFER_SIZE);
+ rstream_start(&channel->data.stream, receive_msgpack, channel);
+ return channel->id;
}
/// Sends event/arguments to channel
@@ -305,11 +337,20 @@ void channel_from_stdio(void)
incref(channel); // stdio channels are only closed on exit
// read stream
rstream_init_fd(&main_loop, &channel->data.std.in, 0, CHANNEL_BUFFER_SIZE);
- rstream_start(&channel->data.std.in, parse_msgpack, channel);
+ rstream_start(&channel->data.std.in, receive_msgpack, channel);
// write stream
wstream_init_fd(&main_loop, &channel->data.std.out, 1, 0);
}
+/// Creates a loopback channel. This is used to avoid deadlock
+/// when an instance connects to its own named pipe.
+uint64_t channel_create_internal(void)
+{
+ Channel *channel = register_channel(kChannelTypeInternal, 0, NULL);
+ incref(channel); // internal channel lives until process exit
+ return channel->id;
+}
+
void channel_process_exit(uint64_t id, int status)
{
Channel *channel = pmap_get(uint64_t)(channels, id);
@@ -318,8 +359,8 @@ void channel_process_exit(uint64_t id, int status)
decref(channel);
}
-static void parse_msgpack(Stream *stream, RBuffer *rbuf, size_t c, void *data,
- bool eof)
+static void receive_msgpack(Stream *stream, RBuffer *rbuf, size_t c,
+ void *data, bool eof)
{
Channel *channel = data;
incref(channel);
@@ -329,7 +370,7 @@ static void parse_msgpack(Stream *stream, RBuffer *rbuf, size_t c, void *data,
char buf[256];
snprintf(buf, sizeof(buf), "ch %" PRIu64 " was closed by the client",
channel->id);
- call_set_error(channel, buf);
+ call_set_error(channel, buf, WARNING_LOG_LEVEL);
goto end;
}
@@ -341,6 +382,14 @@ static void parse_msgpack(Stream *stream, RBuffer *rbuf, size_t c, void *data,
rbuffer_read(rbuf, msgpack_unpacker_buffer(channel->unpacker), count);
msgpack_unpacker_buffer_consumed(channel->unpacker, count);
+ parse_msgpack(channel);
+
+end:
+ decref(channel);
+}
+
+static void parse_msgpack(Channel *channel)
+{
msgpack_unpacked unpacked;
msgpack_unpacked_init(&unpacked);
msgpack_unpack_return result;
@@ -360,11 +409,11 @@ static void parse_msgpack(Stream *stream, RBuffer *rbuf, size_t c, void *data,
"ch %" PRIu64 " returned a response with an unknown request "
"id. Ensure the client is properly synchronized",
channel->id);
- call_set_error(channel, buf);
+ call_set_error(channel, buf, ERROR_LOG_LEVEL);
}
msgpack_unpacked_destroy(&unpacked);
// Bail out from this event loop iteration
- goto end;
+ return;
}
handle_request(channel, &unpacked.data);
@@ -388,11 +437,9 @@ static void parse_msgpack(Stream *stream, RBuffer *rbuf, size_t c, void *data,
"This error can also happen when deserializing "
"an object with high level of nesting");
}
-
-end:
- decref(channel);
}
+
static void handle_request(Channel *channel, msgpack_object *request)
FUNC_ATTR_NONNULL_ALL
{
@@ -412,7 +459,7 @@ static void handle_request(Channel *channel, msgpack_object *request)
snprintf(buf, sizeof(buf),
"ch %" PRIu64 " sent an invalid message, closed.",
channel->id);
- call_set_error(channel, buf);
+ call_set_error(channel, buf, ERROR_LOG_LEVEL);
}
api_clear_error(&error);
return;
@@ -485,7 +532,7 @@ static void on_request_event(void **argv)
static bool channel_write(Channel *channel, WBuffer *buffer)
{
- bool success;
+ bool success = false;
if (channel->closed) {
wstream_release_wbuffer(buffer);
@@ -502,8 +549,11 @@ static bool channel_write(Channel *channel, WBuffer *buffer)
case kChannelTypeStdio:
success = wstream_write(&channel->data.std.out, buffer);
break;
- default:
- abort();
+ case kChannelTypeInternal:
+ incref(channel);
+ CREATE_EVENT(channel->events, internal_read_event, 2, channel, buffer);
+ success = true;
+ break;
}
if (!success) {
@@ -514,12 +564,28 @@ static bool channel_write(Channel *channel, WBuffer *buffer)
"Before returning from a RPC call, ch %" PRIu64 " was "
"closed due to a failed write",
channel->id);
- call_set_error(channel, buf);
+ call_set_error(channel, buf, ERROR_LOG_LEVEL);
}
return success;
}
+static void internal_read_event(void **argv)
+{
+ Channel *channel = argv[0];
+ WBuffer *buffer = argv[1];
+
+ msgpack_unpacker_reserve_buffer(channel->unpacker, buffer->size);
+ memcpy(msgpack_unpacker_buffer(channel->unpacker),
+ buffer->data, buffer->size);
+ msgpack_unpacker_buffer_consumed(channel->unpacker, buffer->size);
+
+ parse_msgpack(channel);
+
+ decref(channel);
+ wstream_release_wbuffer(buffer);
+}
+
static void send_error(Channel *channel, uint64_t id, char *err)
{
Error e = ERROR_INIT;
@@ -636,8 +702,9 @@ static void close_channel(Channel *channel)
stream_close(&channel->data.std.out, NULL, NULL);
multiqueue_put(main_loop.fast_events, exit_event, 1, channel);
return;
- default:
- abort();
+ case kChannelTypeInternal:
+ // nothing to free.
+ break;
}
decref(channel);
@@ -728,9 +795,9 @@ static void complete_call(msgpack_object *obj, Channel *channel)
}
}
-static void call_set_error(Channel *channel, char *msg)
+static void call_set_error(Channel *channel, char *msg, int loglevel)
{
- ELOG("RPC: %s", msg);
+ LOG(loglevel, "RPC: %s", msg);
for (size_t i = 0; i < kv_size(channel->call_stack); i++) {
ChannelCallFrame *frame = kv_A(channel->call_stack, i);
frame->returned = true;
diff --git a/src/nvim/msgpack_rpc/server.c b/src/nvim/msgpack_rpc/server.c
index b6958088ca..1e0cc27886 100644
--- a/src/nvim/msgpack_rpc/server.c
+++ b/src/nvim/msgpack_rpc/server.c
@@ -97,39 +97,61 @@ char *server_address_new(void)
#endif
}
-/// Starts listening for API calls on the TCP address or pipe path `endpoint`.
+/// Check if this instance owns a pipe address.
+/// The argument must already be resolved to an absolute path!
+bool server_owns_pipe_address(const char *path)
+{
+ for (int i = 0; i < watchers.ga_len; i++) {
+ if (!strcmp(path, ((SocketWatcher **)watchers.ga_data)[i]->addr)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/// Starts listening for API calls.
+///
/// The socket type is determined by parsing `endpoint`: If it's a valid IPv4
-/// address in 'ip[:port]' format, then it will be TCP socket. The port is
-/// optional and if omitted defaults to NVIM_DEFAULT_TCP_PORT. Otherwise it
-/// will be a unix socket or named pipe.
+/// or IPv6 address in 'ip:[port]' format, then it will be a TCP socket.
+/// Otherwise it will be a Unix socket or named pipe (Windows).
+///
+/// If no port is given, a random one will be assigned.
///
-/// @param endpoint Address of the server. Either a 'ip[:port]' string or an
-/// arbitrary identifier (trimmed to 256 bytes) for the unix socket or
-/// named pipe.
+/// @param endpoint Address of the server. Either a 'ip:[port]' string or an
+/// arbitrary identifier (trimmed to 256 bytes) for the Unix
+/// socket or named pipe.
/// @returns 0 on success, 1 on a regular error, and negative errno
-/// on failure to bind or connect.
+/// on failure to bind or listen.
int server_start(const char *endpoint)
{
- if (endpoint == NULL) {
- ELOG("Attempting to start server on NULL endpoint");
+ if (endpoint == NULL || endpoint[0] == '\0') {
+ WLOG("Empty or NULL endpoint");
return 1;
}
SocketWatcher *watcher = xmalloc(sizeof(SocketWatcher));
- socket_watcher_init(&main_loop, watcher, endpoint, NULL);
+
+ int result = socket_watcher_init(&main_loop, watcher, endpoint);
+ if (result < 0) {
+ xfree(watcher);
+ return result;
+ }
// Check if a watcher for the endpoint already exists
for (int i = 0; i < watchers.ga_len; i++) {
if (!strcmp(watcher->addr, ((SocketWatcher **)watchers.ga_data)[i]->addr)) {
ELOG("Already listening on %s", watcher->addr);
+ if (watcher->stream->type == UV_TCP) {
+ uv_freeaddrinfo(watcher->uv.tcp.addrinfo);
+ }
socket_watcher_close(watcher, free_server);
return 1;
}
}
- int result = socket_watcher_start(watcher, MAX_CONNECTIONS, connection_cb);
+ result = socket_watcher_start(watcher, MAX_CONNECTIONS, connection_cb);
if (result < 0) {
- ELOG("Failed to start server: %s", uv_strerror(result));
+ WLOG("Failed to start server: %s", uv_strerror(result));
socket_watcher_close(watcher, free_server);
return result;
}
diff --git a/src/nvim/ops.c b/src/nvim/ops.c
index c77781b1d1..5c6f4d0d07 100644
--- a/src/nvim/ops.c
+++ b/src/nvim/ops.c
@@ -938,13 +938,11 @@ static int stuff_yank(int regname, char_u *p)
static int execreg_lastc = NUL;
-/*
- * execute a yank register: copy it into the stuff buffer
- *
- * return FAIL for failure, OK otherwise
- */
-int
-do_execreg (
+/// Execute a yank register: copy it into the stuff buffer
+///
+/// Return FAIL for failure, OK otherwise
+int
+do_execreg(
int regname,
int colon, /* insert ':' before each line */
int addcr, /* always add '\n' to end of line */
@@ -1410,6 +1408,9 @@ int op_delete(oparg_T *oap)
}
if (oap->regname == 0) {
+ if (reg == NULL) {
+ abort();
+ }
set_clipboard(0, reg);
do_autocmd_textyankpost(oap, reg);
}
@@ -3181,7 +3182,7 @@ error:
if (curbuf->b_op_start.lnum + (y_type == kMTCharWise) - 1 + nr_lines
< curbuf->b_ml.ml_line_count) {
mark_adjust(curbuf->b_op_start.lnum + (y_type == kMTCharWise),
- (linenr_T)MAXLNUM, nr_lines, 0L);
+ (linenr_T)MAXLNUM, nr_lines, 0L, false);
}
// note changed text for displaying and folding
@@ -4439,8 +4440,8 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1)
char_u buf2[NUMBUFLEN];
int pre; // 'X' or 'x': hex; '0': octal; 'B' or 'b': bin
static bool hexupper = false; // 0xABC
- unsigned long n;
- unsigned long oldn;
+ uvarnumber_T n;
+ uvarnumber_T oldn;
char_u *ptr;
int c;
int todel;
@@ -4635,20 +4636,20 @@ int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1)
oldn = n;
- n = subtract ? n - (unsigned long) Prenum1
- : n + (unsigned long) Prenum1;
+ n = subtract ? n - (uvarnumber_T)Prenum1
+ : n + (uvarnumber_T)Prenum1;
// handle wraparound for decimal numbers
if (!pre) {
if (subtract) {
if (n > oldn) {
- n = 1 + (n ^ (unsigned long)-1);
+ n = 1 + (n ^ (uvarnumber_T)-1);
negative ^= true;
}
} else {
// add
if (n < oldn) {
- n = (n ^ (unsigned long)-1);
+ n = (n ^ (uvarnumber_T)-1);
negative ^= true;
}
}
@@ -5238,11 +5239,13 @@ void clear_oparg(oparg_T *oap)
* case, eol_size will be added to the character count to account for
* the size of the EOL character.
*/
-static long line_count_info(char_u *line, long *wc, long *cc, long limit, int eol_size)
+static varnumber_T line_count_info(char_u *line, varnumber_T *wc,
+ varnumber_T *cc, varnumber_T limit,
+ int eol_size)
{
- long i;
- long words = 0;
- long chars = 0;
+ varnumber_T i;
+ varnumber_T words = 0;
+ varnumber_T chars = 0;
int is_word = 0;
for (i = 0; i < limit && line[i] != NUL; ) {
@@ -5280,15 +5283,15 @@ void cursor_pos_info(dict_T *dict)
char_u buf1[50];
char_u buf2[40];
linenr_T lnum;
- long byte_count = 0;
- long bom_count = 0;
- long byte_count_cursor = 0;
- long char_count = 0;
- long char_count_cursor = 0;
- long word_count = 0;
- long word_count_cursor = 0;
+ varnumber_T byte_count = 0;
+ varnumber_T bom_count = 0;
+ varnumber_T byte_count_cursor = 0;
+ varnumber_T char_count = 0;
+ varnumber_T char_count_cursor = 0;
+ varnumber_T word_count = 0;
+ varnumber_T word_count_cursor = 0;
int eol_size;
- long last_check = 100000L;
+ varnumber_T last_check = 100000L;
long line_count_selected = 0;
pos_T min_pos, max_pos;
oparg_T oparg;
@@ -5395,15 +5398,16 @@ void cursor_pos_info(dict_T *dict)
if (lnum == curwin->w_cursor.lnum) {
word_count_cursor += word_count;
char_count_cursor += char_count;
- byte_count_cursor = byte_count +
- line_count_info(ml_get(lnum),
- &word_count_cursor, &char_count_cursor,
- (long)(curwin->w_cursor.col + 1), eol_size);
+ byte_count_cursor = byte_count
+ + line_count_info(ml_get(lnum), &word_count_cursor,
+ &char_count_cursor,
+ (varnumber_T)(curwin->w_cursor.col + 1),
+ eol_size);
}
}
- /* Add to the running totals */
- byte_count += line_count_info(ml_get(lnum), &word_count,
- &char_count, (long)MAXCOL, eol_size);
+ // Add to the running totals
+ byte_count += line_count_info(ml_get(lnum), &word_count, &char_count,
+ (varnumber_T)MAXCOL, eol_size);
}
// Correction for when last line doesn't have an EOL.
@@ -5780,7 +5784,7 @@ static inline bool reg_empty(const yankreg_T *const reg)
/// @return Pointer that needs to be passed to next `op_register_iter` call or
/// NULL if iteration is over.
const void *op_register_iter(const void *const iter, char *const name,
- yankreg_T *const reg)
+ yankreg_T *const reg, bool *is_unnamed)
FUNC_ATTR_NONNULL_ARG(2, 3) FUNC_ATTR_WARN_UNUSED_RESULT
{
*name = NUL;
@@ -5796,6 +5800,7 @@ const void *op_register_iter(const void *const iter, char *const name,
int iter_off = (int)(iter_reg - &(y_regs[0]));
*name = (char)get_register_name(iter_off);
*reg = *iter_reg;
+ *is_unnamed = (iter_reg == y_previous);
while (++iter_reg - &(y_regs[0]) < NUM_SAVED_REGISTERS) {
if (!reg_empty(iter_reg)) {
return (void *) iter_reg;
@@ -5820,10 +5825,11 @@ size_t op_register_amount(void)
/// Set register to a given value
///
/// @param[in] name Register name.
-/// @param[in] reg Register value.
+/// @param[in] reg Register value.
+/// @param[in] is_unnamed Whether to set the unnamed regiseter to reg
///
/// @return true on success, false on failure.
-bool op_register_set(const char name, const yankreg_T reg)
+bool op_register_set(const char name, const yankreg_T reg, bool is_unnamed)
{
int i = op_reg_index(name);
if (i == -1) {
@@ -5831,6 +5837,10 @@ bool op_register_set(const char name, const yankreg_T reg)
}
free_register(&y_regs[i]);
y_regs[i] = reg;
+
+ if (is_unnamed) {
+ y_previous = &y_regs[i];
+ }
return true;
}
@@ -5847,3 +5857,20 @@ const yankreg_T *op_register_get(const char name)
}
return &y_regs[i];
}
+
+/// Set the previous yank register
+///
+/// @param[in] name Register name.
+///
+/// @return true on success, false on failure.
+bool op_register_set_previous(const char name)
+ FUNC_ATTR_WARN_UNUSED_RESULT
+{
+ int i = op_reg_index(name);
+ if (i == -1) {
+ return false;
+ }
+
+ y_previous = &y_regs[i];
+ return true;
+}
diff --git a/src/nvim/option.c b/src/nvim/option.c
index 392a2f3908..b48ffae85b 100644
--- a/src/nvim/option.c
+++ b/src/nvim/option.c
@@ -1144,7 +1144,7 @@ do_set (
int afterchar; /* character just after option name */
int len;
int i;
- long value;
+ varnumber_T value;
int key;
uint32_t flags; /* flags for current option */
char_u *varp = NULL; /* pointer to variable for current option */
@@ -1477,7 +1477,7 @@ do_set (
if (removing) {
value = *(long *)varp - value;
}
- errmsg = (char_u *)set_num_option(opt_idx, varp, value,
+ errmsg = (char_u *)set_num_option(opt_idx, varp, (long)value,
errbuf, sizeof(errbuf),
opt_flags);
} else if (opt_idx >= 0) { // String.
@@ -3579,7 +3579,9 @@ static char_u *compile_cap_prog(synblock_T *synblock)
/// Handle setting `winhighlight' in window "wp"
static bool parse_winhl_opt(win_T *wp)
{
- int w_hl_id = 0, w_hl_id_inactive = 0;
+ int w_hl_id_normal = 0;
+ int w_hl_ids[HLF_COUNT] = { 0 };
+ int hlf;
const char *p = (const char *)wp->w_p_winhl;
while (*p) {
@@ -3593,18 +3595,25 @@ static bool parse_winhl_opt(win_T *wp)
int hl_id = syn_check_group((char_u *)hi, (int)(commap-hi));
if (strncmp("Normal", p, nlen) == 0) {
- w_hl_id = hl_id;
- } else if (strncmp("NormalNC", p, nlen) == 0) {
- w_hl_id_inactive = hl_id;
+ w_hl_id_normal = hl_id;
} else {
- return false;
+ for (hlf = 0; hlf < (int)HLF_COUNT; hlf++) {
+ if (strncmp(hlf_names[hlf], p, nlen) == 0) {
+ w_hl_ids[hlf] = hl_id;
+ break;
+ }
+ }
+ if (hlf == HLF_COUNT) {
+ return false;
+ }
}
p = *commap ? commap+1 : "";
}
- wp->w_hl_id = w_hl_id;
- wp->w_hl_id_inactive = w_hl_id_inactive;
+ wp->w_hl_id_normal = w_hl_id_normal;
+ memcpy(wp->w_hl_ids, w_hl_ids, sizeof(w_hl_ids));
+ wp->w_hl_needs_update = true;
return true;
}
@@ -4630,7 +4639,7 @@ get_option_value (
if ((int *)varp == &curbuf->b_changed) {
*numval = curbufIsChanged();
} else {
- *numval = *(int *)varp;
+ *numval = (long) *(int *)varp; // NOLINT(whitespace/cast)
}
}
return 1;
diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c
index b9a9480cb8..14dacd97c4 100644
--- a/src/nvim/os/fs.c
+++ b/src/nvim/os/fs.c
@@ -171,6 +171,10 @@ int os_nodetype(const char *name)
| O_NONBLOCK
#endif
, 0);
+ if (fd == -1) {
+ return NODE_OTHER; // open() failed.
+ }
+
switch (uv_guess_handle(fd)) {
case UV_TTY: // FILE_TYPE_CHAR
nodetype = NODE_WRITABLE;
diff --git a/src/nvim/os/pty_process_unix.c b/src/nvim/os/pty_process_unix.c
index eb9335b03c..ee3ab96a83 100644
--- a/src/nvim/os/pty_process_unix.c
+++ b/src/nvim/os/pty_process_unix.c
@@ -12,7 +12,7 @@
#include <sys/ioctl.h>
// forkpty is not in POSIX, so headers are platform-specific
-#if defined(__FreeBSD__)
+#if defined(__FreeBSD__) || defined (__DragonFly__)
# include <libutil.h>
#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
# include <util.h>
diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c
index 1a40309655..9d80a43718 100644
--- a/src/nvim/os/shell.c
+++ b/src/nvim/os/shell.c
@@ -496,8 +496,12 @@ static void out_data_cb(Stream *stream, RBuffer *buf, size_t count, void *data,
size_t cnt;
char *ptr = rbuffer_read_ptr(buf, &cnt);
- if (ptr != NULL && cnt > 0
- && out_data_decide_throttle(cnt)) { // Skip output above a threshold.
+ if (ptr == NULL || cnt == 0) {
+ // Nothing to read;
+ return;
+ }
+
+ if (out_data_decide_throttle(cnt)) { // Skip output above a threshold.
// Save the skipped output. If it is the final chunk, we display it later.
out_data_ring(ptr, cnt);
} else {
@@ -685,7 +689,7 @@ static void shell_write_cb(Stream *stream, void *data, int status)
uv_err_name(status));
}
if (stream->closed) { // Process may have exited before this write.
- ELOG("stream was already closed");
+ WLOG("stream was already closed");
return;
}
stream_close(stream, NULL, NULL);
diff --git a/src/nvim/os_unix.c b/src/nvim/os_unix.c
index 7cf0d7817c..692bcc97f4 100644
--- a/src/nvim/os_unix.c
+++ b/src/nvim/os_unix.c
@@ -141,7 +141,9 @@ void mch_exit(int r) FUNC_ATTR_NORETURN
ui_flush();
ml_close_all(true); // remove all memfiles
- event_teardown();
+ if (!event_teardown() && r == 0) {
+ r = 1; // Exit with error if main_loop did not teardown gracefully.
+ }
stream_set_blocking(input_global_fd(), true); // normalize stream (#2598)
#ifdef EXITFREE
@@ -173,7 +175,7 @@ void mch_exit(int r) FUNC_ATTR_NORETURN
/// @returns OK for success or FAIL for error.
int mch_expand_wildcards(int num_pat, char_u **pat, int *num_file,
char_u ***file, int flags) FUNC_ATTR_NONNULL_ARG(3)
- FUNC_ATTR_NONNULL_ARG(4)
+ FUNC_ATTR_NONNULL_ARG(4)
{
int i;
size_t len;
diff --git a/src/nvim/path.c b/src/nvim/path.c
index 9162b6da4d..f2339c8046 100644
--- a/src/nvim/path.c
+++ b/src/nvim/path.c
@@ -1715,7 +1715,7 @@ int vim_FullName(const char *fname, char *buf, size_t len, bool force)
///
/// @param fname is the filename to expand
/// @return [allocated] Full path (NULL for failure).
-char *fix_fname(char *fname)
+char *fix_fname(const char *fname)
{
#ifdef UNIX
return FullName_save(fname, true);
diff --git a/src/nvim/popupmnu.c b/src/nvim/popupmnu.c
index 9f3abfcb89..2462975c9b 100644
--- a/src/nvim/popupmnu.c
+++ b/src/nvim/popupmnu.c
@@ -307,10 +307,10 @@ void pum_redraw(void)
{
int row = pum_row;
int col;
- int attr_norm = highlight_attr[HLF_PNI];
- int attr_select = highlight_attr[HLF_PSI];
- int attr_scroll = highlight_attr[HLF_PSB];
- int attr_thumb = highlight_attr[HLF_PST];
+ int attr_norm = win_hl_attr(curwin, HLF_PNI);
+ int attr_select = win_hl_attr(curwin, HLF_PSI);
+ int attr_scroll = win_hl_attr(curwin, HLF_PSB);
+ int attr_thumb = win_hl_attr(curwin, HLF_PST);
int attr;
int i;
int idx;
diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c
index 0ec0d5df9d..bd5dfa92cc 100644
--- a/src/nvim/quickfix.c
+++ b/src/nvim/quickfix.c
@@ -188,6 +188,11 @@ typedef struct {
*/
#define GET_LOC_LIST(wp) (IS_LL_WINDOW(wp) ? wp->w_llist_ref : wp->w_llist)
+// Looking up a buffer can be slow if there are many. Remember the last one
+// to make this a lot faster if there are multiple matches in the same file.
+static char_u *qf_last_bufname = NULL;
+static bufref_T qf_last_bufref = { NULL, 0, 0 };
+
/*
* Read the errorfile "efile" into memory, line by line, building the error
* list. Set the error list's title to qf_title.
@@ -968,6 +973,10 @@ qf_init_ext(
int retval = -1; // default: return error flag
int status;
+ // Do not used the cached buffer, it may have been wiped out.
+ xfree(qf_last_bufname);
+ qf_last_bufname = NULL;
+
fields.namebuf = xmalloc(CMDBUFFSIZE + 1);
fields.errmsglen = CMDBUFFSIZE + 1;
fields.errmsg = xmalloc(fields.errmsglen);
@@ -1399,11 +1408,6 @@ void copy_loclist(win_T *from, win_T *to)
to->w_llist->qf_curlist = qi->qf_curlist; /* current list */
}
-// Looking up a buffer can be slow if there are many. Remember the last one to
-// make this a lot faster if there are multiple matches in the same file.
-static char_u *qf_last_bufname = NULL;
-static bufref_T qf_last_bufref = { NULL, 0 };
-
// Get buffer number for file "directory.fname".
// Also sets the b_has_qf_entry flag.
static int qf_get_fnum(qf_info_T *qi, char_u *directory, char_u *fname)
@@ -2326,9 +2330,7 @@ void qf_history(exarg_T *eap)
}
}
-/*
- * Free error list "idx".
- */
+/// Free all the entries in the error list "idx".
static void qf_free(qf_info_T *qi, int idx)
{
qfline_T *qfp;
@@ -4023,7 +4025,7 @@ int get_errorlist_properties(win_T *wp, dict_T *what, dict_T *retdict)
if ((di = tv_dict_find(what, S_LEN("nr"))) != NULL) {
// Use the specified quickfix/location list
if (di->di_tv.v_type == VAR_NUMBER) {
- qf_idx = di->di_tv.vval.v_number - 1;
+ qf_idx = (int)di->di_tv.vval.v_number - 1;
if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
return FAIL;
}
@@ -4097,7 +4099,7 @@ static int qf_add_entries(qf_info_T *qi, list_T *list, char_u *title,
char *const filename = tv_dict_get_string(d, "filename", true);
int bufnum = (int)tv_dict_get_number(d, "bufnr");
- long lnum = tv_dict_get_number(d, "lnum");
+ long lnum = (long)tv_dict_get_number(d, "lnum");
int col = (int)tv_dict_get_number(d, "col");
char_u vcol = (char_u)tv_dict_get_number(d, "vcol");
int nr = (int)tv_dict_get_number(d, "nr");
@@ -4179,7 +4181,7 @@ static int qf_set_properties(qf_info_T *qi, dict_T *what, int action)
if ((di = tv_dict_find(what, S_LEN("nr"))) != NULL) {
// Use the specified quickfix/location list
if (di->di_tv.v_type == VAR_NUMBER) {
- qf_idx = di->di_tv.vval.v_number - 1;
+ qf_idx = (int)di->di_tv.vval.v_number - 1;
if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
return FAIL;
}
diff --git a/src/nvim/screen.c b/src/nvim/screen.c
index 4f4363d121..2f7fa8724f 100644
--- a/src/nvim/screen.c
+++ b/src/nvim/screen.c
@@ -155,7 +155,6 @@ static schar_T *current_ScreenLine;
StlClickDefinition *tab_page_click_defs = NULL;
long tab_page_click_defs_size = 0;
-# define SCREEN_LINE(r, o, e, c, rl) screen_line((r), (o), (e), (c), (rl))
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "screen.c.generated.h"
#endif
@@ -380,15 +379,24 @@ void update_screen(int type)
))
curwin->w_redr_type = type;
- /* Redraw the tab pages line if needed. */
- if (redraw_tabline || type >= NOT_VALID)
+ // Redraw the tab pages line if needed.
+ if (redraw_tabline || type >= NOT_VALID) {
+ update_window_hl(curwin, type >= NOT_VALID);
+ FOR_ALL_TABS(tp) {
+ if (tp != curtab) {
+ update_window_hl(tp->tp_curwin, type >= NOT_VALID);
+ }
+ }
draw_tabline();
+ }
/*
* Correct stored syntax highlighting info for changes in each displayed
* buffer. Each buffer must only be done once.
*/
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
+ update_window_hl(wp, type >= NOT_VALID);
+
if (wp->w_buffer->b_mod_set) {
win_T *wwp;
@@ -1488,11 +1496,11 @@ static void win_update(win_T *wp)
// Last line isn't finished: Display "@@@" in the last screen line.
screen_puts_len((char_u *)"@@", 2, scr_row, wp->w_wincol,
- hl_attr(HLF_AT));
+ win_hl_attr(wp, HLF_AT));
screen_fill(scr_row, scr_row + 1,
(int)wp->w_wincol + 2, (int)W_ENDCOL(wp),
- '@', ' ', hl_attr(HLF_AT));
+ '@', ' ', win_hl_attr(wp, HLF_AT));
set_empty_rows(wp, srow);
wp->w_botline = lnum;
} else if (dy_flags & DY_LASTLINE) { // 'display' has "lastline"
@@ -1500,7 +1508,7 @@ static void win_update(win_T *wp)
screen_fill(wp->w_winrow + wp->w_height - 1,
wp->w_winrow + wp->w_height,
W_ENDCOL(wp) - 3, W_ENDCOL(wp),
- '@', '@', hl_attr(HLF_AT));
+ '@', '@', win_hl_attr(wp, HLF_AT));
set_empty_rows(wp, srow);
wp->w_botline = lnum;
} else {
@@ -1584,10 +1592,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T h
# define FDC_OFF n
int fdc = compute_foldcolumn(wp, 0);
- int attr = hl_attr(hl);
- if (wp->w_hl_attr != 0) {
- attr = hl_combine_attr(wp->w_hl_attr, attr);
- }
+ int attr = win_hl_attr(wp, hl);
if (wp->w_p_rl) {
// No check for cmdline window: should never be right-left.
@@ -1599,7 +1604,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T h
n = wp->w_width;
screen_fill(wp->w_winrow + row, wp->w_winrow + endrow,
W_ENDCOL(wp) - n, W_ENDCOL(wp),
- ' ', ' ', hl_attr(HLF_FC));
+ ' ', ' ', win_hl_attr(wp, HLF_FC));
}
if (signcolumn_on(wp)) {
@@ -1611,7 +1616,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T h
}
screen_fill(wp->w_winrow + row, wp->w_winrow + endrow,
W_ENDCOL(wp) - nn, W_ENDCOL(wp) - n,
- ' ', ' ', hl_attr(HLF_SC));
+ ' ', ' ', win_hl_attr(wp, HLF_SC));
n = nn;
}
@@ -1629,7 +1634,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T h
n = wp->w_width;
screen_fill(wp->w_winrow + row, wp->w_winrow + endrow,
wp->w_wincol, wp->w_wincol + n,
- cmdwin_type, ' ', hl_attr(HLF_AT));
+ cmdwin_type, ' ', win_hl_attr(wp, HLF_AT));
}
if (fdc > 0) {
int nn = n + fdc;
@@ -1639,7 +1644,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T h
nn = wp->w_width;
screen_fill(wp->w_winrow + row, wp->w_winrow + endrow,
wp->w_wincol + n, wp->w_wincol + nn,
- ' ', ' ', hl_attr(HLF_FC));
+ ' ', ' ', win_hl_attr(wp, HLF_FC));
n = nn;
}
@@ -1652,7 +1657,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T h
}
screen_fill(wp->w_winrow + row, wp->w_winrow + endrow,
wp->w_wincol + n, wp->w_wincol + nn,
- ' ', ' ', hl_attr(HLF_SC));
+ ' ', ' ', win_hl_attr(wp, HLF_SC));
n = nn;
}
@@ -1720,10 +1725,9 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
*/
if (cmdwin_type != 0 && wp == curwin) {
ScreenLines[off] = cmdwin_type;
- ScreenAttrs[off] = hl_attr(HLF_AT);
- if (enc_utf8)
- ScreenLinesUC[off] = 0;
- ++col;
+ ScreenAttrs[off] = win_hl_attr(wp, HLF_AT);
+ ScreenLinesUC[off] = 0;
+ col++;
}
// 2. Add the 'foldcolumn'
@@ -1735,12 +1739,14 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
int i;
copy_text_attr(off + wp->w_width - fdc - col, buf, fdc,
- hl_attr(HLF_FC));
- /* reverse the fold column */
- for (i = 0; i < fdc; ++i)
+ win_hl_attr(wp, HLF_FC));
+ // reverse the fold column
+ for (i = 0; i < fdc; i++) {
ScreenLines[off + wp->w_width - i - 1 - col] = buf[i];
- } else
- copy_text_attr(off + col, buf, fdc, hl_attr(HLF_FC));
+ }
+ } else {
+ copy_text_attr(off + col, buf, fdc, win_hl_attr(wp, HLF_FC));
+ }
col += fdc;
}
@@ -1753,7 +1759,7 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
/* Set all attributes of the 'number' or 'relativenumber' column and the
* text */
- RL_MEMSET(col, hl_attr(HLF_FL), wp->w_width - col);
+ RL_MEMSET(col, win_hl_attr(wp, HLF_FL), wp->w_width - col);
// If signs are being displayed, add two spaces.
if (signcolumn_on(wp)) {
@@ -1762,7 +1768,8 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
if (len > 2) {
len = 2;
}
- copy_text_attr(off + col, (char_u *)" ", len, hl_attr(HLF_FL));
+ copy_text_attr(off + col, (char_u *)" ", len,
+ win_hl_attr(wp, HLF_FL));
col += len;
}
}
@@ -1794,13 +1801,14 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
}
}
- sprintf((char *)buf, fmt, w, num);
- if (wp->w_p_rl)
- /* the line number isn't reversed */
+ snprintf((char *)buf, FOLD_TEXT_LEN, fmt, w, num);
+ if (wp->w_p_rl) {
+ // the line number isn't reversed
copy_text_attr(off + wp->w_width - len - col, buf, len,
- hl_attr(HLF_FL));
- else
- copy_text_attr(off + col, buf, len, hl_attr(HLF_FL));
+ win_hl_attr(wp, HLF_FL));
+ } else {
+ copy_text_attr(off + col, buf, len, win_hl_attr(wp, HLF_FL));
+ }
col += len;
}
}
@@ -1958,12 +1966,12 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
len = wp->w_old_cursor_lcol;
else
len = wp->w_width - txtcol;
- RL_MEMSET(wp->w_old_cursor_fcol + txtcol, hl_attr(HLF_V),
- len - (int)wp->w_old_cursor_fcol);
+ RL_MEMSET(wp->w_old_cursor_fcol + txtcol, win_hl_attr(wp, HLF_V),
+ len - (int)wp->w_old_cursor_fcol);
}
} else {
- /* Set all attributes of the text */
- RL_MEMSET(txtcol, hl_attr(HLF_V), wp->w_width - txtcol);
+ // Set all attributes of the text
+ RL_MEMSET(txtcol, win_hl_attr(wp, HLF_V), wp->w_width - txtcol);
}
}
}
@@ -1983,7 +1991,7 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
}
if (txtcol >= 0 && txtcol < wp->w_width) {
ScreenAttrs[off + txtcol] =
- hl_combine_attr(ScreenAttrs[off + txtcol], hl_attr(HLF_MC));
+ hl_combine_attr(ScreenAttrs[off + txtcol], win_hl_attr(wp, HLF_MC));
}
txtcol = old_txtcol;
j = wp->w_p_cc_cols[++i];
@@ -1999,11 +2007,11 @@ static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T
txtcol -= wp->w_leftcol;
if (txtcol >= 0 && txtcol < wp->w_width)
ScreenAttrs[off + txtcol] = hl_combine_attr(
- ScreenAttrs[off + txtcol], hl_attr(HLF_CUC));
+ ScreenAttrs[off + txtcol], win_hl_attr(wp, HLF_CUC));
}
- SCREEN_LINE(row + wp->w_winrow, wp->w_wincol, wp->w_width,
- wp->w_width, FALSE);
+ screen_line(row + wp->w_winrow, wp->w_wincol, wp->w_width,
+ wp->w_width, false, wp);
/*
* Update w_cline_height and w_cline_folded if the cursor line was
@@ -2202,7 +2210,7 @@ win_line (
bool search_attr_from_match = false; // if search_attr is from :match
bool has_bufhl = false; // this buffer has highlight matches
int bufhl_attr = 0; // attributes desired by bufhl
- bufhl_lineinfo_T bufhl_info; // bufhl data for this line
+ BufhlLineInfo bufhl_info; // bufhl data for this line
/* draw_state: items that are drawn in sequence: */
#define WL_START 0 /* nothing done yet */
@@ -2218,7 +2226,7 @@ win_line (
int syntax_flags = 0;
int syntax_seqnr = 0;
int prev_syntax_id = 0;
- int conceal_attr = hl_attr(HLF_CONCEAL);
+ int conceal_attr = win_hl_attr(wp, HLF_CONCEAL);
int is_concealing = false;
int boguscols = 0; ///< nonexistent columns added to
///< force wrapping
@@ -2366,8 +2374,8 @@ win_line (
/* if inverting in this line set area_highlighting */
if (fromcol >= 0) {
- area_highlighting = TRUE;
- attr = hl_attr(HLF_V);
+ area_highlighting = true;
+ attr = win_hl_attr(wp, HLF_V);
}
}
/*
@@ -2391,8 +2399,8 @@ win_line (
/* do at least one character; happens when past end of line */
if (fromcol == tocol)
tocol = fromcol + 1;
- area_highlighting = TRUE;
- attr = hl_attr(HLF_I);
+ area_highlighting = true;
+ attr = win_hl_attr(wp, HLF_I);
}
filler_lines = diff_check(wp, lnum);
@@ -2420,11 +2428,11 @@ win_line (
// Highlight the current line in the quickfix window.
if (bt_quickfix(wp->w_buffer) && qf_current_entry(wp) == lnum) {
- line_attr = hl_attr(HLF_QFL);
+ line_attr = win_hl_attr(wp, HLF_QFL);
}
- if (wp->w_hl_attr != 0) {
- line_attr = hl_combine_attr(wp->w_hl_attr, line_attr);
+ if (wp->w_hl_attr_normal != 0) {
+ line_attr = hl_combine_attr(wp->w_hl_attr_normal, line_attr);
}
if (line_attr != 0) {
@@ -2652,9 +2660,9 @@ win_line (
&& !(wp == curwin && VIsual_active)) {
if (line_attr != 0 && !(State & INSERT) && bt_quickfix(wp->w_buffer)
&& qf_current_entry(wp) == lnum) {
- line_attr = hl_combine_attr(hl_attr(HLF_CUL), line_attr);
+ line_attr = hl_combine_attr(win_hl_attr(wp, HLF_CUL), line_attr);
} else {
- line_attr = hl_attr(HLF_CUL);
+ line_attr = win_hl_attr(wp, HLF_CUL);
}
area_highlighting = true;
}
@@ -2687,7 +2695,7 @@ win_line (
/* Draw the cmdline character. */
n_extra = 1;
c_extra = cmdwin_type;
- char_attr = hl_attr(HLF_AT);
+ char_attr = win_hl_attr(wp, HLF_AT);
}
}
@@ -2702,7 +2710,7 @@ win_line (
p_extra = extra;
p_extra[n_extra] = NUL;
c_extra = NUL;
- char_attr = hl_attr(HLF_FC);
+ char_attr = win_hl_attr(wp, HLF_FC);
}
}
@@ -2715,7 +2723,7 @@ win_line (
int text_sign;
/* Draw two cells with the sign value or blank. */
c_extra = ' ';
- char_attr = hl_attr(HLF_SC);
+ char_attr = win_hl_attr(wp, HLF_SC);
n_extra = 2;
if (row == startrow + filler_lines && filler_todo <= 0) {
@@ -2772,14 +2780,15 @@ win_line (
} else
c_extra = ' ';
n_extra = number_width(wp) + 1;
- char_attr = hl_attr(HLF_N);
- /* When 'cursorline' is set highlight the line number of
- * the current line differently.
- * TODO: Can we use CursorLine instead of CursorLineNr
- * when CursorLineNr isn't set? */
+ char_attr = win_hl_attr(wp, HLF_N);
+ // When 'cursorline' is set highlight the line number of
+ // the current line differently.
+ // TODO(vim): Can we use CursorLine instead of CursorLineNr
+ // when CursorLineNr isn't set?
if ((wp->w_p_cul || wp->w_p_rnu)
- && lnum == wp->w_cursor.lnum)
- char_attr = hl_attr(HLF_CLN);
+ && lnum == wp->w_cursor.lnum) {
+ char_attr = win_hl_attr(wp, HLF_CLN);
+ }
}
}
@@ -2796,12 +2805,12 @@ win_line (
if (draw_state == WL_BRI - 1 && n_extra == 0) {
draw_state = WL_BRI;
if (wp->w_p_bri && row != startrow && filler_lines == 0) {
- char_attr = 0; // was: hl_attr(HLF_AT);
+ char_attr = wp->w_hl_attr_normal; // was: hl_attr(HLF_AT);
if (diff_hlf != (hlf_T)0) {
- char_attr = hl_attr(diff_hlf);
+ char_attr = win_hl_attr(wp, diff_hlf);
if (wp->w_p_cul && lnum == wp->w_cursor.lnum) {
- char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUL));
+ char_attr = hl_combine_attr(char_attr, win_hl_attr(wp, HLF_CUL));
}
}
p_extra = NULL;
@@ -2826,15 +2835,15 @@ win_line (
n_extra = col + 1;
else
n_extra = wp->w_width - col;
- char_attr = hl_attr(HLF_DED);
+ char_attr = win_hl_attr(wp, HLF_DED);
}
if (*p_sbr != NUL && need_showbreak) {
/* Draw 'showbreak' at the start of each broken line. */
p_extra = p_sbr;
c_extra = NUL;
n_extra = (int)STRLEN(p_sbr);
- char_attr = hl_attr(HLF_AT);
- need_showbreak = FALSE;
+ char_attr = win_hl_attr(wp, HLF_AT);
+ need_showbreak = false;
vcol_sbr = vcol + MB_CHARLEN(p_sbr);
/* Correct end of highlighted area for 'showbreak',
* required when 'linebreak' is also set. */
@@ -2842,7 +2851,7 @@ win_line (
tocol += n_extra;
/* combine 'showbreak' with 'cursorline' */
if (wp->w_p_cul && lnum == wp->w_cursor.lnum) {
- char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUL));
+ char_attr = hl_combine_attr(char_attr, win_hl_attr(wp, HLF_CUL));
}
}
}
@@ -2855,12 +2864,9 @@ win_line (
c_extra = saved_c_extra;
p_extra = saved_p_extra;
char_attr = saved_char_attr;
- } else
- char_attr = 0;
- }
-
- if (wp->w_hl_attr != 0) {
- char_attr = hl_combine_attr(wp->w_hl_attr, char_attr);
+ } else {
+ char_attr = wp->w_hl_attr_normal;
+ }
}
}
@@ -2869,13 +2875,14 @@ win_line (
&& lnum == wp->w_cursor.lnum && vcol >= (long)wp->w_virtcol
&& filler_todo <= 0
) {
- SCREEN_LINE(screen_row, wp->w_wincol, col, -wp->w_width, wp->w_p_rl);
- /* Pretend we have finished updating the window. Except when
- * 'cursorcolumn' is set. */
- if (wp->w_p_cuc)
+ screen_line(screen_row, wp->w_wincol, col, -wp->w_width, wp->w_p_rl, wp);
+ // Pretend we have finished updating the window. Except when
+ // 'cursorcolumn' is set.
+ if (wp->w_p_cuc) {
row = wp->w_cline_row + wp->w_cline_height;
- else
+ } else {
row = wp->w_height;
+ }
break;
}
@@ -3003,14 +3010,16 @@ win_line (
if (diff_hlf != (hlf_T)0) {
if (diff_hlf == HLF_CHD && ptr - line >= change_start
- && n_extra == 0)
- diff_hlf = HLF_TXD; /* changed text */
+ && n_extra == 0) {
+ diff_hlf = HLF_TXD; // changed text
+ }
if (diff_hlf == HLF_TXD && ptr - line > change_end
- && n_extra == 0)
- diff_hlf = HLF_CHD; /* changed line */
- line_attr = hl_attr(diff_hlf);
+ && n_extra == 0) {
+ diff_hlf = HLF_CHD; // changed line
+ }
+ line_attr = win_hl_attr(wp, diff_hlf);
if (wp->w_p_cul && lnum == wp->w_cursor.lnum) {
- line_attr = hl_combine_attr(line_attr, hl_attr(HLF_CUL));
+ line_attr = hl_combine_attr(line_attr, win_hl_attr(wp, HLF_CUL));
}
}
@@ -3026,14 +3035,15 @@ win_line (
// (area_attr may be 0 when "noinvcur" is set).
else if (line_attr != 0 && ((fromcol == -10 && tocol == MAXCOL)
|| vcol < fromcol || vcol_prev < fromcol_prev
- || vcol >= tocol))
+ || vcol >= tocol)) {
char_attr = line_attr;
- else {
- attr_pri = FALSE;
- if (has_syntax)
+ } else {
+ attr_pri = false;
+ if (has_syntax) {
char_attr = syntax_attr;
- else
- char_attr = 0;
+ } else {
+ char_attr = wp->w_hl_attr_normal;
+ }
}
}
@@ -3094,11 +3104,8 @@ win_line (
c = '>';
mb_c = c;
mb_l = 1;
- mb_utf8 = FALSE;
- multi_attr = hl_attr(HLF_AT);
- if (wp->w_hl_attr != 0) {
- multi_attr = hl_combine_attr(wp->w_hl_attr, multi_attr);
- }
+ mb_utf8 = false;
+ multi_attr = win_hl_attr(wp, HLF_AT);
// put the pointer back to output the double-width
// character at the start of the next line.
@@ -3166,8 +3173,8 @@ win_line (
c_extra = NUL;
if (area_attr == 0 && search_attr == 0) {
n_attr = n_extra + 1;
- extra_attr = hl_attr(HLF_8);
- saved_attr2 = char_attr; /* save current attr */
+ extra_attr = win_hl_attr(wp, HLF_8);
+ saved_attr2 = char_attr; // save current attr
}
} else if (mb_l == 0) /* at the NUL at end-of-line */
mb_l = 1;
@@ -3219,8 +3226,8 @@ win_line (
c = *p_extra++;
if (area_attr == 0 && search_attr == 0) {
n_attr = n_extra + 1;
- extra_attr = hl_attr(HLF_8);
- saved_attr2 = char_attr; /* save current attr */
+ extra_attr = win_hl_attr(wp, HLF_8);
+ saved_attr2 = char_attr; // save current attr
}
mb_c = c;
}
@@ -3237,10 +3244,7 @@ win_line (
mb_c = c;
mb_utf8 = FALSE;
mb_l = 1;
- multi_attr = hl_attr(HLF_AT);
- if (wp->w_hl_attr != 0) {
- multi_attr = hl_combine_attr(wp->w_hl_attr, multi_attr);
- }
+ multi_attr = win_hl_attr(wp, HLF_AT);
// Put pointer back so that the character will be
// displayed at the start of the next line.
ptr--;
@@ -3257,8 +3261,8 @@ win_line (
c = ' ';
if (area_attr == 0 && search_attr == 0) {
n_attr = n_extra + 1;
- extra_attr = hl_attr(HLF_AT);
- saved_attr2 = char_attr; /* save current attr */
+ extra_attr = win_hl_attr(wp, HLF_AT);
+ saved_attr2 = char_attr; // save current attr
}
mb_c = c;
mb_utf8 = FALSE;
@@ -3306,7 +3310,7 @@ win_line (
else
syntax_flags = get_syntax_info(&syntax_seqnr);
} else if (!attr_pri) {
- char_attr = 0;
+ char_attr = wp->w_hl_attr_normal;
}
/* Check spelling (unless at the end of the line).
@@ -3432,7 +3436,7 @@ win_line (
|| (c == ' ' && lcs_space && ptr - line <= trailcol))) {
c = (c == ' ') ? lcs_space : lcs_nbsp;
n_attr = 1;
- extra_attr = hl_attr(HLF_0);
+ extra_attr = win_hl_attr(wp, HLF_0);
saved_attr2 = char_attr; // save current attr
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1) {
@@ -3447,7 +3451,7 @@ win_line (
if (trailcol != MAXCOL && ptr > line + trailcol && c == ' ') {
c = lcs_trail;
n_attr = 1;
- extra_attr = hl_attr(HLF_0);
+ extra_attr = win_hl_attr(wp, HLF_0);
saved_attr2 = char_attr; // save current attr
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1) {
@@ -3548,7 +3552,7 @@ win_line (
c_extra = lcs_tab2;
}
n_attr = tab_len + 1;
- extra_attr = hl_attr(HLF_0);
+ extra_attr = win_hl_attr(wp, HLF_0);
saved_attr2 = char_attr; // save current attr
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1) {
@@ -3595,7 +3599,7 @@ win_line (
}
lcs_eol_one = -1;
ptr--; // put it back at the NUL
- extra_attr = hl_attr(HLF_AT);
+ extra_attr = win_hl_attr(wp, HLF_AT);
n_attr = 1;
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1) {
@@ -3626,7 +3630,7 @@ win_line (
c = *p_extra++;
}
n_attr = n_extra + 1;
- extra_attr = hl_attr(HLF_8);
+ extra_attr = win_hl_attr(wp, HLF_8);
saved_attr2 = char_attr; // save current attr
mb_utf8 = false; // don't draw as UTF-8
} else if (VIsual_active
@@ -3658,9 +3662,10 @@ win_line (
if (diff_hlf == HLF_TXD) {
diff_hlf = HLF_CHD;
if (attr == 0 || char_attr != attr) {
- char_attr = hl_attr(diff_hlf);
+ char_attr = win_hl_attr(wp, diff_hlf);
if (wp->w_p_cul && lnum == wp->w_cursor.lnum) {
- char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUL));
+ char_attr = hl_combine_attr(char_attr,
+ win_hl_attr(wp, HLF_CUL));
}
}
}
@@ -3762,7 +3767,7 @@ win_line (
c_extra = MB_FILLER_CHAR;
n_extra = 1;
n_attr = 2;
- extra_attr = hl_attr(HLF_AT);
+ extra_attr = win_hl_attr(wp, HLF_AT);
}
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1) {
@@ -3773,10 +3778,7 @@ win_line (
mb_utf8 = false; // don't draw as UTF-8
}
saved_attr3 = char_attr; // save current attr
- char_attr = hl_attr(HLF_AT); // overwriting char_attr
- if (wp->w_hl_attr != 0) {
- char_attr = hl_combine_attr(wp->w_hl_attr, char_attr);
- }
+ char_attr = win_hl_attr(wp, HLF_AT); // overwriting char_attr
n_attr3 = 1;
}
@@ -3861,8 +3863,8 @@ win_line (
}
}
- if (wp->w_hl_attr != 0) {
- char_attr = hl_combine_attr(wp->w_hl_attr, char_attr);
+ if (wp->w_hl_attr_normal != 0) {
+ char_attr = hl_combine_attr(wp->w_hl_attr_normal, char_attr);
}
ScreenAttrs[off] = char_attr;
if (wp->w_p_rl) {
@@ -3925,13 +3927,8 @@ win_line (
if (rightmost_vcol < color_cols[i])
rightmost_vcol = color_cols[i];
- int cuc_attr = hl_attr(HLF_CUC);
- int mc_attr = hl_attr(HLF_MC);
- if (wp->w_hl_attr != 0) {
- cuc_attr = hl_combine_attr(wp->w_hl_attr, cuc_attr);
- mc_attr = hl_combine_attr(wp->w_hl_attr, mc_attr);
- }
-
+ int cuc_attr = win_hl_attr(wp, HLF_CUC);
+ int mc_attr = win_hl_attr(wp, HLF_MC);
while (col < wp->w_width) {
ScreenLines[off] = ' ';
@@ -3947,7 +3944,7 @@ win_line (
} else if (draw_color_col && VCOL_HLC == *color_cols) {
ScreenAttrs[off++] = mc_attr;
} else {
- ScreenAttrs[off++] = wp->w_hl_attr;
+ ScreenAttrs[off++] = wp->w_hl_attr_normal;
}
if (VCOL_HLC >= rightmost_vcol)
@@ -3970,7 +3967,7 @@ win_line (
col++;
}
}
- SCREEN_LINE(screen_row, wp->w_wincol, col, wp->w_width, wp->w_p_rl);
+ screen_line(screen_row, wp->w_wincol, col, wp->w_width, wp->w_p_rl, wp);
row++;
/*
@@ -3998,10 +3995,7 @@ win_line (
|| (wp->w_p_list && lcs_eol_one > 0)
|| (n_extra && (c_extra != NUL || *p_extra != NUL)))) {
c = lcs_ext;
- char_attr = hl_attr(HLF_AT);
- if (wp->w_hl_attr != 0) {
- char_attr = hl_combine_attr(wp->w_hl_attr, char_attr);
- }
+ char_attr = win_hl_attr(wp, HLF_AT);
mb_c = c;
if (enc_utf8 && (*mb_char2len)(c) > 1) {
mb_utf8 = TRUE;
@@ -4024,10 +4018,10 @@ win_line (
if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol
&& lnum != wp->w_cursor.lnum) {
vcol_save_attr = char_attr;
- char_attr = hl_combine_attr(char_attr, hl_attr(HLF_CUC));
+ char_attr = hl_combine_attr(char_attr, win_hl_attr(wp, HLF_CUC));
} else if (draw_color_col && VCOL_HLC == *color_cols) {
vcol_save_attr = char_attr;
- char_attr = hl_combine_attr(char_attr, hl_attr(HLF_MC));
+ char_attr = hl_combine_attr(char_attr, win_hl_attr(wp, HLF_MC));
}
}
@@ -4195,8 +4189,8 @@ win_line (
|| (wp->w_p_list && lcs_eol != NUL && p_extra != at_end_str)
|| (n_extra != 0 && (c_extra != NUL || *p_extra != NUL)))
) {
- SCREEN_LINE(screen_row, wp->w_wincol, col - boguscols,
- wp->w_width, wp->w_p_rl);
+ screen_line(screen_row, wp->w_wincol, col - boguscols,
+ wp->w_width, wp->w_p_rl, wp);
boguscols = 0;
++row;
++screen_row;
@@ -4364,7 +4358,8 @@ static int char_needs_redraw(int off_from, int off_to, int cols)
* When TRUE and "clear_width" > 0, clear columns 0 to "endcol"
* When FALSE and "clear_width" > 0, clear columns "endcol" to "clear_width"
*/
-static void screen_line(int row, int coloff, int endcol, int clear_width, int rlflag)
+static void screen_line(int row, int coloff, int endcol,
+ int clear_width, int rlflag, win_T *wp)
{
unsigned off_from;
unsigned off_to;
@@ -4526,11 +4521,11 @@ static void screen_line(int row, int coloff, int endcol, int clear_width, int rl
}
if (clear_width > 0) {
- /* For a window that's left of another, draw the separator char. */
- if (col + coloff < Columns) {
+ // For a window that's left of another, draw the separator char.
+ if (col + coloff < Columns && wp->w_vsep_width > 0) {
int c;
- c = fillchar_vsep(&hl);
+ c = fillchar_vsep(wp, &hl);
if (ScreenLines[off_to] != (schar_T)c
|| (enc_utf8 && (int)ScreenLinesUC[off_to]
!= (c >= 0x80 ? c : 0))
@@ -4635,8 +4630,8 @@ static void draw_vsep_win(win_T *wp, int row)
int c;
if (wp->w_vsep_width) {
- /* draw the vertical separator right of this window */
- c = fillchar_vsep(&hl);
+ // draw the vertical separator right of this window
+ c = fillchar_vsep(wp, &hl);
screen_fill(wp->w_winrow + row, wp->w_winrow + wp->w_height,
W_ENDCOL(wp), W_ENDCOL(wp) + 1,
c, ' ', hl);
@@ -4766,7 +4761,7 @@ win_redr_status_matches (
--first_match;
}
- fillchar = fillchar_status(&attr, TRUE);
+ fillchar = fillchar_status(&attr, curwin);
if (first_match == 0) {
*buf = NUL;
@@ -4898,7 +4893,7 @@ void win_redr_status(win_T *wp)
/* redraw custom status line */
redraw_custom_statusline(wp);
} else {
- fillchar = fillchar_status(&attr, wp == curwin);
+ fillchar = fillchar_status(&attr, wp);
get_trans_bufname(wp->w_buffer);
p = NameBuff;
@@ -4970,10 +4965,11 @@ void win_redr_status(win_T *wp)
* May need to draw the character below the vertical separator.
*/
if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing()) {
- if (stl_connected(wp))
- fillchar = fillchar_status(&attr, wp == curwin);
- else
- fillchar = fillchar_vsep(&attr);
+ if (stl_connected(wp)) {
+ fillchar = fillchar_status(&attr, wp);
+ } else {
+ fillchar = fillchar_vsep(wp, &attr);
+ }
screen_putchar(fillchar, wp->w_winrow + wp->w_height,
W_ENDCOL(wp), attr);
}
@@ -5123,7 +5119,7 @@ win_redr_custom (
use_sandbox = was_set_insecurely((char_u *)"tabline", 0);
} else {
row = wp->w_winrow + wp->w_height;
- fillchar = fillchar_status(&attr, wp == curwin);
+ fillchar = fillchar_status(&attr, wp);
maxwidth = wp->w_width;
if (draw_ruler) {
@@ -5508,8 +5504,7 @@ static void start_search_hl(void)
{
if (p_hls && !no_hlsearch) {
last_pat_prog(&search_hl.rm);
- search_hl.attr = hl_attr(HLF_L);
- /* Set the time limit to 'redrawtime'. */
+ // Set the time limit to 'redrawtime'.
search_hl.tm = profile_setlimit(p_rdt);
}
}
@@ -5525,6 +5520,42 @@ static void end_search_hl(void)
}
}
+static void update_window_hl(win_T *wp, bool invalid)
+{
+ if (!wp->w_hl_needs_update && !invalid) {
+ return;
+ }
+ wp->w_hl_needs_update = false;
+
+ // determine window specific background set in 'winhighlight'
+ if (wp != curwin && wp->w_hl_ids[HLF_INACTIVE] > 0) {
+ wp->w_hl_attr_normal = syn_id2attr(wp->w_hl_ids[HLF_INACTIVE]);
+ } else if (wp->w_hl_id_normal > 0) {
+ wp->w_hl_attr_normal = syn_id2attr(wp->w_hl_id_normal);
+ } else {
+ wp->w_hl_attr_normal = 0;
+ }
+ if (wp != curwin) {
+ wp->w_hl_attr_normal = hl_combine_attr(hl_attr(HLF_INACTIVE),
+ wp->w_hl_attr_normal);
+ }
+
+ for (int hlf = 0; hlf < (int)HLF_COUNT; hlf++) {
+ int attr;
+ if (wp->w_hl_ids[hlf] > 0) {
+ attr = syn_id2attr(wp->w_hl_ids[hlf]);
+ } else {
+ attr = hl_attr(hlf);
+ }
+ if (wp->w_hl_attr_normal != 0) {
+ attr = hl_combine_attr(wp->w_hl_attr_normal, attr);
+ }
+ wp->w_hl_attrs[hlf] = attr;
+ }
+}
+
+
+
/*
* Init for calling prepare_search_hl().
*/
@@ -5551,19 +5582,9 @@ static void init_search_hl(win_T *wp)
search_hl.buf = wp->w_buffer;
search_hl.lnum = 0;
search_hl.first_lnum = 0;
- // time limit is set at the toplevel, for all windows
+ search_hl.attr = win_hl_attr(wp, HLF_L);
- // determine window specific background set in 'winhighlight'
- if (wp != curwin && wp->w_hl_id_inactive > 0) {
- wp->w_hl_attr = syn_id2attr(wp->w_hl_id_inactive);
- } else if (wp->w_hl_id > 0) {
- wp->w_hl_attr = syn_id2attr(wp->w_hl_id);
- } else {
- wp->w_hl_attr = 0;
- }
- if (wp != curwin) {
- wp->w_hl_attr = hl_combine_attr(hl_attr(HLF_INACTIVE), wp->w_hl_attr);
- }
+ // time limit is set at the toplevel, for all windows
}
/*
@@ -6775,7 +6796,7 @@ int showmode(void)
if (edit_submode_extra != NULL) {
MSG_PUTS_ATTR(" ", attr); // Add a space in between.
if ((int)edit_submode_highl < (int)HLF_COUNT) {
- sub_attr = hl_attr(edit_submode_highl);
+ sub_attr = win_hl_attr(curwin, edit_submode_highl);
} else {
sub_attr = attr;
}
@@ -6928,7 +6949,6 @@ static void draw_tabline(void)
int modified;
int c;
int len;
- int attr_sel = hl_attr(HLF_TPS);
int attr_nosel = hl_attr(HLF_TP);
int attr_fill = hl_attr(HLF_TPF);
char_u *p;
@@ -6990,16 +7010,6 @@ static void draw_tabline(void)
scol = col;
- if (tp->tp_topframe == topframe)
- attr = attr_sel;
- if (use_sep_chars && col > 0)
- screen_putchar('|', 0, col++, attr);
-
- if (tp->tp_topframe != topframe)
- attr = attr_nosel;
-
- screen_putchar(' ', 0, col++, attr);
-
if (tp == curtab) {
cwp = curwin;
wp = firstwin;
@@ -7008,10 +7018,29 @@ static void draw_tabline(void)
wp = tp->tp_firstwin;
}
- modified = FALSE;
- for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
- if (bufIsChanged(wp->w_buffer))
- modified = TRUE;
+
+ if (tp->tp_topframe == topframe) {
+ attr = win_hl_attr(cwp, HLF_TPS);
+ }
+ if (use_sep_chars && col > 0) {
+ screen_putchar('|', 0, col++, attr);
+ }
+
+ if (tp->tp_topframe != topframe) {
+ attr = win_hl_attr(cwp, HLF_TP);
+ }
+
+ screen_putchar(' ', 0, col++, attr);
+
+ modified = false;
+
+ for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount) {
+ if (bufIsChanged(wp->w_buffer)) {
+ modified = true;
+ }
+ }
+
+
if (modified || wincount > 1) {
if (wincount > 1) {
vim_snprintf((char *)NameBuff, MAXPATHL, "%d", wincount);
@@ -7019,7 +7048,7 @@ static void draw_tabline(void)
if (col + len >= Columns - 3)
break;
screen_puts_len(NameBuff, len, 0, col,
- hl_combine_attr(attr, hl_attr(HLF_T)));
+ hl_combine_attr(attr, win_hl_attr(cwp, HLF_T)));
col += len;
}
if (modified)
@@ -7117,25 +7146,28 @@ void get_trans_bufname(buf_T *buf)
/*
* Get the character to use in a status line. Get its attributes in "*attr".
*/
-static int fillchar_status(int *attr, int is_curwin)
+static int fillchar_status(int *attr, win_T *wp)
{
int fill;
+ bool is_curwin = (wp == curwin);
if (is_curwin) {
- *attr = hl_attr(HLF_S);
+ *attr = win_hl_attr(wp, HLF_S);
fill = fill_stl;
} else {
- *attr = hl_attr(HLF_SNC);
+ *attr = win_hl_attr(wp, HLF_SNC);
fill = fill_stlnc;
}
/* Use fill when there is highlighting, and highlighting of current
* window differs, or the fillchars differ, or this is not the
* current window */
- if (*attr != 0 && ((hl_attr(HLF_S) != hl_attr(HLF_SNC)
+ if (*attr != 0 && ((win_hl_attr(wp, HLF_S) != win_hl_attr(wp, HLF_SNC)
|| !is_curwin || firstwin == lastwin)
- || (fill_stl != fill_stlnc)))
+ || (fill_stl != fill_stlnc))) {
return fill;
- if (is_curwin)
+ }
+ if (is_curwin) {
return '^';
+ }
return '=';
}
@@ -7143,13 +7175,14 @@ static int fillchar_status(int *attr, int is_curwin)
* Get the character to use in a separator between vertically split windows.
* Get its attributes in "*attr".
*/
-static int fillchar_vsep(int *attr)
+static int fillchar_vsep(win_T *wp, int *attr)
{
- *attr = hl_attr(HLF_C);
- if (*attr == 0 && fill_vert == ' ')
+ *attr = win_hl_attr(wp, HLF_C);
+ if (*attr == 0 && fill_vert == ' ') {
return '|';
- else
+ } else {
return fill_vert;
+ }
}
/*
@@ -7264,7 +7297,7 @@ static void win_redr_ruler(win_T *wp, int always)
if (wp->w_status_height) {
row = wp->w_winrow + wp->w_height;
- fillchar = fillchar_status(&attr, wp == curwin);
+ fillchar = fillchar_status(&attr, wp);
off = wp->w_wincol;
width = wp->w_width;
} else {
diff --git a/src/nvim/search.c b/src/nvim/search.c
index 61ef2e9ba3..1bf2317d2a 100644
--- a/src/nvim/search.c
+++ b/src/nvim/search.c
@@ -1005,14 +1005,13 @@ int do_search(
dircp = NULL;
/* use previous pattern */
if (pat == NULL || *pat == NUL || *pat == dirc) {
- if (spats[RE_SEARCH].pat == NULL) { /* no previous pattern */
- pat = spats[RE_SUBST].pat;
- if (pat == NULL) {
+ if (spats[RE_SEARCH].pat == NULL) { // no previous pattern
+ searchstr = spats[RE_SUBST].pat;
+ if (searchstr == NULL) {
EMSG(_(e_noprevre));
retval = 0;
goto end_do_search;
}
- searchstr = pat;
} else {
/* make search_regcomp() use spats[RE_SEARCH].pat */
searchstr = (char_u *)"";
diff --git a/src/nvim/shada.c b/src/nvim/shada.c
index 87b4617099..4788b1e7d0 100644
--- a/src/nvim/shada.c
+++ b/src/nvim/shada.c
@@ -98,6 +98,7 @@ KHASH_SET_INIT_STR(strset)
#define REG_KEY_TYPE "rt"
#define REG_KEY_WIDTH "rw"
#define REG_KEY_CONTENTS "rc"
+#define REG_KEY_UNNAMED "ru"
#define KEY_LNUM "l"
#define KEY_COL "c"
@@ -284,6 +285,7 @@ typedef struct {
char name;
MotionType type;
char **contents;
+ bool is_unnamed;
size_t contents_size;
size_t width;
dict_T *additional_data;
@@ -473,6 +475,7 @@ static const ShadaEntry sd_default_values[] = {
.type = kMTCharWise,
.contents = NULL,
.contents_size = 0,
+ .is_unnamed = false,
.width = 0,
.additional_data = NULL),
DEF_SDE(Variable, global_var,
@@ -1335,7 +1338,7 @@ static void shada_read(ShaDaReadDef *const sd_reader, const int flags)
.y_width = (colnr_T) cur_entry.data.reg.width,
.timestamp = cur_entry.timestamp,
.additional_data = cur_entry.data.reg.additional_data,
- })) {
+ }, cur_entry.data.reg.is_unnamed)) {
shada_free_shada_entry(&cur_entry);
}
// Do not free shada entry: its allocated memory was saved above.
@@ -1780,6 +1783,7 @@ static ShaDaWriteResult shada_pack_entry(msgpack_packer *const packer,
2 // Register contents and name
+ ONE_IF_NOT_DEFAULT(entry, reg.type)
+ ONE_IF_NOT_DEFAULT(entry, reg.width)
+ + ONE_IF_NOT_DEFAULT(entry, reg.is_unnamed)
// Additional entries, if any:
+ (size_t) (entry.data.reg.additional_data == NULL
? 0
@@ -1800,6 +1804,14 @@ static ShaDaWriteResult shada_pack_entry(msgpack_packer *const packer,
PACK_STATIC_STR(REG_KEY_WIDTH);
msgpack_pack_uint64(spacker, (uint64_t) entry.data.reg.width);
}
+ if (!CHECK_DEFAULT(entry, reg.is_unnamed)) {
+ PACK_STATIC_STR(REG_KEY_UNNAMED);
+ if (entry.data.reg.is_unnamed) {
+ msgpack_pack_true(spacker);
+ } else {
+ msgpack_pack_false(spacker);
+ }
+ }
DUMP_ADDITIONAL_DATA(entry.data.reg.additional_data, "register item");
break;
}
@@ -2318,6 +2330,48 @@ static inline void add_search_pattern(PossiblyFreedShadaEntry *const ret_pse,
}
}
+/// Initialize registers for writing to the ShaDa file
+///
+/// @param[in] wms The WriteMergerState used when writing.
+/// @param[in] max_reg_lines The maximum number of register lines.
+static inline void shada_initialize_registers(WriteMergerState *const wms,
+ int max_reg_lines)
+ FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
+{
+ const void *reg_iter = NULL;
+ const bool limit_reg_lines = max_reg_lines >= 0;
+ do {
+ yankreg_T reg;
+ char name = NUL;
+ bool is_unnamed = false;
+ reg_iter = op_register_iter(reg_iter, &name, &reg, &is_unnamed);
+ if (name == NUL) {
+ break;
+ }
+ if (limit_reg_lines && reg.y_size > (size_t)max_reg_lines) {
+ continue;
+ }
+ wms->registers[op_reg_index(name)] = (PossiblyFreedShadaEntry) {
+ .can_free_entry = false,
+ .data = {
+ .type = kSDItemRegister,
+ .timestamp = reg.timestamp,
+ .data = {
+ .reg = {
+ .contents = (char **)reg.y_array,
+ .contents_size = (size_t)reg.y_size,
+ .type = reg.y_type,
+ .width = (size_t)(reg.y_type == kMTBlockWise ? reg.y_width : 0),
+ .additional_data = reg.additional_data,
+ .name = name,
+ .is_unnamed = is_unnamed,
+ }
+ }
+ }
+ };
+ } while (reg_iter != NULL);
+}
+
/// Write ShaDa file
///
/// @param[in] sd_writer Structure containing file writer definition.
@@ -2344,7 +2398,6 @@ static ShaDaWriteResult shada_write(ShaDaWriteDef *const sd_writer,
if (max_reg_lines < 0) {
max_reg_lines = get_shada_parameter('"');
}
- const bool limit_reg_lines = max_reg_lines >= 0;
const bool dump_registers = (max_reg_lines != 0);
khash_t(bufset) removable_bufs = KHASH_EMPTY_TABLE(bufset);
const size_t max_kbyte = (size_t) max_kbyte_i;
@@ -2587,35 +2640,7 @@ static ShaDaWriteResult shada_write(ShaDaWriteDef *const sd_writer,
// Initialize registers
if (dump_registers) {
- const void *reg_iter = NULL;
- do {
- yankreg_T reg;
- char name = NUL;
- reg_iter = op_register_iter(reg_iter, &name, &reg);
- if (name == NUL) {
- break;
- }
- if (limit_reg_lines && reg.y_size > (size_t)max_reg_lines) {
- continue;
- }
- wms->registers[op_reg_index(name)] = (PossiblyFreedShadaEntry) {
- .can_free_entry = false,
- .data = {
- .type = kSDItemRegister,
- .timestamp = reg.timestamp,
- .data = {
- .reg = {
- .contents = (char **) reg.y_array,
- .contents_size = (size_t) reg.y_size,
- .type = reg.y_type,
- .width = (size_t) (reg.y_type == kMTBlockWise ? reg.y_width : 0),
- .additional_data = reg.additional_data,
- .name = name,
- }
- }
- }
- };
- } while (reg_iter != NULL);
+ shada_initialize_registers(wms, max_reg_lines);
}
// Initialize buffers
@@ -3594,6 +3619,7 @@ shada_read_next_item_start:
entry->data.reg.contents[i] = BIN_CONVERTED(arr.ptr[i].via.bin);
}
}
+ BOOLEAN_KEY("register", REG_KEY_UNNAMED, entry->data.reg.is_unnamed)
TYPED_KEY("register", REG_KEY_TYPE, "an unsigned integer",
entry->data.reg.type, POSITIVE_INTEGER, u64, TOU8)
TYPED_KEY("register", KEY_NAME_CHAR, "an unsigned integer",
diff --git a/src/nvim/strings.c b/src/nvim/strings.c
index c5fd8741b8..687f734742 100644
--- a/src/nvim/strings.c
+++ b/src/nvim/strings.c
@@ -653,7 +653,7 @@ static float_T tv_float(typval_T *const tvs, int *const idxp)
if (tvs[idx].v_type == VAR_FLOAT) {
f = tvs[idx].vval.v_float;
} else if (tvs[idx].v_type == VAR_NUMBER) {
- f = tvs[idx].vval.v_number;
+ f = (float_T)tvs[idx].vval.v_number;
} else {
EMSG(_("E807: Expected Float argument for printf()"));
}
@@ -910,6 +910,13 @@ int vim_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap,
default: break;
}
+ switch (fmt_spec) {
+ case 'd': case 'u': case 'o': case 'x': case 'X':
+ if (tvs && length_modifier == '\0') {
+ length_modifier = '2';
+ }
+ }
+
// get parameter value, do initial processing
switch (fmt_spec) {
// '%' and 'c' behave similar to 's' regarding flags and field widths
diff --git a/src/nvim/syntax_defs.h b/src/nvim/syntax_defs.h
index 8d207e6286..9f309451b0 100644
--- a/src/nvim/syntax_defs.h
+++ b/src/nvim/syntax_defs.h
@@ -1,10 +1,9 @@
#ifndef NVIM_SYNTAX_DEFS_H
#define NVIM_SYNTAX_DEFS_H
+#include "nvim/highlight_defs.h"
#include "nvim/regexp_defs.h"
-typedef int32_t RgbValue;
-
# define SST_MIN_ENTRIES 150 /* minimal size for state stack array */
# define SST_MAX_ENTRIES 1000 /* maximal size for state stack array */
# define SST_FIX_STATES 7 /* size of sst_stack[]. */
diff --git a/src/nvim/tag.c b/src/nvim/tag.c
index 88b45add54..be9d621c7d 100644
--- a/src/nvim/tag.c
+++ b/src/nvim/tag.c
@@ -106,15 +106,6 @@ static char_u *topmsg = (char_u *)N_("E556: at top of tag stack");
static char_u *tagmatchname = NULL; /* name of last used tag */
/*
- * We use ftello() here, if available. It returns off_t instead of long,
- * which helps if long is 32 bit and off_t is 64 bit.
- * We assume that when fseeko() is available then ftello() is too.
- */
-#ifdef HAVE_FSEEKO
-# define ftell ftello
-#endif
-
-/*
* Tag for preview window is remembered separately, to avoid messing up the
* normal tagstack.
*/
@@ -1088,22 +1079,21 @@ find_tags (
char_u *p;
char_u *s;
int i;
- int tag_file_sorted = NUL; /* !_TAG_FILE_SORTED value */
- struct tag_search_info /* Binary search file offsets */
- {
- off_t low_offset; /* offset for first char of first line that
- could match */
- off_t high_offset; /* offset of char after last line that could
- match */
- off_t curr_offset; /* Current file offset in search range */
- off_t curr_offset_used; /* curr_offset used when skipping back */
- off_t match_offset; /* Where the binary search found a tag */
- int low_char; /* first char at low_offset */
- int high_char; /* first char at high_offset */
+ int tag_file_sorted = NUL; // !_TAG_FILE_SORTED value
+ struct tag_search_info { // Binary search file offsets
+ off_T low_offset; // offset for first char of first line that
+ // could match
+ off_T high_offset; // offset of char after last line that could
+ // match
+ off_T curr_offset; // Current file offset in search range
+ off_T curr_offset_used; // curr_offset used when skipping back
+ off_T match_offset; // Where the binary search found a tag
+ int low_char; // first char at low_offset
+ int high_char; // first char at high_offset
} search_info;
- off_t filesize;
+ off_T filesize;
int tagcmp;
- off_t offset;
+ off_T offset;
int round;
enum {
TS_START, /* at start of file */
@@ -1378,36 +1368,28 @@ find_tags (
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;
-#ifdef HAVE_FSEEKO
- fseeko(fp, search_info.curr_offset, SEEK_SET);
-#else
- fseek(fp, (long)search_info.curr_offset, SEEK_SET);
-#endif
+ vim_fseek(fp, search_info.curr_offset, SEEK_SET);
eof = vim_fgets(lbuf, LSIZE, fp);
if (!eof && search_info.curr_offset != 0) {
/* The explicit cast is to work around a bug in gcc 3.4.2
* (repeated below). */
- search_info.curr_offset = ftell(fp);
+ search_info.curr_offset = vim_ftell(fp);
if (search_info.curr_offset == search_info.high_offset) {
- /* oops, gone a bit too far; try from low offset */
-#ifdef HAVE_FSEEKO
- fseeko(fp, search_info.low_offset, SEEK_SET);
-#else
- fseek(fp, (long)search_info.low_offset, SEEK_SET);
-#endif
+ // oops, gone a bit too far; try from low offset
+ vim_fseek(fp, search_info.low_offset, SEEK_SET);
search_info.curr_offset = search_info.low_offset;
}
eof = vim_fgets(lbuf, LSIZE, fp);
}
/* skip empty and blank lines */
while (!eof && vim_isblankline(lbuf)) {
- search_info.curr_offset = ftell(fp);
+ search_info.curr_offset = vim_ftell(fp);
eof = vim_fgets(lbuf, LSIZE, fp);
}
if (eof) {
/* Hit end of file. Skip backwards. */
state = TS_SKIP_BACK;
- search_info.match_offset = ftell(fp);
+ search_info.match_offset = vim_ftell(fp);
search_info.curr_offset = search_info.curr_offset_used;
continue;
}
@@ -1523,10 +1505,10 @@ line_read_in:
*/
if (state == TS_BINARY) {
// Get the tag file size.
- if ((filesize = lseek(fileno(fp), (off_t)0L, SEEK_END)) <= 0) {
+ if ((filesize = vim_lseek(fileno(fp), (off_T)0L, SEEK_END)) <= 0) {
state = TS_LINEAR;
} else {
- lseek(fileno(fp), (off_t)0L, SEEK_SET);
+ vim_lseek(fileno(fp), (off_T)0L, SEEK_SET);
/* Calculate the first read offset in the file. Start
* the search in the middle of the file. */
@@ -1564,11 +1546,7 @@ parse_line:
/* Avoid getting stuck. */
linear = TRUE;
state = TS_LINEAR;
-# ifdef HAVE_FSEEKO
- fseeko(fp, search_info.low_offset, SEEK_SET);
-# else
- fseek(fp, (long)search_info.low_offset, SEEK_SET);
-# endif
+ vim_fseek(fp, search_info.low_offset, SEEK_SET);
}
continue;
}
@@ -1647,7 +1625,7 @@ parse_line:
continue;
}
if (tagcmp < 0) {
- search_info.curr_offset = ftell(fp);
+ search_info.curr_offset = vim_ftell(fp);
if (search_info.curr_offset < search_info.high_offset) {
search_info.low_offset = search_info.curr_offset;
if (sortic)
@@ -1683,10 +1661,11 @@ parse_line:
} else if (state == TS_STEP_FORWARD) {
assert(cmplen >= 0);
if (mb_strnicmp(tagp.tagname, orgpat.head, (size_t)cmplen) != 0) {
- if ((off_t)ftell(fp) > search_info.match_offset)
- break; /* past last match */
- else
- continue; /* before first match */
+ if ((off_T)vim_ftell(fp) > search_info.match_offset) {
+ break; // past last match
+ } else {
+ continue; // before first match
+ }
}
} else
/* skip this match if it can't match */
@@ -1907,10 +1886,11 @@ parse_line:
if (line_error) {
EMSG2(_("E431: Format error in tags file \"%s\""), tag_fname);
- if (!use_cscope)
- EMSGN(_("Before byte %" PRId64), ftell(fp));
- stop_searching = TRUE;
- line_error = FALSE;
+ if (!use_cscope) {
+ EMSGN(_("Before byte %" PRId64), vim_ftell(fp));
+ }
+ stop_searching = true;
+ line_error = false;
}
if (!use_cscope)
diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c
index b8b7085c5e..1882f263db 100644
--- a/src/nvim/terminal.c
+++ b/src/nvim/terminal.c
@@ -237,8 +237,6 @@ Terminal *terminal_open(TerminalOptions opts)
curbuf->b_p_scbk = p_scbk; // 'scrollback'
curbuf->b_p_tw = 0; // 'textwidth'
set_option_value("wrap", false, NULL, OPT_LOCAL);
- set_option_value("number", false, NULL, OPT_LOCAL);
- set_option_value("relativenumber", false, NULL, OPT_LOCAL);
set_option_value("list", false, NULL, OPT_LOCAL);
buf_set_term_title(curbuf, (char *)curbuf->b_ffname);
RESET_BINDING(curwin);
@@ -603,8 +601,10 @@ void terminal_get_line_attributes(Terminal *term, win_T *wp, int linenr,
if (term->cursor.visible && term->cursor.row == row
&& term->cursor.col == col) {
- attr_id = hl_combine_attr(attr_id, is_focused(term) && wp == curwin ?
- hl_attr(HLF_TERM) : hl_attr(HLF_TERMNC));
+ attr_id = hl_combine_attr(attr_id,
+ is_focused(term) && wp == curwin
+ ? win_hl_attr(wp, HLF_TERM)
+ : win_hl_attr(wp, HLF_TERMNC));
}
term_attrs[col] = attr_id;
@@ -639,7 +639,7 @@ static int term_movecursor(VTermPos new, VTermPos old, int visible,
}
static void buf_set_term_title(buf_T *buf, char *title)
- FUNC_ATTR_NONNULL_ALL
+ FUNC_ATTR_NONNULL_ALL
{
Error err = ERROR_INIT;
dict_set_var(buf->b_vars,
diff --git a/src/nvim/testdir/Makefile b/src/nvim/testdir/Makefile
index 70a9f2b8c4..7e55fffa06 100644
--- a/src/nvim/testdir/Makefile
+++ b/src/nvim/testdir/Makefile
@@ -58,8 +58,10 @@ NEW_TESTS ?= \
test_nested_function.res \
test_normal.res \
test_quickfix.res \
+ test_search.res \
test_signs.res \
test_smartindent.res \
+ test_stat.res \
test_substitute.res \
test_syntax.res \
test_tabpage.res \
@@ -67,7 +69,7 @@ NEW_TESTS ?= \
test_timers.res \
test_undo.res \
test_usercommands.res \
- test_viml.res \
+ test_vimscript.res \
test_visual.res \
test_window_id.res \
test_writefile.res \
diff --git a/src/nvim/testdir/runtest.vim b/src/nvim/testdir/runtest.vim
index a754e5fdfb..117ba52eb6 100644
--- a/src/nvim/testdir/runtest.vim
+++ b/src/nvim/testdir/runtest.vim
@@ -74,9 +74,9 @@ set backspace=
set nohidden smarttab noautoindent noautoread complete-=i noruler noshowcmd
set listchars=eol:$
" Prevent Nvim log from writing to stderr.
-let $NVIM_LOG_FILE='Xnvim.log'
+let $NVIM_LOG_FILE = exists($NVIM_LOG_FILE) ? $NVIM_LOG_FILE : 'Xnvim.log'
-function RunTheTest(test)
+func RunTheTest(test)
echo 'Executing ' . a:test
if exists("*SetUp")
call SetUp()
@@ -113,6 +113,60 @@ function RunTheTest(test)
set nomodified
endfunc
+func AfterTheTest()
+ if len(v:errors) > 0
+ let s:fail += 1
+ call add(s:errors, 'Found errors in ' . s:test . ':')
+ call extend(s:errors, v:errors)
+ let v:errors = []
+ endif
+endfunc
+
+" This function can be called by a test if it wants to abort testing.
+func FinishTesting()
+ call AfterTheTest()
+
+ " Don't write viminfo on exit.
+ set viminfo=
+
+ if s:fail == 0
+ " Success, create the .res file so that make knows it's done.
+ exe 'split ' . fnamemodify(g:testname, ':r') . '.res'
+ write
+ endif
+
+ if len(s:errors) > 0
+ " Append errors to test.log
+ split test.log
+ call append(line('$'), '')
+ call append(line('$'), 'From ' . g:testname . ':')
+ call append(line('$'), s:errors)
+ write
+ endif
+
+ let message = 'Executed ' . s:done . (s:done > 1 ? ' tests' : ' test')
+ echo message
+ call add(s:messages, message)
+ if s:fail > 0
+ let message = s:fail . ' FAILED:'
+ echo message
+ call add(s:messages, message)
+ call extend(s:messages, s:errors)
+ endif
+
+ " Add SKIPPED messages
+ call extend(s:messages, s:skipped)
+
+ " Append messages to the file "messages"
+ split messages
+ call append(line('$'), '')
+ call append(line('$'), 'From ' . g:testname . ':')
+ call append(line('$'), s:messages)
+ write
+
+ qall!
+endfunc
+
" Source the test script. First grab the file name, in case the script
" navigates away. g:testname can be used by the tests.
let g:testname = expand('%')
@@ -121,7 +175,7 @@ let s:fail = 0
let s:errors = []
let s:messages = []
let s:skipped = []
-if expand('%') =~ 'test_viml.vim'
+if expand('%') =~ 'test_vimscript.vim'
" this test has intentional s:errors, don't use try/catch.
source %
else
@@ -136,7 +190,8 @@ endif
" Names of flaky tests.
let s:flaky = [
\ 'Test_with_partial_callback()',
- \ 'Test_oneshot()'
+ \ 'Test_oneshot()',
+ \ 'Test_lambda_with_timer()',
\ ]
" Locate Test_ functions and execute them.
@@ -156,56 +211,14 @@ for s:test in sort(s:tests)
call RunTheTest(s:test)
if len(v:errors) > 0 && index(s:flaky, s:test) >= 0
- call add(s:messages, 'Flaky test failed, running it again')
- let v:errors = []
- call RunTheTest(s:test)
- endif
-
- if len(v:errors) > 0
- let s:fail += 1
- call add(s:errors, 'Found errors in ' . s:test . ':')
- call extend(s:errors, v:errors)
+ call add(s:messages, 'Flaky test failed, running it again')
let v:errors = []
+ call RunTheTest(s:test)
endif
+ call AfterTheTest()
endfor
-" Don't write viminfo on exit.
-set viminfo=
-
-if s:fail == 0
- " Success, create the .res file so that make knows it's done.
- exe 'split ' . fnamemodify(g:testname, ':r') . '.res'
- write
-endif
-
-if len(s:errors) > 0
- " Append errors to test.log
- split test.log
- call append(line('$'), '')
- call append(line('$'), 'From ' . g:testname . ':')
- call append(line('$'), s:errors)
- write
-endif
-
-let message = 'Executed ' . s:done . (s:done > 1 ? ' tests': ' test')
-echo message
-call add(s:messages, message)
-if s:fail > 0
- let message = s:fail . ' FAILED'
- echo message
- call add(s:messages, message)
- call extend(s:messages, s:errors)
-endif
-
-" Add SKIPPED messages
-call extend(s:messages, s:skipped)
-
-" Append messages to the file "messages"
-split messages
-call append(line('$'), '')
-call append(line('$'), 'From ' . g:testname . ':')
-call append(line('$'), s:messages)
-write
+call FinishTesting()
-qall!
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/shared.vim b/src/nvim/testdir/shared.vim
index 784e4a0a02..72cfea96c6 100644
--- a/src/nvim/testdir/shared.vim
+++ b/src/nvim/testdir/shared.vim
@@ -187,7 +187,7 @@ func RunVim(before, after, arguments)
endfunc
func RunVimPiped(before, after, arguments, pipecmd)
- let $NVIM_LOG_FILE='Xnvim.log'
+ let $NVIM_LOG_FILE = exists($NVIM_LOG_FILE) ? $NVIM_LOG_FILE : 'Xnvim.log'
let cmd = GetVimCommand()
if cmd == ''
return 0
diff --git a/src/nvim/testdir/test49.vim b/src/nvim/testdir/test49.vim
index adbabd61b9..467abcd9b9 100644
--- a/src/nvim/testdir/test49.vim
+++ b/src/nvim/testdir/test49.vim
@@ -608,7 +608,7 @@ com! -nargs=1 -bar ExecAsScript call ExecAsScript(<f-args>)
" END_OF_TEST_ENVIRONMENT - do not change or remove this line.
-" Tests 1 to 15 were moved to test_viml.vim
+" Tests 1 to 15 were moved to test_vimscript.vim
let Xtest = 16
"-------------------------------------------------------------------------------
diff --git a/src/nvim/testdir/test_alot.vim b/src/nvim/testdir/test_alot.vim
index 5da9a8b0f4..1103778107 100644
--- a/src/nvim/testdir/test_alot.vim
+++ b/src/nvim/testdir/test_alot.vim
@@ -10,6 +10,8 @@ source test_expr_utf8.vim
source test_feedkeys.vim
source test_filter_cmd.vim
source test_filter_map.vim
+source test_float_func.vim
+source test_functions.vim
source test_goto.vim
source test_jumps.vim
source test_lambda.vim
diff --git a/src/nvim/testdir/test_cscope.vim b/src/nvim/testdir/test_cscope.vim
index c8d2ebd7da..01a9a3f9ad 100644
--- a/src/nvim/testdir/test_cscope.vim
+++ b/src/nvim/testdir/test_cscope.vim
@@ -28,7 +28,7 @@ func Test_cscopeWithCscopeConnections()
cscope add Xcscope.out
set cscopeverbose
catch
- call assert_true(0)
+ call assert_report('exception thrown')
endtry
call assert_fails('cscope add', 'E560')
call assert_fails('cscope add Xcscope.out', 'E568')
diff --git a/src/nvim/testdir/test_cursor_func.vim b/src/nvim/testdir/test_cursor_func.vim
index d819b7b092..e1b9651c84 100644
--- a/src/nvim/testdir/test_cursor_func.vim
+++ b/src/nvim/testdir/test_cursor_func.vim
@@ -1,13 +1,7 @@
" Tests for cursor().
func Test_wrong_arguments()
- try
- call cursor(1. 3)
- " not reached
- call assert_false(1)
- catch
- call assert_exception('E474:')
- endtry
+ call assert_fails('call cursor(1. 3)', 'E474:')
endfunc
func Test_move_cursor()
diff --git a/src/nvim/testdir/test_expr.vim b/src/nvim/testdir/test_expr.vim
index 03a9155512..82c5d21bd0 100644
--- a/src/nvim/testdir/test_expr.vim
+++ b/src/nvim/testdir/test_expr.vim
@@ -78,7 +78,7 @@ endfunc
func Test_loop_over_null_list()
let null_list = submatch(1, 1)
for i in null_list
- call assert_true(0, 'should not get here')
+ call assert_report('should not get here')
endfor
endfunc
@@ -98,6 +98,35 @@ func Test_special_char()
call assert_fails('echo "\<C-">')
endfunc
+func Test_option_value()
+ " boolean
+ set bri
+ call assert_equal(1, &bri)
+ set nobri
+ call assert_equal(0, &bri)
+
+ " number
+ set ts=1
+ call assert_equal(1, &ts)
+ set ts=8
+ call assert_equal(8, &ts)
+
+ " string
+ exe "set cedit=\<Esc>"
+ call assert_equal("\<Esc>", &cedit)
+ set cpo=
+ call assert_equal("", &cpo)
+ set cpo=abcdefi
+ call assert_equal("abcdefi", &cpo)
+ set cpo&vim
+endfunc
+
+function Test_printf_64bit()
+ if has('num64')
+ call assert_equal("123456789012345", printf('%d', 123456789012345))
+ endif
+endfunc
+
func Test_setmatches()
hi def link 1 Comment
hi def link 2 PreProc
diff --git a/src/nvim/testdir/test_float_func.vim b/src/nvim/testdir/test_float_func.vim
new file mode 100644
index 0000000000..5ea5192994
--- /dev/null
+++ b/src/nvim/testdir/test_float_func.vim
@@ -0,0 +1,332 @@
+" test float functions
+
+if !has('float')
+ finish
+end
+
+func Test_abs()
+ call assert_equal('1.23', string(abs(1.23)))
+ call assert_equal('1.23', string(abs(-1.23)))
+ call assert_equal('0.0', string(abs(0.0)))
+ call assert_equal('0.0', string(abs(1.0/(1.0/0.0))))
+ call assert_equal('0.0', string(abs(-1.0/(1.0/0.0))))
+ call assert_equal("str2float('inf')", string(abs(1.0/0.0)))
+ call assert_equal("str2float('inf')", string(abs(-1.0/0.0)))
+ call assert_equal("str2float('nan')", string(abs(0.0/0.0)))
+ call assert_equal('12', string(abs('-12abc')))
+ call assert_fails("call abs([])", 'E745:')
+ call assert_fails("call abs({})", 'E728:')
+ call assert_fails("call abs(function('string'))", 'E703:')
+endfunc
+
+func Test_sqrt()
+ call assert_equal('0.0', string(sqrt(0.0)))
+ call assert_equal('1.414214', string(sqrt(2.0)))
+ call assert_equal("str2float('inf')", string(sqrt(1.0/0.0)))
+ call assert_equal("str2float('nan')", string(sqrt(-1.0)))
+ call assert_equal("str2float('nan')", string(sqrt(0.0/0.0)))
+ call assert_fails('call sqrt("")', 'E808:')
+endfunc
+
+func Test_log()
+ call assert_equal('0.0', string(log(1.0)))
+ call assert_equal('-0.693147', string(log(0.5)))
+ call assert_equal("-str2float('inf')", string(log(0.0)))
+ call assert_equal("str2float('nan')", string(log(-1.0)))
+ call assert_equal("str2float('inf')", string(log(1.0/0.0)))
+ call assert_equal("str2float('nan')", string(log(0.0/0.0)))
+ call assert_fails('call log("")', 'E808:')
+endfunc
+
+func Test_log10()
+ call assert_equal('0.0', string(log10(1.0)))
+ call assert_equal('2.0', string(log10(100.0)))
+ call assert_equal('2.079181', string(log10(120.0)))
+ call assert_equal("-str2float('inf')", string(log10(0.0)))
+ call assert_equal("str2float('nan')", string(log10(-1.0)))
+ call assert_equal("str2float('inf')", string(log10(1.0/0.0)))
+ call assert_equal("str2float('nan')", string(log10(0.0/0.0)))
+ call assert_fails('call log10("")', 'E808:')
+endfunc
+
+func Test_exp()
+ call assert_equal('1.0', string(exp(0.0)))
+ call assert_equal('7.389056', string(exp(2.0)))
+ call assert_equal('0.367879', string(exp(-1.0)))
+ call assert_equal("str2float('inf')", string(exp(1.0/0.0)))
+ call assert_equal('0.0', string(exp(-1.0/0.0)))
+ call assert_equal("str2float('nan')", string(exp(0.0/0.0)))
+ call assert_fails('call exp("")', 'E808:')
+endfunc
+
+func Test_sin()
+ call assert_equal('0.0', string(sin(0.0)))
+ call assert_equal('0.841471', string(sin(1.0)))
+ call assert_equal('-0.479426', string(sin(-0.5)))
+ call assert_equal("str2float('nan')", string(sin(0.0/0.0)))
+ call assert_equal("str2float('nan')", string(sin(1.0/0.0)))
+ call assert_equal('0.0', string(sin(1.0/(1.0/0.0))))
+ call assert_equal('-0.0', string(sin(-1.0/(1.0/0.0))))
+ call assert_fails('call sin("")', 'E808:')
+endfunc
+
+func Test_asin()
+ call assert_equal('0.0', string(asin(0.0)))
+ call assert_equal('1.570796', string(asin(1.0)))
+ call assert_equal('-0.523599', string(asin(-0.5)))
+ call assert_equal("str2float('nan')", string(asin(1.1)))
+ call assert_equal("str2float('nan')", string(asin(1.0/0.0)))
+ call assert_equal("str2float('nan')", string(asin(0.0/0.0)))
+ call assert_fails('call asin("")', 'E808:')
+endfunc
+
+func Test_sinh()
+ call assert_equal('0.0', string(sinh(0.0)))
+ call assert_equal('0.521095', string(sinh(0.5)))
+ call assert_equal('-1.026517', string(sinh(-0.9)))
+ call assert_equal("str2float('inf')", string(sinh(1.0/0.0)))
+ call assert_equal("-str2float('inf')", string(sinh(-1.0/0.0)))
+ call assert_equal("str2float('nan')", string(sinh(0.0/0.0)))
+ call assert_fails('call sinh("")', 'E808:')
+endfunc
+
+func Test_cos()
+ call assert_equal('1.0', string(cos(0.0)))
+ call assert_equal('0.540302', string(cos(1.0)))
+ call assert_equal('0.877583', string(cos(-0.5)))
+ call assert_equal("str2float('nan')", string(cos(0.0/0.0)))
+ call assert_equal("str2float('nan')", string(cos(1.0/0.0)))
+ call assert_fails('call cos("")', 'E808:')
+endfunc
+
+func Test_acos()
+ call assert_equal('1.570796', string(acos(0.0)))
+ call assert_equal('0.0', string(acos(1.0)))
+ call assert_equal('3.141593', string(acos(-1.0)))
+ call assert_equal('2.094395', string(acos(-0.5)))
+ call assert_equal("str2float('nan')", string(acos(1.1)))
+ call assert_equal("str2float('nan')", string(acos(1.0/0.0)))
+ call assert_equal("str2float('nan')", string(acos(0.0/0.0)))
+ call assert_fails('call acos("")', 'E808:')
+endfunc
+
+func Test_cosh()
+ call assert_equal('1.0', string(cosh(0.0)))
+ call assert_equal('1.127626', string(cosh(0.5)))
+ call assert_equal("str2float('inf')", string(cosh(1.0/0.0)))
+ call assert_equal("str2float('inf')", string(cosh(-1.0/0.0)))
+ call assert_equal("str2float('nan')", string(cosh(0.0/0.0)))
+ call assert_fails('call cosh("")', 'E808:')
+endfunc
+
+func Test_tan()
+ call assert_equal('0.0', string(tan(0.0)))
+ call assert_equal('0.546302', string(tan(0.5)))
+ call assert_equal('-0.546302', string(tan(-0.5)))
+ call assert_equal("str2float('nan')", string(tan(1.0/0.0)))
+ call assert_equal("str2float('nan')", string(cos(0.0/0.0)))
+ call assert_equal('0.0', string(tan(1.0/(1.0/0.0))))
+ call assert_equal('-0.0', string(tan(-1.0/(1.0/0.0))))
+ call assert_fails('call tan("")', 'E808:')
+endfunc
+
+func Test_atan()
+ call assert_equal('0.0', string(atan(0.0)))
+ call assert_equal('0.463648', string(atan(0.5)))
+ call assert_equal('-0.785398', string(atan(-1.0)))
+ call assert_equal('1.570796', string(atan(1.0/0.0)))
+ call assert_equal('-1.570796', string(atan(-1.0/0.0)))
+ call assert_equal("str2float('nan')", string(atan(0.0/0.0)))
+ call assert_fails('call atan("")', 'E808:')
+endfunc
+
+func Test_atan2()
+ call assert_equal('-2.356194', string(atan2(-1, -1)))
+ call assert_equal('2.356194', string(atan2(1, -1)))
+ call assert_equal('0.0', string(atan2(1.0, 1.0/0.0)))
+ call assert_equal('1.570796', string(atan2(1.0/0.0, 1.0)))
+ call assert_equal("str2float('nan')", string(atan2(0.0/0.0, 1.0)))
+ call assert_fails('call atan2("", -1)', 'E808:')
+ call assert_fails('call atan2(-1, "")', 'E808:')
+endfunc
+
+func Test_tanh()
+ call assert_equal('0.0', string(tanh(0.0)))
+ call assert_equal('0.462117', string(tanh(0.5)))
+ call assert_equal('-0.761594', string(tanh(-1.0)))
+ call assert_equal('1.0', string(tanh(1.0/0.0)))
+ call assert_equal('-1.0', string(tanh(-1.0/0.0)))
+ call assert_equal("str2float('nan')", string(tanh(0.0/0.0)))
+ call assert_fails('call tanh("")', 'E808:')
+endfunc
+
+func Test_fmod()
+ call assert_equal('0.13', string(fmod(12.33, 1.22)))
+ call assert_equal('-0.13', string(fmod(-12.33, 1.22)))
+ call assert_equal("str2float('nan')", string(fmod(1.0/0.0, 1.0)))
+ " On Windows we get "nan" instead of 1.0, accept both.
+ let res = string(fmod(1.0, 1.0/0.0))
+ if res != "str2float('nan')"
+ call assert_equal('1.0', res)
+ endif
+ call assert_equal("str2float('nan')", string(fmod(1.0, 0.0)))
+ call assert_fails("call fmod('', 1.22)", 'E808:')
+ call assert_fails("call fmod(12.33, '')", 'E808:')
+endfunc
+
+func Test_pow()
+ call assert_equal('1.0', string(pow(0.0, 0.0)))
+ call assert_equal('8.0', string(pow(2.0, 3.0)))
+ call assert_equal("str2float('nan')", string(pow(2.0, 0.0/0.0)))
+ call assert_equal("str2float('nan')", string(pow(0.0/0.0, 3.0)))
+ call assert_equal("str2float('nan')", string(pow(0.0/0.0, 3.0)))
+ call assert_equal("str2float('inf')", string(pow(2.0, 1.0/0.0)))
+ call assert_equal("str2float('inf')", string(pow(1.0/0.0, 3.0)))
+ call assert_fails("call pow('', 2.0)", 'E808:')
+ call assert_fails("call pow(2.0, '')", 'E808:')
+endfunc
+
+func Test_str2float()
+ call assert_equal('1.0', string(str2float('1')))
+ call assert_equal('1.0', string(str2float(' 1 ')))
+ call assert_equal('1.0', string(str2float(' 1.0 ')))
+ call assert_equal('1.23', string(str2float('1.23')))
+ call assert_equal('1.23', string(str2float('1.23abc')))
+ call assert_equal('1.0e40', string(str2float('1e40')))
+ call assert_equal('-1.23', string(str2float('-1.23')))
+ call assert_equal('1.23', string(str2float(' + 1.23 ')))
+
+ call assert_equal('1.0', string(str2float('+1')))
+ call assert_equal('1.0', string(str2float('+1')))
+ call assert_equal('1.0', string(str2float(' +1 ')))
+ call assert_equal('1.0', string(str2float(' + 1 ')))
+
+ call assert_equal('-1.0', string(str2float('-1')))
+ call assert_equal('-1.0', string(str2float('-1')))
+ call assert_equal('-1.0', string(str2float(' -1 ')))
+ call assert_equal('-1.0', string(str2float(' - 1 ')))
+
+ call assert_equal('0.0', string(str2float('+0.0')))
+ call assert_equal('-0.0', string(str2float('-0.0')))
+ call assert_equal("str2float('inf')", string(str2float('1e1000')))
+ call assert_equal("str2float('inf')", string(str2float('inf')))
+ call assert_equal("-str2float('inf')", string(str2float('-inf')))
+ call assert_equal("str2float('inf')", string(str2float('+inf')))
+ call assert_equal("str2float('inf')", string(str2float('Inf')))
+ call assert_equal("str2float('inf')", string(str2float(' +inf ')))
+ call assert_equal("str2float('nan')", string(str2float('nan')))
+ call assert_equal("str2float('nan')", string(str2float('NaN')))
+ call assert_equal("str2float('nan')", string(str2float(' nan ')))
+
+ call assert_fails("call str2float(1.2)", 'E806:')
+ call assert_fails("call str2float([])", 'E730:')
+ call assert_fails("call str2float({})", 'E731:')
+ call assert_fails("call str2float(function('string'))", 'E729:')
+endfunc
+
+func Test_float2nr()
+ call assert_equal(1, float2nr(1.234))
+ call assert_equal(123, float2nr(1.234e2))
+ call assert_equal(12, float2nr(123.4e-1))
+ let max_number = 1/0
+ let min_number = -max_number
+ call assert_equal(max_number/2+1, float2nr(pow(2, 62)))
+ call assert_equal(max_number, float2nr(pow(2, 63)))
+ call assert_equal(max_number, float2nr(pow(2, 64)))
+ call assert_equal(min_number/2-1, float2nr(-pow(2, 62)))
+ call assert_equal(min_number, float2nr(-pow(2, 63)))
+ call assert_equal(min_number, float2nr(-pow(2, 64)))
+endfunc
+
+func Test_floor()
+ call assert_equal('2.0', string(floor(2.0)))
+ call assert_equal('2.0', string(floor(2.11)))
+ call assert_equal('2.0', string(floor(2.99)))
+ call assert_equal('-3.0', string(floor(-2.11)))
+ call assert_equal('-3.0', string(floor(-2.99)))
+ call assert_equal("str2float('nan')", string(floor(0.0/0.0)))
+ call assert_equal("str2float('inf')", string(floor(1.0/0.0)))
+ call assert_equal("-str2float('inf')", string(floor(-1.0/0.0)))
+ call assert_fails("call floor('')", 'E808:')
+endfunc
+
+func Test_ceil()
+ call assert_equal('2.0', string(ceil(2.0)))
+ call assert_equal('3.0', string(ceil(2.11)))
+ call assert_equal('3.0', string(ceil(2.99)))
+ call assert_equal('-2.0', string(ceil(-2.11)))
+ call assert_equal('-2.0', string(ceil(-2.99)))
+ call assert_equal("str2float('nan')", string(ceil(0.0/0.0)))
+ call assert_equal("str2float('inf')", string(ceil(1.0/0.0)))
+ call assert_equal("-str2float('inf')", string(ceil(-1.0/0.0)))
+ call assert_fails("call ceil('')", 'E808:')
+endfunc
+
+func Test_round()
+ call assert_equal('2.0', string(round(2.1)))
+ call assert_equal('3.0', string(round(2.5)))
+ call assert_equal('3.0', string(round(2.9)))
+ call assert_equal('-2.0', string(round(-2.1)))
+ call assert_equal('-3.0', string(round(-2.5)))
+ call assert_equal('-3.0', string(round(-2.9)))
+ call assert_equal("str2float('nan')", string(round(0.0/0.0)))
+ call assert_equal("str2float('inf')", string(round(1.0/0.0)))
+ call assert_equal("-str2float('inf')", string(round(-1.0/0.0)))
+ call assert_fails("call round('')", 'E808:')
+endfunc
+
+func Test_trunc()
+ call assert_equal('2.0', string(trunc(2.1)))
+ call assert_equal('2.0', string(trunc(2.5)))
+ call assert_equal('2.0', string(trunc(2.9)))
+ call assert_equal('-2.0', string(trunc(-2.1)))
+ call assert_equal('-2.0', string(trunc(-2.5)))
+ call assert_equal('-2.0', string(trunc(-2.9)))
+ call assert_equal("str2float('nan')", string(trunc(0.0/0.0)))
+ call assert_equal("str2float('inf')", string(trunc(1.0/0.0)))
+ call assert_equal("-str2float('inf')", string(trunc(-1.0/0.0)))
+ call assert_fails("call trunc('')", 'E808:')
+endfunc
+
+func Test_isnan()
+ throw 'skipped: Nvim does not support isnan()'
+ call assert_equal(0, isnan(1.0))
+ call assert_equal(1, isnan(0.0/0.0))
+ call assert_equal(0, isnan(1.0/0.0))
+ call assert_equal(0, isnan('a'))
+ call assert_equal(0, isnan([]))
+ call assert_equal(0, isnan({}))
+endfunc
+
+" This was converted from test65
+func Test_float_misc()
+ call assert_equal('123.456000', printf('%f', 123.456))
+ call assert_equal('1.234560e+02', printf('%e', 123.456))
+ call assert_equal('123.456', printf('%g', 123.456))
+ " +=
+ let v = 1.234
+ let v += 6.543
+ call assert_equal('7.777', printf('%g', v))
+ let v = 1.234
+ let v += 5
+ call assert_equal('6.234', printf('%g', v))
+ let v = 5
+ let v += 3.333
+ call assert_equal('8.333', string(v))
+ " ==
+ let v = 1.234
+ call assert_true(v == 1.234)
+ call assert_false(v == 1.2341)
+ " add-subtract
+ call assert_equal('5.234', printf('%g', 4 + 1.234))
+ call assert_equal('-6.766', printf('%g', 1.234 - 8))
+ " mult-div
+ call assert_equal('4.936', printf('%g', 4 * 1.234))
+ call assert_equal('0.003241', printf('%g', 4.0 / 1234))
+ " dict
+ call assert_equal("{'x': 1.234, 'y': -2.0e20}", string({'x': 1.234, 'y': -2.0e20}))
+ " list
+ call assert_equal('[-123.4, 2.0e-20]', string([-123.4, 2.0e-20]))
+endfunc
+
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim
index 3c258299c1..237a2dc820 100644
--- a/src/nvim/testdir/test_functions.vim
+++ b/src/nvim/testdir/test_functions.vim
@@ -1,3 +1,22 @@
+" Tests for various functions.
+
+func Test_str2nr()
+ call assert_equal(0, str2nr(''))
+ call assert_equal(1, str2nr('1'))
+ call assert_equal(1, str2nr(' 1 '))
+
+ call assert_equal(1, str2nr('+1'))
+ call assert_equal(1, str2nr('+ 1'))
+ call assert_equal(1, str2nr(' + 1 '))
+
+ call assert_equal(-1, str2nr('-1'))
+ call assert_equal(-1, str2nr('- 1'))
+ call assert_equal(-1, str2nr(' - 1 '))
+
+ call assert_equal(123456789, str2nr('123456789'))
+ call assert_equal(-123456789, str2nr('-123456789'))
+endfunc
+
func Test_setbufvar_options()
" This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the
" window layout.
diff --git a/src/nvim/testdir/test_largefile.vim b/src/nvim/testdir/test_largefile.vim
new file mode 100644
index 0000000000..1b3e02a0c8
--- /dev/null
+++ b/src/nvim/testdir/test_largefile.vim
@@ -0,0 +1,34 @@
+" Tests for large files
+" This is only executed manually: "make test_largefile".
+" This is not run as part of "make test".
+
+func Test_largefile()
+ let fname = 'Xlarge.txt'
+
+ call delete(fname)
+ exe "e" fname
+ " Make sure that a line break is 1 byte (LF).
+ set ff=unix
+ set undolevels=-1
+ " Input 99 'A's. The line becomes 100 bytes including a line break.
+ exe "normal 99iA\<Esc>"
+ yank
+ " Put 39,999,999 times. The file becomes 4,000,000,000 bytes.
+ normal 39999999p
+ " Moving around in the file randomly.
+ normal G
+ normal 10%
+ normal 90%
+ normal 50%
+ normal gg
+ w
+ " Check if the file size is 4,000,000,000 bytes.
+ let fsize=getfsize(fname)
+ if has('num64')
+ call assert_true(fsize == 4000000000)
+ else
+ " getfsize() returns -2 if a Number is 32 bits.
+ call assert_true(fsize == -2)
+ endif
+ call delete(fname)
+endfunc
diff --git a/src/nvim/testdir/test_menu.vim b/src/nvim/testdir/test_menu.vim
index be559467c8..af18760065 100644
--- a/src/nvim/testdir/test_menu.vim
+++ b/src/nvim/testdir/test_menu.vim
@@ -4,6 +4,6 @@ func Test_load_menu()
try
source $VIMRUNTIME/menu.vim
catch
- call assert_false(1, 'error while loading menus: ' . v:exception)
+ call assert_report('error while loading menus: ' . v:exception)
endtry
endfunc
diff --git a/src/nvim/testdir/test_popup.vim b/src/nvim/testdir/test_popup.vim
index fd0f3c0d2d..519d855cd8 100644
--- a/src/nvim/testdir/test_popup.vim
+++ b/src/nvim/testdir/test_popup.vim
@@ -533,7 +533,7 @@ func Test_completion_comment_formatting()
%d
try
call feedkeys("o/*\<cr>\<cr>\<c-x>\<c-u>/\<esc>", 'tx')
- call assert_false(1, 'completefunc not set, should have failed')
+ call assert_report('completefunc not set, should have failed')
catch
call assert_exception('E764:')
endtry
diff --git a/src/nvim/testdir/test_search.vim b/src/nvim/testdir/test_search.vim
new file mode 100644
index 0000000000..e85525e663
--- /dev/null
+++ b/src/nvim/testdir/test_search.vim
@@ -0,0 +1,12 @@
+" Test for the search command
+
+func Test_use_sub_pat()
+ split
+ let @/ = ''
+ func X()
+ s/^/a/
+ /
+ endfunc
+ call X()
+ bwipe!
+endfunc
diff --git a/src/nvim/testdir/test_startup.vim b/src/nvim/testdir/test_startup.vim
index f78d92f3ff..5996b2cd4a 100644
--- a/src/nvim/testdir/test_startup.vim
+++ b/src/nvim/testdir/test_startup.vim
@@ -83,7 +83,7 @@ func Test_help_arg()
call add(found, "--version")
endif
endfor
- call assert_equal(['--version'], found)
+ call assert_equal(['Readonly mode', '--version'], found)
endif
call delete('Xtestout')
endfunc
diff --git a/src/nvim/testdir/test_stat.vim b/src/nvim/testdir/test_stat.vim
new file mode 100644
index 0000000000..89ca9ef379
--- /dev/null
+++ b/src/nvim/testdir/test_stat.vim
@@ -0,0 +1,64 @@
+" Tests for stat functions and checktime
+
+func Test_existent_file()
+ let fname='Xtest.tmp'
+
+ let ts=localtime()
+ sleep 1
+ let fl=['Hello World!']
+ call writefile(fl, fname)
+ let tf=getftime(fname)
+ sleep 1
+ let te=localtime()
+
+ call assert_true(ts <= tf && tf <= te)
+ call assert_equal(strlen(fl[0] . "\n"), getfsize(fname))
+ call assert_equal('file', getftype(fname))
+ call assert_equal('rw-', getfperm(fname)[0:2])
+endfunc
+
+func Test_existent_directory()
+ let dname='.'
+
+ call assert_equal(0, getfsize(dname))
+ call assert_equal('dir', getftype(dname))
+ call assert_equal('rwx', getfperm(dname)[0:2])
+endfunc
+
+func Test_checktime()
+ let fname='Xtest.tmp'
+
+ let fl=['Hello World!']
+ call writefile(fl, fname)
+ set autoread
+ exec 'e' fname
+ sleep 2
+ let fl=readfile(fname)
+ let fl[0] .= ' - checktime'
+ call writefile(fl, fname)
+ checktime
+ call assert_equal(fl[0], getline(1))
+endfunc
+
+func Test_nonexistent_file()
+ let fname='Xtest.tmp'
+
+ call delete(fname)
+ call assert_equal(-1, getftime(fname))
+ call assert_equal(-1, getfsize(fname))
+ call assert_equal('', getftype(fname))
+ call assert_equal('', getfperm(fname))
+endfunc
+
+func Test_win32_symlink_dir()
+ " On Windows, non-admin users cannot create symlinks.
+ " So we use an existing symlink for this test.
+ if has('win32')
+ " Check if 'C:\Users\All Users' is a symlink to a directory.
+ let res=system('dir C:\Users /a')
+ if match(res, '\C<SYMLINKD> *All Users') >= 0
+ " Get the filetype of the symlink.
+ call assert_equal('dir', getftype('C:\Users\All Users'))
+ endif
+ endif
+endfunc
diff --git a/src/nvim/testdir/test_viml.vim b/src/nvim/testdir/test_vimscript.vim
index a2997b6d4d..4e0f1bbd2f 100644
--- a/src/nvim/testdir/test_viml.vim
+++ b/src/nvim/testdir/test_vimscript.vim
@@ -1062,6 +1062,157 @@ func Test_echo_and_string()
call assert_equal(["{'a': [], 'b': []}",
\ "{'a': [], 'b': []}"], l)
+"-------------------------------------------------------------------------------
+" Test 94: 64-bit Numbers {{{1
+"-------------------------------------------------------------------------------
+
+func Test_num64()
+ if !has('num64')
+ return
+ endif
+
+ call assert_notequal( 4294967296, 0)
+ call assert_notequal(-4294967296, 0)
+ call assert_equal( 4294967296, 0xFFFFffff + 1)
+ call assert_equal(-4294967296, -0xFFFFffff - 1)
+
+ call assert_equal( 9223372036854775807, 1 / 0)
+ call assert_equal(-9223372036854775807, -1 / 0)
+ call assert_equal(-9223372036854775807 - 1, 0 / 0)
+
+ call assert_equal( 0x7FFFffffFFFFffff, float2nr( 1.0e150))
+ call assert_equal(-0x7FFFffffFFFFffff, float2nr(-1.0e150))
+
+ let rng = range(0xFFFFffff, 0x100000001)
+ call assert_equal([0xFFFFffff, 0x100000000, 0x100000001], rng)
+ call assert_equal(0x100000001, max(rng))
+ call assert_equal(0xFFFFffff, min(rng))
+ call assert_equal(rng, sort(range(0x100000001, 0xFFFFffff, -1), 'N'))
+endfunc
+
+"-------------------------------------------------------------------------------
+" Test 95: lines of :append, :change, :insert {{{1
+"-------------------------------------------------------------------------------
+
+function! DefineFunction(name, body)
+ let func = join(['function! ' . a:name . '()'] + a:body + ['endfunction'], "\n")
+ exec func
+endfunction
+
+func Test_script_lines()
+ " :append
+ try
+ call DefineFunction('T_Append', [
+ \ 'append',
+ \ 'py <<EOS',
+ \ '.',
+ \ ])
+ catch
+ call assert_report("Can't define function")
+ endtry
+ try
+ call DefineFunction('T_Append', [
+ \ 'append',
+ \ 'abc',
+ \ ])
+ call assert_report("Shouldn't be able to define function")
+ catch
+ call assert_exception('Vim(function):E126: Missing :endfunction')
+ endtry
+
+ " :change
+ try
+ call DefineFunction('T_Change', [
+ \ 'change',
+ \ 'py <<EOS',
+ \ '.',
+ \ ])
+ catch
+ call assert_report("Can't define function")
+ endtry
+ try
+ call DefineFunction('T_Change', [
+ \ 'change',
+ \ 'abc',
+ \ ])
+ call assert_report("Shouldn't be able to define function")
+ catch
+ call assert_exception('Vim(function):E126: Missing :endfunction')
+ endtry
+
+ " :insert
+ try
+ call DefineFunction('T_Insert', [
+ \ 'insert',
+ \ 'py <<EOS',
+ \ '.',
+ \ ])
+ catch
+ call assert_report("Can't define function")
+ endtry
+ try
+ call DefineFunction('T_Insert', [
+ \ 'insert',
+ \ 'abc',
+ \ ])
+ call assert_report("Shouldn't be able to define function")
+ catch
+ call assert_exception('Vim(function):E126: Missing :endfunction')
+ endtry
+endfunc
+
+"-------------------------------------------------------------------------------
+" Test 96: line continuation {{{1
+"
+" Undefined behavior was detected by ubsan with line continuation
+" after an empty line.
+"-------------------------------------------------------------------------------
+func Test_script_emty_line_continuation()
+
+ \
+endfunc
+
+"-------------------------------------------------------------------------------
+" Test 97: bitwise functions {{{1
+"-------------------------------------------------------------------------------
+func Test_bitwise_functions()
+ " and
+ call assert_equal(127, and(127, 127))
+ call assert_equal(16, and(127, 16))
+ call assert_equal(0, and(127, 128))
+ call assert_fails("call and(1.0, 1)", 'E805:')
+ call assert_fails("call and([], 1)", 'E745:')
+ call assert_fails("call and({}, 1)", 'E728:')
+ call assert_fails("call and(1, 1.0)", 'E805:')
+ call assert_fails("call and(1, [])", 'E745:')
+ call assert_fails("call and(1, {})", 'E728:')
+ " or
+ call assert_equal(23, or(16, 7))
+ call assert_equal(15, or(8, 7))
+ call assert_equal(123, or(0, 123))
+ call assert_fails("call or(1.0, 1)", 'E805:')
+ call assert_fails("call or([], 1)", 'E745:')
+ call assert_fails("call or({}, 1)", 'E728:')
+ call assert_fails("call or(1, 1.0)", 'E805:')
+ call assert_fails("call or(1, [])", 'E745:')
+ call assert_fails("call or(1, {})", 'E728:')
+ " xor
+ call assert_equal(0, xor(127, 127))
+ call assert_equal(111, xor(127, 16))
+ call assert_equal(255, xor(127, 128))
+ call assert_fails("call xor(1.0, 1)", 'E805:')
+ call assert_fails("call xor([], 1)", 'E745:')
+ call assert_fails("call xor({}, 1)", 'E728:')
+ call assert_fails("call xor(1, 1.0)", 'E805:')
+ call assert_fails("call xor(1, [])", 'E745:')
+ call assert_fails("call xor(1, {})", 'E728:')
+ " invert
+ call assert_equal(65408, and(invert(127), 65535))
+ call assert_equal(65519, and(invert(16), 65535))
+ call assert_equal(65407, and(invert(128), 65535))
+ call assert_fails("call invert(1.0)", 'E805:')
+ call assert_fails("call invert([])", 'E745:')
+ call assert_fails("call invert({})", 'E728:')
endfunc
"-------------------------------------------------------------------------------
diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c
index 4ff7993f4a..736d50ee8b 100644
--- a/src/nvim/tui/tui.c
+++ b/src/nvim/tui/tui.c
@@ -53,6 +53,9 @@ typedef enum TermType {
kTermiTerm,
kTermKonsole,
kTermRxvt,
+ kTermDTTerm,
+ kTermXTerm,
+ kTermTeraTerm,
} TermType;
typedef struct {
@@ -79,7 +82,10 @@ typedef struct {
UGrid grid;
kvec_t(Rect) invalid_regions;
int out_fd;
- bool can_use_terminal_scroll;
+ bool scroll_region_is_full_screen;
+ bool can_change_scroll_region;
+ bool can_set_lr_margin;
+ bool can_set_left_right_margin;
bool mouse_enabled;
bool busy;
cursorentry_T cursor_shapes[SHAPE_IDX_COUNT];
@@ -89,9 +95,12 @@ typedef struct {
struct {
int enable_mouse, disable_mouse;
int enable_bracketed_paste, disable_bracketed_paste;
+ int enable_lr_margin, disable_lr_margin;
int set_rgb_foreground, set_rgb_background;
int set_cursor_color;
int enable_focus_reporting, disable_focus_reporting;
+ int resize_screen;
+ int reset_scroll_region;
} unibi_ext;
} TUIData;
@@ -143,7 +152,7 @@ UI *tui_start(void)
static void terminfo_start(UI *ui)
{
TUIData *data = ui->data;
- data->can_use_terminal_scroll = true;
+ data->scroll_region_is_full_screen = true;
data->bufpos = 0;
data->bufsize = sizeof(data->buf) - CNORM_COMMAND_MAX_SIZE;
data->showing_mode = SHAPE_IDX_N;
@@ -152,8 +161,12 @@ static void terminfo_start(UI *ui)
data->unibi_ext.set_cursor_color = -1;
data->unibi_ext.enable_bracketed_paste = -1;
data->unibi_ext.disable_bracketed_paste = -1;
+ data->unibi_ext.enable_lr_margin = -1;
+ data->unibi_ext.disable_lr_margin = -1;
data->unibi_ext.enable_focus_reporting = -1;
data->unibi_ext.disable_focus_reporting = -1;
+ data->unibi_ext.resize_screen = -1;
+ data->unibi_ext.reset_scroll_region = -1;
data->out_fd = 1;
data->out_isatty = os_isatty(data->out_fd);
// setup unibilium
@@ -164,6 +177,13 @@ static void terminfo_start(UI *ui)
data->ut = unibi_dummy();
}
fix_terminfo(data);
+ data->can_change_scroll_region =
+ !!unibi_get_str(data->ut, unibi_change_scroll_region);
+ data->can_set_lr_margin =
+ !!unibi_get_str(data->ut, unibi_set_lr_margin);
+ data->can_set_left_right_margin =
+ !!unibi_get_str(data->ut, unibi_set_left_margin_parm)
+ && !!unibi_get_str(data->ut, unibi_set_right_margin_parm);
// Set 't_Co' from the result of unibilium & fix_terminfo.
t_colors = unibi_get_num(data->ut, unibi_max_colors);
// Enter alternate screen and clear
@@ -216,11 +236,6 @@ static void tui_terminal_start(UI *ui)
terminfo_start(ui);
update_size(ui);
signal_watcher_start(&data->winch_handle, sigwinch_cb, SIGWINCH);
-
-#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18
- data->input.tk_ti_hook_fn = tui_tk_ti_getstr;
-#endif
- term_input_init(&data->input, data->loop);
term_input_start(&data->input);
}
@@ -255,8 +270,14 @@ static void tui_main(UIBridgeData *bridge, UI *ui)
#ifdef UNIX
signal_watcher_start(&data->cont_handle, sigcont_cb, SIGCONT);
#endif
+
+#if TERMKEY_VERSION_MAJOR > 0 || TERMKEY_VERSION_MINOR > 18
+ data->input.tk_ti_hook_fn = tui_tk_ti_getstr;
+#endif
+ term_input_init(&data->input, &tui_loop);
tui_terminal_start(ui);
data->stop = false;
+
// allow the main thread to continue, we are ready to start handling UI
// callbacks
CONTINUE(bridge);
@@ -418,15 +439,83 @@ static void clear_region(UI *ui, int top, int bot, int left, int right)
unibi_goto(ui, grid->row, grid->col);
}
+static bool can_use_scroll(UI * ui)
+{
+ TUIData *data = ui->data;
+ UGrid *grid = &data->grid;
+
+ return data->scroll_region_is_full_screen
+ || (data->can_change_scroll_region
+ && ((grid->left == 0 && grid->right == ui->width - 1)
+ || data->can_set_lr_margin
+ || data->can_set_left_right_margin));
+}
+
+static void set_scroll_region(UI *ui)
+{
+ TUIData *data = ui->data;
+ UGrid *grid = &data->grid;
+
+ data->params[0].i = grid->top;
+ data->params[1].i = grid->bot;
+ unibi_out(ui, unibi_change_scroll_region);
+ if (grid->left != 0 || grid->right != ui->width - 1) {
+ unibi_out(ui, data->unibi_ext.enable_lr_margin);
+ if (data->can_set_lr_margin) {
+ data->params[0].i = grid->left;
+ data->params[1].i = grid->right;
+ unibi_out(ui, unibi_set_lr_margin);
+ } else {
+ data->params[0].i = grid->left;
+ unibi_out(ui, unibi_set_left_margin_parm);
+ data->params[0].i = grid->right;
+ unibi_out(ui, unibi_set_right_margin_parm);
+ }
+ }
+ unibi_goto(ui, grid->row, grid->col);
+}
+
+static void reset_scroll_region(UI *ui)
+{
+ TUIData *data = ui->data;
+ UGrid *grid = &data->grid;
+
+ if (0 <= data->unibi_ext.reset_scroll_region) {
+ unibi_out(ui, data->unibi_ext.reset_scroll_region);
+ } else {
+ data->params[0].i = 0;
+ data->params[1].i = ui->height - 1;
+ unibi_out(ui, unibi_change_scroll_region);
+ }
+ if (grid->left != 0 || grid->right != ui->width - 1) {
+ if (data->can_set_lr_margin) {
+ data->params[0].i = 0;
+ data->params[1].i = ui->width - 1;
+ unibi_out(ui, unibi_set_lr_margin);
+ } else {
+ data->params[0].i = 0;
+ unibi_out(ui, unibi_set_left_margin_parm);
+ data->params[0].i = ui->width - 1;
+ unibi_out(ui, unibi_set_right_margin_parm);
+ }
+ unibi_out(ui, data->unibi_ext.disable_lr_margin);
+ }
+ unibi_goto(ui, grid->row, grid->col);
+}
+
static void tui_resize(UI *ui, Integer width, Integer height)
{
TUIData *data = ui->data;
ugrid_resize(&data->grid, (int)width, (int)height);
if (!got_winch) { // Try to resize the terminal window.
- char r[16]; // enough for 9999x9999
- snprintf(r, sizeof(r), "\x1b[8;%d;%dt", (int)height, (int)width);
- out(ui, r, strlen(r));
+ data->params[0].i = (int)height;
+ data->params[1].i = (int)width;
+ unibi_out(ui, data->unibi_ext.resize_screen);
+ // DECSLPP does not reset the scroll region.
+ if (data->scroll_region_is_full_screen) {
+ reset_scroll_region(ui);
+ }
} else { // Already handled the SIGWINCH signal; avoid double-resize.
got_winch = false;
}
@@ -613,10 +702,9 @@ static void tui_set_scroll_region(UI *ui, Integer top, Integer bot,
TUIData *data = ui->data;
ugrid_set_scroll_region(&data->grid, (int)top, (int)bot,
(int)left, (int)right);
- data->can_use_terminal_scroll =
+ data->scroll_region_is_full_screen =
left == 0 && right == ui->width - 1
- && ((top == 0 && bot == ui->height - 1)
- || unibi_get_str(data->ut, unibi_change_scroll_region));
+ && top == 0 && bot == ui->height - 1;
}
static void tui_scroll(UI *ui, Integer count)
@@ -626,31 +714,31 @@ static void tui_scroll(UI *ui, Integer count)
int clear_top, clear_bot;
ugrid_scroll(grid, (int)count, &clear_top, &clear_bot);
- if (data->can_use_terminal_scroll) {
+ if (can_use_scroll(ui)) {
+ bool scroll_clears_to_current_colour =
+ unibi_get_bool(data->ut, unibi_back_color_erase);
+
// Change terminal scroll region and move cursor to the top
- data->params[0].i = grid->top;
- data->params[1].i = grid->bot;
- unibi_out(ui, unibi_change_scroll_region);
+ if (!data->scroll_region_is_full_screen) {
+ set_scroll_region(ui);
+ }
unibi_goto(ui, grid->top, grid->left);
// also set default color attributes or some terminals can become funny
- HlAttrs clear_attrs = EMPTY_ATTRS;
- clear_attrs.foreground = grid->fg;
- clear_attrs.background = grid->bg;
- update_attrs(ui, clear_attrs);
- }
+ if (scroll_clears_to_current_colour) {
+ HlAttrs clear_attrs = EMPTY_ATTRS;
+ clear_attrs.foreground = grid->fg;
+ clear_attrs.background = grid->bg;
+ update_attrs(ui, clear_attrs);
+ }
- if (count > 0) {
- if (data->can_use_terminal_scroll) {
+ if (count > 0) {
if (count == 1) {
unibi_out(ui, unibi_delete_line);
} else {
data->params[0].i = (int)count;
unibi_out(ui, unibi_parm_delete_line);
}
- }
-
- } else {
- if (data->can_use_terminal_scroll) {
+ } else {
if (count == -1) {
unibi_out(ui, unibi_insert_line);
} else {
@@ -658,20 +746,16 @@ static void tui_scroll(UI *ui, Integer count)
unibi_out(ui, unibi_parm_insert_line);
}
}
- }
- if (data->can_use_terminal_scroll) {
// Restore terminal scroll region and cursor
- data->params[0].i = 0;
- data->params[1].i = ui->height - 1;
- unibi_out(ui, unibi_change_scroll_region);
+ if (!data->scroll_region_is_full_screen) {
+ reset_scroll_region(ui);
+ }
unibi_goto(ui, grid->row, grid->col);
- if (grid->bg != -1) {
- // Update the cleared area of the terminal if its builtin scrolling
- // facility was used and the background color is not the default. This is
- // required because scrolling may leave wrong background in the cleared
- // area.
+ if (!scroll_clears_to_current_colour) {
+ // This is required because scrolling will leave wrong background in the
+ // cleared area on non-bge terminals.
clear_region(ui, clear_top, clear_bot, grid->left, grid->right);
}
} else {
@@ -956,6 +1040,15 @@ static TermType detect_term(const char *term, const char *colorterm)
if (colorterm && strstr(colorterm, "gnome-terminal")) {
return kTermGnome;
}
+ if (STARTS_WITH(term, "xterm")) {
+ return kTermXTerm;
+ }
+ if (STARTS_WITH(term, "dtterm")) {
+ return kTermDTTerm;
+ }
+ if (STARTS_WITH(term, "teraterm")) {
+ return kTermTeraTerm;
+ }
return kTermUnknown;
}
@@ -976,14 +1069,14 @@ static void fix_terminfo(TUIData *data)
unibi_set_if_empty(ut, unibi_flash_screen, "\x1b[?5h$<20/>\x1b[?5l");
unibi_set_if_empty(ut, unibi_enter_italics_mode, "\x1b[3m");
unibi_set_if_empty(ut, unibi_to_status_line, "\x1b]2");
- } else if (STARTS_WITH(term, "xterm")) {
+ } else if (data->term == kTermXTerm) {
unibi_set_if_empty(ut, unibi_to_status_line, "\x1b]0;");
} else if (STARTS_WITH(term, "screen") || STARTS_WITH(term, "tmux")) {
unibi_set_if_empty(ut, unibi_to_status_line, "\x1b_");
unibi_set_if_empty(ut, unibi_from_status_line, "\x1b\\");
}
- if (STARTS_WITH(term, "xterm") || data->term == kTermRxvt) {
+ if (data->term == kTermXTerm || data->term == kTermRxvt) {
const char *normal = unibi_get_str(ut, unibi_cursor_normal);
if (!normal) {
unibi_set_str(ut, unibi_cursor_normal, "\x1b[?25h");
@@ -997,11 +1090,21 @@ static void fix_terminfo(TUIData *data)
unibi_set_if_empty(ut, unibi_cursor_invisible, "\x1b[?25l");
unibi_set_if_empty(ut, unibi_flash_screen, "\x1b[?5h$<100/>\x1b[?5l");
unibi_set_if_empty(ut, unibi_exit_attribute_mode, "\x1b(B\x1b[m");
+ unibi_set_if_empty(ut, unibi_set_tb_margin, "\x1b[%i%p1%d;%p2%dr");
+ unibi_set_if_empty(ut, unibi_set_lr_margin, "\x1b[%i%p1%d;%p2%ds");
+ unibi_set_if_empty(ut, unibi_set_left_margin_parm, "\x1b[%i%p1%ds");
+ unibi_set_if_empty(ut, unibi_set_right_margin_parm, "\x1b[%i;%p2%ds");
unibi_set_if_empty(ut, unibi_change_scroll_region, "\x1b[%i%p1%d;%p2%dr");
unibi_set_if_empty(ut, unibi_clear_screen, "\x1b[H\x1b[2J");
unibi_set_if_empty(ut, unibi_from_status_line, "\x07");
+ unibi_set_bool(ut, unibi_back_color_erase, true);
}
+ data->unibi_ext.enable_lr_margin = (int)unibi_add_ext_str(ut, NULL,
+ "\x1b[?69h");
+ data->unibi_ext.disable_lr_margin = (int)unibi_add_ext_str(ut, NULL,
+ "\x1b[?69l");
+
data->unibi_ext.enable_bracketed_paste = (int)unibi_add_ext_str(ut, NULL,
"\x1b[?2004h");
data->unibi_ext.disable_bracketed_paste = (int)unibi_add_ext_str(ut, NULL,
@@ -1028,6 +1131,21 @@ static void fix_terminfo(TUIData *data)
unibi_set_str(ut, unibi_set_a_background, XTERM_SETAB);
}
+ // Only define this capability for terminal types that we know understand it.
+ if (data->term == kTermDTTerm // originated this extension
+ || data->term == kTermXTerm // per xterm ctlseqs doc
+ || data->term == kTermKonsole // per commentary in VT102Emulation.cpp
+ || data->term == kTermTeraTerm // per "Supported Control Functions" doc
+ || data->term == kTermRxvt) { // per command.C
+ data->unibi_ext.resize_screen = (int)unibi_add_ext_str(ut, NULL,
+ "\x1b[8;%p1%d;%p2%dt");
+ }
+
+ if (data->term == kTermXTerm || data->term == kTermRxvt) {
+ data->unibi_ext.reset_scroll_region = (int)unibi_add_ext_str(ut, NULL,
+ "\x1b[r");
+ }
+
end:
// Fill some empty slots with common terminal strings
if (data->term == kTermiTerm) {
diff --git a/src/nvim/undo.c b/src/nvim/undo.c
index 290d5d7553..81af3bfda9 100644
--- a/src/nvim/undo.c
+++ b/src/nvim/undo.c
@@ -2232,11 +2232,13 @@ static void u_undoredo(int undo)
/* adjust marks */
if (oldsize != newsize) {
mark_adjust(top + 1, top + oldsize, (long)MAXLNUM,
- (long)newsize - (long)oldsize);
- if (curbuf->b_op_start.lnum > top + oldsize)
+ (long)newsize - (long)oldsize, false);
+ if (curbuf->b_op_start.lnum > top + oldsize) {
curbuf->b_op_start.lnum += newsize - oldsize;
- if (curbuf->b_op_end.lnum > top + oldsize)
+ }
+ if (curbuf->b_op_end.lnum > top + oldsize) {
curbuf->b_op_end.lnum += newsize - oldsize;
+ }
}
changed_lines(top + 1, 0, bot, newsize - oldsize);
diff --git a/src/nvim/version.c b/src/nvim/version.c
index b579cdef12..a28dbcf061 100644
--- a/src/nvim/version.c
+++ b/src/nvim/version.c
@@ -84,11 +84,11 @@ static const int included_patches[] = {
// 2363 NA
2362,
// 2361 NA
- // 2360,
+ 2360,
2359,
// 2358 NA
2357,
- // 2356,
+ 2356,
2355,
// 2354,
2353,
@@ -220,7 +220,7 @@ static const int included_patches[] = {
2227,
2226,
2225,
- // 2224,
+ 2224,
2223,
2222,
2221,
@@ -254,7 +254,7 @@ static const int included_patches[] = {
// 2193 NA
// 2192 NA
// 2191 NA
- // 2190,
+ 2190,
// 2189,
2188,
2187,
@@ -415,7 +415,7 @@ static const int included_patches[] = {
// 2032 NA
2031,
// 2030 NA
- // 2029,
+ 2029,
2028,
// 2027 NA
// 2026 NA
@@ -458,18 +458,18 @@ static const int included_patches[] = {
1989,
// 1988 NA
// 1987 NA
- // 1986,
+ 1986,
// 1985 NA
1984,
// 1983 NA
// 1982 NA
1981,
1980,
- // 1979,
- // 1978,
- // 1977,
- // 1976,
- // 1975,
+ 1979,
+ 1978,
+ 1977,
+ 1976,
+ 1975,
// 1974 NA
1973,
// 1972 NA
diff --git a/src/nvim/window.c b/src/nvim/window.c
index b71b48a6b7..43af2e5e4f 100644
--- a/src/nvim/window.c
+++ b/src/nvim/window.c
@@ -3723,8 +3723,8 @@ static void win_enter_ext(win_T *wp, bool undo_sync, int curwin_invalid,
redraw_later(VALID); /* causes status line redraw */
if (hl_attr(HLF_INACTIVE)
- || (prevwin && prevwin->w_hl_id_inactive)
- || curwin->w_hl_id_inactive) {
+ || (prevwin && prevwin->w_hl_ids[HLF_INACTIVE])
+ || curwin->w_hl_ids[HLF_INACTIVE]) {
redraw_all_later(NOT_VALID);
}
diff --git a/test/README.md b/test/README.md
index 2857cc0ecf..01db5960cd 100644
--- a/test/README.md
+++ b/test/README.md
@@ -2,6 +2,8 @@
Tests are run by `/cmake/RunTests.cmake` file, using busted.
+For some failures, `.nvimlog` (or `$NVIM_LOG_FILE`) may provide insight.
+
## Directory structure
Directories with tests: `/test/benchmark` for benchmarks, `/test/functional` for
diff --git a/test/functional/api/keymap_spec.lua b/test/functional/api/keymap_spec.lua
new file mode 100644
index 0000000000..833e0d2f3c
--- /dev/null
+++ b/test/functional/api/keymap_spec.lua
@@ -0,0 +1,246 @@
+
+local helpers = require('test.functional.helpers')(after_each)
+local clear = helpers.clear
+local command = helpers.command
+local curbufmeths = helpers.curbufmeths
+local eq = helpers.eq
+local funcs = helpers.funcs
+local meths = helpers.meths
+local source = helpers.source
+
+local function local_copy(t)
+ local copy = {}
+ for k,v in pairs(t) do
+ copy[k] = v
+ end
+ return copy
+end
+
+describe('get_keymap', function()
+ before_each(clear)
+
+ -- Basic mapping and table to be used to describe results
+ local foo_bar_string = 'nnoremap foo bar'
+ local foo_bar_map_table = {
+ lhs='foo',
+ silent=0,
+ rhs='bar',
+ expr=0,
+ sid=0,
+ buffer=0,
+ nowait=0,
+ mode='n',
+ noremap=1,
+ }
+
+ it('returns empty list when no map', function()
+ eq({}, meths.get_keymap('n'))
+ end)
+
+ it('returns list of all applicable mappings', function()
+ command(foo_bar_string)
+ -- Only one mapping available
+ -- Should be the same as the dictionary we supplied earlier
+ -- and the dictionary you would get from maparg
+ -- since this is a global map, and not script local
+ eq({foo_bar_map_table}, meths.get_keymap('n'))
+ eq({funcs.maparg('foo', 'n', false, true)},
+ meths.get_keymap('n')
+ )
+
+ -- Add another mapping
+ command('nnoremap foo_longer bar_longer')
+ local foolong_bar_map_table = local_copy(foo_bar_map_table)
+ foolong_bar_map_table['lhs'] = 'foo_longer'
+ foolong_bar_map_table['rhs'] = 'bar_longer'
+
+ eq({foolong_bar_map_table, foo_bar_map_table},
+ meths.get_keymap('n')
+ )
+
+ -- Remove a mapping
+ command('unmap foo_longer')
+ eq({foo_bar_map_table},
+ meths.get_keymap('n')
+ )
+ end)
+
+ it('works for other modes', function()
+ -- Add two mappings, one in insert and one normal
+ -- We'll only check the insert mode one
+ command('nnoremap not_going to_check')
+
+ command('inoremap foo bar')
+ -- The table will be the same except for the mode
+ local insert_table = local_copy(foo_bar_map_table)
+ insert_table['mode'] = 'i'
+
+ eq({insert_table}, meths.get_keymap('i'))
+ end)
+
+ it('considers scope', function()
+ -- change the map slightly
+ command('nnoremap foo_longer bar_longer')
+ local foolong_bar_map_table = local_copy(foo_bar_map_table)
+ foolong_bar_map_table['lhs'] = 'foo_longer'
+ foolong_bar_map_table['rhs'] = 'bar_longer'
+
+ local buffer_table = local_copy(foo_bar_map_table)
+ buffer_table['buffer'] = 1
+
+ command('nnoremap <buffer> foo bar')
+
+ -- The buffer mapping should not show up
+ eq({foolong_bar_map_table}, meths.get_keymap('n'))
+ eq({buffer_table}, curbufmeths.get_keymap('n'))
+ end)
+
+ it('considers scope for overlapping maps', function()
+ command('nnoremap foo bar')
+
+ local buffer_table = local_copy(foo_bar_map_table)
+ buffer_table['buffer'] = 1
+
+ command('nnoremap <buffer> foo bar')
+
+ eq({foo_bar_map_table}, meths.get_keymap('n'))
+ eq({buffer_table}, curbufmeths.get_keymap('n'))
+ end)
+
+ it('can retrieve mapping for different buffers', function()
+ local original_buffer = curbufmeths.get_number()
+ -- Place something in each of the buffers to make sure they stick around
+ -- and set hidden so we can leave them
+ command('set hidden')
+ command('new')
+ command('normal! ihello 2')
+ command('new')
+ command('normal! ihello 3')
+
+ local final_buffer = curbufmeths.get_number()
+
+ command('nnoremap <buffer> foo bar')
+ -- Final buffer will have buffer mappings
+ local buffer_table = local_copy(foo_bar_map_table)
+ buffer_table['buffer'] = final_buffer
+ eq({buffer_table}, meths.buf_get_keymap(final_buffer, 'n'))
+ eq({buffer_table}, meths.buf_get_keymap(0, 'n'))
+
+ command('buffer ' .. original_buffer)
+ eq(original_buffer, curbufmeths.get_number())
+ -- Original buffer won't have any mappings
+ eq({}, meths.get_keymap('n'))
+ eq({}, curbufmeths.get_keymap('n'))
+ eq({buffer_table}, meths.buf_get_keymap(final_buffer, 'n'))
+ end)
+
+ -- Test toggle switches for basic options
+ -- @param option The key represented in the `maparg()` result dict
+ local function global_and_buffer_test(map,
+ option,
+ option_token,
+ global_on_result,
+ buffer_on_result,
+ global_off_result,
+ buffer_off_result,
+ new_windows)
+
+ local function make_new_windows(number_of_windows)
+ if new_windows == nil then
+ return nil
+ end
+
+ for _=1,number_of_windows do
+ command('new')
+ end
+ end
+
+ local mode = string.sub(map, 1,1)
+ -- Don't run this for the <buffer> mapping, since it doesn't make sense
+ if option_token ~= '<buffer>' then
+ it(string.format( 'returns %d for the key "%s" when %s is used globally with %s (%s)',
+ global_on_result, option, option_token, map, mode), function()
+ make_new_windows(new_windows)
+ command(map .. ' ' .. option_token .. ' foo bar')
+ local result = meths.get_keymap(mode)[1][option]
+ eq(global_on_result, result)
+ end)
+ end
+
+ it(string.format('returns %d for the key "%s" when %s is used for buffers with %s (%s)',
+ buffer_on_result, option, option_token, map, mode), function()
+ make_new_windows(new_windows)
+ command(map .. ' <buffer> ' .. option_token .. ' foo bar')
+ local result = curbufmeths.get_keymap(mode)[1][option]
+ eq(buffer_on_result, result)
+ end)
+
+ -- Don't run these for the <buffer> mapping, since it doesn't make sense
+ if option_token ~= '<buffer>' then
+ it(string.format('returns %d for the key "%s" when %s is not used globally with %s (%s)',
+ global_off_result, option, option_token, map, mode), function()
+ make_new_windows(new_windows)
+ command(map .. ' baz bat')
+ local result = meths.get_keymap(mode)[1][option]
+ eq(global_off_result, result)
+ end)
+
+ it(string.format('returns %d for the key "%s" when %s is not used for buffers with %s (%s)',
+ buffer_off_result, option, option_token, map, mode), function()
+ make_new_windows(new_windows)
+ command(map .. ' <buffer> foo bar')
+
+ local result = curbufmeths.get_keymap(mode)[1][option]
+ eq(buffer_off_result, result)
+ end)
+ end
+ end
+
+ -- Standard modes and returns the same values in the dictionary as maparg()
+ local mode_list = {'nnoremap', 'nmap', 'imap', 'inoremap', 'cnoremap'}
+ for mode in pairs(mode_list) do
+ global_and_buffer_test(mode_list[mode], 'silent', '<silent>', 1, 1, 0, 0)
+ global_and_buffer_test(mode_list[mode], 'nowait', '<nowait>', 1, 1, 0, 0)
+ global_and_buffer_test(mode_list[mode], 'expr', '<expr>', 1, 1, 0, 0)
+ end
+
+ -- noremap will now be 2 if script was used, which is not the same as maparg()
+ global_and_buffer_test('nmap', 'noremap', '<script>', 2, 2, 0, 0)
+ global_and_buffer_test('nnoremap', 'noremap', '<script>', 2, 2, 1, 1)
+
+ -- buffer will return the buffer ID, which is not the same as maparg()
+ -- Three of these tests won't run
+ global_and_buffer_test('nnoremap', 'buffer', '<buffer>', nil, 3, nil, nil, 2)
+
+ it('returns script numbers for global maps', function()
+ source([[
+ function! s:maparg_test_function() abort
+ return 'testing'
+ endfunction
+
+ nnoremap fizz :call <SID>maparg_test_function()<CR>
+ ]])
+ local sid_result = meths.get_keymap('n')[1]['sid']
+ eq(1, sid_result)
+ eq('testing', meths.call_function('<SNR>' .. sid_result .. '_maparg_test_function', {}))
+ end)
+
+ it('returns script numbers for buffer maps', function()
+ source([[
+ function! s:maparg_test_function() abort
+ return 'testing'
+ endfunction
+
+ nnoremap <buffer> fizz :call <SID>maparg_test_function()<CR>
+ ]])
+ local sid_result = curbufmeths.get_keymap('n')[1]['sid']
+ eq(1, sid_result)
+ eq('testing', meths.call_function('<SNR>' .. sid_result .. '_maparg_test_function', {}))
+ end)
+
+ it('works with <F12> and others', function()
+ command('nnoremap <F12> :let g:maparg_test_var = 1<CR>')
+ eq('<F12>', meths.get_keymap('n')[1]['lhs'])
+ eq(':let g:maparg_test_var = 1<CR>', meths.get_keymap('n')[1]['rhs'])
+ end)
+end)
diff --git a/test/functional/api/server_requests_spec.lua b/test/functional/api/server_requests_spec.lua
index 658077b112..cf15062325 100644
--- a/test/functional/api/server_requests_spec.lua
+++ b/test/functional/api/server_requests_spec.lua
@@ -9,6 +9,8 @@ local nvim_prog, command, funcs = helpers.nvim_prog, helpers.command, helpers.fu
local source, next_message = helpers.source, helpers.next_message
local ok = helpers.ok
local meths = helpers.meths
+local spawn, nvim_argv = helpers.spawn, helpers.nvim_argv
+local set_session = helpers.set_session
describe('server -> client', function()
local cid
@@ -225,4 +227,75 @@ describe('server -> client', function()
end)
end)
+ describe('when connecting to another nvim instance', function()
+ local function connect_test(server, mode, address)
+ local serverpid = funcs.getpid()
+ local client = spawn(nvim_argv)
+ set_session(client, true)
+ local clientpid = funcs.getpid()
+ neq(serverpid, clientpid)
+ local id = funcs.sockconnect(mode, address, {rpc=true})
+ ok(id > 0)
+
+ funcs.rpcrequest(id, 'nvim_set_current_line', 'hello')
+ local client_id = funcs.rpcrequest(id, 'nvim_get_api_info')[1]
+
+ set_session(server, true)
+ eq(serverpid, funcs.getpid())
+ eq('hello', meths.get_current_line())
+
+ -- method calls work both ways
+ funcs.rpcrequest(client_id, 'nvim_set_current_line', 'howdy!')
+ eq(id, funcs.rpcrequest(client_id, 'nvim_get_api_info')[1])
+
+ set_session(client, true)
+ eq(clientpid, funcs.getpid())
+ eq('howdy!', meths.get_current_line())
+
+ server:close()
+ client:close()
+ end
+
+ it('over a named pipe', function()
+ local server = spawn(nvim_argv)
+ set_session(server)
+ local address = funcs.serverlist()[1]
+ local first = string.sub(address,1,1)
+ ok(first == '/' or first == '\\')
+ connect_test(server, 'pipe', address)
+ end)
+
+ it('to an ip adress', function()
+ local server = spawn(nvim_argv)
+ set_session(server)
+ local address = funcs.serverstart("127.0.0.1:")
+ eq('127.0.0.1:', string.sub(address,1,10))
+ connect_test(server, 'tcp', address)
+ end)
+
+ it('to a hostname', function()
+ local server = spawn(nvim_argv)
+ set_session(server)
+ local address = funcs.serverstart("localhost:")
+ eq('localhost:', string.sub(address,1,10))
+ connect_test(server, 'tcp', address)
+ end)
+ end)
+
+ describe('when connecting to its own pipe adress', function()
+ it('it does not deadlock', function()
+ local address = funcs.serverlist()[1]
+ local first = string.sub(address,1,1)
+ ok(first == '/' or first == '\\')
+ local serverpid = funcs.getpid()
+
+ local id = funcs.sockconnect('pipe', address, {rpc=true})
+
+ funcs.rpcrequest(id, 'nvim_set_current_line', 'hello')
+ eq('hello', meths.get_current_line())
+ eq(serverpid, funcs.rpcrequest(id, "nvim_eval", "getpid()"))
+
+ eq(id, funcs.rpcrequest(id, 'nvim_get_api_info')[1])
+ end)
+ end)
end)
diff --git a/test/functional/eval/function_spec.lua b/test/functional/eval/function_spec.lua
new file mode 100644
index 0000000000..776e760aaf
--- /dev/null
+++ b/test/functional/eval/function_spec.lua
@@ -0,0 +1,29 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local eq = helpers.eq
+local exc_exec = helpers.exc_exec
+
+describe('Up to MAX_FUNC_ARGS arguments are handled by', function()
+ local max_func_args = 20 -- from eval.h
+ local range = helpers.funcs.range
+
+ before_each(clear)
+
+ it('printf()', function()
+ local printf = helpers.funcs.printf
+ local rep = helpers.funcs['repeat']
+ local expected = '2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,'
+ eq(expected, printf(rep('%d,', max_func_args-1), unpack(range(2, max_func_args))))
+ local ret = exc_exec('call printf("", 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)')
+ eq('Vim(call):E740: Too many arguments for function printf', ret)
+ end)
+
+ it('rpcnotify()', function()
+ local rpcnotify = helpers.funcs.rpcnotify
+ local ret = rpcnotify(0, 'foo', unpack(range(3, max_func_args)))
+ eq(1, ret)
+ ret = exc_exec('call rpcnotify(0, "foo", 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)')
+ eq('Vim(call):E740: Too many arguments for function rpcnotify', ret)
+ end)
+end)
diff --git a/test/functional/eval/map_functions_spec.lua b/test/functional/eval/map_functions_spec.lua
new file mode 100644
index 0000000000..a260522aa3
--- /dev/null
+++ b/test/functional/eval/map_functions_spec.lua
@@ -0,0 +1,120 @@
+
+local helpers = require('test.functional.helpers')(after_each)
+local clear = helpers.clear
+local eq = helpers.eq
+local eval = helpers.eval
+local funcs = helpers.funcs
+local nvim = helpers.nvim
+local source = helpers.source
+
+describe('maparg()', function()
+ before_each(clear)
+
+ local foo_bar_map_table = {
+ lhs='foo',
+ silent=0,
+ rhs='bar',
+ expr=0,
+ sid=0,
+ buffer=0,
+ nowait=0,
+ mode='n',
+ noremap=1,
+ }
+
+ it('returns a dictionary', function()
+ nvim('command', 'nnoremap foo bar')
+ eq('bar', funcs.maparg('foo'))
+ eq(foo_bar_map_table, funcs.maparg('foo', 'n', false, true))
+ end)
+
+ it('returns 1 for silent when <silent> is used', function()
+ nvim('command', 'nnoremap <silent> foo bar')
+ eq(1, funcs.maparg('foo', 'n', false, true)['silent'])
+
+ nvim('command', 'nnoremap baz bat')
+ eq(0, funcs.maparg('baz', 'n', false, true)['silent'])
+ end)
+
+ it('returns an empty string when no map is present', function()
+ eq('', funcs.maparg('not a mapping'))
+ end)
+
+ it('returns an empty dictionary when no map is present and dict is requested', function()
+ eq({}, funcs.maparg('not a mapping', 'n', false, true))
+ end)
+
+ it('returns the same value for noremap and <script>', function()
+ nvim('command', 'inoremap <script> hello world')
+ nvim('command', 'inoremap this that')
+ eq(
+ funcs.maparg('hello', 'i', false, true)['noremap'],
+ funcs.maparg('this', 'i', false, true)['noremap']
+ )
+ end)
+
+ it('returns a boolean for buffer', function()
+ -- Open enough windows to know we aren't on buffer number 1
+ nvim('command', 'new')
+ nvim('command', 'new')
+ nvim('command', 'new')
+ nvim('command', 'cnoremap <buffer> this that')
+ eq(1, funcs.maparg('this', 'c', false, true)['buffer'])
+
+ -- Global will return 0 always
+ nvim('command', 'nnoremap other another')
+ eq(0, funcs.maparg('other', 'n', false, true)['buffer'])
+ end)
+
+ it('returns script numbers', function()
+ source([[
+ function! s:maparg_test_function() abort
+ return 'testing'
+ endfunction
+
+ nnoremap fizz :call <SID>maparg_test_function()<CR>
+ ]])
+ eq(1, funcs.maparg('fizz', 'n', false, true)['sid'])
+ eq('testing', nvim('call_function', '<SNR>1_maparg_test_function', {}))
+ end)
+
+ it('works with <F12> and others', function()
+ source([[
+ let g:maparg_test_var = 0
+
+ nnoremap <F12> :let g:maparg_test_var = 1<CR>
+ ]])
+ eq(0, eval('g:maparg_test_var'))
+ source([[
+ call feedkeys("\<F12>")
+ ]])
+ eq(1, eval('g:maparg_test_var'))
+
+ eq(':let g:maparg_test_var = 1<CR>', funcs.maparg('<F12>', 'n', false, true)['rhs'])
+ end)
+
+ it('works with <expr>', function()
+ source([[
+ let counter = 0
+ inoremap <expr> <C-L> ListItem()
+ inoremap <expr> <C-R> ListReset()
+
+ func ListItem()
+ let g:counter += 1
+ return g:counter . '. '
+ endfunc
+
+ func ListReset()
+ let g:counter = 0
+ return ''
+ endfunc
+
+ call feedkeys("i\<C-L>")
+ ]])
+ eq(1, eval('g:counter'))
+
+ local map_dict = funcs.maparg('<C-L>', 'i', false, true)
+ eq(1, map_dict['expr'])
+ eq('i', map_dict['mode'])
+ end)
+end)
diff --git a/test/functional/eval/msgpack_functions_spec.lua b/test/functional/eval/msgpack_functions_spec.lua
index 4a052b4aff..b241635dfe 100644
--- a/test/functional/eval/msgpack_functions_spec.lua
+++ b/test/functional/eval/msgpack_functions_spec.lua
@@ -337,7 +337,8 @@ describe('msgpack*() functions', function()
eq(1, eval('type(parsed[0]) == type(0) ' ..
'|| parsed[0]._TYPE is v:msgpack_types.integer'))
if eval('type(parsed[0]) == type(0)') == 1 then
- eq(1, eval('0xFFFFFFFFFFFFFFFF == parsed[0]'))
+ command('call assert_equal(0xFFFFFFFFFFFFFFFF, parsed[0])')
+ eq({}, eval('v:errors'))
else
eq({_TYPE={}, _VAL={1, 3, 0x7FFFFFFF, 0x7FFFFFFF}}, eval('parsed[0]'))
end
@@ -351,7 +352,8 @@ describe('msgpack*() functions', function()
eq(1, eval('type(parsed[0]) == type(0) ' ..
'|| parsed[0]._TYPE is v:msgpack_types.integer'))
if eval('type(parsed[0]) == type(0)') == 1 then
- eq(1, eval('-0x8000000000000000 == parsed[0]'))
+ command('call assert_equal(-0x7fffffffffffffff - 1, parsed[0])')
+ eq({}, eval('v:errors'))
else
eq({_TYPE={}, _VAL={-1, 2, 0, 0}}, eval('parsed[0]'))
end
diff --git a/test/functional/eval/server_spec.lua b/test/functional/eval/server_spec.lua
index 420aea04aa..115114c3c3 100644
--- a/test/functional/eval/server_spec.lua
+++ b/test/functional/eval/server_spec.lua
@@ -1,20 +1,27 @@
local helpers = require('test.functional.helpers')(after_each)
-local nvim, eq, neq, eval = helpers.nvim, helpers.eq, helpers.neq, helpers.eval
+local eq, neq, eval = helpers.eq, helpers.neq, helpers.eval
+local command = helpers.command
local clear, funcs, meths = helpers.clear, helpers.funcs, helpers.meths
local os_name = helpers.os_name
+local function clear_serverlist()
+ for _, server in pairs(funcs.serverlist()) do
+ funcs.serverstop(server)
+ end
+end
+
describe('serverstart(), serverstop()', function()
before_each(clear)
it('sets $NVIM_LISTEN_ADDRESS on first invocation', function()
-- Unset $NVIM_LISTEN_ADDRESS
- nvim('command', 'let $NVIM_LISTEN_ADDRESS = ""')
+ command('let $NVIM_LISTEN_ADDRESS = ""')
local s = eval('serverstart()')
assert(s ~= nil and s:len() > 0, "serverstart() returned empty")
eq(s, eval('$NVIM_LISTEN_ADDRESS'))
- nvim('command', "call serverstop('"..s.."')")
+ command("call serverstop('"..s.."')")
eq('', eval('$NVIM_LISTEN_ADDRESS'))
end)
@@ -47,10 +54,38 @@ describe('serverstart(), serverstop()', function()
end)
it('serverstop() ignores invalid input', function()
- nvim('command', "call serverstop('')")
- nvim('command', "call serverstop('bogus-socket-name')")
+ command("call serverstop('')")
+ command("call serverstop('bogus-socket-name')")
end)
+ it('parses endpoints correctly', function()
+ clear_serverlist()
+ eq({}, funcs.serverlist())
+
+ local s = funcs.serverstart('127.0.0.1:0') -- assign random port
+ assert(string.match(s, '127.0.0.1:%d+'))
+ eq(s, funcs.serverlist()[1])
+ clear_serverlist()
+
+ s = funcs.serverstart('127.0.0.1:') -- assign random port
+ assert(string.match(s, '127.0.0.1:%d+'))
+ eq(s, funcs.serverlist()[1])
+ clear_serverlist()
+
+ funcs.serverstart('127.0.0.1:12345')
+ funcs.serverstart('127.0.0.1:12345') -- exists already; ignore
+ funcs.serverstart('::1:12345')
+ funcs.serverstart('::1:12345') -- exists already; ignore
+ local expected = {
+ '127.0.0.1:12345',
+ '::1:12345',
+ }
+ eq(expected, funcs.serverlist())
+ clear_serverlist()
+
+ funcs.serverstart('127.0.0.1:65536') -- invalid port
+ eq({}, funcs.serverlist())
+ end)
end)
describe('serverlist()', function()
@@ -75,7 +110,7 @@ describe('serverlist()', function()
-- The new servers should be at the end of the list.
for i = 1, #servs do
eq(servs[i], new_servs[i + n])
- nvim('command', "call serverstop('"..servs[i].."')")
+ command("call serverstop('"..servs[i].."')")
end
-- After serverstop() the servers should NOT be in the list.
eq(n, eval('len(serverlist())'))
diff --git a/test/functional/ex_cmds/mksession_spec.lua b/test/functional/ex_cmds/mksession_spec.lua
new file mode 100644
index 0000000000..5d658f10bb
--- /dev/null
+++ b/test/functional/ex_cmds/mksession_spec.lua
@@ -0,0 +1,49 @@
+local lfs = require('lfs')
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local command = helpers.command
+local get_pathsep = helpers.get_pathsep
+local eq = helpers.eq
+local funcs = helpers.funcs
+
+local file_prefix = 'Xtest-functional-ex_cmds-mksession_spec'
+
+describe(':mksession', function()
+ local session_file = file_prefix .. '.vim'
+ local tab_dir = file_prefix .. '.d'
+
+ before_each(function()
+ clear()
+ lfs.mkdir(tab_dir)
+ end)
+
+ after_each(function()
+ os.remove(session_file)
+ lfs.rmdir(tab_dir)
+ end)
+
+ it('restores tab-local working directories', function()
+ local tmpfile_base = file_prefix .. '-tmpfile'
+ local cwd_dir = funcs.getcwd()
+
+ -- :mksession does not save empty tabs, so create some buffers.
+ command('edit ' .. tmpfile_base .. '1')
+ command('tabnew')
+ command('edit ' .. tmpfile_base .. '2')
+ command('tcd ' .. tab_dir)
+ command('tabfirst')
+ command('mksession ' .. session_file)
+
+ -- Create a new test instance of Nvim.
+ clear()
+
+ command('source ' .. session_file)
+ -- First tab should have the original working directory.
+ command('tabnext 1')
+ eq(cwd_dir, funcs.getcwd())
+ -- Second tab should have the tab-local working directory.
+ command('tabnext 2')
+ eq(cwd_dir .. get_pathsep() .. tab_dir, funcs.getcwd())
+ end)
+end)
diff --git a/test/functional/helpers.lua b/test/functional/helpers.lua
index 4bd9ae4bfb..4a170d993b 100644
--- a/test/functional/helpers.lua
+++ b/test/functional/helpers.lua
@@ -76,8 +76,8 @@ end
local session, loop_running, last_error
-local function set_session(s)
- if session then
+local function set_session(s, keep)
+ if session and not keep then
session:close()
end
session = s
@@ -174,7 +174,7 @@ local os_name = (function()
end)()
local function iswin()
- return os_name() == 'windows'
+ return package.config:sub(1,1) == '\\'
end
-- Executes a VimL function.
@@ -492,17 +492,6 @@ local exc_exec = function(cmd)
return ret
end
-local function redir_exec(cmd)
- nvim_command(([[
- redir => g:__output
- silent! execute "%s"
- redir END
- ]]):format(cmd:gsub('\n', '\\n'):gsub('[\\"]', '\\%0')))
- local ret = nvim_eval('get(g:, "__output", 0)')
- nvim_command('unlet! g:__output')
- return ret
-end
-
local function create_callindex(func)
local table = {}
setmetatable(table, {
@@ -562,6 +551,19 @@ local curbufmeths = create_callindex(curbuf)
local curwinmeths = create_callindex(curwin)
local curtabmeths = create_callindex(curtab)
+local function redir_exec(cmd)
+ meths.set_var('__redir_exec_cmd', cmd)
+ nvim_command([[
+ redir => g:__redir_exec_output
+ silent! execute g:__redir_exec_cmd
+ redir END
+ ]])
+ local ret = meths.get_var('__redir_exec_output')
+ meths.del_var('__redir_exec_output')
+ meths.del_var('__redir_exec_cmd')
+ return ret
+end
+
local function get_pathsep()
return funcs.fnamemodify('.', ':p'):sub(-1)
end
@@ -627,6 +629,7 @@ local module = {
nvim = nvim,
nvim_async = nvim_async,
nvim_prog = nvim_prog,
+ nvim_argv = nvim_argv,
nvim_set = nvim_set,
nvim_dir = nvim_dir,
buffer = buffer,
diff --git a/test/functional/legacy/assert_spec.lua b/test/functional/legacy/assert_spec.lua
index d6255d42e7..2f342ec9a3 100644
--- a/test/functional/legacy/assert_spec.lua
+++ b/test/functional/legacy/assert_spec.lua
@@ -255,6 +255,16 @@ describe('assert function:', function()
end)
end)
+ -- assert_report({msg})
+ describe('assert_report()', function()
+ it('should add a message to v:errors', function()
+ command("call assert_report('something is wrong')")
+ command("call assert_match('something is wrong', v:errors[0])")
+ command('call remove(v:errors, 0)')
+ expected_empty()
+ end)
+ end)
+
-- assert_exception({cmd}, [, {error}])
describe('assert_exception()', function()
it('should assert thrown exceptions properly', function()
diff --git a/test/functional/legacy/eval_spec.lua b/test/functional/legacy/eval_spec.lua
index d7ef508194..c5d38d6d05 100644
--- a/test/functional/legacy/eval_spec.lua
+++ b/test/functional/legacy/eval_spec.lua
@@ -516,6 +516,15 @@ describe('eval', function()
eq({'item'}, eval("y"))
end)
+ it('sets the unnamed register when the "u" option is passed to setreg', function()
+ command("call setreg('a','a reg', 'cu')")
+ eq("a reg", eval('@"'))
+ command("call setreg('b','b reg', 'cu')")
+ eq("b reg", eval('@"'))
+ command("call setreg('c','c reg', 'c')")
+ eq("b reg", eval('@"'))
+ end)
+
it('search and expressions', function()
command('so test_eval_setup.vim')
command([=[call SetReg('/', ['abc/'])]=])
diff --git a/test/functional/options/defaults_spec.lua b/test/functional/options/defaults_spec.lua
index dc73679bb4..b83b7b8eee 100644
--- a/test/functional/options/defaults_spec.lua
+++ b/test/functional/options/defaults_spec.lua
@@ -8,6 +8,8 @@ local clear = helpers.clear
local eval = helpers.eval
local eq = helpers.eq
local neq = helpers.neq
+local mkdir = helpers.mkdir
+local rmdir = helpers.rmdir
local function init_session(...)
local args = { helpers.nvim_prog, '-i', 'NONE', '--embed',
@@ -121,6 +123,56 @@ describe('startup defaults', function()
it('v:progpath is set to the absolute path', function()
eq(eval("fnamemodify(v:progpath, ':p')"), eval('v:progpath'))
end)
+
+ describe('$NVIM_LOG_FILE', function()
+ -- TODO(jkeyes): use stdpath('data') instead.
+ local datasubdir = helpers.iswin() and 'nvim-data' or 'nvim'
+ local xdgdir = 'Xtest-startup-xdg-logpath'
+ local xdgdatadir = xdgdir..'/'..datasubdir
+ after_each(function()
+ os.remove('Xtest-logpath')
+ rmdir(xdgdir)
+ end)
+
+ it('is used if expansion succeeds', function()
+ clear({env={
+ NVIM_LOG_FILE='Xtest-logpath',
+ }})
+ eq('Xtest-logpath', eval('$NVIM_LOG_FILE'))
+ end)
+ it('defaults to stdpath("data")/log if empty', function()
+ eq(true, mkdir(xdgdir) and mkdir(xdgdatadir))
+ clear({env={
+ XDG_DATA_HOME=xdgdir,
+ NVIM_LOG_FILE='', -- Empty is invalid.
+ }})
+ -- server_start() calls ELOG, which tickles log_path_init().
+ pcall(command, 'call serverstart(serverlist()[0])')
+
+ eq(xdgdir..'/'..datasubdir..'/log', string.gsub(eval('$NVIM_LOG_FILE'), '\\', '/'))
+ end)
+ it('defaults to stdpath("data")/log if invalid', function()
+ eq(true, mkdir(xdgdir) and mkdir(xdgdatadir))
+ clear({env={
+ XDG_DATA_HOME=xdgdir,
+ NVIM_LOG_FILE='.', -- Any directory is invalid.
+ }})
+ -- server_start() calls ELOG, which tickles log_path_init().
+ pcall(command, 'call serverstart(serverlist()[0])')
+
+ eq(xdgdir..'/'..datasubdir..'/log', string.gsub(eval('$NVIM_LOG_FILE'), '\\', '/'))
+ end)
+ it('defaults to .nvimlog if stdpath("data") is invalid', function()
+ clear({env={
+ XDG_DATA_HOME='Xtest-missing-xdg-dir',
+ NVIM_LOG_FILE='.', -- Any directory is invalid.
+ }})
+ -- server_start() calls ELOG, which tickles log_path_init().
+ pcall(command, 'call serverstart(serverlist()[0])')
+
+ eq('.nvimlog', eval('$NVIM_LOG_FILE'))
+ end)
+ end)
end)
describe('XDG-based defaults', function()
diff --git a/test/functional/options/pastetoggle_spec.lua b/test/functional/options/pastetoggle_spec.lua
index ec3c60fe37..a1f86f73ff 100644
--- a/test/functional/options/pastetoggle_spec.lua
+++ b/test/functional/options/pastetoggle_spec.lua
@@ -6,32 +6,35 @@ local command = helpers.command
local eq = helpers.eq
local eval = helpers.eval
local sleep = helpers.sleep
+local expect = helpers.expect
describe("'pastetoggle' option", function()
before_each(function()
clear()
command('set nopaste')
- command('set pastetoggle=a')
end)
+
it("toggles 'paste'", function()
- eq(eval('&paste'), 0)
+ command('set pastetoggle=a')
+ eq(0, eval('&paste'))
feed('a')
-- Need another key so that the vgetorpeek() function returns.
feed('j')
- eq(eval('&paste'), 1)
+ eq(1, eval('&paste'))
end)
- it("multiple key 'pastetoggle' is waited for", function()
- eq(eval('&paste'), 0)
- local pastetoggle = 'lllll'
- command('set pastetoggle=' .. pastetoggle)
- command('set timeoutlen=1 ttimeoutlen=10000')
- feed(pastetoggle:sub(0, 2))
- -- sleep() for long enough that vgetorpeek() is gotten into, but short
- -- enough that ttimeoutlen is not reached.
- sleep(200)
- feed(pastetoggle:sub(3, -1))
- -- Need another key so that the vgetorpeek() function returns.
- feed('j')
- eq(eval('&paste'), 1)
+
+
+ it('does not wait for timeout', function()
+ command('set pastetoggle=abc')
+ command('set ttimeoutlen=9999999')
+ eq(0, eval('&paste'))
+ -- n.b. need <esc> to return from vgetorpeek()
+ feed('abc<esc>')
+ eq(1, eval('&paste'))
+ feed('ab')
+ sleep(10)
+ feed('c<esc>')
+ expect('bc')
+ eq(1, eval('&paste'))
end)
end)
diff --git a/test/functional/plugin/shada_spec.lua b/test/functional/plugin/shada_spec.lua
index b543037ae2..639833071b 100644
--- a/test/functional/plugin/shada_spec.lua
+++ b/test/functional/plugin/shada_spec.lua
@@ -179,6 +179,7 @@ describe('In autoload/shada.vim', function()
' + n name \'@\'',
' + rc contents ["abc", "def"]',
' + rt type CHARACTERWISE',
+ ' + ru is_unnamed FALSE',
' + rw block width 10',
' + sb search backward TRUE',
' + sc smartcase value FALSE',
@@ -204,6 +205,7 @@ describe('In autoload/shada.vim', function()
'rt': 0,
'rw': 10,
'rc': ['abc', 'def'],
+ 'ru': {'_TYPE': v:msgpack_types.boolean, '_VAL': 0},
'n': 0x40,
'l': 10,
'c': 0,
@@ -226,6 +228,8 @@ describe('In autoload/shada.vim', function()
.. '0 (CHARACTERWISE), 1 (LINEWISE), 2 (BLOCKWISE)',
' + rt type 10',
' # Expected boolean',
+ ' + ru is_unnamed 10',
+ ' # Expected boolean',
' + sc smartcase value NIL',
' # Expected boolean',
' + sm magic value "TRUE"',
@@ -240,6 +244,7 @@ describe('In autoload/shada.vim', function()
'sp': {'_TYPE': v:msgpack_types.string, '_VAL': ["abc"]},
'rt': 10,
'rc': '10',
+ 'ru': 10,
'n': -0x40,
'l': -10,
'c': 'abc',
@@ -636,6 +641,7 @@ describe('In autoload/shada.vim', function()
' # Required key missing: rc',
' + rw block width 0',
' + rt type CHARACTERWISE',
+ ' + ru is_unnamed FALSE',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
}}] ]]):gsub('\n', ''))
sd2strings_eq({
@@ -645,6 +651,7 @@ describe('In autoload/shada.vim', function()
' # Required key missing: rc',
' + rw block width 0',
' + rt type CHARACTERWISE',
+ ' + ru is_unnamed FALSE',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
}}] ]]):gsub('\n', ''))
@@ -655,9 +662,11 @@ describe('In autoload/shada.vim', function()
' + rc contents ["abc", "def"]',
' + rw block width 0',
' + rt type CHARACTERWISE',
+ ' + ru is_unnamed FALSE',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
'rc': ["abc", "def"],
+ 'ru': {'_TYPE': v:msgpack_types.boolean, '_VAL': 0},
}}] ]]):gsub('\n', ''))
sd2strings_eq({
'Register with timestamp ' .. epoch .. ':',
@@ -668,9 +677,11 @@ describe('In autoload/shada.vim', function()
' | - "abcdefghijklmnopqrstuvwxyz"',
' + rw block width 0',
' + rt type CHARACTERWISE',
+ ' + ru is_unnamed TRUE',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
'rc': ['abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz'],
+ 'ru': {'_TYPE': v:msgpack_types.boolean, '_VAL': 1},
}}] ]]):gsub('\n', ''))
sd2strings_eq({
'Register with timestamp ' .. epoch .. ':',
@@ -681,6 +692,7 @@ describe('In autoload/shada.vim', function()
' | - "abcdefghijklmnopqrstuvwxyz"',
' + rw block width 0',
' + rt type CHARACTERWISE',
+ ' + ru is_unnamed FALSE',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
'rc': ['abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz'],
@@ -696,6 +708,7 @@ describe('In autoload/shada.vim', function()
' | - "abcdefghijklmnopqrstuvwxyz"',
' + rw block width 5',
' + rt type LINEWISE',
+ ' + ru is_unnamed FALSE',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
'rc': ['abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz'],
@@ -712,11 +725,14 @@ describe('In autoload/shada.vim', function()
' # Expected integer',
' + rw block width ""',
' + rt type BLOCKWISE',
+ ' # Expected boolean',
+ ' + ru is_unnamed ""',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
'rc': ['abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz'],
'rw': "",
'rt': 2,
+ 'ru': ""
}}] ]]):gsub('\n', ''))
sd2strings_eq({
'Register with timestamp ' .. epoch .. ':',
@@ -729,11 +745,32 @@ describe('In autoload/shada.vim', function()
' # Unexpected enum value: expected one of 0 (CHARACTERWISE), '
.. '1 (LINEWISE), 2 (BLOCKWISE)',
' + rt type 10',
+ ' # Expected boolean',
+ ' + ru is_unnamed ["abc", "def"]',
}, ([[ [{'type': 5, 'timestamp': 0, 'data': {
'n': 0x20,
'rc': 0,
'rw': -1,
'rt': 10,
+ 'ru': ['abc', 'def'],
+ }}] ]]):gsub('\n', ''))
+ sd2strings_eq({
+ 'Register with timestamp ' .. epoch .. ':',
+ ' % Key Description Value',
+ ' + n name \' \'',
+ ' + rc contents @',
+ ' | - "abcdefghijklmnopqrstuvwxyz"',
+ ' | - "abcdefghijklmnopqrstuvwxyz"',
+ ' + rw block width 5',
+ ' + rt type LINEWISE',
+ ' # Expected boolean',
+ ' + ru is_unnamed 0',
+ }, ([[ [{'type': 5, 'timestamp': 0, 'data': {
+ 'n': 0x20,
+ 'rc': ['abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz'],
+ 'rw': 5,
+ 'rt': 1,
+ 'ru': 0,
}}] ]]):gsub('\n', ''))
end)
diff --git a/test/functional/shada/registers_spec.lua b/test/functional/shada/registers_spec.lua
index fc812f799c..71af14aba8 100644
--- a/test/functional/shada/registers_spec.lua
+++ b/test/functional/shada/registers_spec.lua
@@ -148,4 +148,40 @@ describe('ShaDa support code', function()
eq({{'\171«'}, 'v'}, getreg('e'))
end)
+ it('has a blank unnamed register if it wasn\'t set and register 0 is empty',
+ function()
+ setreg('1', {'one'}, 'c')
+ setreg('2', {'two'}, 'c')
+ setreg('a', {'a'}, 'c')
+ nvim_command('qall')
+ reset()
+ eq({{}, ''}, getreg('0'))
+ eq({{'one'}, 'v'}, getreg('1'))
+ eq({{}, ''}, getreg('"'))
+ eq({{'a'}, 'v'}, getreg('a'))
+ end)
+
+ it('defaults the unnamed register to register 0 if it wasn\'t set',
+ function()
+ setreg('0', {'zero'}, 'c')
+ setreg('1', {'one'}, 'c')
+ setreg('2', {'two'}, 'c')
+ nvim_command('qall')
+ reset()
+ eq({{'zero'}, 'v'}, getreg('0'))
+ eq({{'one'}, 'v'}, getreg('1'))
+ eq({{'zero'}, 'v'}, getreg('"'))
+ end)
+
+ it('remembers which register was the unnamed register when loading',
+ function()
+ setreg('0', {'zero'}, 'c')
+ setreg('1', {'one'}, 'cu')
+ setreg('2', {'two'}, 'c')
+ nvim_command('qall')
+ reset()
+ eq({{'zero'}, 'v'}, getreg('0'))
+ eq({{'one'}, 'v'}, getreg('1'))
+ eq({{'one'}, 'v'}, getreg('"'))
+ end)
end)
diff --git a/test/functional/ui/highlight_spec.lua b/test/functional/ui/highlight_spec.lua
index 4fd00cc320..d1357ea525 100644
--- a/test/functional/ui/highlight_spec.lua
+++ b/test/functional/ui/highlight_spec.lua
@@ -5,6 +5,7 @@ local clear, feed, insert = helpers.clear, helpers.feed, helpers.insert
local command = helpers.command
local eval, exc_exec = helpers.eval, helpers.exc_exec
local feed_command, request, eq = helpers.feed_command, helpers.request, helpers.eq
+local curbufmeths = helpers.curbufmeths
describe('colorscheme compatibility', function()
before_each(function()
@@ -670,12 +671,26 @@ describe("'winhighlight' highlight", function()
[8] = {background = Screen.colors.DarkMagenta, bold = true, foreground = Screen.colors.Blue1},
[9] = {foreground = Screen.colors.Brown},
[10] = {foreground = Screen.colors.Brown, background = Screen.colors.DarkBlue},
+ [11] = {background = Screen.colors.DarkBlue, bold = true, reverse = true},
+ [12] = {background = Screen.colors.DarkGreen, reverse = true},
+ [13] = {background = Screen.colors.Magenta4, reverse = true},
+ [14] = {background = Screen.colors.DarkBlue, reverse = true},
+ [15] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red},
+ [16] = {foreground = Screen.colors.Blue1},
+ [17] = {background = Screen.colors.LightRed},
+ [18] = {background = Screen.colors.Gray90},
+ [19] = {foreground = Screen.colors.LightGrey, background = Screen.colors.DarkGray},
+ [20] = {background = Screen.colors.LightGrey, underline = true},
+ [21] = {bold = true},
+ [22] = {bold = true, foreground = Screen.colors.SeaGreen4},
+ [23] = {background = Screen.colors.LightMagenta},
+ [24] = {background = Screen.colors.WebGray},
})
command("hi Background1 guibg=DarkBlue")
command("hi Background2 guibg=DarkGreen")
end)
- it('works', function()
+ it('works for background color', function()
insert("aa")
command("split")
command("set winhl=Normal:Background1")
@@ -683,7 +698,7 @@ describe("'winhighlight' highlight", function()
{1:a^a }|
{2:~ }|
{2:~ }|
- {3:[No Name] [+] }|
+ {11:[No Name] [+] }|
aa |
{0:~ }|
{4:[No Name] [+] }|
@@ -695,7 +710,7 @@ describe("'winhighlight' highlight", function()
{1:^ }|
{2:~ }|
{2:~ }|
- {3:[No Name] }|
+ {11:[No Name] }|
aa |
{0:~ }|
{4:[No Name] [+] }|
@@ -740,7 +755,7 @@ describe("'winhighlight' highlight", function()
{1:a^a }|
{2:~ }|
{2:~ }|
- {3:[No Name] [+] }|
+ {11:[No Name] [+] }|
aa |
{0:~ }|
{4:[No Name] [+] }|
@@ -764,16 +779,15 @@ describe("'winhighlight' highlight", function()
{1:^aa }|
{2:~ }|
{2:~ }|
- {3:[No Name] [+] }|
+ {11:[No Name] [+] }|
aa |
{0:~ }|
{4:[No Name] [+] }|
<f 1 --100%-- col 1 |
]])
-
end)
- it('for inactive window works', function()
+ it('for inactive window background works', function()
command("set winhl=Normal:Background1,NormalNC:Background2")
-- tests global value is copied across split
command("split")
@@ -781,10 +795,10 @@ describe("'winhighlight' highlight", function()
{1:^ }|
{2:~ }|
{2:~ }|
- {3:[No Name] }|
+ {11:[No Name] }|
{5: }|
{6:~ }|
- {4:[No Name] }|
+ {12:[No Name] }|
|
]])
@@ -793,10 +807,10 @@ describe("'winhighlight' highlight", function()
{5: }|
{6:~ }|
{6:~ }|
- {4:[No Name] }|
+ {12:[No Name] }|
{1:^ }|
{2:~ }|
- {3:[No Name] }|
+ {11:[No Name] }|
|
]])
@@ -805,13 +819,12 @@ describe("'winhighlight' highlight", function()
{1:^ }|
{2:~ }|
{2:~ }|
- {3:[No Name] }|
+ {11:[No Name] }|
{5: }|
{6:~ }|
- {4:[No Name] }|
+ {12:[No Name] }|
|
]])
-
end)
it('works with NormalNC', function()
@@ -825,7 +838,7 @@ describe("'winhighlight' highlight", function()
{3:[No Name] }|
{7: }|
{8:~ }|
- {4:[No Name] }|
+ {13:[No Name] }|
|
]])
@@ -834,7 +847,7 @@ describe("'winhighlight' highlight", function()
{7: }|
{8:~ }|
{8:~ }|
- {4:[No Name] }|
+ {13:[No Name] }|
^ |
{0:~ }|
{3:[No Name] }|
@@ -848,10 +861,10 @@ describe("'winhighlight' highlight", function()
{7: }|
{8:~ }|
{8:~ }|
- {4:[No Name] }|
+ {13:[No Name] }|
{1:^ }|
{2:~ }|
- {3:[No Name] }|
+ {11:[No Name] }|
|
]])
@@ -863,7 +876,7 @@ describe("'winhighlight' highlight", function()
{3:[No Name] }|
{1: }|
{2:~ }|
- {4:[No Name] }|
+ {14:[No Name] }|
|
]])
@@ -873,10 +886,10 @@ describe("'winhighlight' highlight", function()
{7: }|
{8:~ }|
{8:~ }|
- {4:[No Name] }|
+ {13:[No Name] }|
{1:^ }|
{2:~ }|
- {3:[No Name] }|
+ {11:[No Name] }|
|
]])
@@ -888,13 +901,12 @@ describe("'winhighlight' highlight", function()
{3:[No Name] }|
{5: }|
{6:~ }|
- {4:[No Name] }|
+ {12:[No Name] }|
|
]])
-
end)
- it('applies also to non-text', function()
+ it('background applies also to non-text', function()
insert('Lorem ipsum dolor sit amet ')
command('set shiftwidth=2')
feed('>>')
@@ -940,6 +952,114 @@ describe("'winhighlight' highlight", function()
|
]])
end)
-end)
+ it('can override NonText, Conceal and EndOfBuffer', function()
+ curbufmeths.set_lines(0,-1,true, {"raa\000"})
+ command('call matchaddpos("Conceal", [[1,2]], 0, -1, {"conceal": "#"})')
+ command('set cole=2 cocu=nvic')
+ command('split')
+ command('call matchaddpos("Conceal", [[1,2]], 0, -1, {"conceal": "#"})')
+ command('set winhl=SpecialKey:ErrorMsg,EndOfBuffer:Background1,'
+ ..'Conceal:Background2')
+
+ screen:expect([[
+ ^r{5:#}a{15:^@} |
+ {1:~ }|
+ {1:~ }|
+ {3:[No Name] [+] }|
+ r{19:#}a{16:^@} |
+ {0:~ }|
+ {4:[No Name] [+] }|
+ |
+ ]])
+ end)
+
+ it('can override LineNr, CursorColumn and ColorColumn', function()
+ insert('very text\nmore text')
+ command('set number')
+ command('set colorcolumn=2')
+ command('set cursorcolumn')
+
+ command('split')
+ command('set winhl=LineNr:Background1,CursorColumn:Background2,'
+ ..'ColorColumn:ErrorMsg')
+ screen:expect([[
+ {1: 1 }v{15:e}ry tex{5:t} |
+ {1: 2 }m{15:o}re tex^t |
+ {0:~ }|
+ {3:[No Name] [+] }|
+ {9: 1 }v{17:e}ry tex{18:t} |
+ {9: 2 }m{17:o}re text |
+ {4:[No Name] [+] }|
+ |
+ ]])
+ end)
+
+ it('can override Tabline', function()
+ command('tabnew')
+ command('set winhl=TabLine:Background1,TabLineSel:ErrorMsg')
+
+ screen:expect([[
+ {20: No Name] }{15: No Name]}{20:X}|
+ ^ |
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ |
+ ]])
+ command("tabnext")
+ screen:expect([[
+ {21: No Name] }{1: No Name]}{20:X}|
+ ^ |
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ |
+ ]])
+ end)
+
+ it('can override popupmenu', function()
+ insert('word wording wordy')
+ command('split')
+ command('set winhl=Pmenu:Background1,PmenuSel:Background2,'
+ ..'PmenuSbar:ErrorMsg,PmenuThumb:Normal')
+ screen:expect([[
+ word wording word^y |
+ {0:~ }|
+ {0:~ }|
+ {3:[No Name] [+] }|
+ word wording wordy |
+ {0:~ }|
+ {4:[No Name] [+] }|
+ |
+ ]])
+ feed('oword<c-x><c-p>')
+ screen:expect([[
+ word wording wordy |
+ wordy^ |
+ {1:word }{0: }|
+ {1:wording }{3: }|
+ {5:wordy }rdy |
+ wordy |
+ {4:[No Name] [+] }|
+ {21:-- }{22:match 1 of 3} |
+ ]])
+
+ feed('<esc>u<c-w><c-w>oword<c-x><c-p>')
+ screen:expect([[
+ word wording wordy |
+ wordy |
+ {23:word }{0: }|
+ {23:wording }{4: }|
+ {24:wordy }rdy |
+ wordy^ |
+ {3:[No Name] [+] }|
+ {21:-- }{22:match 1 of 3} |
+ ]])
+ end)
+end)
diff --git a/test/functional/ui/screen.lua b/test/functional/ui/screen.lua
index 7d9cd6c026..5408e1e195 100644
--- a/test/functional/ui/screen.lua
+++ b/test/functional/ui/screen.lua
@@ -198,8 +198,9 @@ function Screen:expect(expected, attr_ids, attr_ignore, condition, any)
condition = expected
expected = nil
else
- -- Remove the last line and dedent.
- expected = dedent(expected:gsub('\n[ ]+$', ''))
+ -- Remove the last line and dedent. Note that gsub returns more then one
+ -- value.
+ expected = dedent(expected:gsub('\n[ ]+$', ''), 0)
for row in expected:gmatch('[^\n]+') do
row = row:sub(1, #row - 1) -- Last char must be the screen delimiter.
table.insert(expected_rows, row)
diff --git a/test/functional/viml/function_spec.lua b/test/functional/viml/function_spec.lua
index 776e760aaf..0cf92f7d40 100644
--- a/test/functional/viml/function_spec.lua
+++ b/test/functional/viml/function_spec.lua
@@ -1,29 +1,221 @@
local helpers = require('test.functional.helpers')(after_each)
-local clear = helpers.clear
local eq = helpers.eq
-local exc_exec = helpers.exc_exec
+local clear = helpers.clear
+local funcs = helpers.funcs
+local dedent = helpers.dedent
+local redir_exec = helpers.redir_exec
-describe('Up to MAX_FUNC_ARGS arguments are handled by', function()
- local max_func_args = 20 -- from eval.h
- local range = helpers.funcs.range
+before_each(clear)
- before_each(clear)
+local function check_nofunc(fname)
+ eq(0, funcs.exists('*' .. fname))
+end
- it('printf()', function()
- local printf = helpers.funcs.printf
- local rep = helpers.funcs['repeat']
- local expected = '2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,'
- eq(expected, printf(rep('%d,', max_func_args-1), unpack(range(2, max_func_args))))
- local ret = exc_exec('call printf("", 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)')
- eq('Vim(call):E740: Too many arguments for function printf', ret)
- end)
+local function check_func(fname, body, indent)
+ if type(body) == 'number' then
+ body = ('return %i'):format(body)
+ end
+ eq(dedent(([[
- it('rpcnotify()', function()
- local rpcnotify = helpers.funcs.rpcnotify
- local ret = rpcnotify(0, 'foo', unpack(range(3, max_func_args)))
- eq(1, ret)
- ret = exc_exec('call rpcnotify(0, "foo", 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)')
- eq('Vim(call):E740: Too many arguments for function rpcnotify', ret)
+ function %s()%s
+ endfunction]]
+ ), 3):format(
+ fname,
+ body and ('\n1' .. (' '):rep(2 + (indent or 8)) .. body) or ''),
+ redir_exec('function ' .. fname))
+end
+
+describe(':endfunction', function()
+ it('accepts bang', function()
+ eq('', redir_exec([[
+ function F()
+ endfunction!
+ ]]))
+ check_func('F')
+ eq('', redir_exec([[
+ function! F()
+ return 1
+ endfunction!
+ ]]))
+ check_func('F', 1)
+ end)
+ it('accepts comments', function()
+ eq('', redir_exec([[
+ function F1()
+ endfunction " Comment
+ ]]))
+ check_func('F1')
+ eq('', redir_exec([[
+ function F2()
+ endfunction " }}}
+ ]]))
+ check_func('F2')
+ eq('', redir_exec([[
+ function F3()
+ endfunction " F3
+ ]]))
+ check_func('F3')
+ eq('', redir_exec([[
+ function F4()
+ endfunction! " F4
+ ]]))
+ check_func('F4')
+ eq('', redir_exec([[
+ function! F4()
+ return 2
+ endfunction! " F4
+ ]]))
+ check_func('F4', 2)
+ end)
+ it('accepts function name', function()
+ eq('', redir_exec([[
+ function F0()
+ endfunction F0
+ ]]))
+ check_func('F0')
+ eq('', redir_exec([[
+ function F1()
+ endfunction! F1
+ ]]))
+ check_func('F1')
+ eq('', redir_exec([[
+ function! F2()
+ endfunction! F2
+ ]]))
+ check_func('F2')
+ eq('', redir_exec([[
+ function! F2()
+ return 3
+ endfunction! F2
+ ]]))
+ check_func('F2', 3)
+ end)
+ it('accepts weird characters', function()
+ eq('', redir_exec([[
+ function F1()
+ endfunction: }}}
+ ]]))
+ check_func('F1')
+ -- From accurev
+ eq('', redir_exec([[
+ function F2()
+ endfunction :}}}
+ ]]))
+ check_func('F2')
+ -- From cream-vimabbrev
+ eq('', redir_exec([[
+ function F3()
+ endfunction 1}}}
+ ]]))
+ check_func('F3')
+ -- From pyunit
+ eq('', redir_exec([[
+ function F4()
+ endfunction # }}}
+ ]]))
+ check_func('F4')
+ -- From vim-lldb
+ eq('', redir_exec([[
+ function F5()
+ endfunction()
+ ]]))
+ check_func('F5')
+ -- From vim-mail
+ eq('', redir_exec([[
+ function F6()
+ endfunction;
+ ]]))
+ check_func('F6')
+ end)
+ it('accepts commented bar', function()
+ eq('', redir_exec([[
+ function F1()
+ endfunction " F1 | echo 42
+ ]]))
+ check_func('F1')
+ eq('', redir_exec([[
+ function! F1()
+ return 42
+ endfunction! " F1 | echo 42
+ ]]))
+ check_func('F1', 42)
+ end)
+ it('errors out on an uncommented bar', function()
+ eq('\nE488: Trailing characters: | echo 42', redir_exec([[
+ function F1()
+ endfunction | echo 42
+ ]]))
+ check_nofunc('F1')
+ end)
+ it('allows running multiple commands', function()
+ eq('\n2', redir_exec([[
+ function F1()
+ echo 2
+ endfunction
+ call F1()
+ ]]))
+ check_func('F1', 'echo 2')
+ eq('\n2\n3\n4', redir_exec([[
+ function F2()
+ echo 2
+ endfunction F2
+ function F3()
+ echo 3
+ endfunction " F3
+ function! F4()
+ echo 4
+ endfunction!
+ call F2()
+ call F3()
+ call F4()
+ ]]))
+ check_func('F2', 'echo 2')
+ check_func('F3', 'echo 3')
+ check_func('F4', 'echo 4')
+ end)
+ it('allows running multiple commands with only one character in between',
+ function()
+ eq('\n3', redir_exec(dedent([[
+ function! F1()
+ echo 3
+ endfunction!
+ call F1()]])))
+ check_func('F1', 'echo 3', 2)
+ eq('\n4', redir_exec(dedent([[
+ function F5()
+ echo 4
+ endfunction
+ call F5()]])))
+ check_func('F5', 'echo 4', 2)
+ eq('\n5', redir_exec(dedent([[
+ function F6()
+ echo 5
+ endfunction " TEST
+ call F6()]])))
+ check_func('F6', 'echo 5', 2)
+ eq('\n6', redir_exec(dedent([[
+ function F7()
+ echo 6
+ endfunction F7
+ call F7()]])))
+ check_func('F7', 'echo 6', 2)
+ eq('\n2\n3\n4', redir_exec(dedent([[
+ function F2()
+ echo 2
+ endfunction F2
+ function F3()
+ echo 3
+ endfunction " F3
+ function! F4()
+ echo 4
+ endfunction!
+ call F2()
+ call F3()
+ call F4()]])))
+ check_func('F2', 'echo 2', 2)
+ check_func('F3', 'echo 3', 2)
+ check_func('F4', 'echo 4', 2)
end)
end)
+-- vim: foldmarker=▶,▲
diff --git a/test/helpers.lua b/test/helpers.lua
index 7a0e4b8c3c..260f10002e 100644
--- a/test/helpers.lua
+++ b/test/helpers.lua
@@ -284,7 +284,7 @@ local function concat_tables(...)
return ret
end
-local function dedent(str)
+local function dedent(str, leave_indent)
-- find minimum common indent across lines
local indent = nil
for line in str:gmatch('[^\n]+') do
@@ -297,12 +297,13 @@ local function dedent(str)
-- no minimum common indent
return str
end
+ local left_indent = (' '):rep(leave_indent or 0)
-- create a pattern for the indent
indent = indent:gsub('%s', '[ \t]')
-- strip it from the first line
- str = str:gsub('^'..indent, '')
+ str = str:gsub('^'..indent, left_indent)
-- strip it from the remaining lines
- str = str:gsub('[\n]'..indent, '\n')
+ str = str:gsub('[\n]'..indent, '\n' .. left_indent)
return str
end
diff --git a/test/unit/os/shell_spec.lua b/test/unit/os/shell_spec.lua
index e883301cfb..37274502de 100644
--- a/test/unit/os/shell_spec.lua
+++ b/test/unit/os/shell_spec.lua
@@ -15,7 +15,7 @@ local NULL = ffi.cast('void *', 0)
describe('shell functions', function()
before_each(function()
-- os_system() can't work when the p_sh and p_shcf variables are unset
- cimported.p_sh = to_cstr('/bin/bash')
+ cimported.p_sh = to_cstr('/bin/sh')
cimported.p_shcf = to_cstr('-c')
cimported.p_sxq = to_cstr('')
cimported.p_sxe = to_cstr('')
@@ -53,14 +53,14 @@ describe('shell functions', function()
describe('os_system', function()
itp('can echo some output (shell builtin)', function()
- local cmd, text = 'echo -n', 'some text'
+ local cmd, text = 'printf "%s "', 'some text '
local status, output = os_system(cmd .. ' ' .. text)
eq(text, output)
eq(0, status)
end)
itp('can deal with empty output', function()
- local cmd = 'echo -n'
+ local cmd = 'printf ""'
local status, output = os_system(cmd)
eq('', output)
eq(0, status)
@@ -81,19 +81,19 @@ describe('shell functions', function()
describe('shell_build_argv', function()
itp('works with NULL arguments', function()
- eq({'/bin/bash'}, shell_build_argv(nil, nil))
+ eq({'/bin/sh'}, shell_build_argv(nil, nil))
end)
itp('works with cmd', function()
- eq({'/bin/bash', '-c', 'abc def'}, shell_build_argv('abc def', nil))
+ eq({'/bin/sh', '-c', 'abc def'}, shell_build_argv('abc def', nil))
end)
itp('works with extra_args', function()
- eq({'/bin/bash', 'ghi jkl'}, shell_build_argv(nil, 'ghi jkl'))
+ eq({'/bin/sh', 'ghi jkl'}, shell_build_argv(nil, 'ghi jkl'))
end)
itp('works with cmd and extra_args', function()
- eq({'/bin/bash', 'ghi jkl', '-c', 'abc def'}, shell_build_argv('abc def', 'ghi jkl'))
+ eq({'/bin/sh', 'ghi jkl', '-c', 'abc def'}, shell_build_argv('abc def', 'ghi jkl'))
end)
itp('splits and unquotes &shell and &shellcmdflag', function()
@@ -112,7 +112,7 @@ describe('shell functions', function()
local argv = ffi.cast('char**',
cimported.shell_build_argv(to_cstr('echo &|<>()@^'), nil))
- eq(ffi.string(argv[0]), '/bin/bash')
+ eq(ffi.string(argv[0]), '/bin/sh')
eq(ffi.string(argv[1]), '-c')
eq(ffi.string(argv[2]), '(echo ^&^|^<^>^(^)^@^^)')
eq(nil, argv[3])
@@ -124,7 +124,7 @@ describe('shell functions', function()
local argv = ffi.cast('char**', cimported.shell_build_argv(
to_cstr('echo -n some text'), nil))
- eq(ffi.string(argv[0]), '/bin/bash')
+ eq(ffi.string(argv[0]), '/bin/sh')
eq(ffi.string(argv[1]), '-c')
eq(ffi.string(argv[2]), '"(echo -n some text)"')
eq(nil, argv[3])
@@ -136,7 +136,7 @@ describe('shell functions', function()
local argv = ffi.cast('char**', cimported.shell_build_argv(
to_cstr('echo -n some text'), nil))
- eq(ffi.string(argv[0]), '/bin/bash')
+ eq(ffi.string(argv[0]), '/bin/sh')
eq(ffi.string(argv[1]), '-c')
eq(ffi.string(argv[2]), '"echo -n some text"')
eq(nil, argv[3])
@@ -145,7 +145,7 @@ describe('shell functions', function()
itp('with empty shellxquote/shellxescape', function()
local argv = ffi.cast('char**', cimported.shell_build_argv(
to_cstr('echo -n some text'), nil))
- eq(ffi.string(argv[0]), '/bin/bash')
+ eq(ffi.string(argv[0]), '/bin/sh')
eq(ffi.string(argv[1]), '-c')
eq(ffi.string(argv[2]), 'echo -n some text')
eq(nil, argv[3])
diff --git a/third-party/CMakeLists.txt b/third-party/CMakeLists.txt
index b8dad75b24..bd4567cff7 100644
--- a/third-party/CMakeLists.txt
+++ b/third-party/CMakeLists.txt
@@ -87,20 +87,21 @@ endif()
include(ExternalProject)
-set(LIBUV_URL https://github.com/libuv/libuv/archive/v1.9.1.tar.gz)
-set(LIBUV_SHA256 a6ca9f0648973d1463f46b495ce546ddcbe7cce2f04b32e802a15539e46c57ad)
+set(LIBUV_URL https://github.com/libuv/libuv/archive/v1.12.0.tar.gz)
+set(LIBUV_SHA256 41ce914a88da21d3b07a76023beca57576ca5b376c6ac440c80bc581cbca1250)
-set(MSGPACK_URL https://github.com/msgpack/msgpack-c/archive/cpp-2.1.1.tar.gz)
-set(MSGPACK_SHA256 d6bef12d959816a39c7a6972f3f16c0724e4c7ff0927eb59a35247dc8267b609)
+set(MSGPACK_URL https://github.com/msgpack/msgpack-c/archive/cpp-2.1.3.tar.gz)
+set(MSGPACK_SHA256 42ff5c213fd24bd4388c45c1f21d84b476678ce6366ea4d4f4086618a1d2cd23)
-set(LUAJIT_URL https://github.com/neovim/deps/raw/master/opt/LuaJIT-2.0.4.tar.gz)
-set(LUAJIT_SHA256 620fa4eb12375021bef6e4f237cbd2dd5d49e56beb414bee052c746beef1807d)
+set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/82151a4514e6538086f3f5e01cb8d4b22287b14f.tar.gz)
+set(LUAJIT_SHA256 8bc4e96ebab74e12ab84e751360e864714289bb089b51b6f396fa9a97df69798)
set(LUA_URL https://www.lua.org/ftp/lua-5.1.5.tar.gz)
set(LUA_SHA256 2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333)
-set(LUAROCKS_URL https://github.com/keplerproject/luarocks/archive/5d8a16526573b36d5b22aa74866120c998466697.tar.gz)
-set(LUAROCKS_SHA256 cae709111c5701235770047dfd7169f66b82ae1c7b9b79207f9df0afb722bfd9)
+# NOTE: Version must match LUAROCKS_VERSION in third-party/cmake/BuildLuarocks.cmake
+set(LUAROCKS_URL https://github.com/luarocks/luarocks/archive/v2.4.2.tar.gz)
+set(LUAROCKS_SHA256 eef88c2429c715a7beb921e4b1ba571dddb7c74a250fbb0d3cc0d4be7a5865d9)
set(UNIBILIUM_URL https://github.com/mauke/unibilium/archive/v1.2.0.tar.gz)
set(UNIBILIUM_SHA256 623af1099515e673abfd3cae5f2fa808a09ca55dda1c65a7b5c9424eb304ead8)
@@ -116,14 +117,14 @@ endif()
set(LIBVTERM_URL https://github.com/neovim/libvterm/archive/a9c7c6fd20fa35e0ad3e0e98901ca12dfca9c25c.tar.gz)
set(LIBVTERM_SHA256 1a4272be91d9614dc183a503786df83b6584e4afaab7feaaa5409f841afbd796)
-set(JEMALLOC_URL https://github.com/jemalloc/jemalloc/releases/download/4.3.1/jemalloc-4.3.1.tar.bz2)
-set(JEMALLOC_SHA256 f7bb183ad8056941791e0f075b802e8ff10bd6e2d904e682f87c8f6a510c278b)
+set(JEMALLOC_URL https://github.com/jemalloc/jemalloc/releases/download/4.5.0/jemalloc-4.5.0.tar.bz2)
+set(JEMALLOC_SHA256 9409d85664b4f135b77518b0b118c549009dc10f6cba14557d170476611f6780)
-set(LUV_URL https://github.com/luvit/luv/archive/1.9.1-0.tar.gz)
-set(LUV_SHA256 86a199403856018cd8e5529c8527450c83664a3d36f52d5253cbe909ea6c5a06)
+set(LUV_URL https://github.com/luvit/luv/archive/1.9.1-1.tar.gz)
+set(LUV_SHA256 562b9efaad30aa051a40eac9ade0c3df48bb8186763769abe47ec3fb3edb1268)
-set(GPERF_URL http://ftp.gnu.org/pub/gnu/gperf/gperf-3.0.4.tar.gz)
-set(GPERF_SHA256 767112a204407e62dbc3106647cf839ed544f3cf5d0f0523aaa2508623aad63e)
+set(GPERF_URL https://ftp.gnu.org/pub/gnu/gperf/gperf-3.1.tar.gz)
+set(GPERF_SHA256 588546b945bba4b70b6a3a616e80b4ab466e3f33024a352fc2198112cdbb3ae2)
# 7za.exe cat.exe curl.exe ca-bundle.crt diff.exe tee.exe tidy.exe xxd.exe
set(WINTOOLS_URL https://github.com/neovim/deps/raw/2f9acbecf06365c10baa3c0087f34a54c9c6f949/opt/win32tools.zip)
diff --git a/third-party/cmake/BuildLuarocks.cmake b/third-party/cmake/BuildLuarocks.cmake
index 88ddaf44ce..ef8a8450f1 100644
--- a/third-party/cmake/BuildLuarocks.cmake
+++ b/third-party/cmake/BuildLuarocks.cmake
@@ -41,6 +41,9 @@ endfunction()
# The luarocks binary location
set(LUAROCKS_BINARY ${HOSTDEPS_BIN_DIR}/luarocks)
+# NOTE: Version must match version of LuaRocks in third-party/CMakeLists.txt
+set(LUAROCKS_VERSION 2.4)
+
# Arguments for calls to 'luarocks build'
if(NOT MSVC)
# In MSVC don't pass the compiler/linker to luarocks, the bundled
@@ -73,13 +76,13 @@ elseif(MSVC OR MINGW)
/LIB ${DEPS_LIB_DIR}
/BIN ${DEPS_BIN_DIR}
/INC ${DEPS_INSTALL_DIR}/include/luajit-2.0/
- /P ${DEPS_INSTALL_DIR} /TREE ${DEPS_INSTALL_DIR}
+ /P ${DEPS_INSTALL_DIR}/${LUAROCKS_VERSION} /TREE ${DEPS_INSTALL_DIR}
/SCRIPTS ${DEPS_BIN_DIR}
/CMOD ${DEPS_BIN_DIR}
${MINGW_FLAG}
/LUAMOD ${DEPS_BIN_DIR}/lua)
- set(LUAROCKS_BINARY ${DEPS_INSTALL_DIR}/2.2/luarocks.bat)
+ set(LUAROCKS_BINARY ${DEPS_INSTALL_DIR}/${LUAROCKS_VERSION}/luarocks.bat)
else()
message(FATAL_ERROR "Trying to build luarocks in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}")
endif()