aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml32
-rw-r--r--CMakeLists.txt18
-rw-r--r--runtime/autoload/man.vim45
-rw-r--r--runtime/doc/deprecated.txt3
-rw-r--r--runtime/doc/eval.txt19
-rw-r--r--runtime/doc/options.txt79
-rw-r--r--runtime/doc/syntax.txt9
-rw-r--r--runtime/doc/vim_diff.txt10
-rwxr-xr-xscripts/pvscheck.sh48
-rw-r--r--src/nvim/CMakeLists.txt77
-rw-r--r--src/nvim/api/vim.c20
-rw-r--r--src/nvim/buffer.c2
-rw-r--r--src/nvim/charset.c12
-rw-r--r--src/nvim/edit.c2
-rw-r--r--src/nvim/eval.c170
-rw-r--r--src/nvim/eval/encode.c6
-rw-r--r--src/nvim/eval/typval.c29
-rw-r--r--src/nvim/event/libuv_process.c10
-rw-r--r--src/nvim/event/process.c10
-rw-r--r--src/nvim/event/socket.c9
-rw-r--r--src/nvim/event/stream.c8
-rw-r--r--src/nvim/generators/gen_options.lua2
-rw-r--r--src/nvim/getchar.c19
-rw-r--r--src/nvim/globals.h61
-rw-r--r--src/nvim/lua/converter.c3
-rw-r--r--src/nvim/lua/executor.c65
-rw-r--r--src/nvim/macros.h12
-rw-r--r--src/nvim/main.c29
-rw-r--r--src/nvim/memfile.c4
-rw-r--r--src/nvim/option.c35
-rw-r--r--src/nvim/options.lua7
-rw-r--r--src/nvim/os/env.c61
-rw-r--r--src/nvim/os/fs.c6
-rw-r--r--src/nvim/path.c47
-rw-r--r--src/nvim/search.c2
-rw-r--r--src/nvim/shada.c2
-rw-r--r--src/nvim/spellfile.c3
-rw-r--r--src/nvim/syntax.c114
-rw-r--r--src/nvim/tag.c7
-rw-r--r--src/nvim/testdir/runtest.vim5
-rw-r--r--src/nvim/tui/tui.c7
-rw-r--r--test/functional/api/vim_spec.lua30
-rw-r--r--test/functional/eval/input_spec.lua354
-rw-r--r--test/functional/ex_cmds/encoding_spec.lua4
-rw-r--r--test/functional/fixtures/tty-test.c9
-rw-r--r--test/functional/ui/cursor_spec.lua4
-rw-r--r--test/unit/eval/typval_spec.lua49
-rw-r--r--test/unit/os/env_spec.lua2
-rw-r--r--test/unit/path_spec.lua55
49 files changed, 1116 insertions, 500 deletions
diff --git a/.travis.yml b/.travis.yml
index 5c600ce823..8ca6f58fec 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -48,14 +48,19 @@ env:
- FUNCTIONALTEST=functionaltest
- CI_TARGET=tests
-matrix:
+jobs:
include:
+ - stage: sanitizers
+ os: linux
+ compiler: clang-3.9
+ env: >
+ CLANG_SANITIZER=ASAN_UBSAN
+ CMAKE_FLAGS="$CMAKE_FLAGS -DPREFER_LUA=ON"
- os: linux
- env: CI_TARGET=lint
- - os: linux
- compiler: gcc-5
- env: GCOV=gcov-5 CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
- - os: linux
+ compiler: clang-3.9
+ env: CLANG_SANITIZER=TSAN
+ - stage: normal builds
+ os: linux
compiler: gcc-5
env: FUNCTIONALTEST=functionaltest-lua
- os: linux
@@ -64,20 +69,19 @@ matrix:
# dependencies in a separate cache.
compiler: gcc-5 -m32
env: BUILD_32BIT=ON
- - os: linux
- compiler: clang-3.9
- env: >
- CLANG_SANITIZER=ASAN_UBSAN
- CMAKE_FLAGS="$CMAKE_FLAGS -DPREFER_LUAJIT=false"
- - os: linux
- compiler: clang-3.9
- env: CLANG_SANITIZER=TSAN
- os: osx
compiler: clang
osx_image: xcode7.3 # macOS 10.11
- os: osx
compiler: gcc-4.9
osx_image: xcode7.3 # macOS 10.11
+ - stage: lint
+ os: linux
+ env: CI_TARGET=lint
+ - stage: coverage
+ os: linux
+ compiler: gcc-5
+ env: GCOV=gcov-5 CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
allow_failures:
- env: GCOV=gcov-5 CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
fast_finish: true
diff --git a/CMakeLists.txt b/CMakeLists.txt
index eb259bc983..ab7595eb11 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -68,9 +68,9 @@ set(NVIM_VERSION_PATCH 1)
set(NVIM_VERSION_PRERELEASE "-dev") # for package maintainers
# API level
-set(NVIM_API_LEVEL 2) # Bump this after any API change.
+set(NVIM_API_LEVEL 3) # Bump this after any API change.
set(NVIM_API_LEVEL_COMPAT 0) # Adjust this after a _breaking_ API change.
-set(NVIM_API_PRERELEASE false)
+set(NVIM_API_PRERELEASE true)
file(TO_CMAKE_PATH ${CMAKE_CURRENT_LIST_DIR}/.git FORCED_GIT_DIR)
include(GetGitRevisionDescription)
@@ -314,12 +314,18 @@ include_directories(SYSTEM ${LIBUV_INCLUDE_DIRS})
find_package(Msgpack 1.0.0 REQUIRED)
include_directories(SYSTEM ${MSGPACK_INCLUDE_DIRS})
-option(PREFER_LUAJIT "Prefer LuaJIT over Lua when compiling executable. Test library always uses luajit." ON)
+# Note: The test lib requires LuaJIT; it will be skipped if LuaJIT is missing.
+option(PREFER_LUA "Prefer Lua over LuaJIT in the nvim executable." OFF)
-find_package(LuaJit REQUIRED)
-
-if(NOT PREFER_LUAJIT)
+if(PREFER_LUA)
find_package(Lua REQUIRED)
+ set(LUA_PREFERRED_INCLUDE_DIRS ${LUA_INCLUDE_DIR})
+ set(LUA_PREFERRED_LIBRARIES ${LUA_LIBRARIES})
+ find_package(LuaJit)
+else()
+ find_package(LuaJit REQUIRED)
+ set(LUA_PREFERRED_INCLUDE_DIRS ${LUAJIT_INCLUDE_DIRS})
+ set(LUA_PREFERRED_LIBRARIES ${LUAJIT_LIBRARIES})
endif()
list(APPEND CMAKE_REQUIRED_INCLUDES "${MSGPACK_INCLUDE_DIRS}")
diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim
index f5b863a899..361ade59d3 100644
--- a/runtime/autoload/man.vim
+++ b/runtime/autoload/man.vim
@@ -1,16 +1,22 @@
" Maintainer: Anmol Sethi <anmol@aubble.com>
-let s:man_find_arg = "-w"
+let s:find_arg = '-w'
+let s:localfile_arg = v:true " Always use -l if possible. #6683
-" TODO(nhooyr) Completion may work on SunOS; I'm not sure if `man -l` displays
-" the list of searched directories.
-try
- if !has('win32') && $OSTYPE !~? 'cygwin\|linux' && system('uname -s') =~? 'SunOS' && system('uname -r') =~# '^5'
- let s:man_find_arg = '-l'
- endif
-catch /E145:/
- " Ignore the error in restricted mode
-endtry
+function! s:init() abort
+ " 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'
+ let s:find_arg = '-l'
+ endif
+ " Check for -l support.
+ call s:get_page(s:get_path('', 'man')[0:-2])
+ catch /E145:/
+ " Ignore the error in restricted mode
+ catch /command error .*/
+ let s:localfile_arg = v:false
+ endtry
+endfunction
function! man#open_page(count, count1, mods, ...) abort
if a:0 > 2
@@ -88,10 +94,8 @@ endfunction
" Handler for s:system() function.
function! s:system_handler(jobid, data, event) dict abort
- if a:event == 'stdout'
- let self.stdout .= join(a:data, "\n")
- elseif a:event == 'stderr'
- let self.stderr .= join(a:data, "\n")
+ if a:event is# 'stdout' || a:event is# 'stderr'
+ let self[a:event] .= join(a:data, "\n")
else
let self.exit_code = a:data
endif
@@ -118,7 +122,7 @@ function! s:system(cmd, ...) abort
try
call jobstop(jobid)
throw printf('command timed out: %s', join(a:cmd))
- catch /^Vim\%((\a\+)\)\=:E900/
+ catch /^Vim(call):E900:/
endtry
elseif res[0] == -2
throw printf('command interrupted: %s', join(a:cmd))
@@ -136,8 +140,7 @@ function! s:get_page(path) abort
" Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db).
" http://comments.gmane.org/gmane.editors.vim.devel/29085
let cmd = ['env', 'MANPAGER=cat', 'MANWIDTH='.manwidth, 'man']
- " Use -l everywhere except macOS. #6683
- return s:system(cmd + (has('mac') ? [a:path] : ['-l', a:path]))
+ return s:system(cmd + (s:localfile_arg ? ['-l', a:path] : [a:path]))
endfunction
function! s:put_page(page) abort
@@ -201,14 +204,14 @@ endfunction
function! s:get_path(sect, name) abort
if empty(a:sect)
- return s:system(['man', s:man_find_arg, a:name])
+ return s:system(['man', s:find_arg, a:name])
endif
" '-s' flag handles:
" - tokens like 'printf(echo)'
" - sections starting with '-'
" - 3pcap section (found on macOS)
" - commas between sections (for section priority)
- return s:system(['man', s:man_find_arg, '-s', a:sect, a:name])
+ return s:system(['man', s:find_arg, '-s', a:sect, a:name])
endfunction
function! s:verify_exists(sect, name) abort
@@ -333,7 +336,7 @@ endfunction
function! s:complete(sect, psect, name) abort
try
- let mandirs = join(split(s:system(['man', s:man_find_arg]), ':\|\n'), ',')
+ let mandirs = join(split(s:system(['man', s:find_arg]), ':\|\n'), ',')
catch
call s:error(v:exception)
return
@@ -375,3 +378,5 @@ function! man#init_pager() abort
endtry
execute 'silent file man://'.fnameescape(ref)
endfunction
+
+call s:init()
diff --git a/runtime/doc/deprecated.txt b/runtime/doc/deprecated.txt
index e77d20172e..26cd5b24cc 100644
--- a/runtime/doc/deprecated.txt
+++ b/runtime/doc/deprecated.txt
@@ -26,9 +26,6 @@ Events ~
*EncodingChanged* Never fired; 'encoding' is always "utf-8".
*FileEncoding* Never fired; equivalent to |EncodingChanged|.
-Highlight groups ~
-*hl-VisualNOS* Obsolete. |vim-differences| {Nvim}
-
Keycodes ~
*<MouseDown>* Use <ScrollWheelUp> instead.
*<MouseUp>* Use <ScrollWheelDown> instead.
diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt
index 911fe43819..44f2b3688c 100644
--- a/runtime/doc/eval.txt
+++ b/runtime/doc/eval.txt
@@ -1749,9 +1749,7 @@ v:profiling Normally zero. Set to one after using ":profile start".
See |profiling|.
*v:progname* *progname-variable*
-v:progname Contains the name (with path removed) with which Nvim was
- invoked. Allows you to do special initialisations for any
- name you might symlink to Nvim.
+v:progname The name by which Nvim was invoked (with path removed).
Read-only.
*v:progpath* *progpath-variable*
@@ -4665,10 +4663,23 @@ index({list}, {expr} [, {start} [, {ic}]]) *index()*
input({prompt} [, {text} [, {completion}]]) *input()*
+input({opts})
The result is a String, which is whatever the user typed on
the command-line. The {prompt} argument is either a prompt
string, or a blank string (for no prompt). A '\n' can be used
in the prompt to start a new line.
+
+ In the second form it accepts a single dictionary with the
+ following keys, any of which may be omitted:
+
+ Key Default Description ~
+ prompt "" Same as {prompt} in the first form.
+ default "" Same as {text} in the first form.
+ completion nothing Same as {completion} in the first form.
+ cancelreturn "" Same as {cancelreturn} from
+ |inputdialog()|. Also works with
+ input().
+
The highlighting set with |:echohl| is used for the prompt.
The input is entered just like a command-line, with the same
editing commands and mappings. There is a separate history
@@ -4710,6 +4721,7 @@ input({prompt} [, {text} [, {completion}]]) *input()*
:endfunction
inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
+inputdialog({opts})
Like |input()|, but when the GUI is running and text dialogs
are supported, a dialog window pops up to input the text.
Example: >
@@ -4721,7 +4733,6 @@ inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
omitted an empty string is returned.
Hitting <Enter> works like pressing the OK button. Hitting
<Esc> works like pressing the Cancel button.
- NOTE: Command-line completion is not supported.
inputlist({textlist}) *inputlist()*
{textlist} must be a |List| of strings. This |List| is
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt
index afc7c20ed5..8949d27dd6 100644
--- a/runtime/doc/options.txt
+++ b/runtime/doc/options.txt
@@ -3120,82 +3120,9 @@ A jump table for the options with a short description can be found at |Q_op|.
Think twice when using ":q!" or ":qa!".
*'highlight'* *'hl'*
-'highlight' 'hl' string (default: string of "c:group,..." pairs)
- global
- This option can be used to set highlighting mode for various
- occasions. It is a comma separated list of character pairs. The
- first character in a pair gives the occasion, the second the mode to
- use for that occasion. The occasions are:
- |hl-SpecialKey| 8 Meta and special keys listed with ":map"
- |hl-Whitespace| 0
- |hl-EndOfBuffer| ~ lines after the last line in the buffer
- |hl-NormalNC| I non-current ("inactive") window
- |hl-TermCursor| z Cursor in a focused terminal
- |hl-TermCursorNC| Z Cursor in an unfocused terminal
- |hl-NonText| @ '@' at the end of the window and
- characters from 'showbreak'
- |hl-Directory| d directories in CTRL-D listing and other special
- things in listings
- |hl-ErrorMsg| e error messages
- |hl-IncSearch| i 'incsearch' highlighting
- |hl-Search| l last search pattern highlighting (see 'hlsearch')
- |hl-MoreMsg| m |more-prompt|
- |hl-ModeMsg| M Mode (e.g., "-- INSERT --")
- |hl-LineNr| n line number for ":number" and ":#" commands, and
- when 'number' or 'relativenumber' option is set.
- |hl-CursorLineNr| N like n for when 'cursorline' or 'relativenumber' is
- set.
- |hl-Question| r |hit-enter| prompt and yes/no questions
- |hl-StatusLine| s status line of current window |status-line|
- |hl-StatusLineNC| S status lines of not-current windows
- |hl-Title| t Titles for output from ":set all", ":autocmd" etc.
- |hl-VertSplit| c column used to separate vertically split windows
- |hl-Visual| v Visual mode
- |hl-WarningMsg| w warning messages
- |hl-WildMenu| W wildcard matches displayed for 'wildmenu'
- |hl-Folded| f line used for closed folds
- |hl-FoldColumn| F 'foldcolumn'
- |hl-DiffAdd| A added line in diff mode
- |hl-DiffChange| C changed line in diff mode
- |hl-DiffDelete| D deleted line in diff mode
- |hl-DiffText| T inserted text in diff mode
- |hl-SignColumn| > column used for |signs|
- |hl-SpellBad| B misspelled word |spell|
- |hl-SpellCap| P word that should start with capital |spell|
- |hl-SpellRare| R rare word |spell|
- |hl-SpellLocal| L word from other region |spell|
- |hl-Conceal| - the placeholders used for concealed characters
- (see 'conceallevel')
- |hl-Pmenu| + popup menu normal line
- |hl-PmenuSel| = popup menu normal line
- |hl-PmenuSbar| x popup menu scrollbar
- |hl-PmenuThumb| X popup menu scrollbar thumb
-
- |hl-TabLine| *
- |hl-TabLineFill| _
- |hl-TabLineSel| #
-
- |hl-ColorColumn| o
- |hl-CursorColumn| !
- |hl-CursorLine| .
- |hl-QuickFixLine| q
-
- The display modes are:
- r reverse (termcap entry "mr" and "me")
- i italic (termcap entry "ZH" and "ZR")
- b bold (termcap entry "md" and "me")
- s standout (termcap entry "so" and "se")
- u underline (termcap entry "us" and "ue")
- c undercurl (termcap entry "Cs" and "Ce")
- n no highlighting
- - no highlighting
- : use a highlight group
- The default is used for occasions that are not included.
- When using the ':' display mode, this must be followed by the name of
- a highlight group. A highlight group can be used to define any type
- of highlighting, including using color. See |:highlight| on how to
- define one. The default uses a different group for each occasion.
- See |highlight-default| for the default highlight groups.
+'highlight' 'hl' Removed. |vim-differences|
+ global
+ The builtin |highlight-groups| cannot be changed.
*'hlsearch'* *'hls'* *'nohlsearch'* *'nohls'*
'hlsearch' 'hls' boolean (default on)
diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt
index 18920d81e3..d711aa6a29 100644
--- a/runtime/doc/syntax.txt
+++ b/runtime/doc/syntax.txt
@@ -4849,10 +4849,9 @@ guisp={color-name} *highlight-guisp*
:highlight Comment guifg=#11f0c3 guibg=#ff00ff
<
*highlight-groups* *highlight-default*
-These are the default highlighting groups. These groups are used by the
-'highlight' option default. Note that the highlighting depends on the value
-of 'background'. You can see the current settings with the ":highlight"
-command.
+These are the builtin highlighting groups. Note that the highlighting depends
+on the value of 'background'. You can see the current settings with the
+":highlight" command.
*hl-ColorColumn*
ColorColumn used for the columns set with 'colorcolumn'
*hl-Conceal*
@@ -4973,6 +4972,8 @@ TabLineSel tab pages line, active tab page label
Title titles for output from ":set all", ":autocmd" etc.
*hl-Visual*
Visual Visual mode selection
+ *hl-VisualNOS*
+VisualNOS Visual mode selection when vim is "Not Owning the Selection".
*hl-WarningMsg*
WarningMsg warning messages
*hl-Whitespace*
diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt
index aba4420ebe..9a7789c0f5 100644
--- a/runtime/doc/vim_diff.txt
+++ b/runtime/doc/vim_diff.txt
@@ -107,8 +107,10 @@ Options:
'cpoptions' flags: |cpo-_|
'guicursor' works in the terminal
'inccommand' shows interactive results for |:substitute|-like commands
+ 'scrollback'
'statusline' supports unlimited alignment sections
'tabline' %@Func@foo%X can call any function on mouse-click
+ 'winhighlight' window-local highlights
Variables:
|v:event|
@@ -244,6 +246,10 @@ Lua interface (|if_lua.txt|):
- Lua has direct access to Nvim |API| via `vim.api`.
- Currently, most legacy Vim features are missing.
+|input()| and |inputdialog()| gained support for each other’s features (return
+on cancel and completion respectively) via dictionary argument (replaces all
+other arguments if used).
+
==============================================================================
5. Missing legacy features *nvim-features-missing*
@@ -287,9 +293,6 @@ MS-DOS support:
'bioskey'
'conskey'
-Highlight groups:
- |hl-VisualNOS|
-
Test functions:
test_alloc_fail()
test_autochdir()
@@ -310,6 +313,7 @@ Other options:
'esckeys'
'guioptions' "t" flag was removed
*'guipty'* (Nvim uses pipes and PTYs consistently on all platforms.)
+ 'highlight' (the builtin |highlight-groups| cannot be changed)
*'imactivatefunc'* *'imaf'*
*'imactivatekey'* *'imak'*
*'imstatusfunc'* *'imsf'*
diff --git a/scripts/pvscheck.sh b/scripts/pvscheck.sh
index c75dd2ab76..ca85b6be7f 100755
--- a/scripts/pvscheck.sh
+++ b/scripts/pvscheck.sh
@@ -14,7 +14,7 @@ get_jobs_num() {
help() {
echo 'Usage:'
echo ' pvscheck.sh [--pvs URL] [--deps] [target-directory [branch]]'
- echo ' pvscheck.sh [--pvs URL] [--recheck] [target-directory]'
+ echo ' pvscheck.sh [--pvs URL] [--recheck|--only-analyse] [target-directory]'
echo ' pvscheck.sh [--pvs URL] --pvs-install {target-directory}'
echo ' pvscheck.sh --patch [--only-build]'
echo
@@ -39,6 +39,9 @@ help() {
echo
echo ' --recheck: run analysis on a prepared target directory.'
echo
+ echo ' --only-analyse: run analysis on a prepared target directory '
+ echo ' without building Neovim.'
+ echo
echo ' target-directory: Directory where build should occur.'
echo ' Default: ../neovim-pvs'
echo
@@ -47,7 +50,17 @@ help() {
}
getopts_error() {
- printf '%s\n' "$1" >&2
+ local msg="$1" ; shift
+ local do_help=
+ if test "$msg" = "--help" ; then
+ msg="$1" ; shift
+ do_help=1
+ fi
+ printf '%s\n' "$msg" >&2
+ if test -n "$do_help" ; then
+ printf '\n' >&2
+ help >&2
+ fi
echo 'return 1'
return 1
}
@@ -143,8 +156,8 @@ getopts_long() {
if test -n "$opt_base" ; then
eval "local occurred_$opt_base=1"
- eval "local act_1=\"\$act_1_$opt_base\""
- eval "local varname=\"\$varname_$opt_base\""
+ eval "local act_1=\"\${act_1_$opt_base:-}\""
+ eval "local varname=\"\${varname_$opt_base:-}\""
local need_val=
local func=
case "$act_1" in
@@ -167,6 +180,9 @@ getopts_long() {
eval "varname=\"\${act_3_${opt_base}:-$varname}\""
need_val=1
;;
+ ("")
+ getopts_error --help "Wrong argument: $argument"
+ ;;
esac
if test -n "$need_val" ; then
local val=
@@ -290,7 +306,7 @@ realdir() {(
patch_sources() {(
local tgt="$1" ; shift
- local only_bulid="${1:-}"
+ local only_bulid="${1}" ; shift
get_pvs_comment "$tgt"
@@ -348,20 +364,23 @@ do_check() {
install_pvs "$tgt" "$pvs_url"
- adjust_path "$tgt"
+ do_recheck "$tgt" "$deps"
+}
+
+do_recheck() {
+ local tgt="$1" ; shift
+ local deps="$2" ; shift
create_compile_commands "$tgt" "$deps"
- run_analysis "$tgt"
+ do_analysis "$tgt"
}
-do_recheck() {
- local tgt="$1"
+do_analysis() {
+ local tgt="$1" ; shift
adjust_path "$tgt"
- create_compile_commands "$tgt" "$deps"
-
run_analysis "$tgt"
}
@@ -384,6 +403,7 @@ main() {
patch store_const \
only-build 'store_const --only-build' \
recheck store_const \
+ only-analyse store_const \
pvs-install store_const \
deps store_const \
-- \
@@ -400,11 +420,13 @@ main() {
set -x
if test -n "$patch" ; then
- patch_sources "$only_build" "$tgt"
+ patch_sources "$tgt" "$only_build"
elif test -n "$pvs_install" ; then
install_pvs "$tgt" "$pvs_url"
elif test -n "$recheck" ; then
- do_recheck "$tgt"
+ do_recheck "$tgt" "$deps"
+ elif test -n "$only_analyse" ; then
+ do_analysis "$tgt"
else
do_check "$tgt" "$branch" "$pvs_url" "$deps"
fi
diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt
index a5d4170062..c46c0bed6d 100644
--- a/src/nvim/CMakeLists.txt
+++ b/src/nvim/CMakeLists.txt
@@ -171,7 +171,7 @@ if(CLANG_ASAN_UBSAN OR CLANG_MSAN OR CLANG_TSAN)
endif()
get_directory_property(gen_includes INCLUDE_DIRECTORIES)
-foreach(gen_include ${gen_includes} ${LUAJIT_INCLUDE_DIRS})
+foreach(gen_include ${gen_includes} ${LUA_PREFERRED_INCLUDE_DIRS})
list(APPEND gen_cflags "-I${gen_include}")
endforeach()
string(TOUPPER "${CMAKE_BUILD_TYPE}" build_type)
@@ -367,24 +367,13 @@ if(UNIX)
)
endif()
-set(NVIM_EXEC_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES})
-set(NVIM_TEST_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES})
+set(NVIM_EXEC_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES} ${LUA_PREFERRED_LIBRARIES})
if(CMAKE_VERSION VERSION_LESS "2.8.8")
- if(PREFER_LUAJIT)
- include_directories(${LUAJIT_INCLUDE_DIRS})
- else()
- message(FATAL_ERROR
- "Must support INCLUDE_DIRECTORIES target property to build")
- endif()
-endif()
-
-if(PREFER_LUAJIT)
- list(APPEND NVIM_EXEC_LINK_LIBRARIES ${LUAJIT_LIBRARIES})
-else()
- list(APPEND NVIM_EXEC_LINK_LIBRARIES ${LUA_LIBRARIES})
+ # Use include_directories() because INCLUDE_DIRECTORIES target property
+ # is not supported
+ include_directories(${LUA_PREFERRED_INCLUDE_DIRS})
endif()
-list(APPEND NVIM_TEST_LINK_LIBRARIES ${LUAJIT_LIBRARIES})
# Don't use jemalloc in the unit test library.
if(JEMALLOC_FOUND)
@@ -396,11 +385,6 @@ add_executable(nvim ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS}
target_link_libraries(nvim ${NVIM_EXEC_LINK_LIBRARIES})
install_helper(TARGETS nvim)
-if(PREFER_LUAJIT)
- set(LUA_PREFERRED_INCLUDE_DIRS ${LUAJIT_INCLUDE_DIRS})
-else()
- set(LUA_PREFERRED_INCLUDE_DIRS ${LUA_INCLUDE_DIRS})
-endif()
set_property(TARGET nvim APPEND PROPERTY
INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS})
@@ -458,8 +442,7 @@ add_library(
${NVIM_HEADERS} ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS}
)
set_property(TARGET libnvim APPEND PROPERTY
- INCLUDE_DIRECTORIES ${LUAJIT_INCLUDE_DIRS})
-target_link_libraries(libnvim ${NVIM_TEST_LINK_LIBRARIES})
+ INCLUDE_DIRECTORIES ${LUA_PREFERRED_INCLUDE_DIRS})
set_target_properties(
libnvim
PROPERTIES
@@ -471,28 +454,32 @@ set_property(
APPEND_STRING PROPERTY COMPILE_FLAGS " -DMAKE_LIB "
)
-add_library(
- nvim-test
- MODULE
- EXCLUDE_FROM_ALL
- ${NVIM_SOURCES} ${NVIM_GENERATED_SOURCES}
- ${NVIM_HEADERS} ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS}
- ${UNIT_TEST_FIXTURES}
-)
-target_link_libraries(nvim-test ${NVIM_TEST_LINK_LIBRARIES})
-set_property(
- TARGET nvim-test
- APPEND PROPERTY INCLUDE_DIRECTORIES ${LUAJIT_INCLUDE_DIRS}
-)
-set_target_properties(
- nvim-test
- PROPERTIES
- POSITION_INDEPENDENT_CODE ON
-)
-set_property(
- TARGET nvim-test
- APPEND_STRING PROPERTY COMPILE_FLAGS " -DUNIT_TESTING "
-)
+if(LUAJIT_FOUND)
+ set(NVIM_TEST_LINK_LIBRARIES ${NVIM_LINK_LIBRARIES} ${LUAJIT_LIBRARIES})
+ add_library(
+ nvim-test
+ MODULE
+ EXCLUDE_FROM_ALL
+ ${NVIM_SOURCES} ${NVIM_GENERATED_SOURCES}
+ ${NVIM_HEADERS} ${NVIM_GENERATED_FOR_SOURCES} ${NVIM_GENERATED_FOR_HEADERS}
+ ${UNIT_TEST_FIXTURES}
+ )
+ target_link_libraries(nvim-test ${NVIM_TEST_LINK_LIBRARIES})
+ target_link_libraries(libnvim ${NVIM_TEST_LINK_LIBRARIES})
+ set_property(
+ TARGET nvim-test
+ APPEND PROPERTY INCLUDE_DIRECTORIES ${LUAJIT_INCLUDE_DIRS}
+ )
+ set_target_properties(
+ nvim-test
+ PROPERTIES
+ POSITION_INDEPENDENT_CODE ON
+ )
+ set_property(
+ TARGET nvim-test
+ APPEND_STRING PROPERTY COMPILE_FLAGS " -DUNIT_TESTING "
+ )
+endif()
if(CLANG_ASAN_UBSAN)
message(STATUS "Enabling Clang address sanitizer and undefined behavior sanitizer for nvim.")
diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c
index d0bb840b8d..1fedaf30ef 100644
--- a/src/nvim/api/vim.c
+++ b/src/nvim/api/vim.c
@@ -15,6 +15,7 @@
#include "nvim/api/private/defs.h"
#include "nvim/api/buffer.h"
#include "nvim/msgpack_rpc/channel.h"
+#include "nvim/lua/executor.h"
#include "nvim/vim.h"
#include "nvim/buffer.h"
#include "nvim/file_search.h"
@@ -254,6 +255,25 @@ free_vim_args:
return rv;
}
+/// Execute lua code. Parameters might be passed, they are available inside
+/// the chunk as `...`. The chunk can return a value.
+///
+/// To evaluate an expression, it must be prefixed with "return ". For
+/// instance, to call a lua function with arguments sent in and get its
+/// return value back, use the code "return my_function(...)".
+///
+/// @param code lua code to execute
+/// @param args Arguments to the code
+/// @param[out] err Details of an error encountered while parsing
+/// or executing the lua code.
+///
+/// @return Return value of lua code if present or NIL.
+Object nvim_execute_lua(String code, Array args, Error *err)
+ FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY
+{
+ return executor_exec_lua_api(code, args, err);
+}
+
/// Calculates the number of display cells occupied by `text`.
/// <Tab> counts as one cell.
///
diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c
index e3897e3929..6abd505ead 100644
--- a/src/nvim/buffer.c
+++ b/src/nvim/buffer.c
@@ -828,7 +828,7 @@ void handle_swap_exists(bufref_T *old_curbuf)
* new aborting error, interrupt, or uncaught exception. */
leave_cleanup(&cs);
}
- swap_exists_action = SEA_NONE;
+ swap_exists_action = SEA_NONE; // -V519
}
/*
diff --git a/src/nvim/charset.c b/src/nvim/charset.c
index ee58e0af91..5a0590d075 100644
--- a/src/nvim/charset.c
+++ b/src/nvim/charset.c
@@ -545,18 +545,8 @@ void transchar_nonprint(char_u *buf, int c)
buf[1] = (char_u)(c ^ 0x40);
buf[2] = NUL;
- } else if (c >= 0x80) {
- transchar_hex(buf, c);
- } else if ((c >= ' ' + 0x80) && (c <= '~' + 0x80)) {
- // 0xa0 - 0xfe
- buf[0] = '|';
- buf[1] = (char_u)(c - 0x80);
- buf[2] = NUL;
} else {
- // 0x80 - 0x9f and 0xff
- buf[0] = '~';
- buf[1] = (char_u)((c - 0x80) ^ 0x40);
- buf[2] = NUL;
+ transchar_hex(buf, c);
}
}
diff --git a/src/nvim/edit.c b/src/nvim/edit.c
index bfdec90a32..08a2f42f74 100644
--- a/src/nvim/edit.c
+++ b/src/nvim/edit.c
@@ -3422,7 +3422,6 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
else
return; /* nothing to do */
}
- assert(ptr != NULL);
if (compl_orig_text != NULL) {
p = compl_orig_text;
for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
@@ -3434,7 +3433,6 @@ static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
} else {
len = 0;
}
- assert(ptr != NULL);
AppendToRedobuffLit(ptr + len, -1);
}
diff --git a/src/nvim/eval.c b/src/nvim/eval.c
index 31e5ae8806..e4b3128930 100644
--- a/src/nvim/eval.c
+++ b/src/nvim/eval.c
@@ -10980,81 +10980,122 @@ void get_user_input(const typval_T *const argvars,
typval_T *const rettv, const bool inputdialog)
FUNC_ATTR_NONNULL_ALL
{
- const char *prompt = tv_get_string_chk(&argvars[0]);
- int cmd_silent_save = cmd_silent;
- int xp_type = EXPAND_NOTHING;
- char_u *xp_arg = NULL;
-
rettv->v_type = VAR_STRING;
rettv->vval.v_string = NULL;
- cmd_silent = FALSE; /* Want to see the prompt. */
- if (prompt != NULL) {
- // Only the part of the message after the last NL is considered as
- // prompt for the command line.
- const char *p = strrchr(prompt, '\n');
- if (p == NULL) {
- p = prompt;
- } else {
- p++;
- msg_start();
- msg_clr_eos();
- msg_puts_attr_len(prompt, p - prompt, echo_attr);
- msg_didout = false;
- msg_starthere();
+ const char *prompt = "";
+ const char *defstr = "";
+ const char *cancelreturn = NULL;
+ const char *xp_name = NULL;
+ char prompt_buf[NUMBUFLEN];
+ char defstr_buf[NUMBUFLEN];
+ char cancelreturn_buf[NUMBUFLEN];
+ char xp_name_buf[NUMBUFLEN];
+ if (argvars[0].v_type == VAR_DICT) {
+ if (argvars[1].v_type != VAR_UNKNOWN) {
+ emsgf(_("E5050: {opts} must be the only argument"));
+ return;
+ }
+ const dict_T *const dict = argvars[0].vval.v_dict;
+ prompt = tv_dict_get_string_buf_chk(dict, S_LEN("prompt"), prompt_buf, "");
+ if (prompt == NULL) {
+ return;
+ }
+ defstr = tv_dict_get_string_buf_chk(dict, S_LEN("default"), defstr_buf, "");
+ if (defstr == NULL) {
+ return;
+ }
+ char def[1] = { 0 };
+ cancelreturn = tv_dict_get_string_buf_chk(dict, S_LEN("cancelreturn"),
+ cancelreturn_buf, def);
+ if (cancelreturn == NULL) { // error
+ return;
+ }
+ if (*cancelreturn == NUL) {
+ cancelreturn = NULL;
+ }
+ xp_name = tv_dict_get_string_buf_chk(dict, S_LEN("completion"),
+ xp_name_buf, def);
+ if (xp_name == NULL) { // error
+ return;
+ }
+ if (xp_name == def) { // default to NULL
+ xp_name = NULL;
+ }
+ } else {
+ prompt = tv_get_string_buf_chk(&argvars[0], prompt_buf);
+ if (prompt == NULL) {
+ return;
}
- cmdline_row = msg_row;
-
- const char *defstr = "";
- char buf[NUMBUFLEN];
if (argvars[1].v_type != VAR_UNKNOWN) {
- defstr = tv_get_string_buf_chk(&argvars[1], buf);
- if (defstr != NULL) {
- stuffReadbuffSpec(defstr);
+ defstr = tv_get_string_buf_chk(&argvars[1], defstr_buf);
+ if (defstr == NULL) {
+ return;
}
-
- if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN) {
- char buf2[NUMBUFLEN];
- // input() with a third argument: completion
- rettv->vval.v_string = NULL;
-
- const char *const xp_name = tv_get_string_buf_chk(&argvars[2], buf2);
- if (xp_name == NULL) {
+ if (argvars[2].v_type != VAR_UNKNOWN) {
+ const char *const arg2 = tv_get_string_buf_chk(&argvars[2],
+ cancelreturn_buf);
+ if (arg2 == NULL) {
return;
}
-
- const int xp_namelen = (int)strlen(xp_name);
-
- uint32_t argt;
- if (parse_compl_arg((char_u *)xp_name, xp_namelen, &xp_type, &argt,
- &xp_arg) == FAIL) {
- return;
+ if (inputdialog) {
+ cancelreturn = arg2;
+ } else {
+ xp_name = arg2;
}
}
}
+ }
- if (defstr != NULL) {
- int save_ex_normal_busy = ex_normal_busy;
- ex_normal_busy = 0;
- rettv->vval.v_string =
- getcmdline_prompt(inputsecret_flag ? NUL : '@', (char_u *)p, echo_attr,
- xp_type, xp_arg);
- ex_normal_busy = save_ex_normal_busy;
- }
- if (inputdialog && rettv->vval.v_string == NULL
- && argvars[1].v_type != VAR_UNKNOWN
- && argvars[2].v_type != VAR_UNKNOWN) {
- char buf[NUMBUFLEN];
- rettv->vval.v_string = (char_u *)xstrdup(tv_get_string_buf(
- &argvars[2], buf));
+ int xp_type = EXPAND_NOTHING;
+ char *xp_arg = NULL;
+ if (xp_name != NULL) {
+ // input() with a third argument: completion
+ const int xp_namelen = (int)strlen(xp_name);
+
+ uint32_t argt;
+ if (parse_compl_arg((char_u *)xp_name, xp_namelen, &xp_type,
+ &argt, (char_u **)&xp_arg) == FAIL) {
+ return;
}
+ }
- xfree(xp_arg);
+ int cmd_silent_save = cmd_silent;
- /* since the user typed this, no need to wait for return */
- need_wait_return = FALSE;
- msg_didout = FALSE;
+ cmd_silent = false; // Want to see the prompt.
+ // Only the part of the message after the last NL is considered as
+ // prompt for the command line.
+ const char *p = strrchr(prompt, '\n');
+ if (p == NULL) {
+ p = prompt;
+ } else {
+ p++;
+ msg_start();
+ msg_clr_eos();
+ msg_puts_attr_len(prompt, p - prompt, echo_attr);
+ msg_didout = false;
+ msg_starthere();
}
+ cmdline_row = msg_row;
+
+ stuffReadbuffSpec(defstr);
+
+ int save_ex_normal_busy = ex_normal_busy;
+ ex_normal_busy = 0;
+ rettv->vval.v_string =
+ getcmdline_prompt(inputsecret_flag ? NUL : '@', (char_u *)p, echo_attr,
+ xp_type, (char_u *)xp_arg);
+ ex_normal_busy = save_ex_normal_busy;
+
+ if (rettv->vval.v_string == NULL && cancelreturn != NULL) {
+ rettv->vval.v_string = (char_u *)xstrdup(cancelreturn);
+ }
+
+ xfree(xp_arg);
+
+ // Since the user typed this, no need to wait for return.
+ need_wait_return = false;
+ msg_didout = false;
cmd_silent = cmd_silent_save;
}
@@ -13017,8 +13058,9 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
/* have to shuffle buf to close gap */
int adjust_prevlen = 0;
- if (dest < buf) {
- adjust_prevlen = (int)(buf - dest); /* must be 1 or 2 */
+ if (dest < buf) { // -V782
+ adjust_prevlen = (int)(buf - dest); // -V782
+ // adjust_prevlen must be 1 or 2.
dest = buf;
}
if (readlen > p - buf + 1)
@@ -21052,9 +21094,9 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars,
// Do not want errors such as E724 here.
emsg_off++;
char *tofree = encode_tv2string(&argvars[i], NULL);
- char *s = tofree;
emsg_off--;
- if (s != NULL) {
+ if (tofree != NULL) {
+ char *s = tofree;
char buf[MSG_BUF_LEN];
if (vim_strsize((char_u *)s) > MSG_BUF_CLEN) {
trunc_string((char_u *)s, (char_u *)buf, MSG_BUF_CLEN,
@@ -21118,7 +21160,7 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars,
if (func_or_func_caller_profiling) {
call_start = profile_end(call_start);
- call_start = profile_sub_wait(wait_start, call_start);
+ call_start = profile_sub_wait(wait_start, call_start); // -V614
fp->uf_tm_total = profile_add(fp->uf_tm_total, call_start);
fp->uf_tm_self = profile_self(fp->uf_tm_self, call_start,
fp->uf_tm_children);
diff --git a/src/nvim/eval/encode.c b/src/nvim/eval/encode.c
index 742497c1ca..ef647b3ee4 100644
--- a/src/nvim/eval/encode.c
+++ b/src/nvim/eval/encode.c
@@ -253,9 +253,11 @@ int encode_read_from_list(ListReaderState *const state, char *const buf,
char *const buf_end = buf + nbuf;
char *p = buf;
while (p < buf_end) {
+ assert(state->li_length == 0 || state->li->li_tv.vval.v_string != NULL);
for (size_t i = state->offset; i < state->li_length && p < buf_end; i++) {
- const char ch = (char) state->li->li_tv.vval.v_string[state->offset++];
- *p++ = (char) ((char) ch == (char) NL ? (char) NUL : (char) ch);
+ assert(state->li->li_tv.vval.v_string != NULL);
+ const char ch = (char)state->li->li_tv.vval.v_string[state->offset++];
+ *p++ = (char)((char)ch == (char)NL ? (char)NUL : (char)ch);
}
if (p < buf_end) {
state->li = state->li->li_next;
diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c
index 19d9d56058..f017f57b12 100644
--- a/src/nvim/eval/typval.c
+++ b/src/nvim/eval/typval.c
@@ -1210,7 +1210,8 @@ char *tv_dict_get_string(const dict_T *const d, const char *const key,
///
/// @param[in] d Dictionary to get item from.
/// @param[in] key Dictionary key.
-/// @param[in] numbuf Numbuf for.
+/// @param[in] numbuf Buffer for non-string items converted to strings, at
+/// least of #NUMBUFLEN length.
///
/// @return NULL if key does not exist, empty string in case of type error,
/// string item value otherwise.
@@ -1225,6 +1226,32 @@ const char *tv_dict_get_string_buf(const dict_T *const d, const char *const key,
return tv_get_string_buf(&di->di_tv, numbuf);
}
+/// Get a string item from a dictionary
+///
+/// @param[in] d Dictionary to get item from.
+/// @param[in] key Dictionary key.
+/// @param[in] key_len Key length.
+/// @param[in] numbuf Buffer for non-string items converted to strings, at
+/// least of #NUMBUFLEN length.
+/// @param[in] def Default return when key does not exist.
+///
+/// @return `def` when key does not exist,
+/// NULL in case of type error,
+/// string item value in case of success.
+const char *tv_dict_get_string_buf_chk(const dict_T *const d,
+ const char *const key,
+ const ptrdiff_t key_len,
+ char *const numbuf,
+ const char *const def)
+ FUNC_ATTR_WARN_UNUSED_RESULT
+{
+ const dictitem_T *const di = tv_dict_find(d, key, key_len);
+ if (di == NULL) {
+ return def;
+ }
+ return tv_get_string_buf_chk(&di->di_tv, numbuf);
+}
+
/// Get a function from a dictionary
///
/// @param[in] d Dictionary to get callback from.
diff --git a/src/nvim/event/libuv_process.c b/src/nvim/event/libuv_process.c
index 3116adbde8..f6a567a520 100644
--- a/src/nvim/event/libuv_process.c
+++ b/src/nvim/event/libuv_process.c
@@ -11,6 +11,7 @@
#include "nvim/event/process.h"
#include "nvim/event/libuv_process.h"
#include "nvim/log.h"
+#include "nvim/macros.h"
#include "nvim/os/os.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
@@ -47,17 +48,20 @@ int libuv_process_spawn(LibuvProcess *uvproc)
if (proc->in) {
uvproc->uvstdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE;
- uvproc->uvstdio[0].data.stream = (uv_stream_t *)&proc->in->uv.pipe;
+ uvproc->uvstdio[0].data.stream = STRUCT_CAST(uv_stream_t,
+ &proc->in->uv.pipe);
}
if (proc->out) {
uvproc->uvstdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
- uvproc->uvstdio[1].data.stream = (uv_stream_t *)&proc->out->uv.pipe;
+ uvproc->uvstdio[1].data.stream = STRUCT_CAST(uv_stream_t,
+ &proc->out->uv.pipe);
}
if (proc->err) {
uvproc->uvstdio[2].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
- uvproc->uvstdio[2].data.stream = (uv_stream_t *)&proc->err->uv.pipe;
+ uvproc->uvstdio[2].data.stream = STRUCT_CAST(uv_stream_t,
+ &proc->err->uv.pipe);
}
int status;
diff --git a/src/nvim/event/process.c b/src/nvim/event/process.c
index ffda10a494..cad49e2007 100644
--- a/src/nvim/event/process.c
+++ b/src/nvim/event/process.c
@@ -14,6 +14,7 @@
#include "nvim/event/libuv_process.h"
#include "nvim/os/pty_process.h"
#include "nvim/globals.h"
+#include "nvim/macros.h"
#include "nvim/log.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
@@ -82,7 +83,8 @@ int process_spawn(Process *proc) FUNC_ATTR_NONNULL_ALL
}
if (proc->in) {
- stream_init(NULL, proc->in, -1, (uv_stream_t *)&proc->in->uv.pipe);
+ stream_init(NULL, proc->in, -1,
+ STRUCT_CAST(uv_stream_t, &proc->in->uv.pipe));
proc->in->events = proc->events;
proc->in->internal_data = proc;
proc->in->internal_close_cb = on_process_stream_close;
@@ -90,7 +92,8 @@ int process_spawn(Process *proc) FUNC_ATTR_NONNULL_ALL
}
if (proc->out) {
- stream_init(NULL, proc->out, -1, (uv_stream_t *)&proc->out->uv.pipe);
+ stream_init(NULL, proc->out, -1,
+ STRUCT_CAST(uv_stream_t, &proc->out->uv.pipe));
proc->out->events = proc->events;
proc->out->internal_data = proc;
proc->out->internal_close_cb = on_process_stream_close;
@@ -98,7 +101,8 @@ int process_spawn(Process *proc) FUNC_ATTR_NONNULL_ALL
}
if (proc->err) {
- stream_init(NULL, proc->err, -1, (uv_stream_t *)&proc->err->uv.pipe);
+ stream_init(NULL, proc->err, -1,
+ STRUCT_CAST(uv_stream_t, &proc->err->uv.pipe));
proc->err->events = proc->events;
proc->err->internal_data = proc;
proc->err->internal_close_cb = on_process_stream_close;
diff --git a/src/nvim/event/socket.c b/src/nvim/event/socket.c
index e536d79a2a..922e9c8be8 100644
--- a/src/nvim/event/socket.c
+++ b/src/nvim/event/socket.c
@@ -16,6 +16,7 @@
#include "nvim/strings.h"
#include "nvim/path.h"
#include "nvim/memory.h"
+#include "nvim/macros.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "event/socket.c.generated.h"
@@ -71,10 +72,10 @@ void socket_watcher_init(Loop *loop, SocketWatcher *watcher,
if (tcp) {
uv_tcp_init(&loop->uv, &watcher->uv.tcp.handle);
- watcher->stream = (uv_stream_t *)&watcher->uv.tcp.handle;
+ watcher->stream = STRUCT_CAST(uv_stream_t, &watcher->uv.tcp.handle);
} else {
uv_pipe_init(&loop->uv, &watcher->uv.pipe.handle, 0);
- watcher->stream = (uv_stream_t *)&watcher->uv.pipe.handle;
+ watcher->stream = STRUCT_CAST(uv_stream_t, &watcher->uv.pipe.handle);
}
watcher->stream->data = watcher;
@@ -122,10 +123,10 @@ int socket_watcher_accept(SocketWatcher *watcher, Stream *stream)
uv_stream_t *client;
if (watcher->stream->type == UV_TCP) {
- client = (uv_stream_t *)&stream->uv.tcp;
+ client = STRUCT_CAST(uv_stream_t, &stream->uv.tcp);
uv_tcp_init(watcher->uv.tcp.handle.loop, (uv_tcp_t *)client);
} else {
- client = (uv_stream_t *)&stream->uv.pipe;
+ client = STRUCT_CAST(uv_stream_t, &stream->uv.pipe);
uv_pipe_init(watcher->uv.pipe.handle.loop, (uv_pipe_t *)client, 0);
}
diff --git a/src/nvim/event/stream.c b/src/nvim/event/stream.c
index 860a957b3e..60ceff9b24 100644
--- a/src/nvim/event/stream.c
+++ b/src/nvim/event/stream.c
@@ -8,6 +8,7 @@
#include <uv.h>
#include "nvim/rbuffer.h"
+#include "nvim/macros.h"
#include "nvim/event/stream.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
@@ -26,8 +27,9 @@ int stream_set_blocking(int fd, bool blocking)
uv_loop_init(&loop);
uv_pipe_init(&loop, &stream, 0);
uv_pipe_open(&stream, fd);
- int retval = uv_stream_set_blocking((uv_stream_t *)&stream, blocking);
- uv_close((uv_handle_t *)&stream, NULL);
+ int retval = uv_stream_set_blocking(STRUCT_CAST(uv_stream_t, &stream),
+ blocking);
+ uv_close(STRUCT_CAST(uv_handle_t, &stream), NULL);
uv_run(&loop, UV_RUN_NOWAIT); // not necessary, but couldn't hurt.
uv_loop_close(&loop);
return retval;
@@ -52,7 +54,7 @@ void stream_init(Loop *loop, Stream *stream, int fd, uv_stream_t *uvstream)
assert(type == UV_NAMED_PIPE || type == UV_TTY);
uv_pipe_init(&loop->uv, &stream->uv.pipe, 0);
uv_pipe_open(&stream->uv.pipe, fd);
- stream->uvstream = (uv_stream_t *)&stream->uv.pipe;
+ stream->uvstream = STRUCT_CAST(uv_stream_t, &stream->uv.pipe);
}
}
diff --git a/src/nvim/generators/gen_options.lua b/src/nvim/generators/gen_options.lua
index 9d7f235a3b..ca0134043c 100644
--- a/src/nvim/generators/gen_options.lua
+++ b/src/nvim/generators/gen_options.lua
@@ -118,7 +118,7 @@ local get_value = function(v)
end
local get_defaults = function(d)
- return '{' .. get_value(d.vi) .. ', ' .. get_value(d.vim) .. '}'
+ return ('{' .. get_value(d.vi) .. ', ' .. get_value(d.vim) .. '}')
end
local defines = {}
diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c
index 79b95272de..c3c393f1ec 100644
--- a/src/nvim/getchar.c
+++ b/src/nvim/getchar.c
@@ -3794,8 +3794,7 @@ makemap (
char *cmd;
int abbr;
int hash;
- int did_cpo = FALSE;
- int i;
+ bool did_cpo = false;
validate_maphash();
@@ -3923,13 +3922,15 @@ makemap (
/* When outputting <> form, need to make sure that 'cpo'
* is set to the Vim default. */
if (!did_cpo) {
- if (*mp->m_str == NUL) /* will use <Nop> */
- did_cpo = TRUE;
- else
- for (i = 0; i < 2; ++i)
- for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
- if (*p == K_SPECIAL || *p == NL)
- did_cpo = TRUE;
+ if (*mp->m_str == NUL) { // Will use <Nop>.
+ did_cpo = true;
+ } else {
+ const char specials[] = { (char)(uint8_t)K_SPECIAL, NL, NUL };
+ if (strpbrk((const char *)mp->m_str, specials) != NULL
+ || strpbrk((const char *)mp->m_keys, specials) != NULL) {
+ did_cpo = true;
+ }
+ }
if (did_cpo) {
if (fprintf(fd, "let s:cpo_save=&cpo") < 0
|| put_eol(fd) < 0
diff --git a/src/nvim/globals.h b/src/nvim/globals.h
index b820965680..a3657f2122 100644
--- a/src/nvim/globals.h
+++ b/src/nvim/globals.h
@@ -413,8 +413,7 @@ EXTERN int no_check_timestamps INIT(= 0); /* Don't check timestamps */
/*
* Values for index in highlight_attr[].
- * When making changes, also update HL_FLAGS below! And update the default
- * value of 'highlight' in option.c.
+ * When making changes, also update hlf_names below!
*/
typedef enum {
HLF_8 = 0 /* Meta & special keys listed with ":map", text that is
@@ -447,8 +446,8 @@ typedef enum {
, HLF_CHD // Changed diff line
, HLF_DED // Deleted diff line
, HLF_TXD // Text Changed in diff line
- , HLF_CONCEAL // Concealed text
, HLF_SC // Sign column
+ , HLF_CONCEAL // Concealed text
, HLF_SPB // SpellBad
, HLF_SPC // SpellCap
, HLF_SPR // SpellRare
@@ -469,12 +468,56 @@ typedef enum {
, HLF_COUNT // MUST be the last one
} hlf_T;
-/* The HL_FLAGS must be in the same order as the HLF_ enums!
- * When changing this also adjust the default for 'highlight'. */
-#define HL_FLAGS { '8', '~', 'z', 'Z', '@', 'd', 'e', 'i', 'l', 'm', 'M', 'n', \
- 'N', 'r', 's', 'S', 'c', 't', 'v', 'V', 'w', 'W', 'f', 'F', \
- 'A', 'C', 'D', 'T', '-', '>', 'B', 'P', 'R', 'L', '+', '=', \
- 'x', 'X', '*', '#', '_', '!', '.', 'o', 'q', '0', 'I' }
+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 */
diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c
index 31e49df8f9..cacba3ce87 100644
--- a/src/nvim/lua/converter.c
+++ b/src/nvim/lua/converter.c
@@ -1,3 +1,6 @@
+// This is an open source non-commercial project. Dear PVS-Studio, please check
+// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
+
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c
index 7cf326aef5..6f9e381d8d 100644
--- a/src/nvim/lua/executor.c
+++ b/src/nvim/lua/executor.c
@@ -1,3 +1,6 @@
+// This is an open source non-commercial project. Dear PVS-Studio, please check
+// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
+
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
@@ -373,6 +376,46 @@ static int nlua_eval_lua_string(lua_State *const lstate)
return 0;
}
+/// Evaluate lua string
+///
+/// Expects four values on the stack: string to evaluate, pointer to args array,
+/// 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
+{
+ const String *str = (const String *)lua_touserdata(lstate, 1);
+ const Array *args = (const Array *)lua_touserdata(lstate, 2);
+ Object *retval = (Object *)lua_touserdata(lstate, 3);
+ Error *err = (Error *)lua_touserdata(lstate, 4);
+
+ lua_pop(lstate, 4);
+
+ if (luaL_loadbuffer(lstate, str->data, str->size, "<nvim>")) {
+ size_t len;
+ const char *str = lua_tolstring(lstate, -1, &len);
+ api_set_error(err, kErrorTypeValidation,
+ "Error loading lua: %.*s", (int)len, str);
+ return 0;
+ }
+
+ for (size_t i = 0; i < args->size; i++) {
+ nlua_push_Object(lstate, args->items[i]);
+ }
+
+ if (lua_pcall(lstate, (int)args->size, 1, 0)) {
+ size_t len;
+ const char *str = lua_tolstring(lstate, -1, &len);
+ api_set_error(err, kErrorTypeException,
+ "Error executing lua: %.*s", (int)len, str);
+ return 0;
+ }
+
+ *retval = nlua_pop_Object(lstate, err);
+
+ return 0;
+}
+
/// Print as a Vim message
///
/// @param lstate Lua interpreter state.
@@ -516,6 +559,28 @@ void executor_eval_lua(const String str, typval_T *const arg,
(void *)&str, arg, ret_tv);
}
+/// Execute lua string
+///
+/// Used for nvim_execute_lua().
+///
+/// @param[in] str String to execute.
+/// @param[in] args array of ... args
+/// @param[out] err Location where error will be saved.
+///
+/// @return Return value of the execution.
+Object executor_exec_lua_api(const String str, const Array args, Error *err)
+{
+ if (global_lstate == NULL) {
+ global_lstate = init_lua();
+ }
+
+ Object retval = NIL;
+ NLUA_CALL_C_FUNCTION_4(global_lstate, nlua_exec_lua_string_api, 0,
+ (void *)&str, (void *)&args, &retval, err);
+ return retval;
+}
+
+
/// Run lua string
///
/// Used for :lua.
diff --git a/src/nvim/macros.h b/src/nvim/macros.h
index 9ab6dc5d2b..26d4f74b6a 100644
--- a/src/nvim/macros.h
+++ b/src/nvim/macros.h
@@ -171,4 +171,16 @@
# define FALLTHROUGH
#endif
+// -V:STRUCT_CAST:641
+
+/// Change type of structure pointers: cast `struct a *` to `struct b *`
+///
+/// Used to silence PVS errors.
+///
+/// @param Type Structure to cast to.
+/// @param obj Object to cast.
+///
+/// @return ((Type *)obj).
+#define STRUCT_CAST(Type, obj) ((Type *)(obj))
+
#endif // NVIM_MACROS_H
diff --git a/src/nvim/main.c b/src/nvim/main.c
index 40b553e93c..46607da6ea 100644
--- a/src/nvim/main.c
+++ b/src/nvim/main.c
@@ -124,7 +124,7 @@ typedef struct {
Loop main_loop;
-static char *argv0;
+static char *argv0 = NULL;
// Error messages
static const char *err_arg_missing = N_("Argument missing after");
@@ -179,11 +179,9 @@ void early_init(void)
log_init();
fs_init();
handle_init();
-
eval_init(); // init global variables
-
- // Init the table of Normal mode commands.
- init_normal_cmds();
+ init_path(argv0 ? argv0 : "nvim");
+ init_normal_cmds(); // Init the table of Normal mode commands.
#if defined(HAVE_LOCALE_H)
// Setup to use the current locale (for ctype() and many other things).
@@ -221,7 +219,7 @@ int nvim_main(int argc, char **argv)
int main(int argc, char **argv)
#endif
{
- argv0 = (char *)path_tail((char_u *)argv[0]);
+ argv0 = argv[0];
char_u *fname = NULL; // file name from command line
mparm_T params; // various parameters passed between
@@ -241,8 +239,6 @@ int main(int argc, char **argv)
// Check if we have an interactive window.
check_and_set_isatty(&params);
- init_path(argv[0]);
-
event_init();
/*
* Process the command line arguments. File names are put in the global
@@ -660,8 +656,9 @@ void getout(int exitval)
///
/// @return argument's numeric value otherwise
static int get_number_arg(const char *p, int *idx, int def)
+ FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
- if (ascii_isdigit(p[*idx])) {
+ if (ascii_isdigit(p[*idx])) { // -V522
def = atoi(&(p[*idx]));
while (ascii_isdigit(p[*idx])) {
*idx = *idx + 1;
@@ -1217,13 +1214,15 @@ static void check_and_set_isatty(mparm_T *paramp)
}
// Sets v:progname and v:progpath. Also modifies $PATH on Windows.
-static void init_path(char *exename)
+static void init_path(const char *exename)
+ FUNC_ATTR_NONNULL_ALL
{
char exepath[MAXPATHL] = { 0 };
size_t exepathlen = MAXPATHL;
// Make v:progpath absolute.
if (os_exepath(exepath, &exepathlen) != 0) {
- EMSG2(e_intern2, "init_path()");
+ // Fall back to argv[0]. Missing procfs? #6734
+ path_guess_exepath(exename, exepath, sizeof(exepath));
}
set_vim_var_string(VV_PROGPATH, exepath, -1);
set_vim_var_string(VV_PROGNAME, (char *)path_tail((char_u *)exename), -1);
@@ -1684,7 +1683,7 @@ static bool do_user_initialization(void)
do {
const char *dir;
size_t dir_len;
- iter = vim_colon_env_iter(config_dirs, iter, &dir, &dir_len);
+ iter = vim_env_iter(':', config_dirs, iter, &dir, &dir_len);
if (dir == NULL || dir_len == 0) {
break;
}
@@ -1833,9 +1832,11 @@ static bool file_owned(const char *fname)
/// @param str string to append to the primary error message, or NULL
static void mainerr(const char *errstr, const char *str)
{
+ char *prgname = (char *)path_tail((char_u *)argv0);
+
signal_stop(); // kill us with CTRL-C here, if you like
- mch_errmsg(argv0);
+ mch_errmsg(prgname);
mch_errmsg(": ");
mch_errmsg(_(errstr));
if (str != NULL) {
@@ -1844,7 +1845,7 @@ static void mainerr(const char *errstr, const char *str)
mch_errmsg("\"");
}
mch_errmsg(_("\nMore info with \""));
- mch_errmsg(argv0);
+ mch_errmsg(prgname);
mch_errmsg(" -h\"\n");
mch_exit(1);
diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c
index efaf1f94c5..1abc69727c 100644
--- a/src/nvim/memfile.c
+++ b/src/nvim/memfile.c
@@ -54,6 +54,7 @@
#include "nvim/memory.h"
#include "nvim/os_unix.h"
#include "nvim/path.h"
+#include "nvim/assert.h"
#include "nvim/os/os.h"
#include "nvim/os/input.h"
@@ -108,7 +109,8 @@ memfile_T *mf_open(char_u *fname, int flags)
if (mfp->mf_fd >= 0 && os_fileinfo_fd(mfp->mf_fd, &file_info)) {
uint64_t blocksize = os_fileinfo_blocksize(&file_info);
if (blocksize >= MIN_SWAP_PAGE_SIZE && blocksize <= MAX_SWAP_PAGE_SIZE) {
- assert(blocksize <= UINT_MAX);
+ STATIC_ASSERT(MAX_SWAP_PAGE_SIZE <= UINT_MAX,
+ "MAX_SWAP_PAGE_SIZE must fit into an unsigned");
mfp->mf_page_size = (unsigned)blocksize;
}
}
diff --git a/src/nvim/option.c b/src/nvim/option.c
index 9b4cd0924b..392a2f3908 100644
--- a/src/nvim/option.c
+++ b/src/nvim/option.c
@@ -247,7 +247,7 @@ typedef struct vimoption {
"8:SpecialKey,~:EndOfBuffer,z:TermCursor,Z:TermCursorNC,@:NonText," \
"d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr," \
"N:CursorLineNr,r:Question,s:StatusLine,S:StatusLineNC,c:VertSplit,t:Title," \
- "v:Visual,w:WarningMsg,W:WildMenu,f:Folded,F:FoldColumn," \
+ "v:Visual,V:VisualNOS,w:WarningMsg,W:WildMenu,f:Folded,F:FoldColumn," \
"A:DiffAdd,C:DiffChange,D:DiffDelete,T:DiffText,>:SignColumn,-:Conceal," \
"B:SpellBad,P:SpellCap,R:SpellRare,L:SpellLocal,+:Pmenu,=:PmenuSel," \
"x:PmenuSbar,X:PmenuThumb,*:TabLine,#:TabLineSel,_:TabLineFill," \
@@ -341,7 +341,7 @@ static inline size_t compute_double_colon_len(const char *const val,
do {
size_t dir_len;
const char *dir;
- iter = vim_colon_env_iter(val, iter, &dir, &dir_len);
+ iter = vim_env_iter(':', val, iter, &dir, &dir_len);
if (dir != NULL && dir_len > 0) {
ret += ((dir_len + memcnt(dir, ',', dir_len) + common_suf_len
+ !after_pathsep(dir, dir + dir_len)) * 2
@@ -385,8 +385,8 @@ static inline char *add_colon_dirs(char *dest, const char *const val,
do {
size_t dir_len;
const char *dir;
- iter = (forward ? vim_colon_env_iter : vim_colon_env_iter_rev)(
- val, iter, &dir, &dir_len);
+ iter = (forward ? vim_env_iter : vim_env_iter_rev)(':', val, iter, &dir,
+ &dir_len);
if (dir != NULL && dir_len > 0) {
dest = strcpy_comma_escaped(dest, dir, dir_len);
if (!after_pathsep(dest - 1, dest)) {
@@ -2124,7 +2124,7 @@ static void didset_options(void)
static void didset_options2(void)
{
// Initialize the highlight_attr[] table.
- (void)highlight_changed();
+ highlight_changed();
// Parse default for 'clipboard'.
(void)opt_strings_flags(p_cb, p_cb_values, &cb_flags, true);
@@ -2538,11 +2538,11 @@ did_set_string_option (
if (s[2] == NUL)
break;
}
- }
- /* 'highlight' */
- else if (varp == &p_hl) {
- if (highlight_changed() == FAIL)
- errmsg = e_invarg; /* invalid flags */
+ } else if (varp == &p_hl) {
+ // 'highlight'
+ if (strcmp((char *)(*varp), HIGHLIGHT_INIT) != 0) {
+ errmsg = e_unsupportedoption;
+ }
}
/* 'nrformats' */
else if (gvarp == &p_nf) {
@@ -2639,7 +2639,7 @@ did_set_string_option (
if (varp == &p_enc) {
// only encoding=utf-8 allowed
if (STRCMP(p_enc, "utf-8") != 0) {
- errmsg = e_invarg;
+ errmsg = e_unsupportedoption;
}
}
}
@@ -3207,8 +3207,6 @@ did_set_string_option (
*/
if (did_chartab)
(void)init_chartab();
- if (varp == &p_hl)
- (void)highlight_changed();
} else {
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
@@ -4827,17 +4825,6 @@ char *set_option_value(const char *const name, const long number,
return NULL;
}
-char_u *get_highlight_default(void)
-{
- int i;
-
- i = findoption("hl");
- if (i >= 0) {
- return options[i].def_val[VI_DEFAULT];
- }
- return (char_u *)NULL;
-}
-
/*
* Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number.
*/
diff --git a/src/nvim/options.lua b/src/nvim/options.lua
index 6ad0501f0a..c2778a6329 100644
--- a/src/nvim/options.lua
+++ b/src/nvim/options.lua
@@ -34,6 +34,11 @@ local macros=function(s)
return s
end
end
+local imacros=function(s)
+ return function()
+ return '(intptr_t)' .. s
+ end
+end
local N_=function(s)
return function()
return 'N_(' .. cstr(s) .. ')'
@@ -2648,7 +2653,7 @@ return {
type='number', scope={'global'},
vim=true,
varname='p_wc',
- defaults={if_true={vi=macros('Ctrl_E'), vim=macros('TAB')}}
+ defaults={if_true={vi=imacros('Ctrl_E'), vim=imacros('TAB')}}
},
{
full_name='wildcharm', abbreviation='wcm',
diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c
index 8f7a6e72b5..713fa5ea96 100644
--- a/src/nvim/os/env.c
+++ b/src/nvim/os/env.c
@@ -521,10 +521,11 @@ static char *remove_tail(char *path, char *pend, char *dirname)
return pend;
}
-/// Iterate over colon-separated list
+/// Iterate over a delimited list.
///
/// @note Environment variables must not be modified during iteration.
///
+/// @param[in] delim Delimiter character.
/// @param[in] val Value of the environment variable to iterate over.
/// @param[in] iter Pointer used for iteration. Must be NULL on first
/// iteration.
@@ -533,18 +534,19 @@ static char *remove_tail(char *path, char *pend, char *dirname)
/// @param[out] len Location where current directory length should be saved.
///
/// @return Next iter argument value or NULL when iteration should stop.
-const void *vim_colon_env_iter(const char *const val,
- const void *const iter,
- const char **const dir,
- size_t *const len)
- FUNC_ATTR_NONNULL_ARG(1, 3, 4) FUNC_ATTR_WARN_UNUSED_RESULT
+const void *vim_env_iter(const char delim,
+ const char *const val,
+ const void *const iter,
+ const char **const dir,
+ size_t *const len)
+ FUNC_ATTR_NONNULL_ARG(2, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT
{
const char *varval = (const char *) iter;
if (varval == NULL) {
varval = val;
}
*dir = varval;
- const char *const dirend = strchr(varval, ':');
+ const char *const dirend = strchr(varval, delim);
if (dirend == NULL) {
*len = strlen(varval);
return NULL;
@@ -554,10 +556,11 @@ const void *vim_colon_env_iter(const char *const val,
}
}
-/// Iterate over colon-separated list in reverse order
+/// Iterate over a delimited list in reverse order.
///
/// @note Environment variables must not be modified during iteration.
///
+/// @param[in] delim Delimiter character.
/// @param[in] val Value of the environment variable to iterate over.
/// @param[in] iter Pointer used for iteration. Must be NULL on first
/// iteration.
@@ -566,18 +569,19 @@ const void *vim_colon_env_iter(const char *const val,
/// @param[out] len Location where current directory length should be saved.
///
/// @return Next iter argument value or NULL when iteration should stop.
-const void *vim_colon_env_iter_rev(const char *const val,
- const void *const iter,
- const char **const dir,
- size_t *const len)
- FUNC_ATTR_NONNULL_ARG(1, 3, 4) FUNC_ATTR_WARN_UNUSED_RESULT
+const void *vim_env_iter_rev(const char delim,
+ const char *const val,
+ const void *const iter,
+ const char **const dir,
+ size_t *const len)
+ FUNC_ATTR_NONNULL_ARG(2, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT
{
const char *varend = (const char *) iter;
if (varend == NULL) {
varend = val + strlen(val) - 1;
}
- const size_t varlen = (size_t) (varend - val) + 1;
- const char *const colon = xmemrchr(val, ':', varlen);
+ const size_t varlen = (size_t)(varend - val) + 1;
+ const char *const colon = xmemrchr(val, (uint8_t)delim, varlen);
if (colon == NULL) {
*len = varlen;
*dir = val;
@@ -596,6 +600,10 @@ const void *vim_colon_env_iter_rev(const char *const val,
/// @param name Environment variable to expand
char *vim_getenv(const char *name)
{
+ // init_path() should have been called before now.
+ assert(get_vim_var_str(VV_PROGPATH)
+ && get_vim_var_str(VV_PROGPATH)[0] != NUL);
+
const char *kos_env_path = os_getenv(name);
if (kos_env_path != NULL) {
return xstrdup(kos_env_path);
@@ -634,18 +642,17 @@ char *vim_getenv(const char *name)
char exe_name[MAXPATHL];
// Find runtime path relative to the nvim binary: ../share/nvim/runtime
if (vim_path == NULL) {
- size_t exe_name_len = MAXPATHL;
- if (os_exepath(exe_name, &exe_name_len) == 0) {
- char *path_end = (char *)path_tail_with_sep((char_u *)exe_name);
- *path_end = '\0'; // remove the trailing "nvim.exe"
- path_end = (char *)path_tail((char_u *)exe_name);
- *path_end = '\0'; // remove the trailing "bin/"
- if (append_path(
- exe_name,
- "share" _PATHSEPSTR "nvim" _PATHSEPSTR "runtime" _PATHSEPSTR,
- MAXPATHL) == OK) {
- vim_path = exe_name; // -V507
- }
+ xstrlcpy(exe_name, (char *)get_vim_var_str(VV_PROGPATH),
+ sizeof(exe_name));
+ char *path_end = (char *)path_tail_with_sep((char_u *)exe_name);
+ *path_end = '\0'; // remove the trailing "nvim.exe"
+ path_end = (char *)path_tail((char_u *)exe_name);
+ *path_end = '\0'; // remove the trailing "bin/"
+ if (append_path(
+ exe_name,
+ "share" _PATHSEPSTR "nvim" _PATHSEPSTR "runtime" _PATHSEPSTR,
+ MAXPATHL) == OK) {
+ vim_path = exe_name; // -V507
}
}
diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c
index aaa750db50..b9a9480cb8 100644
--- a/src/nvim/os/fs.c
+++ b/src/nvim/os/fs.c
@@ -196,11 +196,13 @@ int os_nodetype(const char *name)
}
/// Gets the absolute path of the currently running executable.
+/// May fail if procfs is missing. #6734
+/// @see path_exepath
///
-/// @param[out] buffer Returns the path string.
+/// @param[out] buffer Full path to the executable.
/// @param[in] size Size of `buffer`.
///
-/// @return `0` on success, or libuv error code on failure.
+/// @return 0 on success, or libuv error code.
int os_exepath(char *buffer, size_t *size)
FUNC_ATTR_NONNULL_ALL
{
diff --git a/src/nvim/path.c b/src/nvim/path.c
index 045902e1c6..9162b6da4d 100644
--- a/src/nvim/path.c
+++ b/src/nvim/path.c
@@ -2237,3 +2237,50 @@ int path_is_absolute_path(const char_u *fname)
return *fname == '/' || *fname == '~';
#endif
}
+
+/// Builds a full path from an invocation name `argv0`, based on heuristics.
+///
+/// @param[in] argv0 Name by which Nvim was invoked.
+/// @param[out] buf Guessed full path to `argv0`.
+/// @param[in] bufsize Size of `buf`.
+///
+/// @see os_exepath
+void path_guess_exepath(const char *argv0, char *buf, size_t bufsize)
+ FUNC_ATTR_NONNULL_ALL
+{
+ char *path = getenv("PATH");
+
+ if (path == NULL || path_is_absolute_path((char_u *)argv0)) {
+ xstrlcpy(buf, argv0, bufsize);
+ } else if (argv0[0] == '.' || strchr(argv0, PATHSEP)) {
+ // Relative to CWD.
+ if (os_dirname((char_u *)buf, MAXPATHL) != OK) {
+ buf[0] = NUL;
+ }
+ xstrlcat(buf, PATHSEPSTR, bufsize);
+ xstrlcat(buf, argv0, bufsize);
+ } else {
+ // Search $PATH for plausible location.
+ const void *iter = NULL;
+ do {
+ const char *dir;
+ size_t dir_len;
+ iter = vim_env_iter(ENV_SEPCHAR, path, iter, &dir, &dir_len);
+ if (dir == NULL || dir_len == 0) {
+ break;
+ }
+ if (dir_len + 1 > sizeof(NameBuff)) {
+ continue;
+ }
+ xstrlcpy((char *)NameBuff, dir, dir_len + 1);
+ xstrlcat((char *)NameBuff, PATHSEPSTR, sizeof(NameBuff));
+ xstrlcat((char *)NameBuff, argv0, sizeof(NameBuff));
+ if (os_can_exe(NameBuff, NULL, false)) {
+ xstrlcpy(buf, (char *)NameBuff, bufsize);
+ return;
+ }
+ } while (iter != NULL);
+ // Not found in $PATH, fall back to argv0.
+ xstrlcpy(buf, argv0, bufsize);
+ }
+}
diff --git a/src/nvim/search.c b/src/nvim/search.c
index c662e3ba40..61ef2e9ba3 100644
--- a/src/nvim/search.c
+++ b/src/nvim/search.c
@@ -616,7 +616,7 @@ int searchit(
* otherwise "/$" will get stuck on end of line.
*/
while (matchpos.lnum == 0
- && ((options & SEARCH_END) && first_match
+ && (((options & SEARCH_END) && first_match)
? (nmatched == 1
&& (int)endpos.col - 1
< (int)start_pos.col + extra_col)
diff --git a/src/nvim/shada.c b/src/nvim/shada.c
index e1879ca8c0..87b4617099 100644
--- a/src/nvim/shada.c
+++ b/src/nvim/shada.c
@@ -1277,8 +1277,6 @@ static void shada_read(ShaDaReadDef *const sd_reader, const int flags)
if (cur_entry.data.search_pattern.is_last_used) {
set_last_used_pattern(
cur_entry.data.search_pattern.is_substitute_pattern);
- }
- if (cur_entry.data.search_pattern.is_last_used) {
SET_NO_HLSEARCH(!cur_entry.data.search_pattern.highlighted);
}
// Do not free shada entry: its allocated memory was saved above.
diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c
index d34d69b3a4..1f7f616782 100644
--- a/src/nvim/spellfile.c
+++ b/src/nvim/spellfile.c
@@ -2468,8 +2468,7 @@ static afffile_T *spell_read_aff(spellinfo_T *spin, char_u *fname)
}
}
- if (aff_entry->ae_chop == NULL
- && aff_entry->ae_flags == NULL) {
+ if (aff_entry->ae_chop == NULL) {
int idx;
char_u **pp;
int n;
diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c
index ce48547163..a4bb260183 100644
--- a/src/nvim/syntax.c
+++ b/src/nvim/syntax.c
@@ -309,6 +309,8 @@ static keyentry_T dumkey;
#define HIKEY2KE(p) ((keyentry_T *)((p) - (dumkey.keyword - (char_u *)&dumkey)))
#define HI2KE(hi) HIKEY2KE((hi)->hi_key)
+// -V:HI2KE:782
+
/*
* To reduce the time spent in keepend(), remember at which level in the state
* stack the first item with "keepend" is present. When "-1", there is no
@@ -7304,110 +7306,34 @@ static void highlight_attr_set_all(void)
}
}
-/*
- * Translate the 'highlight' option into attributes in highlight_attr[] and
- * set up the user highlights User1..9. A set of
- * corresponding highlights to use on top of HLF_SNC is computed.
- * Called only when the 'highlight' option has been changed and upon first
- * screen redraw after any :highlight command.
- * Return FAIL when an invalid flag is found in 'highlight'. OK otherwise.
- */
-int highlight_changed(void)
+/// Tranlate highlight groups into attributes in highlight_attr[] and set up
+/// the user highlights User1..9. A set of corresponding highlights to use on
+/// top of HLF_SNC is computed. Called only when nvim starts and upon first
+/// screen redraw after any :highlight command.
+void highlight_changed(void)
{
- int hlf;
- int i;
- char_u *p;
int attr;
- char_u *end;
int id;
char_u userhl[10];
int id_SNC = -1;
int id_S = -1;
int hlcnt;
- static int hl_flags[HLF_COUNT] = HL_FLAGS;
need_highlight_changed = FALSE;
- /*
- * Clear all attributes.
- */
- for (hlf = 0; hlf < (int)HLF_COUNT; ++hlf)
- highlight_attr[hlf] = 0;
-
- /*
- * First set all attributes to their default value.
- * Then use the attributes from the 'highlight' option.
- */
- for (i = 0; i < 2; ++i) {
- if (i)
- p = p_hl;
- else
- p = get_highlight_default();
- if (p == NULL) /* just in case */
- continue;
-
- while (*p) {
- for (hlf = 0; hlf < (int)HLF_COUNT; ++hlf)
- if (hl_flags[hlf] == *p)
- break;
- ++p;
- if (hlf == (int)HLF_COUNT || *p == NUL)
- return FAIL;
-
- /*
- * Allow several hl_flags to be combined, like "bu" for
- * bold-underlined.
- */
- attr = 0;
- bool colon = false;
- for (; *p && *p != ','; ++p) { // parse upto comma
- if (ascii_iswhite(*p)) { // ignore white space
- continue;
- }
-
- if (colon) /* Combination with ':' is not allowed. */
- return FAIL;
-
- switch (*p) {
- case 'b': attr |= HL_BOLD;
- break;
- case 'i': attr |= HL_ITALIC;
- break;
- case '-':
- case 'n': /* no highlighting */
- break;
- case 'r': attr |= HL_INVERSE;
- break;
- case 's': attr |= HL_STANDOUT;
- break;
- case 'u': attr |= HL_UNDERLINE;
- break;
- case 'c': attr |= HL_UNDERCURL;
- break;
- case ':': ++p; /* highlight group name */
- if (attr || *p == NUL) /* no combinations */
- return FAIL;
- colon = true;
- end = vim_strchr(p, ',');
- if (end == NULL)
- end = p + STRLEN(p);
- id = syn_check_group(p, (int)(end - p));
- if (id == 0)
- return FAIL;
- attr = syn_id2attr(id);
- p = end - 1;
- if (hlf == (int)HLF_SNC)
- id_SNC = syn_get_final_id(id);
- else if (hlf == (int)HLF_S)
- id_S = syn_get_final_id(id);
- break;
- default: return FAIL;
- }
- }
- highlight_attr[hlf] = attr;
-
- p = skip_to_option_part(p); /* skip comma and spaces */
+ /// Translate builtin highlight groups into attributes for quick lookup.
+ for (int hlf = 0; hlf < (int)HLF_COUNT; hlf++) {
+ id = syn_check_group((char_u *)hlf_names[hlf], STRLEN(hlf_names[hlf]));
+ if (id == 0) {
+ abort();
+ }
+ attr = syn_id2attr(id);
+ if (hlf == (int)HLF_SNC) {
+ id_SNC = syn_get_final_id(id);
+ } else if (hlf == (int)HLF_S) {
+ id_S = syn_get_final_id(id);
}
+ highlight_attr[hlf] = attr;
}
/* Setup the user highlights
@@ -7472,8 +7398,6 @@ int highlight_changed(void)
}
}
highlight_ga.ga_len = hlcnt;
-
- return OK;
}
diff --git a/src/nvim/tag.c b/src/nvim/tag.c
index b8b86bf979..88b45add54 100644
--- a/src/nvim/tag.c
+++ b/src/nvim/tag.c
@@ -208,10 +208,9 @@ do_tag (
clearpos(&saved_fmark.mark); /* shutup gcc 4.0 */
saved_fmark.fnum = 0;
- /*
- * Don't add a tag to the tagstack if 'tagstack' has been reset.
- */
- if (!p_tgst && *tag != NUL) {
+ // Don't add a tag to the tagstack if 'tagstack' has been reset.
+ assert(tag != NULL);
+ if (!p_tgst && *tag != NUL) { // -V522
use_tagstack = false;
new_tag = true;
if (g_do_tagpreview != 0) {
diff --git a/src/nvim/testdir/runtest.vim b/src/nvim/testdir/runtest.vim
index 6832622cdf..a754e5fdfb 100644
--- a/src/nvim/testdir/runtest.vim
+++ b/src/nvim/testdir/runtest.vim
@@ -134,7 +134,10 @@ else
endif
" Names of flaky tests.
-let s:flaky = ['Test_with_partial_callback()']
+let s:flaky = [
+ \ 'Test_with_partial_callback()',
+ \ 'Test_oneshot()'
+ \ ]
" Locate Test_ functions and execute them.
set nomore
diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c
index 4a81b32199..4ff7993f4a 100644
--- a/src/nvim/tui/tui.c
+++ b/src/nvim/tui/tui.c
@@ -36,6 +36,7 @@
#include "nvim/tui/tui.h"
#include "nvim/cursor_shape.h"
#include "nvim/syntax.h"
+#include "nvim/macros.h"
// Space reserved in the output buffer to restore the cursor to normal when
// flushing. No existing terminal will require 32 bytes to do that.
@@ -1079,7 +1080,7 @@ static void flush_buf(UI *ui, bool toggle_cursor)
buf.base = data->buf;
buf.len = data->bufpos;
- uv_write(&req, (uv_stream_t *)&data->output_handle, &buf, 1, NULL);
+ uv_write(&req, STRUCT_CAST(uv_stream_t, &data->output_handle), &buf, 1, NULL);
uv_run(&data->write_loop, UV_RUN_DEFAULT);
data->bufpos = 0;
@@ -1122,13 +1123,13 @@ static const char *tui_tk_ti_getstr(const char *name, const char *value,
if (strequal(name, "key_backspace")) {
ILOG("libtermkey:kbs=%s", value);
- if (stty_erase != NULL && stty_erase[0] != 0) {
+ if (stty_erase[0] != 0) {
return stty_erase;
}
} else if (strequal(name, "key_dc")) {
ILOG("libtermkey:kdch1=%s", value);
// Vim: "If <BS> and <DEL> are now the same, redefine <DEL>."
- if (stty_erase != NULL && value != NULL && strequal(stty_erase, value)) {
+ if (value != NULL && strequal(stty_erase, value)) {
return stty_erase[0] == DEL ? CTRL_H_STR : DEL_STR;
}
}
diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua
index 282ecbfd87..61ec6ea829 100644
--- a/test/functional/api/vim_spec.lua
+++ b/test/functional/api/vim_spec.lua
@@ -81,6 +81,36 @@ describe('api', function()
end)
end)
+ describe('nvim_execute_lua', function()
+ it('works', function()
+ meths.execute_lua('vim.api.nvim_set_var("test", 3)', {})
+ eq(3, meths.get_var('test'))
+
+ eq(17, meths.execute_lua('a, b = ...\nreturn a + b', {10,7}))
+
+ eq(NIL, meths.execute_lua('function xx(a,b)\nreturn a..b\nend',{}))
+ eq("xy", meths.execute_lua('return xx(...)', {'x','y'}))
+ end)
+
+ it('reports errors', function()
+ eq({false, 'Error loading lua: [string "<nvim>"]:1: '..
+ "'=' expected near '+'"},
+ meth_pcall(meths.execute_lua, 'a+*b', {}))
+
+ eq({false, 'Error loading lua: [string "<nvim>"]:1: '..
+ "unexpected symbol near '1'"},
+ meth_pcall(meths.execute_lua, '1+2', {}))
+
+ eq({false, 'Error loading lua: [string "<nvim>"]:1: '..
+ "unexpected symbol"},
+ meth_pcall(meths.execute_lua, 'aa=bb\0', {}))
+
+ eq({false, 'Error executing lua: [string "<nvim>"]:1: '..
+ "attempt to call global 'bork' (a nil value)"},
+ meth_pcall(meths.execute_lua, 'bork()', {}))
+ end)
+ end)
+
describe('nvim_input', function()
it("VimL error: does NOT fail, updates v:errmsg", function()
local status, _ = pcall(nvim, "input", ":call bogus_fn()<CR>")
diff --git a/test/functional/eval/input_spec.lua b/test/functional/eval/input_spec.lua
index 393fc10175..74ad32bc6c 100644
--- a/test/functional/eval/input_spec.lua
+++ b/test/functional/eval/input_spec.lua
@@ -1,9 +1,13 @@
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
+local eq = helpers.eq
local feed = helpers.feed
+local meths = helpers.meths
local clear = helpers.clear
+local source = helpers.source
local command = helpers.command
+local exc_exec = helpers.exc_exec
local screen
@@ -11,28 +15,352 @@ before_each(function()
clear()
screen = Screen.new(25, 5)
screen:attach()
+ source([[
+ hi Test ctermfg=Red guifg=Red term=bold
+ function CustomCompl(...)
+ return 'TEST'
+ endfunction
+ function CustomListCompl(...)
+ return ['FOO']
+ endfunction
+ ]])
+ screen:set_default_attr_ids({
+ EOB={bold = true, foreground = Screen.colors.Blue1},
+ T={foreground=Screen.colors.Red},
+ })
end)
describe('input()', function()
- it('works correctly with multiline prompts', function()
+ it('works with multiline prompts', function()
feed([[:call input("Test\nFoo")<CR>]])
screen:expect([[
- {1:~ }|
- {1:~ }|
- {1:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
Test |
Foo^ |
- ]], {{bold=true, foreground=Screen.colors.Blue}})
+ ]])
end)
- it('works correctly with multiline prompts and :echohl', function()
- command('hi Test ctermfg=Red guifg=Red term=bold')
+ it('works with multiline prompts and :echohl', function()
feed([[:echohl Test | call input("Test\nFoo")<CR>]])
screen:expect([[
- {1:~ }|
- {1:~ }|
- {1:~ }|
- {2:Test} |
- {2:Foo}^ |
- ]], {{bold=true, foreground=Screen.colors.Blue}, {foreground=Screen.colors.Red}})
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Test} |
+ {T:Foo}^ |
+ ]])
+ command('redraw!')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo}^ |
+ ]])
+ end)
+ it('allows unequal numeric arguments when using multiple args', function()
+ command('echohl Test')
+ feed([[:call input(1, 2)<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}2^ |
+ ]])
+ feed('<BS>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}^ |
+ ]])
+ end)
+ it('allows unequal numeric values when using {opts} dictionary', function()
+ command('echohl Test')
+ meths.set_var('opts', {prompt=1, default=2, cancelreturn=3})
+ feed([[:echo input(opts)<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}2^ |
+ ]])
+ feed('<BS>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}^ |
+ ]])
+ feed('<Esc>')
+ screen:expect([[
+ ^ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:3} |
+ ]])
+ end)
+ it('works with redraw', function()
+ command('echohl Test')
+ meths.set_var('opts', {prompt='Foo>', default='Bar'})
+ feed([[:echo inputdialog(opts)<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Bar^ |
+ ]])
+ command('redraw!')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Bar^ |
+ ]])
+ feed('<BS>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Ba^ |
+ ]])
+ command('redraw!')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Ba^ |
+ ]])
+ end)
+ it('allows omitting everything with dictionary argument', function()
+ command('echohl Test')
+ feed([[:call input({})<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ ^ |
+ ]])
+ end)
+ it('supports completion', function()
+ feed(':let var = input("", "", "custom,CustomCompl")<CR>')
+ feed('<Tab><CR>')
+ eq('TEST', meths.get_var('var'))
+
+ feed(':let var = input({"completion": "customlist,CustomListCompl"})<CR>')
+ feed('<Tab><CR>')
+ eq('FOO', meths.get_var('var'))
+ end)
+ it('supports cancelreturn', function()
+ feed(':let var = input({"cancelreturn": "BAR"})<CR>')
+ feed('<Esc>')
+ eq('BAR', meths.get_var('var'))
+ end)
+ it('supports default string', function()
+ feed(':let var = input("", "DEF1")<CR>')
+ feed('<CR>')
+ eq('DEF1', meths.get_var('var'))
+
+ feed(':let var = input({"default": "DEF2"})<CR>')
+ feed('<CR>')
+ eq('DEF2', meths.get_var('var'))
+ end)
+ it('errors out on invalid inputs', function()
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input([])'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input("", [])'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input("", "", [])'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input({"prompt": []})'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input({"cancelreturn": []})'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input({"default": []})'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call input({"completion": []})'))
+ eq('Vim(call):E5050: {opts} must be the only argument',
+ exc_exec('call input({}, "default")'))
+ eq('Vim(call):E118: Too many arguments for function: input',
+ exc_exec('call input("prompt> ", "default", "file", "extra")'))
+ end)
+end)
+describe('inputdialog()', function()
+ it('works with multiline prompts', function()
+ feed([[:call inputdialog("Test\nFoo")<CR>]])
+ screen:expect([[
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ Test |
+ Foo^ |
+ ]])
+ end)
+ it('works with multiline prompts and :echohl', function()
+ feed([[:echohl Test | call inputdialog("Test\nFoo")<CR>]])
+ screen:expect([[
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Test} |
+ {T:Foo}^ |
+ ]])
+ command('redraw!')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo}^ |
+ ]])
+ end)
+ it('allows unequal numeric arguments when using multiple args', function()
+ command('echohl Test')
+ feed([[:call inputdialog(1, 2)<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}2^ |
+ ]])
+ feed('<BS>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}^ |
+ ]])
+ end)
+ it('allows unequal numeric values when using {opts} dictionary', function()
+ command('echohl Test')
+ meths.set_var('opts', {prompt=1, default=2, cancelreturn=3})
+ feed([[:echo input(opts)<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}2^ |
+ ]])
+ feed('<BS>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:1}^ |
+ ]])
+ feed('<Esc>')
+ screen:expect([[
+ ^ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:3} |
+ ]])
+ end)
+ it('works with redraw', function()
+ command('echohl Test')
+ meths.set_var('opts', {prompt='Foo>', default='Bar'})
+ feed([[:echo input(opts)<CR>]])
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Bar^ |
+ ]])
+ command('redraw!')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Bar^ |
+ ]])
+ feed('<BS>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Ba^ |
+ ]])
+ command('redraw!')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ {T:Foo>}Ba^ |
+ ]])
+ end)
+ it('allows omitting everything with dictionary argument', function()
+ command('echohl Test')
+ feed(':echo inputdialog({})<CR>')
+ screen:expect([[
+ |
+ {EOB:~ }|
+ {EOB:~ }|
+ {EOB:~ }|
+ ^ |
+ ]])
+ end)
+ it('supports completion', function()
+ feed(':let var = inputdialog({"completion": "customlist,CustomListCompl"})<CR>')
+ feed('<Tab><CR>')
+ eq('FOO', meths.get_var('var'))
+ end)
+ it('supports cancelreturn', function()
+ feed(':let var = inputdialog("", "", "CR1")<CR>')
+ feed('<Esc>')
+ eq('CR1', meths.get_var('var'))
+
+ feed(':let var = inputdialog({"cancelreturn": "BAR"})<CR>')
+ feed('<Esc>')
+ eq('BAR', meths.get_var('var'))
+ end)
+ it('supports default string', function()
+ feed(':let var = inputdialog("", "DEF1")<CR>')
+ feed('<CR>')
+ eq('DEF1', meths.get_var('var'))
+
+ feed(':let var = inputdialog({"default": "DEF2"})<CR>')
+ feed('<CR>')
+ eq('DEF2', meths.get_var('var'))
+ end)
+ it('errors out on invalid inputs', function()
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog([])'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog("", [])'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog("", "", [])'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog({"prompt": []})'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog({"cancelreturn": []})'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog({"default": []})'))
+ eq('Vim(call):E730: using List as a String',
+ exc_exec('call inputdialog({"completion": []})'))
+ eq('Vim(call):E5050: {opts} must be the only argument',
+ exc_exec('call inputdialog({}, "default")'))
+ eq('Vim(call):E118: Too many arguments for function: inputdialog',
+ exc_exec('call inputdialog("prompt> ", "default", "file", "extra")'))
end)
end)
diff --git a/test/functional/ex_cmds/encoding_spec.lua b/test/functional/ex_cmds/encoding_spec.lua
index 0769259be4..7f2bd78a47 100644
--- a/test/functional/ex_cmds/encoding_spec.lua
+++ b/test/functional/ex_cmds/encoding_spec.lua
@@ -15,7 +15,7 @@ describe('&encoding', function()
feed_command('set encoding=latin1')
-- error message expected
feed('<cr>')
- neq(nil, string.find(eval('v:errmsg'), '^E474:'))
+ neq(nil, string.find(eval('v:errmsg'), '^E519:'))
eq('utf-8', eval('&encoding'))
-- check nvim is still in utf-8 mode
eq(3, eval('strwidth("Bär")'))
@@ -25,7 +25,7 @@ describe('&encoding', function()
clear('--cmd', 'set enc=latin1')
-- error message expected
feed('<cr>')
- neq(nil, string.find(eval('v:errmsg'), '^E474:'))
+ neq(nil, string.find(eval('v:errmsg'), '^E519:'))
eq('utf-8', eval('&encoding'))
eq(3, eval('strwidth("Bär")'))
end)
diff --git a/test/functional/fixtures/tty-test.c b/test/functional/fixtures/tty-test.c
index 3406b3a202..7ba21d652a 100644
--- a/test/functional/fixtures/tty-test.c
+++ b/test/functional/fixtures/tty-test.c
@@ -6,6 +6,9 @@
#include <stdlib.h>
#include <uv.h>
+// -V:STRUCT_CAST:641
+#define STRUCT_CAST(Type, obj) ((Type *)(obj))
+
uv_tty_t tty;
#ifdef _WIN32
@@ -88,9 +91,9 @@ static void read_cb(uv_stream_t *stream, ssize_t cnt, const uv_buf_t *buf)
uv_tty_init(&write_loop, &out, 1, 0);
uv_write_t req;
uv_buf_t b = {.base = buf->base, .len = (size_t)cnt};
- uv_write(&req, (uv_stream_t *)&out, &b, 1, NULL);
+ uv_write(&req, STRUCT_CAST(uv_stream_t, &out), &b, 1, NULL);
uv_run(&write_loop, UV_RUN_DEFAULT);
- uv_close((uv_handle_t *)&out, NULL);
+ uv_close(STRUCT_CAST(uv_handle_t, &out), NULL);
uv_run(&write_loop, UV_RUN_DEFAULT);
if (uv_loop_close(&write_loop)) {
abort();
@@ -149,7 +152,7 @@ int main(int argc, char **argv)
uv_tty_init(uv_default_loop(), &tty, fileno(stderr), 1);
uv_tty_set_mode(&tty, UV_TTY_MODE_RAW);
tty.data = &interrupted;
- uv_read_start((uv_stream_t *)&tty, alloc_cb, read_cb);
+ uv_read_start(STRUCT_CAST(uv_stream_t, &tty), alloc_cb, read_cb);
#ifndef WIN32
struct sigaction sa;
sigemptyset(&sa.sa_mask);
diff --git a/test/functional/ui/cursor_spec.lua b/test/functional/ui/cursor_spec.lua
index f4eec4bdc7..b47210a777 100644
--- a/test/functional/ui/cursor_spec.lua
+++ b/test/functional/ui/cursor_spec.lua
@@ -194,8 +194,8 @@ describe('ui/cursor', function()
if m.blinkoff then m.blinkoff = 400 end
if m.blinkwait then m.blinkwait = 700 end
end
- if m.hl_id then m.hl_id = 47 end
- if m.id_lm then m.id_lm = 48 end
+ if m.hl_id then m.hl_id = 48 end
+ if m.id_lm then m.id_lm = 49 end
end
-- Assert the new expectation.
diff --git a/test/unit/eval/typval_spec.lua b/test/unit/eval/typval_spec.lua
index 6308ae7367..5d543f914f 100644
--- a/test/unit/eval/typval_spec.lua
+++ b/test/unit/eval/typval_spec.lua
@@ -1751,6 +1751,55 @@ describe('typval.c', function()
eq('2', s)
end)
end)
+ describe('get_string_buf_chk()', function()
+ local function tv_dict_get_string_buf_chk(d, key, len, buf, def, emsg)
+ buf = buf or ffi.gc(lib.xmalloc(lib.NUMBUFLEN), lib.xfree)
+ def = def or ffi.gc(lib.xstrdup('DEFAULT'), lib.xfree)
+ len = len or #key
+ alloc_log:clear()
+ local ret = check_emsg(function() return lib.tv_dict_get_string_buf_chk(d, key, len, buf, def) end,
+ emsg)
+ local s_ret = (ret ~= nil) and ffi.string(ret) or nil
+ if not emsg then
+ alloc_log:check({})
+ end
+ return s_ret, ret, buf, def
+ end
+ itp('works with NULL dict', function()
+ eq('DEFAULT', tv_dict_get_string_buf_chk(nil, 'test'))
+ end)
+ itp('works', function()
+ local lua_d = {
+ ['']={},
+ t=1,
+ te=int(2),
+ tes=empty_list,
+ test='tset',
+ testt=5,
+ }
+ local d = dict(lua_d)
+ alloc_log:clear()
+ eq(lua_d, dct2tbl(d))
+ alloc_log:check({})
+ local s, r, b, def
+ s, r, b, def = tv_dict_get_string_buf_chk(d, 'test')
+ neq(r, b)
+ neq(r, def)
+ eq('tset', s)
+ s, r, b, def = tv_dict_get_string_buf_chk(d, 'test', 1, nil, nil, 'E806: using Float as a String')
+ neq(r, b)
+ neq(r, def)
+ eq(nil, s)
+ s, r, b, def = tv_dict_get_string_buf_chk(d, 'te')
+ eq(r, b)
+ neq(r, def)
+ eq('2', s)
+ s, r, b, def = tv_dict_get_string_buf_chk(d, 'TEST')
+ eq(r, def)
+ neq(r, b)
+ eq('DEFAULT', s)
+ end)
+ end)
describe('get_callback()', function()
local function tv_dict_get_callback(d, key, key_len, emsg)
key_len = key_len or #key
diff --git a/test/unit/os/env_spec.lua b/test/unit/os/env_spec.lua
index 575787a25e..cefd0315b7 100644
--- a/test/unit/os/env_spec.lua
+++ b/test/unit/os/env_spec.lua
@@ -13,7 +13,7 @@ require('lfs')
local cimp = cimport('./src/nvim/os/os.h')
-describe('env function', function()
+describe('env.c', function()
local function os_setenv(name, value, override)
return cimp.os_setenv(to_cstr(name), to_cstr(value), override)
end
diff --git a/test/unit/path_spec.lua b/test/unit/path_spec.lua
index 6b9e2c8695..a9cba7df84 100644
--- a/test/unit/path_spec.lua
+++ b/test/unit/path_spec.lua
@@ -18,7 +18,7 @@ local cimp = cimport('./src/nvim/os/os.h', './src/nvim/path.h')
local length = 0
local buffer = nil
-describe('path function', function()
+describe('path.c', function()
describe('path_full_dir_name', function()
setup(function()
lfs.mkdir('unit-test-directory')
@@ -293,6 +293,59 @@ describe('path_shorten_fname_if_possible', function()
end)
end)
+describe('path.c path_guess_exepath', function()
+ local cwd = lfs.currentdir()
+
+ for _,name in ipairs({'./nvim', '.nvim', 'foo/nvim'}) do
+ itp('"'..name..'" returns name catenated with CWD', function()
+ local bufsize = 255
+ local buf = cstr(bufsize, '')
+ cimp.path_guess_exepath(name, buf, bufsize)
+ eq(cwd..'/'..name, ffi.string(buf))
+ end)
+ end
+
+ itp('absolute path returns the name unmodified', function()
+ local name = '/foo/bar/baz'
+ local bufsize = 255
+ local buf = cstr(bufsize, '')
+ cimp.path_guess_exepath(name, buf, bufsize)
+ eq(name, ffi.string(buf))
+ end)
+
+ itp('returns the name unmodified if not found in $PATH', function()
+ local name = '23u0293_not_in_path'
+ local bufsize = 255
+ local buf = cstr(bufsize, '')
+ cimp.path_guess_exepath(name, buf, bufsize)
+ eq(name, ffi.string(buf))
+ end)
+
+ itp('does not crash if $PATH item exceeds MAXPATHL', function()
+ local orig_path_env = os.getenv('PATH')
+ local name = 'cat' -- Some executable in $PATH.
+ local bufsize = 255
+ local buf = cstr(bufsize, '')
+ local insane_path = orig_path_env..':'..(("x/"):rep(4097))
+
+ cimp.os_setenv('PATH', insane_path, true)
+ cimp.path_guess_exepath(name, buf, bufsize)
+ eq('bin/' .. name, ffi.string(buf):sub(-#('bin/' .. name), -1))
+
+ -- Restore $PATH.
+ cimp.os_setenv('PATH', orig_path_env, true)
+ end)
+
+ itp('returns full path found in $PATH', function()
+ local name = 'cat' -- Some executable in $PATH.
+ local bufsize = 255
+ local buf = cstr(bufsize, '')
+ cimp.path_guess_exepath(name, buf, bufsize)
+ -- Usually "/bin/cat" on unix, "/path/to/nvim/cat" on Windows.
+ eq('bin/' .. name, ffi.string(buf):sub(-#('bin/' .. name), -1))
+ end)
+end)
+
describe('path.c', function()
setup(function()
lfs.mkdir('unit-test-directory');