test: move oldtests to test directory (#22536)

The new oldtest directory is in test/old/testdir. The reason for this is
that many tests have hardcoded the parent directory name to be
'testdir'.
This commit is contained in:
dundargoc
2023-03-07 04:13:04 +01:00
committed by GitHub
parent bf4eada2c8
commit af23d17388
267 changed files with 30 additions and 28 deletions

View File

@@ -1 +0,0 @@
# Tests may depend on the existence of this file.

View File

@@ -1,154 +0,0 @@
# vim: noet ts=8
# Makefile to run all tests for Vim
#
ifeq ($(OS),Windows_NT)
NVIM_PRG ?= ../../../build/bin/nvim.exe
else
NVIM_PRG ?= ../../../build/bin/nvim
endif
ROOT := ../../..
export SHELL := sh
export NVIM_PRG := $(NVIM_PRG)
export TMPDIR := $(abspath X-test-tmpdir)
ifeq ($(OS),Windows_NT)
FIXFF = fixff
else
FIXFF =
endif
# Tests using runtest.vim.
NEW_TESTS_ALOT := test_alot_utf8 test_alot test_alot_latin
NEW_TESTS_IN_ALOT := $(shell sed -n '/^source/ s/^source //; s/\.vim$$//p' $(addsuffix .vim,$(NEW_TESTS_ALOT)))
# Ignored tests.
# test_largefile: uses too much resources to run on CI.
NEW_TESTS_IGNORE := \
test_largefile \
NEW_TESTS := $(sort $(basename $(notdir $(wildcard test_*.vim))))
NEW_TESTS_RES := $(addsuffix .res,$(filter-out $(NEW_TESTS_ALOT) $(NEW_TESTS_IN_ALOT) $(NEW_TESTS_IGNORE),$(NEW_TESTS)) $(NEW_TESTS_ALOT))
ifdef VALGRIND_GDB
VGDB := --vgdb=yes \
--vgdb-error=0
endif
ifdef USE_VALGRIND
VALGRIND_TOOL := --tool=memcheck \
--leak-check=yes \
--track-origins=yes
# VALGRIND_TOOL := exp-sgcheck
TOOL := valgrind -q \
-q \
$(VALGRIND_TOOL) \
--suppressions=../../.valgrind.supp \
--error-exitcode=123 \
--log-file=valgrind-\%p.$* \
$(VGDB) \
--trace-children=yes
else
ifdef USE_GDB
TOOL = gdb --args
endif
endif
nongui: nolog $(FIXFF) newtests report
.gdbinit:
@echo "[OLDTEST-PREP] Setting up .gdbinit"
@echo 'set $$_exitcode = -1\nrun\nif $$_exitcode != -1\n quit\nend' > .gdbinit
report:
$(NVIM_PRG) -u NONE $(NO_INITS) -S summarize.vim messages
@echo
@echo 'Test results:'
@cat test_result.log
@/bin/sh -c "if test -f test.log; \
then echo TEST FAILURE; exit 1; \
else echo ALL DONE; \
fi"
test1.out: $(NVIM_PRG)
NO_PLUGINS = --noplugin --headless
# In vim, if the -u command line option is specified, compatible is turned on
# and viminfo is not read. Unlike vim, neovim reads viminfo and requires the
# -i command line option.
NO_INITS = -U NONE -i NONE $(NO_PLUGINS)
# TODO: find a way to avoid changing the distributed files.
fixff:
-$(NVIM_PRG) $(NO_INITS) -u unix.vim "+argdo set ff=dos|upd" +q \
*.in *.ok
-$(NVIM_PRG) $(NO_INITS) -u unix.vim "+argdo set ff=dos|upd" +q \
dotest.in
# Execute an individual new style test, e.g.:
# make test_largefile
$(NEW_TESTS):
rm -f $@.res test.log messages
@MAKEFLAGS=--no-print-directory $(MAKE) -f Makefile $@.res
@cat messages
@if test -f test.log; then \
exit 1; \
fi
RM_ON_RUN := test.out X* viminfo
RM_ON_START := test.ok
RUN_VIM := $(TOOL) $(NVIM_PRG) -u unix.vim -U NONE -i viminfo --headless --noplugin -s dotest.in
# Delete files that may interfere with running tests. This includes some files
# that may result from working on the tests, not only from running them.
CLEAN_FILES := *.out \
*.failed \
*.res \
*.rej \
*.orig \
*.tlog \
test.log \
test_result.log \
messages \
$(RM_ON_RUN) \
$(RM_ON_START) \
valgrind.* \
.*.swp \
.*.swo \
.gdbinit \
$(TMPDIR) \
del
clean:
$(RM) -rf $(CLEAN_FILES)
test1.out: .gdbinit test1.in
@echo "[OLDTEST-PREP] Running test1"
@rm -rf $*.failed $(RM_ON_RUN) $(RM_ON_START) wrongtermsize
@mkdir -p $(TMPDIR)
@/bin/sh runnvim.sh $(ROOT) $(NVIM_PRG) $* $(RUN_VIM) $*.in
@rm -f wrongtermsize
@rm -rf X* viminfo
nolog:
@echo "[OLDTEST-PREP] Removing test.log and messages"
@rm -f test.log messages
# New style of tests uses Vim script with assert calls. These are easier
# to write and a lot easier to read and debug.
# Limitation: Only works with the +eval feature.
RUN_VIMTEST = $(TOOL) $(NVIM_PRG) -u unix.vim
newtests: newtestssilent
@/bin/sh -c "if test -f messages && grep -q 'FAILED' messages; then \
cat messages && cat test.log; \
fi"
newtestssilent: $(NEW_TESTS_RES)
%.res: %.vim .gdbinit
@echo "[OLDTEST] Running" $*
@rm -rf $*.failed test.ok $(RM_ON_RUN)
@mkdir -p $(TMPDIR)
@/bin/sh runnvim.sh $(ROOT) $(NVIM_PRG) $* $(RUN_VIMTEST) $(NO_INITS) -u NONE --cmd "set shortmess-=F" -S runtest.vim $*.vim

View File

@@ -1,121 +0,0 @@
This directory contains tests for various Vim features.
For testing an indent script see runtime/indent/testdir/README.txt.
If it makes sense, add a new test method to an already existing file. You may
want to separate it from other tests with comment lines.
TO ADD A NEW STYLE TEST:
1) Create a test_<subject>.vim file.
2) Add test_<subject>.res to NEW_TESTS_RES in Make_all.mak in alphabetical
order.
3) Also add an entry "test_<subject>" to NEW_TESTS in Make_all.mak.
4) Use make test_<subject> to run a single test.
At 2), instead of running the test separately, it can be included in
"test_alot". Do this for quick tests without side effects. The test runs a
bit faster, because Vim doesn't have to be started, one Vim instance runs many
tests.
At 4), to run a test in GUI, add "GUI_FLAG=-g" to the make command.
What you can use (see test_assert.vim for an example):
- Call assert_equal(), assert_true(), assert_false(), etc.
- Use assert_fails() to check for expected errors.
- Use try/catch to avoid an exception aborts the test.
- Use test_alloc_fail() to have memory allocation fail. This makes it possible
to check memory allocation failures are handled gracefully. You need to
change the source code to add an ID to the allocation. Add a new one to
alloc_id_T, before aid_last.
- Use test_override() to make Vim behave differently, e.g. if char_avail()
must return FALSE for a while. E.g. to trigger the CursorMovedI autocommand
event. See test_cursor_func.vim for an example.
- If the bug that is being tested isn't fixed yet, you can throw an exception
with "Skipped" so that it's clear this still needs work. E.g.: throw
"Skipped: Bug with <c-e> and popupmenu not fixed yet"
- The following environment variables are recognized and can be set to
influence the behavior of the test suite (see runtest.vim for details)
- $TEST_MAY_FAIL=Test_channel_one - ignore those failing tests
- $TEST_FILTER=Test_channel - only run test that match this pattern
- $TEST_SKIP_PAT=Test_channel - skip tests that match this pattern
- $TEST_NO_RETRY=yes - do not try to re-run failing tests
You can also set them in Vim:
:let $TEST_MAY_FAIL = 'Test_channel_one'
:let $TEST_FILTER = '_set_mode'
:let $TEST_SKIP_PAT = 'Test_loop_forever'
:let $TEST_NO_RETRY = 'yes'
Use an empty string to revert, e.g.:
:let $TEST_FILTER = ''
- See the start of runtest.vim for more help.
TO ADD A SCREEN DUMP TEST:
Mostly the same as writing a new style test. Additionally, see help on
"terminal-dumptest". Put the reference dump in "dumps/Test_func_name.dump".
OLD STYLE TESTS:
There are a few tests that are used when Vim was built without the +eval
feature. These cannot use the "assert" functions, therefore they consist of a
.in file that contains Normal mode commands between STARTTEST and ENDTEST.
They modify the file and the result gets written in the test.out file. This
is then compared with the .ok file. If they are equal the test passed. If
they differ the test failed.
RUNNING THE TESTS:
To run a single test from the src directory:
$ make test_<name>
The below commands should be run from the src/testdir directory.
To run a single test:
$ make test_<name>.res
The file 'messages' contains the messages generated by the test script. If a
test fails, then the test.log file contains the error messages. If all the
tests are successful, then this file will be an empty file.
- To run a single test function from a test script:
$ ../vim -u NONE -S runtest.vim <test_file>.vim <function_name>
- To execute only specific test functions, add a second argument:
$ ../vim -u NONE -S runtest.vim test_channel.vim open_delay
- To run all the tests:
$ make
- To run the test on MS-Windows using the MSVC nmake:
> nmake -f Make_dos.mak
- To run the tests with GUI Vim:
$ make GUI_FLAG=-g
or
$ make VIMPROG=../gvim
- To cleanup the temporary files after running the tests:
$ make clean

View File

@@ -1,217 +0,0 @@
source shared.vim
source term_util.vim
command -nargs=1 MissingFeature throw 'Skipped: ' .. <args> .. ' feature missing'
" Command to check for the presence of a feature.
command -nargs=1 CheckFeature call CheckFeature(<f-args>)
func CheckFeature(name)
" if !has(a:name, 1)
" throw 'Checking for non-existent feature ' .. a:name
" endif
if !has(a:name)
MissingFeature a:name
endif
endfunc
" Command to check for the absence of a feature.
command -nargs=1 CheckNotFeature call CheckNotFeature(<f-args>)
func CheckNotFeature(name)
" if !has(a:name, 1)
" throw 'Checking for non-existent feature ' .. a:name
" endif
if has(a:name)
throw 'Skipped: ' .. a:name .. ' feature present'
endif
endfunc
" Command to check for the presence of a working option.
command -nargs=1 CheckOption call CheckOption(<f-args>)
func CheckOption(name)
if !exists('&' .. a:name)
throw 'Checking for non-existent option ' .. a:name
endif
if !exists('+' .. a:name)
throw 'Skipped: ' .. a:name .. ' option not supported'
endif
endfunc
" Command to check for the presence of a function.
command -nargs=1 CheckFunction call CheckFunction(<f-args>)
func CheckFunction(name)
if !exists('*' .. a:name)
throw 'Skipped: ' .. a:name .. ' function missing'
endif
endfunc
" Command to check for the presence of an Ex command
command -nargs=1 CheckCommand call CheckCommand(<f-args>)
func CheckCommand(name)
if !exists(':' .. a:name)
throw 'Skipped: ' .. a:name .. ' command not supported'
endif
endfunc
" Command to check for the presence of a shell command
command -nargs=1 CheckExecutable call CheckExecutable(<f-args>)
func CheckExecutable(name)
if !executable(a:name)
throw 'Skipped: ' .. a:name .. ' program not executable'
endif
endfunc
" Command to check for the presence of python. Argument should have been
" obtained with PythonProg()
func CheckPython(name)
if a:name == ''
throw 'Skipped: python command not available'
endif
endfunc
" Command to check for running on MS-Windows
command CheckMSWindows call CheckMSWindows()
func CheckMSWindows()
if !has('win32')
throw 'Skipped: only works on MS-Windows'
endif
endfunc
" Command to check for NOT running on MS-Windows
command CheckNotMSWindows call CheckNotMSWindows()
func CheckNotMSWindows()
if has('win32')
throw 'Skipped: does not work on MS-Windows'
endif
endfunc
" Command to check for running on Unix
command CheckUnix call CheckUnix()
func CheckUnix()
if !has('unix')
throw 'Skipped: only works on Unix'
endif
endfunc
" Command to check for running on Linux
command CheckLinux call CheckLinux()
func CheckLinux()
if !has('linux')
throw 'Skipped: only works on Linux'
endif
endfunc
" Command to check that making screendumps is supported.
" Caller must source screendump.vim
command CheckScreendump call CheckScreendump()
func CheckScreendump()
if !CanRunVimInTerminal()
throw 'Skipped: cannot make screendumps'
endif
endfunc
" Command to check that we can Run Vim in a terminal window
command CheckRunVimInTerminal call CheckRunVimInTerminal()
func CheckRunVimInTerminal()
if !CanRunVimInTerminal()
throw 'Skipped: cannot run Vim in a terminal window'
endif
endfunc
" Command to check that we can run the GUI
command CheckCanRunGui call CheckCanRunGui()
func CheckCanRunGui()
if !has('gui') || ($DISPLAY == "" && !has('gui_running'))
throw 'Skipped: cannot start the GUI'
endif
endfunc
" Command to Check for an environment variable
command -nargs=1 CheckEnv call CheckEnv(<f-args>)
func CheckEnv(name)
if empty(eval('$' .. a:name))
throw 'Skipped: Environment variable ' .. a:name .. ' is not set'
endif
endfunc
" Command to check that we are using the GUI
command CheckGui call CheckGui()
func CheckGui()
if !has('gui_running')
throw 'Skipped: only works in the GUI'
endif
endfunc
" Command to check that not currently using the GUI
command CheckNotGui call CheckNotGui()
func CheckNotGui()
if has('gui_running')
throw 'Skipped: only works in the terminal'
endif
endfunc
" Command to check that test is not running as root
command CheckNotRoot call CheckNotRoot()
func CheckNotRoot()
if IsRoot()
throw 'Skipped: cannot run test as root'
endif
endfunc
" Command to check that the current language is English
command CheckEnglish call CheckEnglish()
func CheckEnglish()
if v:lang != "C" && v:lang !~ '^[Ee]n'
throw 'Skipped: only works in English language environment'
endif
endfunc
" Command to check for not running under ASAN
command CheckNotAsan call CheckNotAsan()
func CheckNotAsan()
if execute('version') =~# '-fsanitize=[a-z,]*\<address\>'
throw 'Skipped: does not work with ASAN'
endif
endfunc
" Command to check for not running under valgrind
command CheckNotValgrind call CheckNotValgrind()
func CheckNotValgrind()
if RunningWithValgrind()
throw 'Skipped: does not work well with valgrind'
endif
endfunc
" Command to check for X11 based GUI
command CheckX11BasedGui call CheckX11BasedGui()
func CheckX11BasedGui()
if !g:x11_based_gui
throw 'Skipped: requires X11 based GUI'
endif
endfunc
" Command to check for satisfying any of the conditions.
" e.g. CheckAnyOf Feature:bsd Feature:sun Linux
command -nargs=+ CheckAnyOf call CheckAnyOf(<f-args>)
func CheckAnyOf(...)
let excp = []
for arg in a:000
try
exe 'Check' .. substitute(arg, ':', ' ', '')
return
catch /^Skipped:/
let excp += [substitute(v:exception, '^Skipped:\s*', '', '')]
endtry
endfor
throw 'Skipped: ' .. join(excp, '; ')
endfunc
" Command to check for satisfying all of the conditions.
" e.g. CheckAllOf Unix Gui Option:ballooneval
command -nargs=+ CheckAllOf call CheckAllOf(<f-args>)
func CheckAllOf(...)
for arg in a:000
exe 'Check' .. substitute(arg, ':', ' ', '')
endfor
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,3 +0,0 @@
:set nomore
:map dotest /^STARTTEST
j:set ff=unix cpo-=A

View File

@@ -1,32 +0,0 @@
" Also used by: test/functional/helpers.lua
function! s:load_factor() abort
let timeout = 200
let times = []
for _ in range(5)
let g:val = 0
let start = reltime()
call timer_start(timeout, {-> nvim_set_var('val', 1)})
while 1
sleep 10m
if g:val == 1
let g:waited_in_ms = float2nr(reltimefloat(reltime(start)) * 1000)
break
endif
endwhile
call insert(times, g:waited_in_ms, 0)
endfor
let longest = max(times)
let factor = (longest + 50.0) / timeout
return factor
endfunction
" Compute load factor only once.
let g:test_load_factor = s:load_factor()
function! LoadAdjust(num) abort
return float2nr(ceil(a:num * g:test_load_factor))
endfunction

View File

@@ -1,4 +0,0 @@
# requires python 2.x
import sys
print(sys.version)

View File

@@ -1,4 +0,0 @@
#!/usr/bin/python2
import sys
print(sys.version)

View File

@@ -1,4 +0,0 @@
# requires python 3.x
import sys
print(sys.version)

View File

@@ -1,4 +0,0 @@
#!/usr/bin/python3
import sys
print(sys.version)

View File

@@ -1,2 +0,0 @@
import sys
print(sys.version)

View File

@@ -1,88 +0,0 @@
#!/usr/bin/env bash
main() {(
local separator="================================================================================"
local oldesttest=
if test "$1" = "--oldesttest" ; then
shift
oldesttest=1
fi
local root="$1" ; shift
local nvim_prg="$1" ; shift
local test_name="$1" ; shift
local tlog="$test_name.tlog"
export NVIM_TEST_ARGC=$#
local arg
local i=0
# shellcheck disable=SC2034 # (unused "arg", used in "eval").
for arg ; do
eval "export NVIM_TEST_ARG$i=\"\$arg\""
i=$(( i+1 ))
done
BUILD_DIR="$(dirname "$nvim_prg")/.."
export BUILD_DIR
export FAILED=0
. $(dirname $0)/test.sh
# Redirect XDG_CONFIG_HOME so users local config doesn't interfere
export XDG_CONFIG_HOME="$root"
export VIMRUNTIME="$root/runtime"
if ! "$nvim_prg" \
-u NONE -i NONE \
--headless \
--cmd 'set shortmess+=I noswapfile noundofile nomore' \
-S runnvim.vim \
"$tlog" > "out-$tlog" 2> "err-$tlog"
then
fail "$test_name" "Nvim exited with non-zero code"
fi
{
echo "Stdout of :terminal runner"
echo "$separator"
cat "out-$tlog"
echo "$separator"
echo "Stderr of :terminal runner"
echo "$separator"
cat "err-$tlog"
echo "$separator"
} >> "$tlog"
if test "$oldesttest" = 1 ; then
if ! diff -q test.out "$test_name.ok" > /dev/null 2>&1 ; then
if test -f test.out ; then
fail "$test_name" "Oldest test .out file differs from .ok file"
{
echo "Diff between test.out and $test_name.ok"
echo "$separator"
diff -a test.out "$test_name.ok"
echo "$separator"
} >> "$tlog"
else
echo "No output in test.out" >> "$tlog"
fi
fi
fi
valgrind_check .
if test -n "$LOG_DIR" ; then
check_sanitizer "$LOG_DIR"
fi
check_core_dumps
if test "$FAILED" = 1 ; then
cat "$tlog"
fi
rm -f "$tlog"
if test "$FAILED" = 1 ; then
echo "Test $test_name failed, see output above and summary for more details" >> test.log
# When Neovim crashed/aborted it might not have created messages.
# test.log itself is used as an indicator to exit non-zero in the Makefile.
if ! test -f message; then
cp -a test.log messages
fi
fi
)}
main "$@"

View File

@@ -1,58 +0,0 @@
let s:logger = {'d_events': []}
function s:logger.on_stdout(id, data, event)
call add(self.d_events, [a:event, a:data])
endfunction
let s:logger.on_stderr = s:logger.on_stdout
function s:logger.on_exit(id, data, event)
call add(self.d_events, [a:event, ['']])
endfunction
" Replace non-printable chars by special sequence, or "<%x>".
let s:escaped_char = {"\n": '\n', "\r": '\r', "\t": '\t'}
function! s:escape_non_printable(char) abort
let r = get(s:escaped_char, a:char)
return r is 0 ? printf('<%x>', char2nr(a:char)) : r
endfunction
function Main()
let argc = +$NVIM_TEST_ARGC
let args = []
for i in range(argc)
call add(args, eval("$NVIM_TEST_ARG" . i))
endfor
set lines=25
set columns=80
enew
let job = termopen(args, s:logger)
let results = jobwait([job], 5 * 60 * 1000)
" TODO(ZyX-I): Get colors
let screen = getline(1, '$')
bwipeout! " kills the job always.
let stringified_events = map(s:logger.d_events,
\'v:val[0] . ": " . ' .
\'join(map(v:val[1], '.
\ '''substitute(v:val, '.
\ '"\\v\\C(\\p@!.|\\<)", '.
\ '"\\=s:escape_non_printable(submatch(0))", '.
\ '"g")''), '.
\ '''\n'')')
call setline(1, [
\ 'Job exited with code ' . results[0],
\ printf('Screen (%u lines)', len(screen)),
\ repeat('=', 80),
\] + screen + [
\ repeat('=', 80),
\ printf('Events (%u lines):', len(stringified_events)),
\ repeat('=', 80),
\] + stringified_events + [
\ repeat('=', 80),
\])
write
if results[0] != 0
cquit
else
qall
endif
endfunction
call Main()

View File

@@ -1,485 +0,0 @@
" This script is sourced while editing the .vim file with the tests.
" When the script is successful the .res file will be created.
" Errors are appended to the test.log file.
"
" To execute only specific test functions, add a second argument. It will be
" matched against the names of the Test_ function. E.g.:
" ../vim -u NONE -S runtest.vim test_channel.vim open_delay
" The output can be found in the "messages" file.
"
" If the environment variable $TEST_FILTER is set then only test functions
" matching this pattern are executed. E.g. for sh/bash:
" export TEST_FILTER=Test_channel
" For csh:
" setenv TEST_FILTER Test_channel
"
" While working on a test you can make $TEST_NO_RETRY non-empty to not retry:
" export TEST_NO_RETRY=yes
"
" To ignore failure for tests that are known to fail in a certain environment,
" set $TEST_MAY_FAIL to a comma separated list of function names. E.g. for
" sh/bash:
" export TEST_MAY_FAIL=Test_channel_one,Test_channel_other
" The failure report will then not be included in the test.log file and
" "make test" will not fail.
"
" The test script may contain anything, only functions that start with
" "Test_" are special. These will be invoked and should contain assert
" functions. See test_assert.vim for an example.
"
" It is possible to source other files that contain "Test_" functions. This
" can speed up testing, since Vim does not need to restart. But be careful
" that the tests do not interfere with each other.
"
" If an error cannot be detected properly with an assert function add the
" error to the v:errors list:
" call add(v:errors, 'test foo failed: Cannot find xyz')
"
" If preparation for each Test_ function is needed, define a SetUp function.
" It will be called before each Test_ function.
"
" If cleanup after each Test_ function is needed, define a TearDown function.
" It will be called after each Test_ function.
"
" When debugging a test it can be useful to add messages to v:errors:
" call add(v:errors, "this happened")
" Check that the screen size is at least 24 x 80 characters.
if &lines < 24 || &columns < 80
let error = 'Screen size too small! Tests require at least 24 lines with 80 characters, got ' .. &lines .. ' lines with ' .. &columns .. ' characters'
echoerr error
split test.log
$put =error
write
split messages
call append(line('$'), '')
call append(line('$'), 'From ' . expand('%') . ':')
call append(line('$'), error)
write
qa!
endif
if has('reltime')
let s:start_time = reltime()
endif
" Always use forward slashes.
set shellslash
" Common with all tests on all systems.
source setup.vim
" For consistency run all tests with 'nocompatible' set.
" This also enables use of line continuation.
set nocp viminfo+=nviminfo
" Use utf-8 by default, instead of whatever the system default happens to be.
" Individual tests can overrule this at the top of the file.
set encoding=utf-8
" REDIR_TEST_TO_NULL has a very permissive SwapExists autocommand which is for
" the test_name.vim file itself. Replace it here with a more restrictive one,
" so we still catch mistakes.
let s:test_script_fname = expand('%')
au! SwapExists * call HandleSwapExists()
func HandleSwapExists()
if exists('g:ignoreSwapExists')
return
endif
" Ignore finding a swap file for the test script (the user might be
" editing it and do ":make test_name") and the output file.
" Report finding another swap file and chose 'q' to avoid getting stuck.
if expand('<afile>') == 'messages' || expand('<afile>') =~ s:test_script_fname
let v:swapchoice = 'e'
else
call assert_report('Unexpected swap file: ' .. v:swapname)
let v:swapchoice = 'q'
endif
endfunc
" Avoid stopping at the "hit enter" prompt
set nomore
" Output all messages in English.
lang mess C
" Nvim: append runtime from build dir, which contains the generated doc/tags.
let &runtimepath ..= ',' .. expand($BUILD_DIR) .. '/runtime/'
let s:t_bold = &t_md
let s:t_normal = &t_me
if has('win32')
" avoid prompt that is long or contains a line break
let $PROMPT = '$P$G'
endif
if has('mac')
" In MacOS, when starting a shell in a terminal, a bash deprecation warning
" message is displayed. This breaks the terminal test. Disable the warning
" message.
let $BASH_SILENCE_DEPRECATION_WARNING = 1
endif
" Prepare for calling test_garbagecollect_now().
let v:testing = 1
" Support function: get the alloc ID by name.
func GetAllocId(name)
exe 'split ' . s:srcdir . '/alloc.h'
let top = search('typedef enum')
if top == 0
call add(v:errors, 'typedef not found in alloc.h')
endif
let lnum = search('aid_' . a:name . ',')
if lnum == 0
call add(v:errors, 'Alloc ID ' . a:name . ' not defined')
endif
close
return lnum - top - 1
endfunc
func RunTheTest(test)
echo 'Executing ' . a:test
if has('reltime')
let func_start = reltime()
endif
" Avoid stopping at the "hit enter" prompt
set nomore
" Avoid a three second wait when a message is about to be overwritten by the
" mode message.
set noshowmode
" Some tests wipe out buffers. To be consistent, always wipe out all
" buffers.
%bwipe!
" The test may change the current directory. Save and restore the
" directory after executing the test.
let save_cwd = getcwd()
" Align Nvim defaults to Vim.
source setup.vim
if exists("*SetUp")
try
call SetUp()
catch
call add(v:errors, 'Caught exception in SetUp() before ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
endtry
endif
au VimLeavePre * call EarlyExit(g:testfunc)
if a:test =~ 'Test_nocatch_'
" Function handles errors itself. This avoids skipping commands after the
" error.
let g:skipped_reason = ''
exe 'call ' . a:test
if g:skipped_reason != ''
call add(s:messages, ' Skipped')
call add(s:skipped, 'SKIPPED ' . a:test . ': ' . g:skipped_reason)
endif
else
try
exe 'call ' . a:test
catch /^\cskipped/
call add(s:messages, ' Skipped')
call add(s:skipped, 'SKIPPED ' . a:test . ': ' . substitute(v:exception, '^\S*\s\+', '', ''))
catch
call add(v:errors, 'Caught exception in ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
endtry
endif
au! VimLeavePre
" In case 'insertmode' was set and something went wrong, make sure it is
" reset to avoid trouble with anything else.
set noinsertmode
if exists("*TearDown")
try
call TearDown()
catch
call add(v:errors, 'Caught exception in TearDown() after ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
endtry
endif
" Clear any autocommands and put back the catch-all for SwapExists.
au!
au SwapExists * call HandleSwapExists()
" Close any extra tab pages and windows and make the current one not modified.
while tabpagenr('$') > 1
let winid = win_getid()
quit!
if winid == win_getid()
echoerr 'Could not quit window'
break
endif
endwhile
while 1
let wincount = winnr('$')
if wincount == 1
break
endif
bwipe!
if wincount == winnr('$')
" Did not manage to close a window.
only!
break
endif
endwhile
exe 'cd ' . save_cwd
let message = 'Executed ' . a:test
if has('reltime')
let message ..= repeat(' ', 50 - len(message))
let time = reltime(func_start)
if has('float') && reltimefloat(time) > 0.1
let message = s:t_bold .. message
endif
let message ..= ' in ' .. reltimestr(time) .. ' seconds'
if has('float') && reltimefloat(time) > 0.1
let message ..= s:t_normal
endif
endif
call add(s:messages, message)
let s:done += 1
endfunc
func AfterTheTest(func_name)
if len(v:errors) > 0
if match(s:may_fail_list, '^' .. a:func_name) >= 0
let s:fail_expected += 1
call add(s:errors_expected, 'Found errors in ' . g:testfunc . ':')
call extend(s:errors_expected, v:errors)
else
let s:fail += 1
call add(s:errors, 'Found errors in ' . g:testfunc . ':')
call extend(s:errors, v:errors)
endif
let v:errors = []
endif
endfunc
func EarlyExit(test)
" It's OK for the test we use to test the quit detection.
if a:test != 'Test_zz_quit_detected()'
call add(v:errors, v:errmsg)
call add(v:errors, 'Test caused Vim to exit: ' . a:test)
endif
call FinishTesting()
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=
" Clean up files created by setup.vim
call delete('XfakeHOME', 'rf')
if s:fail == 0 && s:fail_expected == 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
if s:done == 0
if s:filtered > 0
let message = "NO tests match $TEST_FILTER: '" .. $TEST_FILTER .. "'"
else
let message = 'NO tests executed'
endif
else
if s:filtered > 0
call add(s:messages, "Filtered " .. s:filtered .. " tests with $TEST_FILTER")
endif
let message = 'Executed ' . s:done . (s:done > 1 ? ' tests' : ' test')
endif
if s:done > 0 && has('reltime')
let message = s:t_bold .. message .. repeat(' ', 40 - len(message))
let message ..= ' in ' .. reltimestr(reltime(s:start_time)) .. ' seconds'
let message ..= s:t_normal
endif
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
if s:fail_expected > 0
let message = s:fail_expected . ' FAILED (matching $TEST_MAY_FAIL):'
echo message
call add(s:messages, message)
call extend(s:messages, s:errors_expected)
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('%')
let s:done = 0
let s:fail = 0
let s:fail_expected = 0
let s:errors = []
let s:errors_expected = []
let s:messages = []
let s:skipped = []
if expand('%') =~ 'test_vimscript.vim'
" this test has intentional errors, don't use try/catch.
source %
else
try
source %
catch /^\cskipped/
call add(s:messages, ' Skipped')
call add(s:skipped, 'SKIPPED ' . expand('%') . ': ' . substitute(v:exception, '^\S*\s\+', '', ''))
catch
let s:fail += 1
call add(s:errors, 'Caught exception: ' . v:exception . ' @ ' . v:throwpoint)
endtry
endif
" Names of flaky tests.
let s:flaky_tests = [
\ 'Test_autocmd_SafeState()',
\ 'Test_cursorhold_insert()',
\ 'Test_exit_callback_interval()',
\ 'Test_map_timeout_with_timer_interrupt()',
\ 'Test_out_cb()',
\ 'Test_popup_and_window_resize()',
\ 'Test_quoteplus()',
\ 'Test_quotestar()',
\ 'Test_reltime()',
\ 'Test_state()',
\ 'Test_term_mouse_double_click_to_create_tab()',
\ 'Test_term_mouse_multiple_clicks_to_visually_select()',
\ 'Test_terminal_composing_unicode()',
\ 'Test_terminal_redir_file()',
\ 'Test_terminal_tmap()',
\ 'Test_timer_oneshot()',
\ 'Test_timer_paused()',
\ 'Test_timer_repeat_many()',
\ 'Test_timer_repeat_three()',
\ 'Test_timer_stop_all_in_callback()',
\ 'Test_timer_stop_in_callback()',
\ 'Test_timer_with_partial_callback()',
\ 'Test_termwinscroll()',
\ ]
" Locate Test_ functions and execute them.
redir @q
silent function /^Test_
redir END
let s:tests = split(substitute(@q, 'function \(\k*()\)', '\1', 'g'))
" If there is an extra argument filter the function names against it.
if argc() > 1
let s:tests = filter(s:tests, 'v:val =~ argv(1)')
endif
" If the environment variable $TEST_FILTER is set then filter the function
" names against it.
let s:filtered = 0
if $TEST_FILTER != ''
let s:filtered = len(s:tests)
let s:tests = filter(s:tests, 'v:val =~ $TEST_FILTER')
let s:filtered -= len(s:tests)
endif
let s:may_fail_list = []
if $TEST_MAY_FAIL != ''
" Split the list at commas and add () to make it match g:testfunc.
let s:may_fail_list = split($TEST_MAY_FAIL, ',')->map({i, v -> v .. '()'})
endif
" Execute the tests in alphabetical order.
for g:testfunc in sort(s:tests)
" Silence, please!
set belloff=all
let prev_error = ''
let total_errors = []
let g:run_nr = 1
" A test can set g:test_is_flaky to retry running the test.
let g:test_is_flaky = 0
call RunTheTest(g:testfunc)
" Repeat a flaky test. Give up when:
" - $TEST_NO_RETRY is not empty
" - it fails again with the same message
" - it fails five times (with a different message)
if len(v:errors) > 0
\ && $TEST_NO_RETRY == ''
\ && (index(s:flaky_tests, g:testfunc) >= 0
\ || g:test_is_flaky)
while 1
call add(s:messages, 'Found errors in ' . g:testfunc . ':')
call extend(s:messages, v:errors)
call add(total_errors, 'Run ' . g:run_nr . ':')
call extend(total_errors, v:errors)
if g:run_nr >= 5 || prev_error == v:errors[0]
call add(total_errors, 'Flaky test failed too often, giving up')
let v:errors = total_errors
break
endif
call add(s:messages, 'Flaky test failed, running it again')
" Flakiness is often caused by the system being very busy. Sleep a
" couple of seconds to have a higher chance of succeeding the second
" time.
sleep 2
let prev_error = v:errors[0]
let v:errors = []
let g:run_nr += 1
call RunTheTest(g:testfunc)
if len(v:errors) == 0
" Test passed on rerun.
break
endif
endwhile
endif
call AfterTheTest(g:testfunc)
endfor
call FinishTesting()
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,148 +0,0 @@
// 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
// uncrustify:off
/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* memfile_test.c: Unittests for memfile.c
* Mostly by Ivan Krasilnikov.
*/
#undef NDEBUG
#include <assert.h>
/* Must include main.c because it contains much more than just main() */
#define NO_VIM_MAIN
#include "main.c"
/* This file has to be included because the tested functions are static */
#include "memfile.c"
#define index_to_key(i) ((i) ^ 15167)
#define TEST_COUNT 50000
/*
* Test mf_hash_*() functions.
*/
static void
test_mf_hash(void)
{
mf_hashtab_T ht;
mf_hashitem_T *item;
blocknr_T key;
size_t i;
size_t num_buckets;
mf_hash_init(&ht);
/* insert some items and check invariants */
for (i = 0; i < TEST_COUNT; i++)
{
assert(ht.mht_count == i);
/* check that number of buckets is a power of 2 */
num_buckets = ht.mht_mask + 1;
assert(num_buckets > 0 && (num_buckets & (num_buckets - 1)) == 0);
/* check load factor */
assert(ht.mht_count <= (num_buckets << MHT_LOG_LOAD_FACTOR));
if (i < (MHT_INIT_SIZE << MHT_LOG_LOAD_FACTOR))
{
/* first expansion shouldn't have occurred yet */
assert(num_buckets == MHT_INIT_SIZE);
assert(ht.mht_buckets == ht.mht_small_buckets);
}
else
{
assert(num_buckets > MHT_INIT_SIZE);
assert(ht.mht_buckets != ht.mht_small_buckets);
}
key = index_to_key(i);
assert(mf_hash_find(&ht, key) == NULL);
/* allocate and add new item */
item = (mf_hashitem_T *)lalloc_clear(sizeof(*item), FALSE);
assert(item != NULL);
item->mhi_key = key;
mf_hash_add_item(&ht, item);
assert(mf_hash_find(&ht, key) == item);
if (ht.mht_mask + 1 != num_buckets)
{
/* hash table was expanded */
assert(ht.mht_mask + 1 == num_buckets * MHT_GROWTH_FACTOR);
assert(i + 1 == (num_buckets << MHT_LOG_LOAD_FACTOR));
}
}
/* check presence of inserted items */
for (i = 0; i < TEST_COUNT; i++)
{
key = index_to_key(i);
item = mf_hash_find(&ht, key);
assert(item != NULL);
assert(item->mhi_key == key);
}
/* delete some items */
for (i = 0; i < TEST_COUNT; i++)
{
if (i % 100 < 70)
{
key = index_to_key(i);
item = mf_hash_find(&ht, key);
assert(item != NULL);
assert(item->mhi_key == key);
mf_hash_rem_item(&ht, item);
assert(mf_hash_find(&ht, key) == NULL);
mf_hash_add_item(&ht, item);
assert(mf_hash_find(&ht, key) == item);
mf_hash_rem_item(&ht, item);
assert(mf_hash_find(&ht, key) == NULL);
vim_free(item);
}
}
/* check again */
for (i = 0; i < TEST_COUNT; i++)
{
key = index_to_key(i);
item = mf_hash_find(&ht, key);
if (i % 100 < 70)
{
assert(item == NULL);
}
else
{
assert(item != NULL);
assert(item->mhi_key == key);
}
}
/* free hash table and all remaining items */
mf_hash_free_all(&ht);
}
int
main(void)
{
test_mf_hash();
return 0;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,15 +0,0 @@
let g:loaded_foo_vim += 1
let foo#bar = {}
func foo#bar.echo()
let g:called_foo_bar_echo += 1
endfunc
func foo#addFoo(head)
return a:head .. 'foo'
endfunc
func foo#()
return 'empty'
endfunc

View File

@@ -1,5 +0,0 @@
" Autoload script used by test_listdict.vim, test_exists.vim and test_let.vim
let footest#x = 1
func footest#F()
return 0
endfunc

View File

@@ -1 +0,0 @@
" used by Test_globpath()

View File

@@ -1 +0,0 @@
" used by Test_globpath()

View File

@@ -1,3 +0,0 @@
let g:loaded_sourced_vim += 1
func! sourced#something()
endfunc

View File

@@ -1,2 +0,0 @@
source shared.vim
source term_util.vim

View File

@@ -1,69 +0,0 @@
" Functions shared by the tests for Vim Script
" Commands to track the execution path of a script
com! XpathINIT let g:Xpath = ''
com! -nargs=1 -bar Xpath let g:Xpath ..= <args>
com! XloopINIT let g:Xloop = 1
com! -nargs=1 -bar Xloop let g:Xpath ..= <args> .. g:Xloop
com! XloopNEXT let g:Xloop += 1
" MakeScript() - Make a script file from a function. {{{2
"
" Create a script that consists of the body of the function a:funcname.
" Replace any ":return" by a ":finish", any argument variable by a global
" variable, and every ":call" by a ":source" for the next following argument
" in the variable argument list. This function is useful if similar tests are
" to be made for a ":return" from a function call or a ":finish" in a script
" file.
func MakeScript(funcname, ...)
let script = tempname()
execute "redir! >" . script
execute "function" a:funcname
redir END
execute "edit" script
" Delete the "function" and the "endfunction" lines. Do not include the
" word "function" in the pattern since it might be translated if LANG is
" set. When MakeScript() is being debugged, this deletes also the debugging
" output of its line 3 and 4.
exec '1,/.*' . a:funcname . '(.*)/d'
/^\d*\s*endfunction\>/,$d
%s/^\d*//e
%s/return/finish/e
%s/\<a:\(\h\w*\)/g:\1/ge
normal gg0
let cnt = 0
while search('\<call\s*\%(\u\|s:\)\w*\s*(.*)', 'W') > 0
let cnt = cnt + 1
s/\<call\s*\%(\u\|s:\)\w*\s*(.*)/\='source ' . a:{cnt}/
endwhile
g/^\s*$/d
write
bwipeout
return script
endfunc
" ExecAsScript - Source a temporary script made from a function. {{{2
"
" Make a temporary script file from the function a:funcname, ":source" it, and
" delete it afterwards. However, if an exception is thrown the file may remain,
" the caller should call DeleteTheScript() afterwards.
let s:script_name = ''
func ExecAsScript(funcname)
" Make a script from the function passed as argument.
let s:script_name = MakeScript(a:funcname)
" Source and delete the script.
exec "source" s:script_name
call delete(s:script_name)
let s:script_name = ''
endfunc
func DeleteTheScript()
if s:script_name
call delete(s:script_name)
let s:script_name = ''
endif
endfunc
com! -nargs=1 -bar ExecAsScript call ExecAsScript(<f-args>)

View File

@@ -1,85 +0,0 @@
if exists('s:did_load')
" Align Nvim defaults to Vim.
set backspace=
set complete=.,w,b,u,t,i
set directory&
set directory^=.
set display=
set fillchars=vert:\|,foldsep:\|,fold:-
set formatoptions=tcq
set fsync
set laststatus=1
set listchars=eol:$
set joinspaces
set nohidden nosmarttab noautoindent noautoread noruler noshowcmd
set nohlsearch noincsearch
set nrformats=bin,octal,hex
set shortmess=filnxtToOS
set sidescroll=0
set tags=./tags,tags
set undodir&
set undodir^=.
set wildoptions=
set startofline
set sessionoptions&
set sessionoptions+=options
set viewoptions&
set viewoptions+=options
set switchbuf=
if g:testname !~ 'test_mapping.vim$'
" Make "Q" switch to Ex mode.
" This does not work for all tests.
nnoremap Q gQ
endif
endif
" Common preparations for running tests.
" Only load this once.
if exists('s:did_load')
finish
endif
let s:did_load = 1
" Clear Nvim default mappings and menus.
mapclear
mapclear!
aunmenu *
tlunmenu *
" roughly equivalent to test_setmouse() in Vim
func Ntest_setmouse(row, col)
call nvim_input_mouse('move', '', '', 0, a:row - 1, a:col - 1)
endfunc
" Prevent Nvim log from writing to stderr.
let $NVIM_LOG_FILE = exists($NVIM_LOG_FILE) ? $NVIM_LOG_FILE : 'Xnvim.log'
" Make sure 'runtimepath' and 'packpath' does not include $HOME.
set rtp=$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after
let &packpath = &rtp
" Avoid storing shell history.
let $HISTFILE = ""
" Use default shell on Windows to avoid segfault, caused by TUI
if has('win32')
let $SHELL = ''
let $TERM = ''
let &shell = empty($COMSPEC) ? exepath('cmd.exe') : $COMSPEC
set shellcmdflag=/s/c shellxquote=\" shellredir=>%s\ 2>&1
let &shellpipe = &shellredir
endif
" Detect user modules for language providers
let $PYTHONUSERBASE = $HOME . '/.local'
if executable('gem')
let $GEM_PATH = system('gem env gempath')
endif
" Make sure $HOME does not get read or written.
let $HOME = expand(getcwd() . '/XfakeHOME')
if !isdirectory($HOME)
call mkdir($HOME)
endif

View File

@@ -1,389 +0,0 @@
" Functions shared by several tests.
" Only load this script once.
if exists('*PythonProg')
finish
endif
source view_util.vim
" {Nvim}
" Filepath captured from output may be truncated, like this:
" /home/va...estdir/X-test-tmpdir/nvimxbXN4i/10
" Get last 2 segments, then combine with $TMPDIR.
func! Fix_truncated_tmpfile(fname)
" sanity check
if $TMPDIR ==# ''
throw '$TMPDIR is empty'
endif
let tmpdir_tail = fnamemodify(substitute($TMPDIR, '[\/]\+$', '', 'g'), ':t')
if tmpdir_tail ==# ''
throw 'empty tmpdir_tail'
endif
if a:fname !~# tmpdir_tail
throw printf('$TMPDIR (%s) not in fname: %s', tmpdir_tail, a:fname)
endif
let last2segments = matchstr(a:fname, '[\/][^\/]\+[\/][^\/]\+$')
return $TMPDIR.last2segments
endfunc
" Get the name of the Python executable.
" Also keeps it in s:python.
func PythonProg()
" This test requires the Python command to run the test server.
" This most likely only works on Unix and Windows.
if has('unix')
" We also need the job feature or the pkill command to make sure the server
" can be stopped.
if !(executable('python') && (has('job') || executable('pkill')))
return ''
endif
let s:python = 'python'
elseif has('win32')
" Use Python Launcher for Windows (py.exe) if available.
if executable('py.exe')
let s:python = 'py.exe'
elseif executable('python.exe')
let s:python = 'python.exe'
else
return ''
endif
else
return ''
endif
return s:python
endfunc
" Run "cmd". Returns the job if using a job.
func RunCommand(cmd)
" Running an external command can occasionally be slow or fail.
let g:test_is_flaky = 1
let job = 0
if has('job')
let job = job_start(a:cmd, {"stoponexit": "hup"})
call job_setoptions(job, {"stoponexit": "kill"})
elseif has('win32')
exe 'silent !start cmd /c start "test_channel" ' . a:cmd
else
exe 'silent !' . a:cmd . '&'
endif
return job
endfunc
" Read the port number from the Xportnr file.
func GetPort()
let l = []
" with 200 it sometimes failed
for i in range(400)
try
let l = readfile("Xportnr")
catch
endtry
if len(l) >= 1
break
endif
sleep 10m
endfor
call delete("Xportnr")
if len(l) == 0
" Can't make the connection, give up.
return 0
endif
return l[0]
endfunc
" Run a Python server for "cmd" and call "testfunc".
" Always kills the server before returning.
func RunServer(cmd, testfunc, args)
" The Python program writes the port number in Xportnr.
call delete("Xportnr")
if len(a:args) == 1
let arg = ' ' . a:args[0]
else
let arg = ''
endif
let pycmd = s:python . " " . a:cmd . arg
try
let g:currentJob = RunCommand(pycmd)
" Wait for up to 2 seconds for the port number to be there.
let port = GetPort()
if port == 0
call assert_false(1, "Can't start " . a:cmd)
return
endif
call call(function(a:testfunc), [port])
catch
call assert_false(1, 'Caught exception: "' . v:exception . '" in ' . v:throwpoint)
finally
call s:kill_server(a:cmd)
endtry
endfunc
func s:kill_server(cmd)
if has('job')
if exists('g:currentJob')
call job_stop(g:currentJob)
unlet g:currentJob
endif
elseif has('win32')
let cmd = substitute(a:cmd, ".py", '', '')
call system('taskkill /IM ' . s:python . ' /T /F /FI "WINDOWTITLE eq ' . cmd . '"')
else
call system("pkill -f " . a:cmd)
endif
endfunc
" Wait for up to five seconds for "expr" to become true. "expr" can be a
" stringified expression to evaluate, or a funcref without arguments.
" Using a lambda works best. Example:
" call WaitFor({-> status == "ok"})
"
" A second argument can be used to specify a different timeout in msec.
"
" When successful the time slept is returned.
" When running into the timeout an exception is thrown, thus the function does
" not return.
func WaitFor(expr, ...)
let timeout = get(a:000, 0, 5000)
let slept = s:WaitForCommon(a:expr, v:null, timeout)
if slept < 0
throw 'WaitFor() timed out after ' . timeout . ' msec'
endif
return slept
endfunc
" Wait for up to five seconds for "assert" to return zero. "assert" must be a
" (lambda) function containing one assert function. Example:
" call WaitForAssert({-> assert_equal("dead", job_status(job)})
"
" A second argument can be used to specify a different timeout in msec.
"
" Return zero for success, one for failure (like the assert function).
func WaitForAssert(assert, ...)
let timeout = get(a:000, 0, 5000)
if s:WaitForCommon(v:null, a:assert, timeout) < 0
return 1
endif
return 0
endfunc
" Common implementation of WaitFor() and WaitForAssert().
" Either "expr" or "assert" is not v:null
" Return the waiting time for success, -1 for failure.
func s:WaitForCommon(expr, assert, timeout)
" using reltime() is more accurate, but not always available
let slept = 0
if exists('*reltimefloat')
let start = reltime()
endif
while 1
if type(a:expr) == v:t_func
let success = a:expr()
elseif type(a:assert) == v:t_func
let success = a:assert() == 0
else
let success = eval(a:expr)
endif
if success
return slept
endif
if slept >= a:timeout
break
endif
if type(a:assert) == v:t_func
" Remove the error added by the assert function.
call remove(v:errors, -1)
endif
sleep 10m
if exists('*reltimefloat')
let slept = float2nr(reltimefloat(reltime(start)) * 1000)
else
let slept += 10
endif
endwhile
return -1 " timed out
endfunc
" Wait for up to a given milliseconds.
" With the +timers feature this waits for key-input by getchar(), Resume()
" feeds key-input and resumes process. Return time waited in milliseconds.
" Without +timers it uses simply :sleep.
func Standby(msec)
if has('timers') && exists('*reltimefloat')
let start = reltime()
let g:_standby_timer = timer_start(a:msec, function('s:feedkeys'))
call getchar()
return float2nr(reltimefloat(reltime(start)) * 1000)
else
execute 'sleep ' a:msec . 'm'
return a:msec
endif
endfunc
func Resume()
if exists('g:_standby_timer')
call timer_stop(g:_standby_timer)
call s:feedkeys(0)
unlet g:_standby_timer
endif
endfunc
func s:feedkeys(timer)
call feedkeys('x', 'nt')
endfunc
" Get $VIMPROG to run the Vim executable.
" The Makefile writes it as the first line in the "vimcmd" file.
" Nvim: uses $NVIM_TEST_ARG0.
func GetVimProg()
if empty($NVIM_TEST_ARG0)
" Assume the script was sourced instead of running "make".
return v:progpath
endif
if has('win32')
return substitute($NVIM_TEST_ARG0, '/', '\\', 'g')
else
return $NVIM_TEST_ARG0
endif
endfunc
let g:valgrind_cnt = 1
" Get the command to run Vim, with -u NONE and --headless arguments.
" If there is an argument use it instead of "NONE".
func GetVimCommand(...)
if a:0 == 0
let name = 'NONE'
else
let name = a:1
endif
let cmd = GetVimProg()
let cmd = substitute(cmd, '-u \f\+', '-u ' . name, '')
if cmd !~ '-u '. name
let cmd = cmd . ' -u ' . name
endif
let cmd .= ' --headless -i NONE'
let cmd = substitute(cmd, 'VIMRUNTIME=\S\+', '', '')
" If using valgrind, make sure every run uses a different log file.
if cmd =~ 'valgrind.*--log-file='
let cmd = substitute(cmd, '--log-file=\(\S*\)', '--log-file=\1.' . g:valgrind_cnt, '')
let g:valgrind_cnt += 1
endif
return cmd
endfunc
" Return one when it looks like the tests are run with valgrind, which means
" that everything is much slower.
func RunningWithValgrind()
return GetVimCommand() =~ '\<valgrind\>'
endfunc
" Get the command to run Vim, with --clean instead of "-u NONE".
func GetVimCommandClean()
let cmd = GetVimCommand()
let cmd = substitute(cmd, '-u NONE', '--clean', '')
let cmd = substitute(cmd, '--headless', '', '')
" Force using utf-8, Vim may pick up something else from the environment.
" let cmd ..= ' --cmd "set enc=utf8" '
" Optionally run Vim under valgrind
" let cmd = 'valgrind --tool=memcheck --leak-check=yes --num-callers=25 --log-file=valgrind ' . cmd
return cmd
endfunc
" Get the command to run Vim, with --clean, and force to run in terminal so it
" won't start a new GUI.
func GetVimCommandCleanTerm()
" Add -v to have gvim run in the terminal (if possible)
return GetVimCommandClean() .. ' -v '
endfunc
" Run Vim, using the "vimcmd" file and "-u NORC".
" "before" is a list of Vim commands to be executed before loading plugins.
" "after" is a list of Vim commands to be executed after loading plugins.
" Plugins are not loaded, unless 'loadplugins' is set in "before".
" Return 1 if Vim could be executed.
func RunVim(before, after, arguments)
return RunVimPiped(a:before, a:after, a:arguments, '')
endfunc
func RunVimPiped(before, after, arguments, pipecmd)
let cmd = GetVimCommand()
let args = ''
if len(a:before) > 0
call writefile(a:before, 'Xbefore.vim')
let args .= ' --cmd "so Xbefore.vim"'
endif
if len(a:after) > 0
call writefile(a:after, 'Xafter.vim')
let args .= ' -S Xafter.vim'
endif
" Optionally run Vim under valgrind
" let cmd = 'valgrind --tool=memcheck --leak-check=yes --num-callers=25 --log-file=valgrind ' . cmd
let $NVIM_LOG_FILE = exists($NVIM_LOG_FILE) ? $NVIM_LOG_FILE : 'Xnvim.log'
" Nvim does not support -Z flag, remove it.
exe "silent !" . a:pipecmd . cmd . args . ' ' . substitute(a:arguments, '-Z', '', 'g')
if len(a:before) > 0
call delete('Xbefore.vim')
endif
if len(a:after) > 0
call delete('Xafter.vim')
endif
return 1
endfunc
func IsRoot()
if !has('unix')
return v:false
elseif $USER == 'root' || system('id -un') =~ '\<root\>'
return v:true
endif
return v:false
endfunc
" Get all messages but drop the maintainer entry.
func GetMessages()
redir => result
redraw | messages
redir END
let msg_list = split(result, "\n")
" if msg_list->len() > 0 && msg_list[0] =~ 'Messages maintainer:'
" return msg_list[1:]
" endif
return msg_list
endfunc
" Run the list of commands in 'cmds' and look for 'errstr' in exception.
" Note that assert_fails() cannot be used in some places and this function
" can be used.
func AssertException(cmds, errstr)
let save_exception = ''
try
for cmd in a:cmds
exe cmd
endfor
catch
let save_exception = v:exception
endtry
call assert_match(a:errstr, save_exception)
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,10 +0,0 @@
fail() {
local test_name="$1"
local message="$2"
: "${message:=Test $test_name failed}"
local full_msg="$test_name :: $message"
echo "Failed: $full_msg"
export FAILED=1
}

View File

@@ -1,62 +0,0 @@
set cpo&vim
if 1
" This is executed only with the eval feature
set nocompatible
set viminfo=
func Count(match, type)
if a:type ==# 'executed'
let g:executed += (a:match+0)
elseif a:type ==# 'failed'
let g:failed += a:match+0
elseif a:type ==# 'skipped'
let g:skipped += 1
call extend(g:skipped_output, ["\t" .. a:match])
endif
endfunc
let g:executed = 0
let g:skipped = 0
let g:failed = 0
let g:skipped_output = []
let g:failed_output = []
let output = [""]
if $TEST_FILTER != ''
call extend(g:skipped_output, ["\tAll tests not matching $TEST_FILTER: '" .. $TEST_FILTER .. "'"])
endif
try
" This uses the :s command to just fetch and process the output of the
" tests, it doesn't actually replace anything.
" And it uses "silent" to avoid reporting the number of matches.
silent %s/Executed\s\+\zs\d\+\ze\s\+tests\?/\=Count(submatch(0),'executed')/egn
silent %s/^SKIPPED \zs.*/\=Count(submatch(0), 'skipped')/egn
silent %s/^\(\d\+\)\s\+FAILED:/\=Count(submatch(1), 'failed')/egn
call extend(output, ["Skipped:"])
call extend(output, skipped_output)
call extend(output, [
\ "",
\ "-------------------------------",
\ printf("Executed: %5d Tests", g:executed),
\ printf(" Skipped: %5d Tests", g:skipped),
\ printf(" %s: %5d Tests", g:failed == 0 ? 'Failed' : 'FAILED', g:failed),
\ "",
\ ])
if filereadable('test.log')
" outputs and indents the failed test result
call extend(output, ["", "Failures: "])
let failed_output = filter(readfile('test.log'), { v,k -> !empty(k)})
call extend(output, map(failed_output, { v,k -> "\t".k}))
" Add a final newline
call extend(output, [""])
endif
catch " Catch-all
finally
call writefile(output, 'test_result.log') " overwrites an existing file
endtry
endif
q!

View File

@@ -1,13 +0,0 @@
" Functions about terminal shared by several tests
" Only load this script once.
if exists('*CanRunVimInTerminal')
finish
endif
func CanRunVimInTerminal()
" Nvim: always false, we use Lua screen-tests instead.
return 0
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,91 +0,0 @@
fail() {
local test_name="$1"
local message="$2"
: "${message:=Test $test_name failed}"
local full_msg="$test_name :: $message"
echo "Failed: $full_msg"
export FAILED=1
}
print_core() {
local app="$1"
local core="$2"
if test "$app" = quiet ; then
echo "Found core $core"
return 0
fi
echo "======= Core file $core ======="
if test "${CI_OS_NAME}" = osx ; then
lldb -Q -o "bt all" -f "${app}" -c "${core}"
else
gdb -n -batch -ex 'thread apply all bt full' "${app}" -c "${core}"
fi
}
check_core_dumps() {
local del=
if test "$1" = "--delete" ; then
del=1
shift
fi
local app="${1:-${BUILD_DIR}/bin/nvim}"
local cores
if test "${CI_OS_NAME}" = osx ; then
cores="$(find /cores/ -type f -print)"
local _sudo='sudo'
else
cores="$(find ./ -type f \( -name 'core.*' -o -name core -o -name nvim.core \) -print)"
local _sudo=
fi
if test -z "${cores}" ; then
return
fi
local core
for core in $cores; do
if test "$del" = "1" ; then
print_core "$app" "$core" >&2
"$_sudo" rm "$core"
else
print_core "$app" "$core"
fi
done
if test "$app" != quiet ; then
fail 'cores' 'Core dumps found'
fi
}
check_logs() {
# Iterate through each log to remove an useless warning.
# shellcheck disable=SC2044
for log in $(find "${1}" -type f -name "${2}"); do
sed -i "${log}" \
-e '/Warning: noted but unhandled ioctl/d' \
-e '/could cause spurious value errors to appear/d' \
-e '/See README_MISSING_SYSCALL_OR_IOCTL for guidance/d'
done
# Now do it again, but only consider files with size > 0.
local err=""
# shellcheck disable=SC2044
for log in $(find "${1}" -type f -name "${2}" -size +0); do
cat "${log}"
err=1
rm "${log}"
done
if test -n "${err}" ; then
fail 'logs' 'Runtime errors detected.'
fi
}
valgrind_check() {
check_logs "${1}" "valgrind-*"
}
check_sanitizer() {
if test -n "${CLANG_SANITIZER}"; then
check_logs "${1}" "*san.*" | cat
fi
}

View File

@@ -1,13 +0,0 @@
First a simple test to check if the test script works.
STARTTEST
:" If columns or lines are too small, create wrongtermsize.
:" (Some tests will fail. When columns and/or lines are small)
:if &lines < 24 || &columns < 80 | sp another | w! wrongtermsize | qa! | endif
:"
:" Write a single line to test.out to check if testing works at all.
:%d
athis is a test:w! test.out
:qa!
ENDTEST

View File

@@ -1 +0,0 @@
this is a test

View File

@@ -1,31 +0,0 @@
" A series of tests that can run in one Vim invocation.
" This makes testing go faster, since Vim doesn't need to restart.
source test_backup.vim
source test_behave.vim
source test_compiler.vim
source test_ex_equal.vim
source test_ex_undo.vim
source test_ex_z.vim
source test_ex_mode.vim
source test_expand.vim
source test_expand_func.vim
source test_file_perm.vim
source test_fnamemodify.vim
source test_ga.vim
source test_glob2regpat.vim
source test_global.vim
source test_move.vim
source test_put.vim
source test_reltime.vim
source test_scroll_opt.vim
source test_searchpos.vim
source test_set.vim
source test_shift.vim
source test_sha256.vim
source test_tabline.vim
source test_tagcase.vim
source test_tagfunc.vim
source test_unlet.vim
source test_version.vim
source test_wnext.vim

View File

@@ -1,7 +0,0 @@
" A series of tests that can run in one Vim invocation.
" This makes testing go faster, since Vim doesn't need to restart.
" These tests use latin1 'encoding'. Setting 'encoding' is in the individual
" files, so that they can be run by themselves.
source test_regexp_latin.vim

View File

@@ -1,14 +0,0 @@
" A series of tests that can run in one Vim invocation.
" This makes testing go faster, since Vim doesn't need to restart.
" These tests use utf8 'encoding'. Setting 'encoding' is already done in
" runtest.vim.
source test_charsearch_utf8.vim
source test_expr_utf8.vim
source test_mksession_utf8.vim
source test_regexp_utf8.vim
source test_source_utf8.vim
source test_startup_utf8.vim
source test_utf8.vim
source test_utf8_comparisons.vim

View File

@@ -1,587 +0,0 @@
" Simplistic testing of Arabic mode.
" NOTE: This just checks if the code works. If you know Arabic please add
" functional tests that check the shaping works with real text.
source check.vim
CheckFeature arabic
source view_util.vim
" Return list of Unicode characters at line lnum.
" Combining characters are treated as a single item.
func s:get_chars(lnum)
call cursor(a:lnum, 1)
let chars = []
let numchars = strchars(getline('.'), 1)
for i in range(1, numchars)
exe 'norm ' i . '|'
let c = execute('ascii')
let c = substitute(c, '\n\?<.\{-}Hex\s*', 'U+', 'g')
let c = substitute(c, ',\s*Oct\(al\)\=\s\d*\(, Digr ..\)\=', '', 'g')
call add(chars, c)
endfor
return chars
endfunc
func Test_arabic_toggle()
set arabic
call assert_equal(1, &rightleft)
call assert_equal(1, &arabicshape)
call assert_equal('arabic', &keymap)
call assert_equal(1, &delcombine)
set iminsert=1 imsearch=1
set arabic&
call assert_equal(0, &rightleft)
call assert_equal(1, &arabicshape)
call assert_equal('arabic', &keymap)
call assert_equal(1, &delcombine)
call assert_equal(0, &iminsert)
call assert_equal(-1, &imsearch)
set arabicshape& keymap= delcombine&
endfunc
func Test_arabic_input()
new
set arabic
" Typing sghl in Arabic insert mode should show the
" Arabic word 'Salaam' i.e. 'peace', spelled:
" SEEN, LAM, ALEF, MEEM.
" See: https://www.mediawiki.org/wiki/VisualEditor/Typing/Right-to-left
call feedkeys('isghl!', 'tx')
call assert_match("^ *!\uFEE1\uFEFC\uFEB3$", ScreenLines(1, &columns)[0])
call assert_equal([
\ 'U+0633',
\ 'U+0644 U+0627',
\ 'U+0645',
\ 'U+21'], s:get_chars(1))
" Without shaping, it should give individual Arabic letters.
set noarabicshape
call assert_match("^ *!\u0645\u0627\u0644\u0633$", ScreenLines(1, &columns)[0])
call assert_equal([
\ 'U+0633',
\ 'U+0644',
\ 'U+0627',
\ 'U+0645',
\ 'U+21'], s:get_chars(1))
set arabic& arabicshape&
bwipe!
endfunc
func Test_arabic_toggle_keymap()
new
set arabic
call feedkeys("i12\<C-^>12\<C-^>12", 'tx')
call assert_match("^ *٢١21٢١$", ScreenLines(1, &columns)[0])
call assert_equal('١٢12١٢', getline('.'))
set arabic&
bwipe!
endfunc
func Test_delcombine()
new
set arabic
call feedkeys("isghl\<BS>\<BS>", 'tx')
call assert_match("^ *\uFEDE\uFEB3$", ScreenLines(1, &columns)[0])
call assert_equal(['U+0633', 'U+0644'], s:get_chars(1))
" Now the same with 'nodelcombine'
set nodelcombine
%d
call feedkeys("isghl\<BS>\<BS>", 'tx')
call assert_match("^ *\uFEB1$", ScreenLines(1, &columns)[0])
call assert_equal(['U+0633'], s:get_chars(1))
set arabic&
bwipe!
endfunc
" Values from src/arabic.h (not all used yet)
let s:a_COMMA = "\u060C"
let s:a_SEMICOLON = "\u061B"
let s:a_QUESTION = "\u061F"
let s:a_HAMZA = "\u0621"
let s:a_ALEF_MADDA = "\u0622"
let s:a_ALEF_HAMZA_ABOVE = "\u0623"
let s:a_WAW_HAMZA = "\u0624"
let s:a_ALEF_HAMZA_BELOW = "\u0625"
let s:a_YEH_HAMZA = "\u0626"
let s:a_ALEF = "\u0627"
let s:a_BEH = "\u0628"
let s:a_TEH_MARBUTA = "\u0629"
let s:a_TEH = "\u062a"
let s:a_THEH = "\u062b"
let s:a_JEEM = "\u062c"
let s:a_HAH = "\u062d"
let s:a_KHAH = "\u062e"
let s:a_DAL = "\u062f"
let s:a_THAL = "\u0630"
let s:a_REH = "\u0631"
let s:a_ZAIN = "\u0632"
let s:a_SEEN = "\u0633"
let s:a_SHEEN = "\u0634"
let s:a_SAD = "\u0635"
let s:a_DAD = "\u0636"
let s:a_TAH = "\u0637"
let s:a_ZAH = "\u0638"
let s:a_AIN = "\u0639"
let s:a_GHAIN = "\u063a"
let s:a_TATWEEL = "\u0640"
let s:a_FEH = "\u0641"
let s:a_QAF = "\u0642"
let s:a_KAF = "\u0643"
let s:a_LAM = "\u0644"
let s:a_MEEM = "\u0645"
let s:a_NOON = "\u0646"
let s:a_HEH = "\u0647"
let s:a_WAW = "\u0648"
let s:a_ALEF_MAKSURA = "\u0649"
let s:a_YEH = "\u064a"
let s:a_FATHATAN = "\u064b"
let s:a_DAMMATAN = "\u064c"
let s:a_KASRATAN = "\u064d"
let s:a_FATHA = "\u064e"
let s:a_DAMMA = "\u064f"
let s:a_KASRA = "\u0650"
let s:a_SHADDA = "\u0651"
let s:a_SUKUN = "\u0652"
let s:a_MADDA_ABOVE = "\u0653"
let s:a_HAMZA_ABOVE = "\u0654"
let s:a_HAMZA_BELOW = "\u0655"
let s:a_ZERO = "\u0660"
let s:a_ONE = "\u0661"
let s:a_TWO = "\u0662"
let s:a_THREE = "\u0663"
let s:a_FOUR = "\u0664"
let s:a_FIVE = "\u0665"
let s:a_SIX = "\u0666"
let s:a_SEVEN = "\u0667"
let s:a_EIGHT = "\u0668"
let s:a_NINE = "\u0669"
let s:a_PERCENT = "\u066a"
let s:a_DECIMAL = "\u066b"
let s:a_THOUSANDS = "\u066c"
let s:a_STAR = "\u066d"
let s:a_MINI_ALEF = "\u0670"
let s:a_s_FATHATAN = "\ufe70"
let s:a_m_TATWEEL_FATHATAN = "\ufe71"
let s:a_s_DAMMATAN = "\ufe72"
let s:a_s_KASRATAN = "\ufe74"
let s:a_s_FATHA = "\ufe76"
let s:a_m_FATHA = "\ufe77"
let s:a_s_DAMMA = "\ufe78"
let s:a_m_DAMMA = "\ufe79"
let s:a_s_KASRA = "\ufe7a"
let s:a_m_KASRA = "\ufe7b"
let s:a_s_SHADDA = "\ufe7c"
let s:a_m_SHADDA = "\ufe7d"
let s:a_s_SUKUN = "\ufe7e"
let s:a_m_SUKUN = "\ufe7f"
let s:a_s_HAMZA = "\ufe80"
let s:a_s_ALEF_MADDA = "\ufe81"
let s:a_f_ALEF_MADDA = "\ufe82"
let s:a_s_ALEF_HAMZA_ABOVE = "\ufe83"
let s:a_f_ALEF_HAMZA_ABOVE = "\ufe84"
let s:a_s_WAW_HAMZA = "\ufe85"
let s:a_f_WAW_HAMZA = "\ufe86"
let s:a_s_ALEF_HAMZA_BELOW = "\ufe87"
let s:a_f_ALEF_HAMZA_BELOW = "\ufe88"
let s:a_s_YEH_HAMZA = "\ufe89"
let s:a_f_YEH_HAMZA = "\ufe8a"
let s:a_i_YEH_HAMZA = "\ufe8b"
let s:a_m_YEH_HAMZA = "\ufe8c"
let s:a_s_ALEF = "\ufe8d"
let s:a_f_ALEF = "\ufe8e"
let s:a_s_BEH = "\ufe8f"
let s:a_f_BEH = "\ufe90"
let s:a_i_BEH = "\ufe91"
let s:a_m_BEH = "\ufe92"
let s:a_s_TEH_MARBUTA = "\ufe93"
let s:a_f_TEH_MARBUTA = "\ufe94"
let s:a_s_TEH = "\ufe95"
let s:a_f_TEH = "\ufe96"
let s:a_i_TEH = "\ufe97"
let s:a_m_TEH = "\ufe98"
let s:a_s_THEH = "\ufe99"
let s:a_f_THEH = "\ufe9a"
let s:a_i_THEH = "\ufe9b"
let s:a_m_THEH = "\ufe9c"
let s:a_s_JEEM = "\ufe9d"
let s:a_f_JEEM = "\ufe9e"
let s:a_i_JEEM = "\ufe9f"
let s:a_m_JEEM = "\ufea0"
let s:a_s_HAH = "\ufea1"
let s:a_f_HAH = "\ufea2"
let s:a_i_HAH = "\ufea3"
let s:a_m_HAH = "\ufea4"
let s:a_s_KHAH = "\ufea5"
let s:a_f_KHAH = "\ufea6"
let s:a_i_KHAH = "\ufea7"
let s:a_m_KHAH = "\ufea8"
let s:a_s_DAL = "\ufea9"
let s:a_f_DAL = "\ufeaa"
let s:a_s_THAL = "\ufeab"
let s:a_f_THAL = "\ufeac"
let s:a_s_REH = "\ufead"
let s:a_f_REH = "\ufeae"
let s:a_s_ZAIN = "\ufeaf"
let s:a_f_ZAIN = "\ufeb0"
let s:a_s_SEEN = "\ufeb1"
let s:a_f_SEEN = "\ufeb2"
let s:a_i_SEEN = "\ufeb3"
let s:a_m_SEEN = "\ufeb4"
let s:a_s_SHEEN = "\ufeb5"
let s:a_f_SHEEN = "\ufeb6"
let s:a_i_SHEEN = "\ufeb7"
let s:a_m_SHEEN = "\ufeb8"
let s:a_s_SAD = "\ufeb9"
let s:a_f_SAD = "\ufeba"
let s:a_i_SAD = "\ufebb"
let s:a_m_SAD = "\ufebc"
let s:a_s_DAD = "\ufebd"
let s:a_f_DAD = "\ufebe"
let s:a_i_DAD = "\ufebf"
let s:a_m_DAD = "\ufec0"
let s:a_s_TAH = "\ufec1"
let s:a_f_TAH = "\ufec2"
let s:a_i_TAH = "\ufec3"
let s:a_m_TAH = "\ufec4"
let s:a_s_ZAH = "\ufec5"
let s:a_f_ZAH = "\ufec6"
let s:a_i_ZAH = "\ufec7"
let s:a_m_ZAH = "\ufec8"
let s:a_s_AIN = "\ufec9"
let s:a_f_AIN = "\ufeca"
let s:a_i_AIN = "\ufecb"
let s:a_m_AIN = "\ufecc"
let s:a_s_GHAIN = "\ufecd"
let s:a_f_GHAIN = "\ufece"
let s:a_i_GHAIN = "\ufecf"
let s:a_m_GHAIN = "\ufed0"
let s:a_s_FEH = "\ufed1"
let s:a_f_FEH = "\ufed2"
let s:a_i_FEH = "\ufed3"
let s:a_m_FEH = "\ufed4"
let s:a_s_QAF = "\ufed5"
let s:a_f_QAF = "\ufed6"
let s:a_i_QAF = "\ufed7"
let s:a_m_QAF = "\ufed8"
let s:a_s_KAF = "\ufed9"
let s:a_f_KAF = "\ufeda"
let s:a_i_KAF = "\ufedb"
let s:a_m_KAF = "\ufedc"
let s:a_s_LAM = "\ufedd"
let s:a_f_LAM = "\ufede"
let s:a_i_LAM = "\ufedf"
let s:a_m_LAM = "\ufee0"
let s:a_s_MEEM = "\ufee1"
let s:a_f_MEEM = "\ufee2"
let s:a_i_MEEM = "\ufee3"
let s:a_m_MEEM = "\ufee4"
let s:a_s_NOON = "\ufee5"
let s:a_f_NOON = "\ufee6"
let s:a_i_NOON = "\ufee7"
let s:a_m_NOON = "\ufee8"
let s:a_s_HEH = "\ufee9"
let s:a_f_HEH = "\ufeea"
let s:a_i_HEH = "\ufeeb"
let s:a_m_HEH = "\ufeec"
let s:a_s_WAW = "\ufeed"
let s:a_f_WAW = "\ufeee"
let s:a_s_ALEF_MAKSURA = "\ufeef"
let s:a_f_ALEF_MAKSURA = "\ufef0"
let s:a_s_YEH = "\ufef1"
let s:a_f_YEH = "\ufef2"
let s:a_i_YEH = "\ufef3"
let s:a_m_YEH = "\ufef4"
let s:a_s_LAM_ALEF_MADDA_ABOVE = "\ufef5"
let s:a_f_LAM_ALEF_MADDA_ABOVE = "\ufef6"
let s:a_s_LAM_ALEF_HAMZA_ABOVE = "\ufef7"
let s:a_f_LAM_ALEF_HAMZA_ABOVE = "\ufef8"
let s:a_s_LAM_ALEF_HAMZA_BELOW = "\ufef9"
let s:a_f_LAM_ALEF_HAMZA_BELOW = "\ufefa"
let s:a_s_LAM_ALEF = "\ufefb"
let s:a_f_LAM_ALEF = "\ufefc"
let s:a_BYTE_ORDER_MARK = "\ufeff"
func Test_shape_initial()
new
set arabicshape
" Shaping arabic {testchar} non-arabic Tests chg_c_a2i().
" pair[0] = testchar, pair[1] = next-result, pair[2] = current-result
for pair in [[s:a_YEH_HAMZA, s:a_f_GHAIN, s:a_i_YEH_HAMZA],
\ [s:a_HAMZA, s:a_s_GHAIN, s:a_s_HAMZA],
\ [s:a_ALEF_MADDA, s:a_s_GHAIN, s:a_s_ALEF_MADDA],
\ [s:a_ALEF_HAMZA_ABOVE, s:a_s_GHAIN, s:a_s_ALEF_HAMZA_ABOVE],
\ [s:a_WAW_HAMZA, s:a_s_GHAIN, s:a_s_WAW_HAMZA],
\ [s:a_ALEF_HAMZA_BELOW, s:a_s_GHAIN, s:a_s_ALEF_HAMZA_BELOW],
\ [s:a_ALEF, s:a_s_GHAIN, s:a_s_ALEF],
\ [s:a_TEH_MARBUTA, s:a_s_GHAIN, s:a_s_TEH_MARBUTA],
\ [s:a_DAL, s:a_s_GHAIN, s:a_s_DAL],
\ [s:a_THAL, s:a_s_GHAIN, s:a_s_THAL],
\ [s:a_REH, s:a_s_GHAIN, s:a_s_REH],
\ [s:a_ZAIN, s:a_s_GHAIN, s:a_s_ZAIN],
\ [s:a_TATWEEL, s:a_f_GHAIN, s:a_TATWEEL],
\ [s:a_WAW, s:a_s_GHAIN, s:a_s_WAW],
\ [s:a_ALEF_MAKSURA, s:a_s_GHAIN, s:a_s_ALEF_MAKSURA],
\ [s:a_BEH, s:a_f_GHAIN, s:a_i_BEH],
\ [s:a_TEH, s:a_f_GHAIN, s:a_i_TEH],
\ [s:a_THEH, s:a_f_GHAIN, s:a_i_THEH],
\ [s:a_JEEM, s:a_f_GHAIN, s:a_i_JEEM],
\ [s:a_HAH, s:a_f_GHAIN, s:a_i_HAH],
\ [s:a_KHAH, s:a_f_GHAIN, s:a_i_KHAH],
\ [s:a_SEEN, s:a_f_GHAIN, s:a_i_SEEN],
\ [s:a_SHEEN, s:a_f_GHAIN, s:a_i_SHEEN],
\ [s:a_SAD, s:a_f_GHAIN, s:a_i_SAD],
\ [s:a_DAD, s:a_f_GHAIN, s:a_i_DAD],
\ [s:a_TAH, s:a_f_GHAIN, s:a_i_TAH],
\ [s:a_ZAH, s:a_f_GHAIN, s:a_i_ZAH],
\ [s:a_AIN, s:a_f_GHAIN, s:a_i_AIN],
\ [s:a_GHAIN, s:a_f_GHAIN, s:a_i_GHAIN],
\ [s:a_FEH, s:a_f_GHAIN, s:a_i_FEH],
\ [s:a_QAF, s:a_f_GHAIN, s:a_i_QAF],
\ [s:a_KAF, s:a_f_GHAIN, s:a_i_KAF],
\ [s:a_LAM, s:a_f_GHAIN, s:a_i_LAM],
\ [s:a_MEEM, s:a_f_GHAIN, s:a_i_MEEM],
\ [s:a_NOON, s:a_f_GHAIN, s:a_i_NOON],
\ [s:a_HEH, s:a_f_GHAIN, s:a_i_HEH],
\ [s:a_YEH, s:a_f_GHAIN, s:a_i_YEH],
\ ]
call setline(1, s:a_GHAIN . pair[0] . ' ')
call assert_equal([pair[1] . pair[2] . ' '], ScreenLines(1, 3))
endfor
set arabicshape&
bwipe!
endfunc
func Test_shape_isolated()
new
set arabicshape
" Shaping non-arabic {testchar} non-arabic Tests chg_c_a2s().
" pair[0] = testchar, pair[1] = current-result
for pair in [[s:a_HAMZA, s:a_s_HAMZA],
\ [s:a_ALEF_MADDA, s:a_s_ALEF_MADDA],
\ [s:a_ALEF_HAMZA_ABOVE, s:a_s_ALEF_HAMZA_ABOVE],
\ [s:a_WAW_HAMZA, s:a_s_WAW_HAMZA],
\ [s:a_ALEF_HAMZA_BELOW, s:a_s_ALEF_HAMZA_BELOW],
\ [s:a_YEH_HAMZA, s:a_s_YEH_HAMZA],
\ [s:a_ALEF, s:a_s_ALEF],
\ [s:a_TEH_MARBUTA, s:a_s_TEH_MARBUTA],
\ [s:a_DAL, s:a_s_DAL],
\ [s:a_THAL, s:a_s_THAL],
\ [s:a_REH, s:a_s_REH],
\ [s:a_ZAIN, s:a_s_ZAIN],
\ [s:a_TATWEEL, s:a_TATWEEL],
\ [s:a_WAW, s:a_s_WAW],
\ [s:a_ALEF_MAKSURA, s:a_s_ALEF_MAKSURA],
\ [s:a_BEH, s:a_s_BEH],
\ [s:a_TEH, s:a_s_TEH],
\ [s:a_THEH, s:a_s_THEH],
\ [s:a_JEEM, s:a_s_JEEM],
\ [s:a_HAH, s:a_s_HAH],
\ [s:a_KHAH, s:a_s_KHAH],
\ [s:a_SEEN, s:a_s_SEEN],
\ [s:a_SHEEN, s:a_s_SHEEN],
\ [s:a_SAD, s:a_s_SAD],
\ [s:a_DAD, s:a_s_DAD],
\ [s:a_TAH, s:a_s_TAH],
\ [s:a_ZAH, s:a_s_ZAH],
\ [s:a_AIN, s:a_s_AIN],
\ [s:a_GHAIN, s:a_s_GHAIN],
\ [s:a_FEH, s:a_s_FEH],
\ [s:a_QAF, s:a_s_QAF],
\ [s:a_KAF, s:a_s_KAF],
\ [s:a_LAM, s:a_s_LAM],
\ [s:a_MEEM, s:a_s_MEEM],
\ [s:a_NOON, s:a_s_NOON],
\ [s:a_HEH, s:a_s_HEH],
\ [s:a_YEH, s:a_s_YEH],
\ ]
call setline(1, ' ' . pair[0] . ' ')
call assert_equal([' ' . pair[1] . ' '], ScreenLines(1, 3))
endfor
set arabicshape&
bwipe!
endfunc
func Test_shape_iso_to_medial()
new
set arabicshape
" Shaping arabic {testchar} arabic Tests chg_c_a2m().
" pair[0] = testchar, pair[1] = next-result, pair[2] = current-result,
" pair[3] = previous-result
for pair in [[s:a_HAMZA, s:a_s_GHAIN, s:a_s_HAMZA, s:a_s_BEH],
\[s:a_ALEF_MADDA, s:a_s_GHAIN, s:a_f_ALEF_MADDA, s:a_i_BEH],
\[s:a_ALEF_HAMZA_ABOVE, s:a_s_GHAIN, s:a_f_ALEF_HAMZA_ABOVE, s:a_i_BEH],
\[s:a_WAW_HAMZA, s:a_s_GHAIN, s:a_f_WAW_HAMZA, s:a_i_BEH],
\[s:a_ALEF_HAMZA_BELOW, s:a_s_GHAIN, s:a_f_ALEF_HAMZA_BELOW, s:a_i_BEH],
\[s:a_YEH_HAMZA, s:a_f_GHAIN, s:a_m_YEH_HAMZA, s:a_i_BEH],
\[s:a_ALEF, s:a_s_GHAIN, s:a_f_ALEF, s:a_i_BEH],
\[s:a_BEH, s:a_f_GHAIN, s:a_m_BEH, s:a_i_BEH],
\[s:a_TEH_MARBUTA, s:a_s_GHAIN, s:a_f_TEH_MARBUTA, s:a_i_BEH],
\[s:a_TEH, s:a_f_GHAIN, s:a_m_TEH, s:a_i_BEH],
\[s:a_THEH, s:a_f_GHAIN, s:a_m_THEH, s:a_i_BEH],
\[s:a_JEEM, s:a_f_GHAIN, s:a_m_JEEM, s:a_i_BEH],
\[s:a_HAH, s:a_f_GHAIN, s:a_m_HAH, s:a_i_BEH],
\[s:a_KHAH, s:a_f_GHAIN, s:a_m_KHAH, s:a_i_BEH],
\[s:a_DAL, s:a_s_GHAIN, s:a_f_DAL, s:a_i_BEH],
\[s:a_THAL, s:a_s_GHAIN, s:a_f_THAL, s:a_i_BEH],
\[s:a_REH, s:a_s_GHAIN, s:a_f_REH, s:a_i_BEH],
\[s:a_ZAIN, s:a_s_GHAIN, s:a_f_ZAIN, s:a_i_BEH],
\[s:a_SEEN, s:a_f_GHAIN, s:a_m_SEEN, s:a_i_BEH],
\[s:a_SHEEN, s:a_f_GHAIN, s:a_m_SHEEN, s:a_i_BEH],
\[s:a_SAD, s:a_f_GHAIN, s:a_m_SAD, s:a_i_BEH],
\[s:a_DAD, s:a_f_GHAIN, s:a_m_DAD, s:a_i_BEH],
\[s:a_TAH, s:a_f_GHAIN, s:a_m_TAH, s:a_i_BEH],
\[s:a_ZAH, s:a_f_GHAIN, s:a_m_ZAH, s:a_i_BEH],
\[s:a_AIN, s:a_f_GHAIN, s:a_m_AIN, s:a_i_BEH],
\[s:a_GHAIN, s:a_f_GHAIN, s:a_m_GHAIN, s:a_i_BEH],
\[s:a_TATWEEL, s:a_f_GHAIN, s:a_TATWEEL, s:a_i_BEH],
\[s:a_FEH, s:a_f_GHAIN, s:a_m_FEH, s:a_i_BEH],
\[s:a_QAF, s:a_f_GHAIN, s:a_m_QAF, s:a_i_BEH],
\[s:a_KAF, s:a_f_GHAIN, s:a_m_KAF, s:a_i_BEH],
\[s:a_LAM, s:a_f_GHAIN, s:a_m_LAM, s:a_i_BEH],
\[s:a_MEEM, s:a_f_GHAIN, s:a_m_MEEM, s:a_i_BEH],
\[s:a_NOON, s:a_f_GHAIN, s:a_m_NOON, s:a_i_BEH],
\[s:a_HEH, s:a_f_GHAIN, s:a_m_HEH, s:a_i_BEH],
\[s:a_WAW, s:a_s_GHAIN, s:a_f_WAW, s:a_i_BEH],
\[s:a_ALEF_MAKSURA, s:a_s_GHAIN, s:a_f_ALEF_MAKSURA, s:a_i_BEH],
\[s:a_YEH, s:a_f_GHAIN, s:a_m_YEH, s:a_i_BEH],
\ ]
call setline(1, s:a_GHAIN . pair[0] . s:a_BEH)
call assert_equal([pair[1] . pair[2] . pair[3]], ScreenLines(1, 3))
endfor
set arabicshape&
bwipe!
endfunc
func Test_shape_final()
new
set arabicshape
" Shaping arabic {testchar} arabic Tests chg_c_a2f().
" pair[0] = testchar, pair[1] = current-result, pair[2] = previous-result
for pair in [[s:a_HAMZA, s:a_s_HAMZA, s:a_s_BEH],
\[s:a_ALEF_MADDA, s:a_f_ALEF_MADDA, s:a_i_BEH],
\[s:a_ALEF_HAMZA_ABOVE, s:a_f_ALEF_HAMZA_ABOVE, s:a_i_BEH],
\[s:a_WAW_HAMZA, s:a_f_WAW_HAMZA, s:a_i_BEH],
\[s:a_ALEF_HAMZA_BELOW, s:a_f_ALEF_HAMZA_BELOW, s:a_i_BEH],
\[s:a_YEH_HAMZA, s:a_f_YEH_HAMZA, s:a_i_BEH],
\[s:a_ALEF, s:a_f_ALEF, s:a_i_BEH],
\[s:a_BEH, s:a_f_BEH, s:a_i_BEH],
\[s:a_TEH_MARBUTA, s:a_f_TEH_MARBUTA, s:a_i_BEH],
\[s:a_TEH, s:a_f_TEH, s:a_i_BEH],
\[s:a_THEH, s:a_f_THEH, s:a_i_BEH],
\[s:a_JEEM, s:a_f_JEEM, s:a_i_BEH],
\[s:a_HAH, s:a_f_HAH, s:a_i_BEH],
\[s:a_KHAH, s:a_f_KHAH, s:a_i_BEH],
\[s:a_DAL, s:a_f_DAL, s:a_i_BEH],
\[s:a_THAL, s:a_f_THAL, s:a_i_BEH],
\[s:a_REH, s:a_f_REH, s:a_i_BEH],
\[s:a_ZAIN, s:a_f_ZAIN, s:a_i_BEH],
\[s:a_SEEN, s:a_f_SEEN, s:a_i_BEH],
\[s:a_SHEEN, s:a_f_SHEEN, s:a_i_BEH],
\[s:a_SAD, s:a_f_SAD, s:a_i_BEH],
\[s:a_DAD, s:a_f_DAD, s:a_i_BEH],
\[s:a_TAH, s:a_f_TAH, s:a_i_BEH],
\[s:a_ZAH, s:a_f_ZAH, s:a_i_BEH],
\[s:a_AIN, s:a_f_AIN, s:a_i_BEH],
\[s:a_GHAIN, s:a_f_GHAIN, s:a_i_BEH],
\[s:a_TATWEEL, s:a_TATWEEL, s:a_i_BEH],
\[s:a_FEH, s:a_f_FEH, s:a_i_BEH],
\[s:a_QAF, s:a_f_QAF, s:a_i_BEH],
\[s:a_KAF, s:a_f_KAF, s:a_i_BEH],
\[s:a_LAM, s:a_f_LAM, s:a_i_BEH],
\[s:a_MEEM, s:a_f_MEEM, s:a_i_BEH],
\[s:a_NOON, s:a_f_NOON, s:a_i_BEH],
\[s:a_HEH, s:a_f_HEH, s:a_i_BEH],
\[s:a_WAW, s:a_f_WAW, s:a_i_BEH],
\[s:a_ALEF_MAKSURA, s:a_f_ALEF_MAKSURA, s:a_i_BEH],
\[s:a_YEH, s:a_f_YEH, s:a_i_BEH],
\ ]
call setline(1, ' ' . pair[0] . s:a_BEH)
call assert_equal([' ' . pair[1] . pair[2]], ScreenLines(1, 3))
endfor
set arabicshape&
bwipe!
endfunc
func Test_shape_combination_final()
new
set arabicshape
" Shaping arabic {testchar} arabic Tests chg_c_laa2f().
" pair[0] = testchar, pair[1] = current-result
for pair in [[s:a_ALEF_MADDA, s:a_f_LAM_ALEF_MADDA_ABOVE],
\ [s:a_ALEF_HAMZA_ABOVE, s:a_f_LAM_ALEF_HAMZA_ABOVE],
\ [s:a_ALEF_HAMZA_BELOW, s:a_f_LAM_ALEF_HAMZA_BELOW],
\ [s:a_ALEF, s:a_f_LAM_ALEF],
\ ]
" The test char is a composing char, put on s:a_LAM.
call setline(1, ' ' . s:a_LAM . pair[0] . s:a_BEH)
call assert_equal([' ' . pair[1] . s:a_i_BEH], ScreenLines(1, 3))
endfor
set arabicshape&
bwipe!
endfunc
func Test_shape_combination_isolated()
new
set arabicshape
" Shaping arabic {testchar} arabic Tests chg_c_laa2i().
" pair[0] = testchar, pair[1] = current-result
for pair in [[s:a_ALEF_MADDA, s:a_s_LAM_ALEF_MADDA_ABOVE],
\ [s:a_ALEF_HAMZA_ABOVE, s:a_s_LAM_ALEF_HAMZA_ABOVE],
\ [s:a_ALEF_HAMZA_BELOW, s:a_s_LAM_ALEF_HAMZA_BELOW],
\ [s:a_ALEF, s:a_s_LAM_ALEF],
\ ]
" The test char is a composing char, put on s:a_LAM.
call setline(1, ' ' . s:a_LAM . pair[0] . ' ')
call assert_equal([' ' . pair[1] . ' '], ScreenLines(1, 3))
endfor
set arabicshape&
bwipe!
endfunc
" Test for entering arabic character in a search command
func Test_arabic_chars_in_search_cmd()
new
set arabic
call feedkeys("i\nsghl!\<C-^>vim\<C-^>", 'tx')
call cursor(1, 1)
call feedkeys("/^sghl!\<C-^>vim$\<C-^>\<CR>", 'tx')
call assert_equal([2, 1], [line('.'), col('.')])
" Try searching in left-to-right mode
set rightleftcmd=
call cursor(1, 1)
call feedkeys("/^sghl!\<C-^>vim$\<CR>", 'tx')
call assert_equal([2, 1], [line('.'), col('.')])
set rightleftcmd&
set rightleft&
set arabic&
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,748 +0,0 @@
" Test argument list commands
source check.vim
source shared.vim
source term_util.vim
func Reset_arglist()
args a | %argd
endfunc
func Test_argidx()
args a b c
last
call assert_equal(2, argidx())
%argdelete
call assert_equal(0, argidx())
" doing it again doesn't result in an error
%argdelete
call assert_equal(0, argidx())
call assert_fails('2argdelete', 'E16:')
args a b c
call assert_equal(0, argidx())
next
call assert_equal(1, argidx())
next
call assert_equal(2, argidx())
1argdelete
call assert_equal(1, argidx())
1argdelete
call assert_equal(0, argidx())
1argdelete
call assert_equal(0, argidx())
endfunc
func Test_argadd()
call Reset_arglist()
%argdelete
argadd a b c
call assert_equal(0, argidx())
%argdelete
argadd a
call assert_equal(0, argidx())
argadd b c d
call assert_equal(0, argidx())
call Init_abc()
argadd x
call Assert_argc(['a', 'b', 'x', 'c'])
call assert_equal(1, argidx())
call Init_abc()
0argadd x
call Assert_argc(['x', 'a', 'b', 'c'])
call assert_equal(2, argidx())
call Init_abc()
1argadd x
call Assert_argc(['a', 'x', 'b', 'c'])
call assert_equal(2, argidx())
call Init_abc()
$argadd x
call Assert_argc(['a', 'b', 'c', 'x'])
call assert_equal(1, argidx())
call Init_abc()
$argadd x
+2argadd y
call Assert_argc(['a', 'b', 'c', 'x', 'y'])
call assert_equal(1, argidx())
%argd
edit d
arga
call assert_equal(1, len(argv()))
call assert_equal('d', get(argv(), 0, ''))
%argd
edit some\ file
arga
call assert_equal(1, len(argv()))
call assert_equal('some file', get(argv(), 0, ''))
%argd
new
arga
call assert_equal(0, len(argv()))
if has('unix')
call assert_fails('argadd `Xdoes_not_exist`', 'E479:')
endif
endfunc
func Test_argadd_empty_curbuf()
new
let curbuf = bufnr('%')
call writefile(['test', 'Xargadd'], 'Xargadd')
" must not re-use the current buffer.
argadd Xargadd
call assert_equal(curbuf, bufnr('%'))
call assert_equal('', bufname('%'))
call assert_equal(1, '$'->line())
rew
call assert_notequal(curbuf, '%'->bufnr())
call assert_equal('Xargadd', '%'->bufname())
call assert_equal(2, line('$'))
%argd
bwipe!
endfunc
func Init_abc()
args a b c
next
endfunc
func Assert_argc(l)
call assert_equal(len(a:l), argc())
let i = 0
while i < len(a:l) && i < argc()
call assert_equal(a:l[i], argv(i))
let i += 1
endwhile
endfunc
" Test for [count]argument and [count]argdelete commands
" Ported from the test_argument_count.in test script
func Test_argument()
call Reset_arglist()
let save_hidden = &hidden
set hidden
let g:buffers = []
augroup TEST
au BufEnter * call add(buffers, expand('%:t'))
augroup END
argadd a b c d
$argu
$-argu
-argu
1argu
+2argu
augroup TEST
au!
augroup END
call assert_equal(['d', 'c', 'b', 'a', 'c'], g:buffers)
call assert_equal("\na b [c] d ", execute(':args'))
.argd
call assert_equal(['a', 'b', 'd'], argv())
-argd
call assert_equal(['a', 'd'], argv())
$argd
call assert_equal(['a'], argv())
1arga c
1arga b
$argu
$arga x
call assert_equal(['a', 'b', 'c', 'x'], argv())
0arga y
call assert_equal(['y', 'a', 'b', 'c', 'x'], argv())
%argd
call assert_equal([], argv())
arga a b c d e f
2,$-argd
call assert_equal(['a', 'f'], argv())
let &hidden = save_hidden
let save_columns = &columns
let &columns = 79
exe 'args ' .. join(range(1, 81))
call assert_equal(join([
\ '',
\ '[1] 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 ',
\ '2 7 12 17 22 27 32 37 42 47 52 57 62 67 72 77 ',
\ '3 8 13 18 23 28 33 38 43 48 53 58 63 68 73 78 ',
\ '4 9 14 19 24 29 34 39 44 49 54 59 64 69 74 79 ',
\ '5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 ',
\ ], "\n"),
\ execute('args'))
" No trailing newline with one item per row.
let long_arg = repeat('X', 81)
exe 'args ' .. long_arg
call assert_equal("\n[".long_arg.']', execute('args'))
let &columns = save_columns
" Setting argument list should fail when the current buffer has unsaved
" changes
%argd
enew!
set modified
call assert_fails('args x y z', 'E37:')
args! x y z
call assert_equal(['x', 'y', 'z'], argv())
call assert_equal('x', expand('%:t'))
last | enew | argu
call assert_equal('z', expand('%:t'))
%argdelete
call assert_fails('argument', 'E163:')
endfunc
func Test_list_arguments()
" Clean the argument list
arga a | %argd
" four args half the screen width makes two lines with two columns
let aarg = repeat('a', &columns / 2 - 4)
let barg = repeat('b', &columns / 2 - 4)
let carg = repeat('c', &columns / 2 - 4)
let darg = repeat('d', &columns / 2 - 4)
exe 'argadd ' aarg barg carg darg
redir => result
args
redir END
call assert_match('\[' . aarg . '] \+' . carg . '\n' . barg . ' \+' . darg, trim(result))
" if one arg is longer than half the screen make one column
exe 'argdel' aarg
let aarg = repeat('a', &columns / 2 + 2)
exe '0argadd' aarg
redir => result
args
redir END
call assert_match(aarg . '\n\[' . barg . ']\n' . carg . '\n' . darg, trim(result))
%argdelete
endfunc
func Test_args_with_quote()
" Only on Unix can a file name include a double quote.
if has('unix')
args \"foobar
call assert_equal('"foobar', argv(0))
%argdelete
endif
endfunc
" Test for 0argadd and 0argedit
" Ported from the test_argument_0count.in test script
func Test_zero_argadd()
call Reset_arglist()
arga a b c d
2argu
0arga added
call assert_equal(['added', 'a', 'b', 'c', 'd'], argv())
2argu
arga third
call assert_equal(['added', 'a', 'third', 'b', 'c', 'd'], argv())
%argd
arga a b c d
2argu
0arge edited
call assert_equal(['edited', 'a', 'b', 'c', 'd'], argv())
2argu
arga third
call assert_equal(['edited', 'a', 'third', 'b', 'c', 'd'], argv())
2argu
argedit file\ with\ spaces another file
call assert_equal(['edited', 'a', 'file with spaces', 'another', 'file', 'third', 'b', 'c', 'd'], argv())
call assert_equal('file with spaces', expand('%'))
endfunc
" Test for argc()
func Test_argc()
call Reset_arglist()
call assert_equal(0, argc())
argadd a b
call assert_equal(2, argc())
endfunc
" Test for arglistid()
func Test_arglistid()
call Reset_arglist()
arga a b
call assert_equal(0, arglistid())
split
arglocal
call assert_equal(1, arglistid())
tabnew | tabfirst
call assert_equal(0, arglistid(2))
call assert_equal(1, arglistid(1, 1))
call assert_equal(0, arglistid(2, 1))
call assert_equal(1, arglistid(1, 2))
tabonly | only | enew!
argglobal
call assert_equal(0, arglistid())
endfunc
" Tests for argv() and argc()
func Test_argv()
call Reset_arglist()
call assert_equal([], argv())
call assert_equal("", argv(2))
call assert_equal(0, argc())
argadd a b c d
call assert_equal(4, argc())
call assert_equal('c', argv(2))
let w1_id = win_getid()
split
let w2_id = win_getid()
arglocal
args e f g
tabnew
let w3_id = win_getid()
split
let w4_id = win_getid()
argglobal
tabfirst
call assert_equal(4, argc(w1_id))
call assert_equal('b', argv(1, w1_id))
call assert_equal(['a', 'b', 'c', 'd'], argv(-1, w1_id))
call assert_equal(3, argc(w2_id))
call assert_equal('f', argv(1, w2_id))
call assert_equal(['e', 'f', 'g'], argv(-1, w2_id))
call assert_equal(3, argc(w3_id))
call assert_equal('e', argv(0, w3_id))
call assert_equal(['e', 'f', 'g'], argv(-1, w3_id))
call assert_equal(4, argc(w4_id))
call assert_equal('c', argv(2, w4_id))
call assert_equal(['a', 'b', 'c', 'd'], argv(-1, w4_id))
call assert_equal(4, argc(-1))
call assert_equal(3, argc())
call assert_equal('d', argv(3, -1))
call assert_equal(['a', 'b', 'c', 'd'], argv(-1, -1))
tabonly | only | enew!
" Negative test cases
call assert_equal(-1, argc(100))
call assert_equal('', argv(1, 100))
call assert_equal([], argv(-1, 100))
call assert_equal('', argv(10, -1))
endfunc
" Test for the :argedit command
func Test_argedit()
call Reset_arglist()
argedit a
call assert_equal(['a'], argv())
call assert_equal('a', expand('%:t'))
argedit b
call assert_equal(['a', 'b'], argv())
call assert_equal('b', expand('%:t'))
argedit a
call assert_equal(['a', 'b', 'a'], argv())
call assert_equal('a', expand('%:t'))
" When file name case is ignored, an existing buffer with only case
" difference is re-used.
argedit C D
call assert_equal('C', expand('%:t'))
call assert_equal(['a', 'b', 'a', 'C', 'D'], argv())
argedit c
if has('fname_case')
call assert_equal(['a', 'b', 'a', 'C', 'c', 'D'], argv())
else
call assert_equal(['a', 'b', 'a', 'C', 'C', 'D'], argv())
endif
0argedit x
if has('fname_case')
call assert_equal(['x', 'a', 'b', 'a', 'C', 'c', 'D'], argv())
else
call assert_equal(['x', 'a', 'b', 'a', 'C', 'C', 'D'], argv())
endif
enew! | set modified
call assert_fails('argedit y', 'E37:')
argedit! y
if has('fname_case')
call assert_equal(['x', 'y', 'y', 'a', 'b', 'a', 'C', 'c', 'D'], argv())
else
call assert_equal(['x', 'y', 'y', 'a', 'b', 'a', 'C', 'C', 'D'], argv())
endif
%argd
bwipe! C
bwipe! D
" :argedit reuses the current buffer if it is empty
%argd
" make sure to use a new buffer number for x when it is loaded
bw! x
new
let a = bufnr()
argedit x
call assert_equal(a, bufnr())
call assert_equal('x', bufname())
%argd
bw! x
endfunc
" Test for the :argdedupe command
func Test_argdedupe()
call Reset_arglist()
argdedupe
call assert_equal([], argv())
args a a a aa b b a b aa
argdedupe
call assert_equal(['a', 'aa', 'b'], argv())
args a b c
argdedupe
call assert_equal(['a', 'b', 'c'], argv())
args a
argdedupe
call assert_equal(['a'], argv())
args a A b B
argdedupe
if has('fname_case')
call assert_equal(['a', 'A', 'b', 'B'], argv())
else
call assert_equal(['a', 'b'], argv())
endif
args a b a c a b
last
argdedupe
next
call assert_equal('c', expand('%:t'))
args a ./a
argdedupe
call assert_equal(['a'], argv())
%argd
endfunc
" Test for the :argdelete command
func Test_argdelete()
call Reset_arglist()
args aa a aaa b bb
argdelete a*
call assert_equal(['b', 'bb'], argv())
call assert_equal('aa', expand('%:t'))
last
argdelete %
call assert_equal(['b'], argv())
call assert_fails('argdelete', 'E610:')
call assert_fails('1,100argdelete', 'E16:')
call assert_fails('argdel /\)/', 'E55:')
call assert_fails('1argdel 1', 'E474:')
call Reset_arglist()
args a b c d
next
argdel
call Assert_argc(['a', 'c', 'd'])
%argdel
call assert_fails('argdel does_not_exist', 'E480:')
endfunc
func Test_argdelete_completion()
args foo bar
call feedkeys(":argdelete \<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"argdelete bar foo', @:)
call feedkeys(":argdelete x \<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"argdelete x bar foo', @:)
%argd
endfunc
" Tests for the :next, :prev, :first, :last, :rewind commands
func Test_argpos()
call Reset_arglist()
args a b c d
last
call assert_equal(3, argidx())
call assert_fails('next', 'E165:')
prev
call assert_equal(2, argidx())
Next
call assert_equal(1, argidx())
first
call assert_equal(0, argidx())
call assert_fails('prev', 'E164:')
3next
call assert_equal(3, argidx())
rewind
call assert_equal(0, argidx())
%argd
endfunc
" Test for autocommand that redefines the argument list, when doing ":all".
func Test_arglist_autocmd()
autocmd BufReadPost Xxx2 next Xxx2 Xxx1
call writefile(['test file Xxx1'], 'Xxx1')
call writefile(['test file Xxx2'], 'Xxx2')
call writefile(['test file Xxx3'], 'Xxx3')
new
" redefine arglist; go to Xxx1
next! Xxx1 Xxx2 Xxx3
" open window for all args; Reading Xxx2 will try to change the arglist and
" that will fail
call assert_fails("all", "E1156:")
call assert_equal('test file Xxx1', getline(1))
wincmd w
call assert_equal('test file Xxx2', getline(1))
wincmd w
call assert_equal('test file Xxx3', getline(1))
autocmd! BufReadPost Xxx2
enew! | only
call delete('Xxx1')
call delete('Xxx2')
call delete('Xxx3')
argdelete Xxx*
bwipe! Xxx1 Xxx2 Xxx3
endfunc
func Test_arg_all_expand()
call writefile(['test file Xxx1'], 'Xx x')
next notexist Xx\ x runtest.vim
call assert_equal('notexist Xx\ x runtest.vim', expand('##'))
call delete('Xx x')
endfunc
func Test_large_arg()
" Argument longer or equal to the number of columns used to cause
" access to invalid memory.
exe 'argadd ' .repeat('x', &columns)
args
endfunc
func Test_argdo()
next! Xa.c Xb.c Xc.c
new
let l = []
argdo call add(l, expand('%'))
call assert_equal(['Xa.c', 'Xb.c', 'Xc.c'], l)
bwipe Xa.c Xb.c Xc.c
endfunc
" Test for quitting Vim with unedited files in the argument list
func Test_quit_with_arglist()
CheckRunVimInTerminal
let buf = RunVimInTerminal('', {'rows': 6})
call term_sendkeys(buf, ":set nomore\n")
call term_sendkeys(buf, ":args a b c\n")
call term_sendkeys(buf, ":quit\n")
call term_wait(buf)
call WaitForAssert({-> assert_match('^E173:', term_getline(buf, 6))})
call StopVimInTerminal(buf)
" Try :confirm quit with unedited files in arglist
let buf = RunVimInTerminal('', {'rows': 6})
call term_sendkeys(buf, ":set nomore\n")
call term_sendkeys(buf, ":args a b c\n")
call term_sendkeys(buf, ":confirm quit\n")
call term_wait(buf)
call WaitForAssert({-> assert_match('^\[Y\]es, (N)o: *$',
\ term_getline(buf, 6))})
call term_sendkeys(buf, "N")
call term_wait(buf)
call term_sendkeys(buf, ":confirm quit\n")
call WaitForAssert({-> assert_match('^\[Y\]es, (N)o: *$',
\ term_getline(buf, 6))})
call term_sendkeys(buf, "Y")
call term_wait(buf)
call WaitForAssert({-> assert_equal("finished", term_getstatus(buf))})
only!
" When this test fails, swap files are left behind which breaks subsequent
" tests
call delete('.a.swp')
call delete('.b.swp')
call delete('.c.swp')
endfunc
" Test for ":all" not working when in the cmdline window
func Test_all_not_allowed_from_cmdwin()
au BufEnter * all
next x
" Use try/catch here, somehow assert_fails() doesn't work on MS-Windows
" console.
let caught = 'no'
try
exe ":norm! 7q?apat\<CR>"
catch /E11:/
let caught = 'yes'
endtry
call assert_equal('yes', caught)
au! BufEnter
endfunc
func Test_clear_arglist_in_all()
n 0 00 000 0000 00000 000000
au WinNew 0 n 0
call assert_fails("all", "E1156")
au! *
endfunc
" Test for the :all command
func Test_all_command()
%argdelete
" :all command should not close windows with files in the argument list,
" but can rearrange the windows.
args Xargnew1 Xargnew2
%bw!
edit Xargold1
split Xargnew1
let Xargnew1_winid = win_getid()
split Xargold2
split Xargnew2
let Xargnew2_winid = win_getid()
split Xargold3
all
call assert_equal(2, winnr('$'))
call assert_equal([Xargnew1_winid, Xargnew2_winid],
\ [win_getid(1), win_getid(2)])
call assert_equal([bufnr('Xargnew1'), bufnr('Xargnew2')],
\ [winbufnr(1), winbufnr(2)])
" :all command should close windows for files which are not in the
" argument list in the current tab page.
%bw!
edit Xargold1
split Xargold2
tabedit Xargold3
split Xargold4
tabedit Xargold5
tabfirst
all
call assert_equal(3, tabpagenr('$'))
call assert_equal([bufnr('Xargnew1'), bufnr('Xargnew2')], tabpagebuflist(1))
call assert_equal([bufnr('Xargold4'), bufnr('Xargold3')], tabpagebuflist(2))
call assert_equal([bufnr('Xargold5')], tabpagebuflist(3))
" :tab all command should close windows for files which are not in the
" argument list across all the tab pages.
%bw!
edit Xargold1
split Xargold2
tabedit Xargold3
split Xargold4
tabedit Xargold5
tabfirst
args Xargnew1 Xargnew2
tab all
call assert_equal(2, tabpagenr('$'))
call assert_equal([bufnr('Xargnew1')], tabpagebuflist(1))
call assert_equal([bufnr('Xargnew2')], tabpagebuflist(2))
" If a count is specified, then :all should open only that many windows.
%bw!
args Xargnew1 Xargnew2 Xargnew3 Xargnew4 Xargnew5
all 3
call assert_equal(3, winnr('$'))
call assert_equal([bufnr('Xargnew1'), bufnr('Xargnew2'), bufnr('Xargnew3')],
\ [winbufnr(1), winbufnr(2), winbufnr(3)])
" The :all command should not open more than 'tabpagemax' tab pages.
" If there are more files, then they should be opened in the last tab page.
%bw!
set tabpagemax=3
tab all
call assert_equal(3, tabpagenr('$'))
call assert_equal([bufnr('Xargnew1')], tabpagebuflist(1))
call assert_equal([bufnr('Xargnew2')], tabpagebuflist(2))
call assert_equal([bufnr('Xargnew3'), bufnr('Xargnew4'), bufnr('Xargnew5')],
\ tabpagebuflist(3))
set tabpagemax&
" Without the 'hidden' option, modified buffers should not be closed.
args Xargnew1 Xargnew2
%bw!
edit Xargtemp1
call setline(1, 'temp buffer 1')
split Xargtemp2
call setline(1, 'temp buffer 2')
all
call assert_equal(4, winnr('$'))
call assert_equal([bufnr('Xargtemp2'), bufnr('Xargtemp1'), bufnr('Xargnew1'),
\ bufnr('Xargnew2')],
\ [winbufnr(1), winbufnr(2), winbufnr(3), winbufnr(4)])
" With the 'hidden' option set, both modified and unmodified buffers in
" closed windows should be hidden.
set hidden
all
call assert_equal(2, winnr('$'))
call assert_equal([bufnr('Xargnew1'), bufnr('Xargnew2')],
\ [winbufnr(1), winbufnr(2)])
call assert_equal([1, 1, 0, 0], [getbufinfo('Xargtemp1')[0].hidden,
\ getbufinfo('Xargtemp2')[0].hidden,
\ getbufinfo('Xargnew1')[0].hidden,
\ getbufinfo('Xargnew2')[0].hidden])
set nohidden
" When 'winheight' is set to a large value, :all should open only one
" window.
args Xargnew1 Xargnew2 Xargnew3 Xargnew4 Xargnew5
%bw!
set winheight=9999
call assert_fails('all', 'E36:')
call assert_equal([1, bufnr('Xargnew1')], [winnr('$'), winbufnr(1)])
set winheight&
" When 'winwidth' is set to a large value, :vert all should open only one
" window.
%bw!
set winwidth=9999
call assert_fails('vert all', 'E36:')
call assert_equal([1, bufnr('Xargnew1')], [winnr('$'), winbufnr(1)])
set winwidth&
" empty argument list tests
%bw!
%argdelete
call assert_equal('', execute('args'))
all
call assert_equal(1, winnr('$'))
%argdelete
%bw!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,363 +0,0 @@
" Test that the methods used for testing work.
func Test_assert_false()
call assert_equal(0, assert_false(0))
call assert_equal(0, assert_false(v:false))
call assert_equal(0, v:false->assert_false())
call assert_equal(1, assert_false(123))
call assert_match("Expected False but got 123", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, 123->assert_false())
call assert_match("Expected False but got 123", v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_true()
call assert_equal(0, assert_true(1))
call assert_equal(0, assert_true(123))
call assert_equal(0, assert_true(v:true))
call assert_equal(0, v:true->assert_true())
call assert_equal(1, assert_true(0))
call assert_match("Expected True but got 0", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, 0->assert_true())
call assert_match("Expected True but got 0", v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_equal()
let s = 'foo'
call assert_equal(0, assert_equal('foo', s))
let n = 4
call assert_equal(0, assert_equal(4, n))
let l = [1, 2, 3]
call assert_equal(0, assert_equal([1, 2, 3], l))
call assert_equal(v:_null_list, v:_null_list)
call assert_equal(v:_null_list, [])
call assert_equal([], v:_null_list)
let s = 'foo'
call assert_equal(1, assert_equal('bar', s))
call assert_match("Expected 'bar' but got 'foo'", v:errors[0])
call remove(v:errors, 0)
call assert_equal('XxxxxxxxxxxxxxxxxxxxxxX', 'XyyyyyyyyyyyyyyyyyyyyyyyyyX')
call assert_match("Expected 'X\\\\\\[x occurs 21 times]X' but got 'X\\\\\\[y occurs 25 times]X'", v:errors[0])
call remove(v:errors, 0)
" special characters are escaped
call assert_equal("\b\e\f\n\t\r\\\x01\x7f", 'x')
call assert_match('Expected ''\\b\\e\\f\\n\\t\\r\\\\\\x01\\x7f'' but got ''x''', v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_equal_dict()
call assert_equal(0, assert_equal(#{one: 1, two: 2}, #{two: 2, one: 1}))
call assert_equal(1, assert_equal(#{one: 1, two: 2}, #{two: 2, one: 3}))
call assert_match("Expected {'one': 1} but got {'one': 3} - 1 equal item omitted", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_equal(#{one: 1, two: 2}, #{two: 22, one: 11}))
call assert_match("Expected {'one': 1, 'two': 2} but got {'one': 11, 'two': 22}", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_equal(#{}, #{two: 2, one: 1}))
call assert_match("Expected {} but got {'one': 1, 'two': 2}", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_equal(#{two: 2, one: 1}, #{}))
call assert_match("Expected {'one': 1, 'two': 2} but got {}", v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_equalfile()
call assert_equal(1, assert_equalfile('abcabc', 'xyzxyz'))
call assert_match("E485: Can't read file abcabc", v:errors[0])
call remove(v:errors, 0)
let goodtext = ["one", "two", "three"]
call writefile(goodtext, 'Xone')
call assert_equal(1, 'Xone'->assert_equalfile('xyzxyz'))
call assert_match("E485: Can't read file xyzxyz", v:errors[0])
call remove(v:errors, 0)
call writefile(goodtext, 'Xtwo')
call assert_equal(0, assert_equalfile('Xone', 'Xtwo'))
call writefile([goodtext[0]], 'Xone')
call assert_equal(1, assert_equalfile('Xone', 'Xtwo'))
call assert_match("first file is shorter", v:errors[0])
call remove(v:errors, 0)
call writefile(goodtext, 'Xone')
call writefile([goodtext[0]], 'Xtwo')
call assert_equal(1, assert_equalfile('Xone', 'Xtwo'))
call assert_match("second file is shorter", v:errors[0])
call remove(v:errors, 0)
call writefile(['1234X89'], 'Xone')
call writefile(['1234Y89'], 'Xtwo')
call assert_equal(1, assert_equalfile('Xone', 'Xtwo'))
call assert_match('difference at byte 4, line 1 after "1234X" vs "1234Y"', v:errors[0])
call remove(v:errors, 0)
call writefile([repeat('x', 234) .. 'X'], 'Xone')
call writefile([repeat('x', 234) .. 'Y'], 'Xtwo')
call assert_equal(1, assert_equalfile('Xone', 'Xtwo'))
let xes = repeat('x', 134)
call assert_match('difference at byte 234, line 1 after "' .. xes .. 'X" vs "' .. xes .. 'Y"', v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_equalfile('Xone', 'Xtwo', 'a message'))
call assert_match("a message: difference at byte 234, line 1 after", v:errors[0])
call remove(v:errors, 0)
call delete('Xone')
call delete('Xtwo')
endfunc
func Test_assert_notequal()
let n = 4
call assert_equal(0, assert_notequal('foo', n))
let s = 'foo'
call assert_equal(0, assert_notequal([1, 2, 3], s))
call assert_equal(1, assert_notequal('foo', s))
call assert_match("Expected not equal to 'foo'", v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_report()
call assert_equal(1, assert_report('something is wrong'))
call assert_match('something is wrong', v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, 'also wrong'->assert_report())
call assert_match('also wrong', v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_exception()
try
nocommand
catch
call assert_equal(0, assert_exception('E492:'))
endtry
try
nocommand
catch
call assert_equal(1, assert_exception('E12345:'))
endtry
call assert_match("Expected 'E12345:' but got 'Vim:E492: ", v:errors[0])
call remove(v:errors, 0)
try
nocommand
catch
try
" illegal argument, get NULL for error
call assert_equal(1, assert_exception([]))
catch
call assert_equal(0, assert_exception('E730:'))
endtry
endtry
call assert_equal(1, assert_exception('E492:'))
call assert_match('v:exception is not set', v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_wrong_error_type()
let save_verrors = v:errors
let v:['errors'] = {'foo': 3}
call assert_equal('yes', 'no')
let verrors = v:errors
let v:errors = save_verrors
call assert_equal(type([]), type(verrors))
endfunc
func Test_match()
call assert_equal(0, assert_match('^f.*b.*r$', 'foobar'))
call assert_equal(1, assert_match('bar.*foo', 'foobar'))
call assert_match("Pattern 'bar.*foo' does not match 'foobar'", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_match('bar.*foo', 'foobar', 'wrong'))
call assert_match('wrong', v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, 'foobar'->assert_match('bar.*foo', 'wrong'))
call assert_match('wrong', v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_notmatch()
call assert_equal(0, assert_notmatch('foo', 'bar'))
call assert_equal(0, assert_notmatch('^foobar$', 'foobars'))
call assert_equal(1, assert_notmatch('foo', 'foobar'))
call assert_match("Pattern 'foo' does match 'foobar'", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, 'foobar'->assert_notmatch('foo'))
call assert_match("Pattern 'foo' does match 'foobar'", v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_assert_fail_fails()
call assert_equal(1, assert_fails('xxx', 'E12345'))
call assert_match("Expected 'E12345' but got 'E492:", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_fails('xxx', 'E9876', 'stupid'))
call assert_match("stupid: Expected 'E9876' but got 'E492:", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_fails('xxx', ['E9876']))
call assert_match("Expected \\['E9876'\\] but got 'E492:", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_fails('xxx', ['E492:', 'E9876']))
call assert_match("Expected \\['E492:', 'E9876'\\] but got 'E492:", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_fails('echo', '', 'echo command'))
call assert_match("command did not fail: echo command", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, 'echo'->assert_fails('', 'echo command'))
call assert_match("command did not fail: echo command", v:errors[0])
call remove(v:errors, 0)
try
call assert_equal(1, assert_fails('xxx', []))
catch
let exp = v:exception
endtry
call assert_match("E856: assert_fails() second argument", exp)
try
call assert_equal(1, assert_fails('xxx', ['1', '2', '3']))
catch
let exp = v:exception
endtry
call assert_match("E856: assert_fails() second argument", exp)
try
call assert_equal(1, assert_fails('xxx', #{one: 1}))
catch
let exp = v:exception
endtry
call assert_match("E856: assert_fails() second argument", exp)
try
call assert_equal(1, assert_fails('xxx', 'E492', '', 'burp'))
catch
let exp = v:exception
endtry
call assert_match("E1115: assert_fails() fourth argument must be a number", exp)
try
call assert_equal(1, assert_fails('xxx', 'E492', '', 54, 123))
catch
let exp = v:exception
endtry
call assert_match("E1116: assert_fails() fifth argument must be a string", exp)
endfunc
func Test_assert_fails_in_try_block()
try
call assert_equal(0, assert_fails('throw "error"'))
endtry
endfunc
func Test_assert_beeps()
new
call assert_equal(0, assert_beeps('normal h'))
call assert_equal(1, assert_beeps('normal 0'))
call assert_match("command did not beep: normal 0", v:errors[0])
call remove(v:errors, 0)
call assert_equal(0, 'normal h'->assert_beeps())
call assert_equal(1, 'normal 0'->assert_beeps())
call assert_match("command did not beep: normal 0", v:errors[0])
call remove(v:errors, 0)
bwipe
endfunc
func Test_assert_inrange()
call assert_equal(0, assert_inrange(7, 7, 7))
call assert_equal(0, assert_inrange(5, 7, 5))
call assert_equal(0, assert_inrange(5, 7, 6))
call assert_equal(0, assert_inrange(5, 7, 7))
call assert_equal(1, assert_inrange(5, 7, 4))
call assert_match("Expected range 5 - 7, but got 4", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_inrange(5, 7, 8))
call assert_match("Expected range 5 - 7, but got 8", v:errors[0])
call remove(v:errors, 0)
call assert_equal(0, 5->assert_inrange(5, 7))
call assert_equal(0, 7->assert_inrange(5, 7))
call assert_equal(1, 8->assert_inrange(5, 7))
call assert_match("Expected range 5 - 7, but got 8", v:errors[0])
call remove(v:errors, 0)
call assert_fails('call assert_inrange(1, 1)', 'E119:')
if has('float')
call assert_equal(0, assert_inrange(7.0, 7, 7))
call assert_equal(0, assert_inrange(7, 7.0, 7))
call assert_equal(0, assert_inrange(7, 7, 7.0))
call assert_equal(0, assert_inrange(5, 7, 5.0))
call assert_equal(0, assert_inrange(5, 7, 6.0))
call assert_equal(0, assert_inrange(5, 7, 7.0))
call assert_equal(1, assert_inrange(5, 7, 4.0))
call assert_match("Expected range 5.0 - 7.0, but got 4.0", v:errors[0])
call remove(v:errors, 0)
call assert_equal(1, assert_inrange(5, 7, 8.0))
call assert_match("Expected range 5.0 - 7.0, but got 8.0", v:errors[0])
call remove(v:errors, 0)
endif
endfunc
func Test_assert_with_msg()
call assert_equal('foo', 'bar', 'testing')
call assert_match("testing: Expected 'foo' but got 'bar'", v:errors[0])
call remove(v:errors, 0)
endfunc
func Test_mouse_position()
let save_mouse = &mouse
set mouse=a
new
call setline(1, ['line one', 'line two'])
call assert_equal([0, 1, 1, 0], getpos('.'))
call Ntest_setmouse(1, 5)
call feedkeys("\<LeftMouse>", "xt")
call assert_equal([0, 1, 5, 0], getpos('.'))
call Ntest_setmouse(2, 20)
call feedkeys("\<LeftMouse>", "xt")
call assert_equal([0, 2, 8, 0], getpos('.'))
call Ntest_setmouse(5, 1)
call feedkeys("\<LeftMouse>", "xt")
call assert_equal([0, 2, 1, 0], getpos('.'))
bwipe!
let &mouse = save_mouse
endfunc
" Must be last.
func Test_zz_quit_detected()
" Verify that if a test function ends Vim the test script detects this.
quit
endfunc

View File

@@ -1,130 +0,0 @@
" Test 'autochdir' behavior
source check.vim
CheckOption autochdir
func Test_set_filename()
CheckFunction test_autochdir
let cwd = getcwd()
call test_autochdir()
set acd
let s:li = []
autocmd DirChanged auto call add(s:li, "autocd")
autocmd DirChanged auto call add(s:li, expand("<afile>"))
new
w samples/Xtest
call assert_equal("Xtest", expand('%'))
call assert_equal("samples", substitute(getcwd(), '.*/\(\k*\)', '\1', ''))
call assert_equal(["autocd", getcwd()], s:li)
bwipe!
au! DirChanged
set noacd
call chdir(cwd)
call delete('samples/Xtest')
endfunc
func Test_set_filename_other_window()
CheckFunction test_autochdir
let cwd = getcwd()
call test_autochdir()
call mkdir('Xa')
call mkdir('Xb')
call mkdir('Xc')
try
args Xa/aaa.txt Xb/bbb.txt
set acd
let winid = win_getid()
snext
call assert_equal('Xb', substitute(getcwd(), '.*/\([^/]*\)$', '\1', ''))
call win_execute(winid, 'file ' .. cwd .. '/Xc/ccc.txt')
call assert_equal('Xb', substitute(getcwd(), '.*/\([^/]*\)$', '\1', ''))
finally
set noacd
call chdir(cwd)
call delete('Xa', 'rf')
call delete('Xb', 'rf')
call delete('Xc', 'rf')
bwipe! aaa.txt
bwipe! bbb.txt
bwipe! ccc.txt
endtry
endfunc
func Test_acd_win_execute()
CheckFunction test_autochdir
let cwd = getcwd()
set acd
call test_autochdir()
call mkdir('Xfile')
let winid = win_getid()
new Xfile/file
call assert_match('testdir.Xfile$', getcwd())
cd ..
call assert_match('testdir$', getcwd())
call win_execute(winid, 'echo')
call assert_match('testdir$', getcwd())
bwipe!
set noacd
call chdir(cwd)
call delete('Xfile', 'rf')
endfunc
func Test_verbose_pwd()
CheckFunction test_autochdir
let cwd = getcwd()
call test_autochdir()
edit global.txt
call assert_match('\[global\].*testdir$', execute('verbose pwd'))
call mkdir('Xautodir')
split Xautodir/local.txt
lcd Xautodir
call assert_match('\[window\].*testdir[/\\]Xautodir', execute('verbose pwd'))
set acd
wincmd w
call assert_match('\[autochdir\].*testdir$', execute('verbose pwd'))
execute 'tcd' cwd
call assert_match('\[tabpage\].*testdir$', execute('verbose pwd'))
execute 'cd' cwd
call assert_match('\[global\].*testdir$', execute('verbose pwd'))
execute 'lcd' cwd
call assert_match('\[window\].*testdir$', execute('verbose pwd'))
edit
call assert_match('\[autochdir\].*testdir$', execute('verbose pwd'))
enew
wincmd w
call assert_match('\[autochdir\].*testdir[/\\]Xautodir', execute('verbose pwd'))
wincmd w
call assert_match('\[window\].*testdir$', execute('verbose pwd'))
wincmd w
call assert_match('\[autochdir\].*testdir[/\\]Xautodir', execute('verbose pwd'))
set noacd
call assert_match('\[autochdir\].*testdir[/\\]Xautodir', execute('verbose pwd'))
wincmd w
call assert_match('\[window\].*testdir$', execute('verbose pwd'))
execute 'cd' cwd
call assert_match('\[global\].*testdir$', execute('verbose pwd'))
wincmd w
call assert_match('\[window\].*testdir[/\\]Xautodir', execute('verbose pwd'))
bwipe!
call chdir(cwd)
call delete('Xautodir', 'rf')
endfunc
func Test_multibyte()
" using an invalid character should not cause a crash
set wic
call assert_fails('tc <20><><EFBFBD><EFBFBD><EFBFBD>*', has('win32') ? 'E480:' : 'E344:')
set nowic
endfunc
" vim: shiftwidth=2 sts=2 expandtab

File diff suppressed because it is too large Load Diff

View File

@@ -1,25 +0,0 @@
" Tests for autoload
set runtimepath=./sautest
func Test_autoload_dict_func()
let g:loaded_foo_vim = 0
let g:called_foo_bar_echo = 0
call g:foo#bar.echo()
call assert_equal(1, g:loaded_foo_vim)
call assert_equal(1, g:called_foo_bar_echo)
eval 'bar'->g:foo#addFoo()->assert_equal('barfoo')
" empty name works in legacy script
call assert_equal('empty', foo#())
endfunc
func Test_source_autoload()
let g:loaded_sourced_vim = 0
source sautest/autoload/sourced.vim
call assert_equal(1, g:loaded_sourced_vim)
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,141 +0,0 @@
" Tests for 'backspace' settings
func Test_backspace_option()
set backspace=
call assert_equal('', &backspace)
set backspace=indent
call assert_equal('indent', &backspace)
set backspace=eol
call assert_equal('eol', &backspace)
set backspace=start
call assert_equal('start', &backspace)
set backspace=nostop
call assert_equal('nostop', &backspace)
" Add the value
set backspace=
set backspace=indent
call assert_equal('indent', &backspace)
set backspace+=eol
call assert_equal('indent,eol', &backspace)
set backspace+=start
call assert_equal('indent,eol,start', &backspace)
set backspace+=nostop
call assert_equal('indent,eol,start,nostop', &backspace)
" Delete the value
set backspace-=nostop
call assert_equal('indent,eol,start', &backspace)
set backspace-=indent
call assert_equal('eol,start', &backspace)
set backspace-=start
call assert_equal('eol', &backspace)
set backspace-=eol
call assert_equal('', &backspace)
" Check the error
call assert_fails('set backspace=ABC', 'E474:')
call assert_fails('set backspace+=def', 'E474:')
" NOTE: Vim doesn't check following error...
"call assert_fails('set backspace-=ghi', 'E474:')
" Check backwards compatibility with version 5.4 and earlier
set backspace=0
call assert_equal('0', &backspace)
set backspace=1
call assert_equal('1', &backspace)
set backspace=2
call assert_equal('2', &backspace)
set backspace=3
call assert_equal('3', &backspace)
call assert_fails('set backspace=4', 'E474:')
call assert_fails('set backspace=10', 'E474:')
" Cleared when 'compatible' is set
" set compatible
" call assert_equal('', &backspace)
set nocompatible viminfo+=nviminfo
endfunc
" Test with backspace set to the non-compatible setting
func Test_backspace_ctrl_u()
new
call append(0, [
\ "1 this shouldn't be deleted",
\ "2 this shouldn't be deleted",
\ "3 this shouldn't be deleted",
\ "4 this should be deleted",
\ "5 this shouldn't be deleted",
\ "6 this shouldn't be deleted",
\ "7 this shouldn't be deleted",
\ "8 this shouldn't be deleted (not touched yet)"])
call cursor(2, 1)
" set compatible
set backspace=2
exe "normal Avim1\<C-U>\<Esc>\<CR>"
exe "normal Avim2\<C-G>u\<C-U>\<Esc>\<CR>"
set cpo-=<
inoremap <c-u> <left><c-u>
exe "normal Avim3\<*C-U>\<Esc>\<CR>"
iunmap <c-u>
exe "normal Avim4\<C-U>\<C-U>\<Esc>\<CR>"
" Test with backspace set to the compatible setting
set backspace= visualbell
exe "normal A vim5\<Esc>A\<C-U>\<C-U>\<Esc>\<CR>"
exe "normal A vim6\<Esc>Azwei\<C-G>u\<C-U>\<Esc>\<CR>"
inoremap <c-u> <left><c-u>
exe "normal A vim7\<*C-U>\<*C-U>\<Esc>\<CR>"
call assert_equal([
\ "1 this shouldn't be deleted",
\ "2 this shouldn't be deleted",
\ "3 this shouldn't be deleted",
\ "4 this should be deleted3",
\ "",
\ "6 this shouldn't be deleted vim5",
\ "7 this shouldn't be deleted vim6",
\ "8 this shouldn't be deleted (not touched yet) vim7",
\ ""], getline(1, '$'))
" Reset values
set compatible&vim
set visualbell&vim
set backspace&vim
" Test new nostop option
%d_
let expected = "foo bar foobar"
call setline(1, expected)
call cursor(1, 8)
exe ":norm! ianotherone\<c-u>"
call assert_equal(expected, getline(1))
call cursor(1, 8)
exe ":norm! ianothertwo\<c-w>"
call assert_equal(expected, getline(1))
let content = getline(1)
for value in ['indent,nostop', 'eol,nostop', 'indent,eol,nostop', 'indent,eol,start,nostop']
exe ":set bs=".. value
%d _
call setline(1, content)
let expected = " foobar"
call cursor(1, 8)
exe ":norm! ianotherone\<c-u>"
call assert_equal(expected, getline(1), 'CTRL-U backspace value: '.. &bs)
let expected = "foo foobar"
call setline(1, content)
call cursor(1, 8)
exe ":norm! ianothertwo\<c-w>"
call assert_equal(expected, getline(1), 'CTRL-W backspace value: '.. &bs)
endfor
" Reset options
set compatible&vim
set visualbell&vim
set backspace&vim
close!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,89 +0,0 @@
" Tests for the backup function
source check.vim
func Test_backup()
set backup backupdir=. backupskip=
new
call setline(1, ['line1', 'line2'])
:f Xbackup.txt
:w! Xbackup.txt
" backup file is only created after
" writing a second time (before overwriting)
:w! Xbackup.txt
let l = readfile('Xbackup.txt~')
call assert_equal(['line1', 'line2'], l)
bw!
set backup&vim backupdir&vim backupskip&vim
call delete('Xbackup.txt')
call delete('Xbackup.txt~')
endfunc
func Test_backup_backupskip()
set backup backupdir=. backupskip=*.txt
new
call setline(1, ['line1', 'line2'])
:f Xbackup.txt
:w! Xbackup.txt
" backup file is only created after
" writing a second time (before overwriting)
:w! Xbackup.txt
call assert_false(filereadable('Xbackup.txt~'))
bw!
set backup&vim backupdir&vim backupskip&vim
call delete('Xbackup.txt')
call delete('Xbackup.txt~')
endfunc
func Test_backup2()
set backup backupdir=.// backupskip=
new
call setline(1, ['line1', 'line2', 'line3'])
:f Xbackup.txt
:w! Xbackup.txt
" backup file is only created after
" writing a second time (before overwriting)
:w! Xbackup.txt
sp *Xbackup.txt~
call assert_equal(['line1', 'line2', 'line3'], getline(1,'$'))
let f = expand('%')
call assert_match('%testdir%Xbackup.txt\~', f)
bw!
bw!
call delete('Xbackup.txt')
call delete(f)
set backup&vim backupdir&vim backupskip&vim
endfunc
func Test_backup2_backupcopy()
set backup backupdir=.// backupcopy=yes backupskip=
new
call setline(1, ['line1', 'line2', 'line3'])
:f Xbackup.txt
:w! Xbackup.txt
" backup file is only created after
" writing a second time (before overwriting)
:w! Xbackup.txt
sp *Xbackup.txt~
call assert_equal(['line1', 'line2', 'line3'], getline(1,'$'))
let f = expand('%')
call assert_match('%testdir%Xbackup.txt\~', f)
bw!
bw!
call delete('Xbackup.txt')
call delete(f)
set backup&vim backupdir&vim backupcopy&vim backupskip&vim
endfunc
" Test for using a non-existing directory as a backup directory
func Test_non_existing_backupdir()
throw 'Skipped: Nvim auto-creates backup directory'
set backupdir=./non_existing_dir backupskip=
call writefile(['line1'], 'Xfile')
new Xfile
call assert_fails('write', 'E510:')
set backupdir&vim backupskip&vim
call delete('Xfile')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,29 +0,0 @@
" Test the :behave command
func Test_behave()
behave mswin
call assert_equal('mouse,key', &selectmode)
call assert_equal('popup', &mousemodel)
call assert_equal('startsel,stopsel', &keymodel)
call assert_equal('exclusive', &selection)
behave xterm
call assert_equal('', &selectmode)
call assert_equal('extend', &mousemodel)
call assert_equal('', &keymodel)
call assert_equal('inclusive', &selection)
set selection&
set mousemodel&
set keymodel&
set selection&
endfunc
func Test_behave_completion()
call feedkeys(":behave \<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"behave mswin xterm', @:)
endfunc
func Test_behave_error()
call assert_fails('behave x', 'E475:')
endfunc

View File

@@ -1,830 +0,0 @@
" Tests for the Blob types
source check.vim
source vim9.vim
func TearDown()
" Run garbage collection after every test
call test_garbagecollect_now()
endfunc
" Tests for Blob type
" Blob creation from constant
func Test_blob_create()
let lines =<< trim END
VAR b = 0zDEADBEEF
call assert_equal(v:t_blob, type(b))
call assert_equal(4, len(b))
call assert_equal(0xDE, b[0])
call assert_equal(0xAD, b[1])
call assert_equal(0xBE, b[2])
call assert_equal(0xEF, b[3])
call assert_fails('VAR x = b[4]')
call assert_equal(0xDE, get(b, 0))
call assert_equal(0xEF, get(b, 3))
call assert_fails('VAR b = 0z1', 'E973:')
call assert_fails('VAR b = 0z1x', 'E973:')
call assert_fails('VAR b = 0z12345', 'E973:')
call assert_equal(0z, v:_null_blob)
LET b = 0z001122.33445566.778899.aabbcc.dd
call assert_equal(0z00112233445566778899aabbccdd, b)
call assert_fails('VAR b = 0z1.1')
call assert_fails('VAR b = 0z.')
call assert_fails('VAR b = 0z001122.')
call assert_fails('call get("", 1)', 'E896:')
call assert_equal(0, len(v:_null_blob))
END
call CheckLegacyAndVim9Success(lines)
endfunc
" assignment to a blob
func Test_blob_assign()
let lines =<< trim END
VAR b = 0zDEADBEEF
VAR b2 = b[1 : 2]
call assert_equal(0zADBE, b2)
VAR bcopy = b[:]
call assert_equal(b, bcopy)
call assert_false(b is bcopy)
LET b = 0zDEADBEEF
LET b2 = b
call assert_true(b is b2)
LET b[:] = 0z11223344
call assert_equal(0z11223344, b)
call assert_equal(0z11223344, b2)
call assert_true(b is b2)
LET b = 0zDEADBEEF
LET b[3 :] = 0z66
call assert_equal(0zDEADBE66, b)
LET b[: 1] = 0z8899
call assert_equal(0z8899BE66, b)
LET b = 0zDEADBEEF
LET b += 0z99
call assert_equal(0zDEADBEEF99, b)
VAR l = [0z12]
VAR m = deepcopy(l)
LET m[0] = 0z34 #" E742 or E741 should not occur.
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b[2 : 3] = 0z112233
END
call CheckLegacyAndVim9Failure(lines, 'E972:')
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b[2 : 3] = 0z11
END
call CheckLegacyAndVim9Failure(lines, 'E972:')
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b[3 : 2] = 0z
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b ..= 0z33
END
call CheckLegacyAndVim9Failure(lines, ['E734:', 'E1019:', 'E734:'])
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b ..= "xx"
END
call CheckLegacyAndVim9Failure(lines, ['E734:', 'E1019:', 'E734:'])
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b += "xx"
END
call CheckLegacyAndVim9Failure(lines, ['E734:', 'E1012:', 'E734:'])
let lines =<< trim END
VAR b = 0zDEADBEEF
LET b[1 : 1] ..= 0z55
END
call CheckLegacyAndVim9Failure(lines, ['E734:', 'E1183:', 'E734:'])
endfunc
func Test_blob_get_range()
let lines =<< trim END
VAR b = 0z0011223344
call assert_equal(0z2233, b[2 : 3])
call assert_equal(0z223344, b[2 : -1])
call assert_equal(0z00, b[0 : -5])
call assert_equal(0z, b[0 : -11])
call assert_equal(0z44, b[-1 :])
call assert_equal(0z0011223344, b[:])
call assert_equal(0z0011223344, b[: -1])
call assert_equal(0z, b[5 : 6])
call assert_equal(0z0011, b[-10 : 1])
END
call CheckLegacyAndVim9Success(lines)
" legacy script white space
let b = 0z0011223344
call assert_equal(0z2233, b[2:3])
endfunc
func Test_blob_get()
let lines =<< trim END
VAR b = 0z0011223344
call assert_equal(0x00, get(b, 0))
call assert_equal(0x22, get(b, 2, 999))
call assert_equal(0x44, get(b, 4))
call assert_equal(0x44, get(b, -1))
call assert_equal(-1, get(b, 5))
call assert_equal(999, get(b, 5, 999))
call assert_equal(-1, get(b, -8))
call assert_equal(999, get(b, -8, 999))
call assert_equal(10, get(v:_null_blob, 2, 10))
call assert_equal(0x00, b[0])
call assert_equal(0x22, b[2])
call assert_equal(0x44, b[4])
call assert_equal(0x44, b[-1])
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
VAR b = 0z0011223344
echo b[5]
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
VAR b = 0z0011223344
echo b[-8]
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
endfunc
func Test_blob_to_string()
let lines =<< trim END
VAR b = 0z00112233445566778899aabbccdd
call assert_equal('0z00112233.44556677.8899AABB.CCDD', string(b))
call assert_equal(b, eval(string(b)))
call remove(b, 4, -1)
call assert_equal('0z00112233', string(b))
call remove(b, 0, 3)
call assert_equal('0z', string(b))
call assert_equal('0z', string(v:_null_blob))
END
call CheckLegacyAndVim9Success(lines)
endfunc
func Test_blob_compare()
let lines =<< trim END
VAR b1 = 0z0011
VAR b2 = 0z1100
VAR b3 = 0z001122
call assert_true(b1 == b1)
call assert_false(b1 == b2)
call assert_false(b1 == b3)
call assert_true(b1 != b2)
call assert_true(b1 != b3)
call assert_true(b1 == 0z0011)
call assert_false(b1 is b2)
LET b2 = b1
call assert_true(b1 == b2)
call assert_true(b1 is b2)
LET b2 = copy(b1)
call assert_true(b1 == b2)
call assert_false(b1 is b2)
LET b2 = b1[:]
call assert_true(b1 == b2)
call assert_false(b1 is b2)
call assert_true(b1 isnot b2)
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
VAR b1 = 0z0011
echo b1 == 9
END
call CheckLegacyAndVim9Failure(lines, ['E977:', 'E1072', 'E1072'])
let lines =<< trim END
VAR b1 = 0z0011
echo b1 != 9
END
call CheckLegacyAndVim9Failure(lines, ['E977:', 'E1072', 'E1072'])
let lines =<< trim END
VAR b1 = 0z0011
VAR b2 = 0z1100
VAR x = b1 > b2
END
call CheckLegacyAndVim9Failure(lines, ['E978:', 'E1072:', 'E1072:'])
let lines =<< trim END
VAR b1 = 0z0011
VAR b2 = 0z1100
VAR x = b1 < b2
END
call CheckLegacyAndVim9Failure(lines, ['E978:', 'E1072:', 'E1072:'])
let lines =<< trim END
VAR b1 = 0z0011
VAR b2 = 0z1100
VAR x = b1 - b2
END
call CheckLegacyAndVim9Failure(lines, ['E974:', 'E1036:', 'E974:'])
let lines =<< trim END
VAR b1 = 0z0011
VAR b2 = 0z1100
VAR x = b1 / b2
END
call CheckLegacyAndVim9Failure(lines, ['E974:', 'E1036:', 'E974:'])
let lines =<< trim END
VAR b1 = 0z0011
VAR b2 = 0z1100
VAR x = b1 * b2
END
call CheckLegacyAndVim9Failure(lines, ['E974:', 'E1036:', 'E974:'])
endfunc
func Test_blob_index_assign()
let lines =<< trim END
VAR b = 0z00
LET b[1] = 0x11
LET b[2] = 0x22
call assert_equal(0z001122, b)
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
VAR b = 0z00
LET b[2] = 0x33
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
VAR b = 0z00
LET b[-2] = 0x33
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
endfunc
func Test_blob_for_loop()
let lines =<< trim END
VAR blob = 0z00010203
VAR i = 0
for byte in blob
call assert_equal(i, byte)
LET i += 1
endfor
call assert_equal(4, i)
LET blob = 0z00
call remove(blob, 0)
call assert_equal(0, len(blob))
for byte in blob
call assert_report('loop over empty blob')
endfor
LET blob = 0z0001020304
LET i = 0
for byte in blob
call assert_equal(i, byte)
if i == 1
call remove(blob, 0)
elseif i == 3
call remove(blob, 3)
endif
LET i += 1
endfor
call assert_equal(5, i)
END
call CheckLegacyAndVim9Success(lines)
endfunc
func Test_blob_concatenate()
let lines =<< trim END
VAR b = 0z0011
LET b += 0z2233
call assert_equal(0z00112233, b)
LET b = 0zDEAD + 0zBEEF
call assert_equal(0zDEADBEEF, b)
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
VAR b = 0z0011
LET b += "a"
END
call CheckLegacyAndVim9Failure(lines, ['E734:', 'E1012:', 'E734:'])
let lines =<< trim END
VAR b = 0z0011
LET b += 88
END
call CheckLegacyAndVim9Failure(lines, ['E734:', 'E1012:', 'E734:'])
endfunc
func Test_blob_add()
let lines =<< trim END
VAR b = 0z0011
call add(b, 0x22)
call assert_equal(0z001122, b)
END
call CheckLegacyAndVim9Success(lines)
" Only works in legacy script
let b = 0z0011
call add(b, '51')
call assert_equal(0z001133, b)
call assert_equal(1, add(v:_null_blob, 0x22))
let lines =<< trim END
VAR b = 0z0011
call add(b, [9])
END
call CheckLegacyAndVim9Failure(lines, ['E745:', 'E1012:', 'E745:'])
let lines =<< trim END
VAR b = 0z0011
call add("", 0x01)
END
call CheckLegacyAndVim9Failure(lines, 'E897:')
let lines =<< trim END
add(v:_null_blob, 0x22)
END
call CheckDefExecAndScriptFailure(lines, 'E1131:')
endfunc
func Test_blob_empty()
call assert_false(empty(0z001122))
call assert_true(empty(0z))
call assert_true(empty(v:_null_blob))
endfunc
" Test removing items in blob
func Test_blob_func_remove()
let lines =<< trim END
#" Test removing 1 element
VAR b = 0zDEADBEEF
call assert_equal(0xDE, remove(b, 0))
call assert_equal(0zADBEEF, b)
LET b = 0zDEADBEEF
call assert_equal(0xEF, remove(b, -1))
call assert_equal(0zDEADBE, b)
LET b = 0zDEADBEEF
call assert_equal(0xAD, remove(b, 1))
call assert_equal(0zDEBEEF, b)
#" Test removing range of element(s)
LET b = 0zDEADBEEF
call assert_equal(0zBE, remove(b, 2, 2))
call assert_equal(0zDEADEF, b)
LET b = 0zDEADBEEF
call assert_equal(0zADBE, remove(b, 1, 2))
call assert_equal(0zDEEF, b)
END
call CheckLegacyAndVim9Success(lines)
" Test invalid cases
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(b, 5)
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(b, 1, 5)
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(b, 3, 2)
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(1, 0)
END
call CheckLegacyAndVim9Failure(lines, 'E896:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(b, b)
END
call CheckLegacyAndVim9Failure(lines, 'E974:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(b, 1, [])
END
call CheckLegacyAndVim9Failure(lines, 'E745:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call remove(v:_null_blob, 1, 2)
END
call CheckLegacyAndVim9Failure(lines, 'E979:')
let lines =<< trim END
let b = 0zDEADBEEF
lockvar b
call remove(b, 0)
unlockvar b
END
call CheckScriptFailure(lines, 'E741:')
" can only check at script level, not in a :def function
let lines =<< trim END
vim9script
var b = 0zDEADBEEF
lockvar b
remove(b, 0)
END
call CheckScriptFailure(lines, 'E741:')
endfunc
func Test_blob_read_write()
let lines =<< trim END
VAR b = 0zDEADBEEF
call writefile(b, 'Xblob')
VAR br = readfile('Xblob', 'B')
call assert_equal(b, br)
VAR br2 = readblob('Xblob')
call assert_equal(b, br2)
VAR br3 = readblob('Xblob', 1)
call assert_equal(b[1 :], br3)
VAR br4 = readblob('Xblob', 1, 2)
call assert_equal(b[1 : 2], br4)
VAR br5 = readblob('Xblob', -3)
call assert_equal(b[-3 :], br5)
VAR br6 = readblob('Xblob', -3, 2)
call assert_equal(b[-3 : -2], br6)
#" reading past end of file, empty result
VAR br1e = readblob('Xblob', 10000)
call assert_equal(0z, br1e)
#" reading too much, result is truncated
VAR blong = readblob('Xblob', -1000)
call assert_equal(b, blong)
LET blong = readblob('Xblob', -10, 8)
call assert_equal(b, blong)
LET blong = readblob('Xblob', 0, 10)
call assert_equal(b, blong)
call delete('Xblob')
END
call CheckLegacyAndVim9Success(lines)
if filereadable('/dev/random')
let b = readblob('/dev/random', 0, 10)
call assert_equal(10, len(b))
endif
call assert_fails("call readblob('notexist')", 'E484:')
" TODO: How do we test for the E485 error?
" This was crashing when calling readfile() with a directory.
call assert_fails("call readfile('.', 'B')", 'E17: "." is a directory')
endfunc
" filter() item in blob
func Test_blob_filter()
let lines =<< trim END
call assert_equal(v:_null_blob, filter(v:_null_blob, '0'))
call assert_equal(0z, filter(0zDEADBEEF, '0'))
call assert_equal(0zADBEEF, filter(0zDEADBEEF, 'v:val != 0xDE'))
call assert_equal(0zDEADEF, filter(0zDEADBEEF, 'v:val != 0xBE'))
call assert_equal(0zDEADBE, filter(0zDEADBEEF, 'v:val != 0xEF'))
call assert_equal(0zDEADBEEF, filter(0zDEADBEEF, '1'))
call assert_equal(0z01030103, filter(0z010203010203, 'v:val != 0x02'))
call assert_equal(0zADEF, filter(0zDEADBEEF, 'v:key % 2'))
END
call CheckLegacyAndVim9Success(lines)
endfunc
" map() item in blob
func Test_blob_map()
let lines =<< trim END
call assert_equal(0zDFAEBFF0, map(0zDEADBEEF, 'v:val + 1'))
call assert_equal(0z00010203, map(0zDEADBEEF, 'v:key'))
call assert_equal(0zDEAEC0F2, map(0zDEADBEEF, 'v:key + v:val'))
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
call map(0z00, '[9]')
END
call CheckLegacyAndVim9Failure(lines, 'E978:')
endfunc
func Test_blob_index()
let lines =<< trim END
call assert_equal(2, index(0zDEADBEEF, 0xBE))
call assert_equal(-1, index(0zDEADBEEF, 0))
call assert_equal(2, index(0z11111111, 0x11, 2))
call assert_equal(3, 0z11110111->index(0x11, 2))
call assert_equal(2, index(0z11111111, 0x11, -2))
call assert_equal(3, index(0z11110111, 0x11, -2))
call assert_equal(0, index(0z11110111, 0x11, -10))
call assert_equal(-1, index(v:_null_blob, 1))
END
call CheckLegacyAndVim9Success(lines)
let lines =<< trim END
echo index(0z11110111, 0x11, [])
END
call CheckLegacyAndVim9Failure(lines, 'E745:')
let lines =<< trim END
call index("asdf", 0)
END
call CheckLegacyAndVim9Failure(lines, 'E897:')
endfunc
func Test_blob_insert()
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, 0x33)
call assert_equal(0z33DEADBEEF, b)
LET b = 0zDEADBEEF
call insert(b, 0x33, 2)
call assert_equal(0zDEAD33BEEF, b)
END
call CheckLegacyAndVim9Success(lines)
" only works in legacy script
call assert_equal(0, insert(v:_null_blob, 0x33))
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, -1)
END
call CheckLegacyAndVim9Failure(lines, 'E475:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, 257)
END
call CheckLegacyAndVim9Failure(lines, 'E475:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, 0, [9])
END
call CheckLegacyAndVim9Failure(lines, ['E745:', 'E1013:', 'E745:'])
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, 0, -20)
END
call CheckLegacyAndVim9Failure(lines, 'E475:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, 0, 20)
END
call CheckLegacyAndVim9Failure(lines, 'E475:')
let lines =<< trim END
VAR b = 0zDEADBEEF
call insert(b, [])
END
call CheckLegacyAndVim9Failure(lines, ['E745:', 'E1013:', 'E745:'])
let lines =<< trim END
insert(v:_null_blob, 0x33)
END
call CheckDefExecAndScriptFailure(lines, 'E1131:')
let lines =<< trim END
let b = 0zDEADBEEF
lockvar b
call insert(b, 3)
unlockvar b
END
call CheckScriptFailure(lines, 'E741:')
let lines =<< trim END
vim9script
var b = 0zDEADBEEF
lockvar b
insert(b, 3)
END
call CheckScriptFailure(lines, 'E741:')
endfunc
func Test_blob_reverse()
let lines =<< trim END
call assert_equal(0zEFBEADDE, reverse(0zDEADBEEF))
call assert_equal(0zBEADDE, reverse(0zDEADBE))
call assert_equal(0zADDE, reverse(0zDEAD))
call assert_equal(0zDE, reverse(0zDE))
call assert_equal(0z, reverse(v:_null_blob))
END
call CheckLegacyAndVim9Success(lines)
endfunc
func Test_blob_json_encode()
let lines =<< trim END
#" call assert_equal('[222,173,190,239]', json_encode(0zDEADBEEF))
call assert_equal('[222, 173, 190, 239]', json_encode(0zDEADBEEF))
call assert_equal('[]', json_encode(0z))
END
call CheckLegacyAndVim9Success(lines)
endfunc
func Test_blob_lock()
let lines =<< trim END
let b = 0z112233
lockvar b
unlockvar b
let b = 0z44
END
call CheckScriptSuccess(lines)
let lines =<< trim END
vim9script
var b = 0z112233
lockvar b
unlockvar b
b = 0z44
END
call CheckScriptSuccess(lines)
let lines =<< trim END
let b = 0z112233
lockvar b
let b = 0z44
END
call CheckScriptFailure(lines, 'E741:')
let lines =<< trim END
vim9script
var b = 0z112233
lockvar b
b = 0z44
END
call CheckScriptFailure(lines, 'E741:')
endfunc
func Test_blob_sort()
if has('float')
call CheckLegacyAndVim9Failure(['call sort([1.0, 0z11], "f")'], 'E975:')
endif
call CheckLegacyAndVim9Failure(['call sort([11, 0z11], "N")'], 'E974:')
endfunc
" Tests for the blob2list() function
func Test_blob2list()
call assert_fails('let v = blob2list(10)', 'E1238: Blob required for argument 1')
eval 0zFFFF->blob2list()->assert_equal([255, 255])
let tests = [[0z0102, [1, 2]],
\ [0z00, [0]],
\ [0z, []],
\ [0z00000000, [0, 0, 0, 0]],
\ [0zAABB.CCDD, [170, 187, 204, 221]]]
for t in tests
call assert_equal(t[0]->blob2list(), t[1])
endfor
exe 'let v = 0z' .. repeat('000102030405060708090A0B0C0D0E0F', 64)
call assert_equal(1024, blob2list(v)->len())
call assert_equal([4, 8, 15], [v[100], v[1000], v[1023]])
call assert_equal([], blob2list(v:_null_blob))
endfunc
" Tests for the list2blob() function
func Test_list2blob()
call assert_fails('let b = list2blob(0z10)', 'E1211: List required for argument 1')
let tests = [[[1, 2], 0z0102],
\ [[0], 0z00],
\ [[], 0z],
\ [[0, 0, 0, 0], 0z00000000],
\ [[255, 255], 0zFFFF],
\ [[170, 187, 204, 221], 0zAABB.CCDD],
\ ]
for t in tests
call assert_equal(t[1], t[0]->list2blob())
endfor
call assert_fails('let b = list2blob([1, []])', 'E745:')
call assert_fails('let b = list2blob([-1])', 'E1239:')
call assert_fails('let b = list2blob([256])', 'E1239:')
let b = range(16)->repeat(64)->list2blob()
call assert_equal(1024, b->len())
call assert_equal([4, 8, 15], [b[100], b[1000], b[1023]])
call assert_equal(0z, list2blob(v:_null_list))
endfunc
" The following used to cause an out-of-bounds memory access
func Test_blob2string()
let v = '0z' .. repeat('01010101.', 444)
let v ..= '01'
exe 'let b = ' .. v
call assert_equal(v, string(b))
endfunc
func Test_blob_repeat()
call assert_equal(0z, repeat(0z00, 0))
call assert_equal(0z00, repeat(0z00, 1))
call assert_equal(0z0000, repeat(0z00, 2))
call assert_equal(0z00000000, repeat(0z0000, 2))
call assert_equal(0z, repeat(0z12, 0))
call assert_equal(0z, repeat(0z1234, 0))
call assert_equal(0z1234, repeat(0z1234, 1))
call assert_equal(0z12341234, repeat(0z1234, 2))
endfunc
" Test for blob allocation failure
func Test_blob_alloc_failure()
CheckFunction test_alloc_fail
" blob variable
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let v = 0z10', 'E342:')
" blob slice
let v = 0z1020
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let x = v[0:0]', 'E342:')
call assert_equal(0z1020, x)
" blob remove()
let v = 0z10203040
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let x = remove(v, 1, 2)', 'E342:')
call assert_equal(0, x)
" list2blob()
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let a = list2blob([1, 2, 4])', 'E342:')
call assert_equal(0, a)
" mapnew()
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let x = mapnew(0z1234, {_, v -> 1})', 'E342:')
call assert_equal(0, x)
" copy()
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let x = copy(v)', 'E342:')
call assert_equal(0z, x)
" readblob()
call test_alloc_fail(GetAllocId('blob_alloc'), 0, 0)
call assert_fails('let x = readblob("test_blob.vim")', 'E342:')
call assert_equal(0, x)
endfunc
" Test for the indexof() function
func Test_indexof()
let b = 0zdeadbeef
call assert_equal(0, indexof(b, {i, v -> v == 0xde}))
call assert_equal(3, indexof(b, {i, v -> v == 0xef}))
call assert_equal(-1, indexof(b, {i, v -> v == 0x1}))
call assert_equal(1, indexof(b, "v:val == 0xad"))
call assert_equal(-1, indexof(b, "v:val == 0xff"))
call assert_equal(-1, indexof(b, {_, v -> "v == 0xad"}))
call assert_equal(-1, indexof(0z, "v:val == 0x0"))
call assert_equal(-1, indexof(v:_null_blob, "v:val == 0xde"))
call assert_equal(-1, indexof(b, v:_null_string))
" Nvim doesn't have null functions
" call assert_equal(-1, indexof(b, test_null_function()))
let b = 0z01020102
call assert_equal(1, indexof(b, "v:val == 0x02", #{startidx: 0}))
call assert_equal(2, indexof(b, "v:val == 0x01", #{startidx: -2}))
call assert_equal(-1, indexof(b, "v:val == 0x01", #{startidx: 5}))
call assert_equal(0, indexof(b, "v:val == 0x01", #{startidx: -5}))
call assert_equal(0, indexof(b, "v:val == 0x01", v:_null_dict))
" failure cases
call assert_fails('let i = indexof(b, "val == 0xde")', 'E121:')
call assert_fails('let i = indexof(b, {})', 'E1256:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,132 +0,0 @@
" Test for block inserting
"
func Test_blockinsert_indent()
new
filetype plugin indent on
setlocal sw=2 et ft=vim
call setline(1, ['let a=[', ' ''eins'',', ' ''zwei'',', ' ''drei'']'])
call cursor(2, 3)
exe "norm! \<c-v>2jI\\ \<esc>"
call assert_equal(['let a=[', ' \ ''eins'',', ' \ ''zwei'',', ' \ ''drei'']'],
\ getline(1,'$'))
" reset to sane state
filetype off
bwipe!
endfunc
func Test_blockinsert_autoindent()
new
let lines =<< trim END
var d = {
a: () => 0,
b: () => 0,
c: () => 0,
}
END
call setline(1, lines)
filetype plugin indent on
setlocal sw=2 et ft=vim
setlocal indentkeys+=:
exe "norm! 2Gf)\<c-v>2jA: asdf\<esc>"
let expected =<< trim END
var d = {
a: (): asdf => 0,
b: (): asdf => 0,
c: (): asdf => 0,
}
END
call assert_equal(expected, getline(1, 5))
" insert on the next column should do exactly the same
:%dele
call setline(1, lines)
exe "norm! 2Gf)l\<c-v>2jI: asdf\<esc>"
call assert_equal(expected, getline(1, 5))
:%dele
call setline(1, lines)
setlocal sw=8 noet
exe "norm! 2Gf)\<c-v>2jA: asdf\<esc>"
let expected =<< trim END
var d = {
a: (): asdf => 0,
b: (): asdf => 0,
c: (): asdf => 0,
}
END
call assert_equal(expected, getline(1, 5))
" insert on the next column should do exactly the same
:%dele
call setline(1, lines)
exe "norm! 2Gf)l\<c-v>2jI: asdf\<esc>"
call assert_equal(expected, getline(1, 5))
filetype off
bwipe!
endfunc
func Test_blockinsert_delete()
new
let _bs = &bs
set bs=2
call setline(1, ['case Arg is ', ' when Name_Async,', ' when Name_Num_Gangs,', 'end if;'])
exe "norm! ggjVj\<c-v>$o$A\<bs>\<esc>"
"call feedkeys("Vj\<c-v>$o$A\<bs>\<esc>", 'ti')
call assert_equal(["case Arg is ", " when Name_Async", " when Name_Num_Gangs,", "end if;"],
\ getline(1,'$'))
" reset to sane state
let &bs = _bs
bwipe!
endfunc
func Test_blockappend_eol_cursor()
new
" Test 1 Move 1 char left
call setline(1, ['aaa', 'bbb', 'ccc'])
exe "norm! gg$\<c-v>2jA\<left>x\<esc>"
call assert_equal(['aaxa', 'bbxb', 'ccxc'], getline(1, '$'))
" Test 2 Move 2 chars left
sil %d
call setline(1, ['aaa', 'bbb', 'ccc'])
exe "norm! gg$\<c-v>2jA\<left>\<left>x\<esc>"
call assert_equal(['axaa', 'bxbb', 'cxcc'], getline(1, '$'))
" Test 3 Move 3 chars left (outside of the visual selection)
sil %d
call setline(1, ['aaa', 'bbb', 'ccc'])
exe "norm! ggl$\<c-v>2jA\<left>\<left>\<left>x\<esc>"
call assert_equal(['xaaa', 'bbb', 'ccc'], getline(1, '$'))
bw!
endfunc
func Test_blockappend_eol_cursor2()
new
" Test 1 Move 1 char left
call setline(1, ['aaaaa', 'bbb', 'ccccc'])
exe "norm! gg\<c-v>$2jA\<left>x\<esc>"
call assert_equal(['aaaaxa', 'bbbx', 'ccccxc'], getline(1, '$'))
" Test 2 Move 2 chars left
sil %d
call setline(1, ['aaaaa', 'bbb', 'ccccc'])
exe "norm! gg\<c-v>$2jA\<left>\<left>x\<esc>"
call assert_equal(['aaaxaa', 'bbbx', 'cccxcc'], getline(1, '$'))
" Test 3 Move 3 chars left (to the beginning of the visual selection)
sil %d
call setline(1, ['aaaaa', 'bbb', 'ccccc'])
exe "norm! gg\<c-v>$2jA\<left>\<left>\<left>x\<esc>"
call assert_equal(['aaxaaa', 'bbxb', 'ccxccc'], getline(1, '$'))
" Test 4 Move 3 chars left (outside of the visual selection)
sil %d
call setline(1, ['aaaaa', 'bbb', 'ccccc'])
exe "norm! ggl\<c-v>$2jA\<left>\<left>\<left>x\<esc>"
call assert_equal(['aaxaaa', 'bbxb', 'ccxccc'], getline(1, '$'))
" Test 5 Move 4 chars left (outside of the visual selection)
sil %d
call setline(1, ['aaaaa', 'bbb', 'ccccc'])
exe "norm! ggl\<c-v>$2jA\<left>\<left>\<left>\<left>x\<esc>"
call assert_equal(['axaaaa', 'bxbb', 'cxcccc'], getline(1, '$'))
bw!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

File diff suppressed because it is too large Load Diff

View File

@@ -1,525 +0,0 @@
" Tests for Vim buffer
source check.vim
" Test for the :bunload command with an offset
func Test_bunload_with_offset()
%bwipe!
call writefile(['B1'], 'b1')
call writefile(['B2'], 'b2')
call writefile(['B3'], 'b3')
call writefile(['B4'], 'b4')
" Load four buffers. Unload the second and third buffers and then
" execute .+3bunload to unload the last buffer.
edit b1
new b2
new b3
new b4
bunload b2
bunload b3
exe bufwinnr('b1') . 'wincmd w'
.+3bunload
call assert_equal(0, getbufinfo('b4')[0].loaded)
call assert_equal('b1',
\ fnamemodify(getbufinfo({'bufloaded' : 1})[0].name, ':t'))
" Load four buffers. Unload the third and fourth buffers. Execute .+3bunload
" and check whether the second buffer is unloaded.
ball
bunload b3
bunload b4
exe bufwinnr('b1') . 'wincmd w'
.+3bunload
call assert_equal(0, getbufinfo('b2')[0].loaded)
call assert_equal('b1',
\ fnamemodify(getbufinfo({'bufloaded' : 1})[0].name, ':t'))
" Load four buffers. Unload the second and third buffers and from the last
" buffer execute .-3bunload to unload the first buffer.
ball
bunload b2
bunload b3
exe bufwinnr('b4') . 'wincmd w'
.-3bunload
call assert_equal(0, getbufinfo('b1')[0].loaded)
call assert_equal('b4',
\ fnamemodify(getbufinfo({'bufloaded' : 1})[0].name, ':t'))
" Load four buffers. Unload the first and second buffers. Execute .-3bunload
" from the last buffer and check whether the third buffer is unloaded.
ball
bunload b1
bunload b2
exe bufwinnr('b4') . 'wincmd w'
.-3bunload
call assert_equal(0, getbufinfo('b3')[0].loaded)
call assert_equal('b4',
\ fnamemodify(getbufinfo({'bufloaded' : 1})[0].name, ':t'))
%bwipe!
call delete('b1')
call delete('b2')
call delete('b3')
call delete('b4')
call assert_fails('1,4bunload', 'E16:')
call assert_fails(',100bunload', 'E16:')
call assert_fails('$bunload', 'E90:')
endfunc
" Test for :buffer, :bnext, :bprevious, :brewind, :blast and :bmodified
" commands
func Test_buflist_browse()
%bwipe!
call assert_fails('buffer 1000', 'E86:')
call writefile(['foo1', 'foo2', 'foo3', 'foo4'], 'Xfile1')
call writefile(['bar1', 'bar2', 'bar3', 'bar4'], 'Xfile2')
call writefile(['baz1', 'baz2', 'baz3', 'baz4'], 'Xfile3')
edit Xfile1
let b1 = bufnr()
edit Xfile2
let b2 = bufnr()
edit +/baz4 Xfile3
let b3 = bufnr()
call assert_fails('buffer ' .. b1 .. ' abc', 'E488:')
call assert_equal(b3, bufnr())
call assert_equal(4, line('.'))
exe 'buffer +/bar2 ' .. b2
call assert_equal(b2, bufnr())
call assert_equal(2, line('.'))
exe 'buffer +/bar1'
call assert_equal(b2, bufnr())
call assert_equal(1, line('.'))
brewind +
call assert_equal(b1, bufnr())
call assert_equal(4, line('.'))
blast +/baz2
call assert_equal(b3, bufnr())
call assert_equal(2, line('.'))
bprevious +/bar4
call assert_equal(b2, bufnr())
call assert_equal(4, line('.'))
bnext +/baz3
call assert_equal(b3, bufnr())
call assert_equal(3, line('.'))
call assert_fails('bmodified', 'E84:')
call setbufvar(b2, '&modified', 1)
exe 'bmodified +/bar3'
call assert_equal(b2, bufnr())
call assert_equal(3, line('.'))
" With no listed buffers in the list, :bnext and :bprev should fail
%bwipe!
set nobuflisted
call assert_fails('bnext', 'E85:')
call assert_fails('bprev', 'E85:')
set buflisted
call assert_fails('sandbox bnext', 'E48:')
call delete('Xfile1')
call delete('Xfile2')
call delete('Xfile3')
%bwipe!
endfunc
" Test for :bdelete
func Test_bdelete_cmd()
%bwipe!
call assert_fails('bdelete 5', 'E516:')
call assert_fails('1,1bdelete 1 2', 'E488:')
call assert_fails('bdelete \)', 'E55:')
" Deleting a unlisted and unloaded buffer
edit Xfile1
let bnr = bufnr()
set nobuflisted
enew
call assert_fails('bdelete ' .. bnr, 'E516:')
" Deleting more than one buffer
new Xbuf1
new Xbuf2
exe 'bdel ' .. bufnr('Xbuf2') .. ' ' .. bufnr('Xbuf1')
call assert_equal(1, winnr('$'))
call assert_equal(0, getbufinfo('Xbuf1')[0].loaded)
call assert_equal(0, getbufinfo('Xbuf2')[0].loaded)
" Deleting more than one buffer and an invalid buffer
new Xbuf1
new Xbuf2
let cmd = "exe 'bdel ' .. bufnr('Xbuf2') .. ' xxx ' .. bufnr('Xbuf1')"
call assert_fails(cmd, 'E94:')
call assert_equal(2, winnr('$'))
call assert_equal(1, getbufinfo('Xbuf1')[0].loaded)
call assert_equal(0, getbufinfo('Xbuf2')[0].loaded)
%bwipe!
endfunc
func Test_buffer_error()
new foo1
new foo2
call assert_fails('buffer foo', 'E93:')
call assert_fails('buffer bar', 'E94:')
call assert_fails('buffer 0', 'E939:')
%bwipe
endfunc
" Test for the status messages displayed when unloading, deleting or wiping
" out buffers
func Test_buffer_statusmsg()
CheckEnglish
set report=1
new Xbuf1
new Xbuf2
let bnr = bufnr()
exe "normal 2\<C-G>"
call assert_match('buf ' .. bnr .. ':', v:statusmsg)
bunload Xbuf1 Xbuf2
call assert_equal('2 buffers unloaded', v:statusmsg)
bdel Xbuf1 Xbuf2
call assert_equal('2 buffers deleted', v:statusmsg)
bwipe Xbuf1 Xbuf2
call assert_equal('2 buffers wiped out', v:statusmsg)
set report&
endfunc
" Test for quitting the 'swapfile exists' dialog with the split buffer
" command.
func Test_buffer_sbuf_cleanup()
call writefile([], 'Xfile')
" first open the file in a buffer
new Xfile
let bnr = bufnr()
close
" create the swap file
call writefile([], '.Xfile.swp')
" Remove the catch-all that runtest.vim adds
au! SwapExists
augroup BufTest
au!
autocmd SwapExists Xfile let v:swapchoice='q'
augroup END
exe 'sbuf ' . bnr
call assert_equal(1, winnr('$'))
call assert_equal(0, getbufinfo('Xfile')[0].loaded)
" test for :sball
sball
call assert_equal(1, winnr('$'))
call assert_equal(0, getbufinfo('Xfile')[0].loaded)
%bw!
set shortmess+=F
let v:statusmsg = ''
edit Xfile
call assert_equal('', v:statusmsg)
call assert_equal(1, winnr('$'))
call assert_equal(0, getbufinfo('Xfile')[0].loaded)
set shortmess&
call delete('Xfile')
call delete('.Xfile.swp')
augroup BufTest
au!
augroup END
augroup! BufTest
endfunc
" Test for deleting a modified buffer with :confirm
func Test_bdel_with_confirm()
" requires a UI to be active
throw 'Skipped: use test/functional/legacy/buffer_spec.lua'
CheckUnix
CheckNotGui
CheckFeature dialog_con
new
call setline(1, 'test')
call assert_fails('bdel', 'E89:')
call feedkeys('c', 'L')
confirm bdel
call assert_equal(2, winnr('$'))
call assert_equal(1, &modified)
call feedkeys('n', 'L')
confirm bdel
call assert_equal(1, winnr('$'))
endfunc
" Test for editing another buffer from a modified buffer with :confirm
func Test_goto_buf_with_confirm()
" requires a UI to be active
throw 'Skipped: use test/functional/legacy/buffer_spec.lua'
CheckUnix
CheckNotGui
CheckFeature dialog_con
new Xfile
enew
call setline(1, 'test')
call assert_fails('b Xfile', 'E37:')
call feedkeys('c', 'L')
call assert_fails('confirm b Xfile', 'E37:')
call assert_equal(1, &modified)
call assert_equal('', @%)
call feedkeys('y', 'L')
call assert_fails('confirm b Xfile', ['', 'E37:'])
call assert_equal(1, &modified)
call assert_equal('', @%)
call feedkeys('n', 'L')
confirm b Xfile
call assert_equal('Xfile', @%)
close!
endfunc
" Test for splitting buffer with 'switchbuf'
func Test_buffer_switchbuf()
new Xfile
wincmd w
set switchbuf=useopen
sbuf Xfile
call assert_equal(1, winnr())
call assert_equal(2, winnr('$'))
set switchbuf=usetab
tabnew
sbuf Xfile
call assert_equal(1, tabpagenr())
call assert_equal(2, tabpagenr('$'))
set switchbuf&
%bw
endfunc
" Test for BufAdd autocommand wiping out the buffer
func Test_bufadd_autocmd_bwipe()
%bw!
augroup BufAdd_Wipe
au!
autocmd BufAdd Xfile %bw!
augroup END
edit Xfile
call assert_equal('', @%)
call assert_equal(0, bufexists('Xfile'))
augroup BufAdd_Wipe
au!
augroup END
augroup! BufAdd_Wipe
endfunc
" Test for trying to load a buffer with text locked
" <C-\>e in the command line is used to lock the text
func Test_load_buf_with_text_locked()
new Xfile1
edit Xfile2
let cmd = ":\<C-\>eexecute(\"normal \<C-O>\")\<CR>\<C-C>"
call assert_fails("call feedkeys(cmd, 'xt')", 'E565:')
%bw!
endfunc
" Test for using CTRL-^ to edit the alternative file keeping the cursor
" position with 'nostartofline'. Also test using the 'buf' command.
func Test_buffer_edit_altfile()
call writefile(repeat(['one two'], 50), 'Xfile1')
call writefile(repeat(['five six'], 50), 'Xfile2')
set nosol
edit Xfile1
call cursor(25, 5)
edit Xfile2
call cursor(30, 4)
exe "normal \<C-^>"
call assert_equal([0, 25, 5, 0], getpos('.'))
exe "normal \<C-^>"
call assert_equal([0, 30, 4, 0], getpos('.'))
buf Xfile1
call assert_equal([0, 25, 5, 0], getpos('.'))
buf Xfile2
call assert_equal([0, 30, 4, 0], getpos('.'))
set sol&
call delete('Xfile1')
call delete('Xfile2')
endfunc
" Test for running the :sball command with a maximum window count and a
" modified buffer
func Test_sball_with_count()
%bw!
edit Xfile1
call setline(1, ['abc'])
new Xfile2
new Xfile3
new Xfile4
2sball
call assert_equal(bufnr('Xfile4'), winbufnr(1))
call assert_equal(bufnr('Xfile1'), winbufnr(2))
call assert_equal(0, getbufinfo('Xfile2')[0].loaded)
call assert_equal(0, getbufinfo('Xfile3')[0].loaded)
%bw!
endfunc
func Test_badd_options()
new SomeNewBuffer
setlocal numberwidth=3
wincmd p
badd +1 SomeNewBuffer
new SomeNewBuffer
call assert_equal(3, &numberwidth)
close
close
bwipe! SomeNewBuffer
endfunc
func Test_balt()
new SomeNewBuffer
balt +3 OtherBuffer
e #
call assert_equal('OtherBuffer', bufname())
endfunc
" Test for buffer match URL(scheme) check
" scheme is alpha and inner hyphen only.
func Test_buffer_scheme()
CheckMSWindows
set noshellslash
%bwipe!
let bufnames = [
\ #{id: 'ssb0', name: 'test://xyz/foo/ssb0' , match: 1},
\ #{id: 'ssb1', name: 'test+abc://xyz/foo/ssb1', match: 0},
\ #{id: 'ssb2', name: 'test_abc://xyz/foo/ssb2', match: 0},
\ #{id: 'ssb3', name: 'test-abc://xyz/foo/ssb3', match: 1},
\ #{id: 'ssb4', name: '-test://xyz/foo/ssb4' , match: 0},
\ #{id: 'ssb5', name: 'test-://xyz/foo/ssb5' , match: 0},
\]
for buf in bufnames
new `=buf.name`
if buf.match
call assert_equal(buf.name, getbufinfo(buf.id)[0].name)
else
" slashes will have become backslashes
call assert_notequal(buf.name, getbufinfo(buf.id)[0].name)
endif
bwipe
endfor
set shellslash&
endfunc
" this was using a NULL pointer after failing to use the pattern
func Test_buf_pattern_invalid()
vsplit 0000000
silent! buf [0--]\&\zs*\zs*e
bwipe!
vsplit 00000000000000000000000000
silent! buf [0--]\&\zs*\zs*e
bwipe!
" similar case with different code path
split 0
edit ÿ
silent! buf [0--]\&\zs*\zs*0
bwipe!
endfunc
" Test for the 'maxmem' and 'maxmemtot' options
func Test_buffer_maxmem()
" use 1KB per buffer and 2KB for all the buffers
" set maxmem=1 maxmemtot=2
new
let v:errmsg = ''
" try opening some files
edit test_arglist.vim
call assert_equal('test_arglist.vim', bufname())
edit test_eval_stuff.vim
call assert_equal('test_eval_stuff.vim', bufname())
b test_arglist.vim
call assert_equal('test_arglist.vim', bufname())
b test_eval_stuff.vim
call assert_equal('test_eval_stuff.vim', bufname())
close
call assert_equal('', v:errmsg)
" set maxmem& maxmemtot&
endfunc
" Test for buffer allocation failure
func Test_buflist_alloc_failure()
CheckFunction test_alloc_fail
%bw!
edit Xfile1
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('edit Xfile2', 'E342:')
" test for bufadd()
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('call bufadd("Xbuffer")', 'E342:')
" test for setting the arglist
edit Xfile2
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('next Xfile3', 'E342:')
" test for setting the alternate buffer name when writing a file
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('write Xother', 'E342:')
call delete('Xother')
" test for creating a buffer using bufnr()
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails("call bufnr('Xnewbuf', v:true)", 'E342:')
" test for renaming buffer using :file
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('file Xnewfile', 'E342:')
" test for creating a buffer for a popup window
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('call popup_create("mypop", {})', 'E342:')
if has('terminal')
" test for creating a buffer for a terminal window
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('call term_start(&shell)', 'E342:')
%bw!
endif
" test for loading a new buffer after wiping out all the buffers
edit Xfile4
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('%bw!', 'E342:')
" test for :checktime loading the buffer
call writefile(['one'], 'Xfile5')
if has('unix')
edit Xfile5
" sleep for some time to make sure the timestamp is different
sleep 200m
call writefile(['two'], 'Xfile5')
set autoread
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('checktime', 'E342:')
set autoread&
bw!
endif
" test for :vimgrep loading a dummy buffer
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('vimgrep two Xfile5', 'E342:')
call delete('Xfile5')
" test for quickfix command loading a buffer
call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0)
call assert_fails('cexpr "Xfile6:10:Line10"', 'E342:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,296 +0,0 @@
" Tests for setbufline(), getbufline(), appendbufline(), deletebufline()
source shared.vim
source screendump.vim
source check.vim
func Test_setbufline_getbufline()
" similar to Test_set_get_bufline()
new
let b = bufnr('%')
hide
call assert_equal(0, setbufline(b, 1, ['foo', 'bar']))
call assert_equal(['foo'], getbufline(b, 1))
call assert_equal('foo', getbufoneline(b, 1))
call assert_equal(['bar'], getbufline(b, '$'))
call assert_equal('bar', getbufoneline(b, '$'))
call assert_equal(['foo', 'bar'], getbufline(b, 1, 2))
exe "bd!" b
call assert_equal([], getbufline(b, 1, 2))
split Xtest
call setline(1, ['a', 'b', 'c'])
let b = bufnr('%')
wincmd w
call assert_equal(1, setbufline(b, 5, 'x'))
call assert_equal(1, setbufline(b, 5, ['x']))
call assert_equal(1, setbufline(b, 5, []))
call assert_equal(1, setbufline(b, 5, v:_null_list))
call assert_equal(1, 'x'->setbufline(bufnr('$') + 1, 1))
call assert_equal(1, ['x']->setbufline(bufnr('$') + 1, 1))
call assert_equal(1, []->setbufline(bufnr('$') + 1, 1))
call assert_equal(1, v:_null_list->setbufline(bufnr('$') + 1, 1))
call assert_equal(['a', 'b', 'c'], getbufline(b, 1, '$'))
call assert_equal(0, setbufline(b, 4, ['d', 'e']))
call assert_equal(['c'], b->getbufline(3))
call assert_equal('c', b->getbufoneline(3))
call assert_equal(['d'], getbufline(b, 4))
call assert_equal('d', getbufoneline(b, 4))
call assert_equal(['e'], getbufline(b, 5))
call assert_equal('e', getbufoneline(b, 5))
call assert_equal([], getbufline(b, 6))
call assert_equal([], getbufline(b, 2, 1))
if has('job')
call setbufline(b, 2, [function('eval'), #{key: 123}, test_null_job()])
call assert_equal(["function('eval')",
\ "{'key': 123}",
\ "no process"],
\ getbufline(b, 2, 4))
endif
exe "bwipe! " . b
endfunc
func Test_setbufline_getbufline_fold()
split Xtest
setlocal foldmethod=expr foldexpr=0
let b = bufnr('%')
new
call assert_equal(0, setbufline(b, 1, ['foo', 'bar']))
call assert_equal(['foo'], getbufline(b, 1))
call assert_equal(['bar'], getbufline(b, 2))
call assert_equal(['foo', 'bar'], getbufline(b, 1, 2))
exe "bwipe!" b
bwipe!
endfunc
func Test_setbufline_getbufline_fold_tab()
split Xtest
setlocal foldmethod=expr foldexpr=0
let b = bufnr('%')
tab new
call assert_equal(0, setbufline(b, 1, ['foo', 'bar']))
call assert_equal(['foo'], getbufline(b, 1))
call assert_equal(['bar'], getbufline(b, 2))
call assert_equal(['foo', 'bar'], getbufline(b, 1, 2))
exe "bwipe!" b
bwipe!
endfunc
func Test_setline_startup()
let cmd = GetVimCommand('Xscript')
if cmd == ''
return
endif
call writefile(['call setline(1, "Hello")', 'silent w Xtest', 'q!'], 'Xscript')
call system(cmd)
call assert_equal(['Hello'], readfile('Xtest'))
call delete('Xscript')
call delete('Xtest')
endfunc
func Test_appendbufline()
new
let b = bufnr('%')
hide
new
call setline(1, ['line1', 'line2', 'line3'])
normal! 2gggg
call assert_equal(2, line("''"))
call assert_equal(0, appendbufline(b, 0, ['foo', 'bar']))
call assert_equal(['foo'], getbufline(b, 1))
call assert_equal(['bar'], getbufline(b, 2))
call assert_equal(['foo', 'bar'], getbufline(b, 1, 2))
call assert_equal(0, appendbufline(b, 0, 'baz'))
call assert_equal(['baz', 'foo', 'bar'], getbufline(b, 1, 3))
" appendbufline() in a hidden buffer shouldn't move marks in current window.
call assert_equal(2, line("''"))
bwipe!
exe "bd!" b
call assert_equal([], getbufline(b, 1, 3))
split Xtest
call setline(1, ['a', 'b', 'c'])
let b = bufnr('%')
wincmd w
call assert_equal(1, appendbufline(b, -1, 'x'))
call assert_equal(1, appendbufline(b, -1, ['x']))
call assert_equal(1, appendbufline(b, -1, []))
call assert_equal(1, appendbufline(b, -1, v:_null_list))
call assert_equal(1, appendbufline(b, 4, 'x'))
call assert_equal(1, appendbufline(b, 4, ['x']))
call assert_equal(1, appendbufline(b, 4, []))
call assert_equal(1, appendbufline(b, 4, v:_null_list))
call assert_equal(1, appendbufline(1234, 1, 'x'))
call assert_equal(1, appendbufline(1234, 1, ['x']))
call assert_equal(1, appendbufline(1234, 1, []))
call assert_equal(1, appendbufline(1234, 1, v:_null_list))
call assert_equal(0, appendbufline(b, 1, []))
call assert_equal(0, appendbufline(b, 1, v:_null_list))
call assert_equal(1, appendbufline(b, 3, []))
call assert_equal(1, appendbufline(b, 3, v:_null_list))
call assert_equal(['a', 'b', 'c'], getbufline(b, 1, '$'))
call assert_equal(0, appendbufline(b, 3, ['d', 'e']))
call assert_equal(['c'], getbufline(b, 3))
call assert_equal(['d'], getbufline(b, 4))
call assert_equal(['e'], getbufline(b, 5))
call assert_equal([], getbufline(b, 6))
exe "bwipe! " . b
endfunc
func Test_deletebufline()
new
let b = bufnr('%')
call setline(1, ['aaa', 'bbb', 'ccc'])
hide
new
call setline(1, ['line1', 'line2', 'line3'])
normal! 2gggg
call assert_equal(2, line("''"))
call assert_equal(0, deletebufline(b, 2))
call assert_equal(['aaa', 'ccc'], getbufline(b, 1, 2))
call assert_equal(0, deletebufline(b, 2, 8))
call assert_equal(['aaa'], getbufline(b, 1, 2))
" deletebufline() in a hidden buffer shouldn't move marks in current window.
call assert_equal(2, line("''"))
bwipe!
exe "bd!" b
call assert_equal(1, b->deletebufline(1))
call assert_equal(1, deletebufline(-1, 1))
split Xtest
call setline(1, ['a', 'b', 'c'])
call cursor(line('$'), 1)
let b = bufnr('%')
wincmd w
call assert_equal(1, deletebufline(b, 4))
call assert_equal(0, deletebufline(b, 1))
call assert_equal(['b', 'c'], getbufline(b, 1, 2))
exe "bwipe! " . b
edit XbufOne
let one = bufnr()
call setline(1, ['a', 'b', 'c'])
setlocal nomodifiable
split XbufTwo
let two = bufnr()
call assert_fails('call deletebufline(one, 1)', 'E21:')
call assert_equal(two, bufnr())
bwipe! XbufTwo
bwipe! XbufOne
endfunc
func Test_appendbufline_redraw()
CheckScreendump
let lines =<< trim END
new foo
let winnr = 'foo'->bufwinnr()
let buf = bufnr('foo')
wincmd p
call appendbufline(buf, '$', range(1,200))
exe winnr .. 'wincmd w'
norm! G
wincmd p
call deletebufline(buf, 1, '$')
call appendbufline(buf, '$', 'Hello Vim world...')
END
call writefile(lines, 'XscriptMatchCommon')
let buf = RunVimInTerminal('-S XscriptMatchCommon', #{rows: 10})
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_appendbufline_1', {})
call StopVimInTerminal(buf)
call delete('XscriptMatchCommon')
endfunc
func Test_setbufline_select_mode()
new
call setline(1, ['foo', 'bar'])
call feedkeys("j^v2l\<C-G>", 'nx')
let bufnr = bufadd('Xdummy')
call bufload(bufnr)
call setbufline(bufnr, 1, ['abc'])
call feedkeys("x", 'nx')
call assert_equal(['foo', 'x'], getline(1, 2))
exe "bwipe! " .. bufnr
bwipe!
endfunc
func Test_deletebufline_select_mode()
new
call setline(1, ['foo', 'bar'])
call feedkeys("j^v2l\<C-G>", 'nx')
let bufnr = bufadd('Xdummy')
call bufload(bufnr)
call setbufline(bufnr, 1, ['abc', 'def'])
call deletebufline(bufnr, 1)
call feedkeys("x", 'nx')
call assert_equal(['foo', 'x'], getline(1, 2))
exe "bwipe! " .. bufnr
bwipe!
endfunc
func Test_setbufline_startup_nofile()
let before =<< trim [CODE]
set shortmess+=F
file Xresult
set buftype=nofile
call setbufline('', 1, 'success')
[CODE]
let after =<< trim [CODE]
set buftype=
write
quit
[CODE]
if !RunVim(before, after, '--clean')
return
endif
call assert_equal(['success'], readfile('Xresult'))
call delete('Xresult')
endfunc
" Test that setbufline(), appendbufline() and deletebufline() should fail and
" return 1 when "textlock" is active.
func Test_change_bufline_with_textlock()
new
inoremap <buffer> <expr> <F2> setbufline('', 1, '')
call assert_fails("normal a\<F2>", 'E565:')
call assert_equal('1', getline(1))
inoremap <buffer> <expr> <F2> appendbufline('', 1, '')
call assert_fails("normal a\<F2>", 'E565:')
call assert_equal('11', getline(1))
inoremap <buffer> <expr> <F2> deletebufline('', 1)
call assert_fails("normal a\<F2>", 'E565:')
call assert_equal('111', getline(1))
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,187 +0,0 @@
" Tests for the getbufinfo(), getwininfo() and gettabinfo() functions
function Test_getbufwintabinfo()
edit Xtestfile1
edit Xtestfile2
let buflist = getbufinfo()
call assert_equal(2, len(buflist))
call assert_match('Xtestfile1', buflist[0].name)
call assert_match('Xtestfile2', getbufinfo('Xtestfile2')[0].name)
call assert_equal([], getbufinfo(2016))
edit Xtestfile1
hide edit Xtestfile2
hide enew
call assert_equal(3, len(getbufinfo({'bufloaded':1})))
set tabstop&vim
let b:editor = 'vim'
let l = getbufinfo('%')
call assert_equal(bufnr('%'), l[0].bufnr)
call assert_equal('vim', l[0].variables.editor)
call assert_notequal(-1, index(l[0].windows, '%'->bufwinid()))
let l = '%'->getbufinfo()
call assert_equal(bufnr('%'), l[0].bufnr)
" Test for getbufinfo() with 'bufmodified'
call assert_equal(0, len(getbufinfo({'bufmodified' : 1})))
call setbufline('Xtestfile1', 1, ["Line1"])
let l = getbufinfo({'bufmodified' : 1})
call assert_equal(1, len(l))
call assert_equal(bufnr('Xtestfile1'), l[0].bufnr)
if has('signs')
call append(0, ['Linux', 'Windows', 'Mac'])
sign define Mark text=>> texthl=Search
exe "sign place 2 line=3 name=Mark buffer=" . bufnr('%')
let l = getbufinfo('%')
call assert_equal(2, l[0].signs[0].id)
call assert_equal(3, l[0].signs[0].lnum)
call assert_equal('Mark', l[0].signs[0].name)
sign unplace *
sign undefine Mark
enew!
endif
only
let w1_id = win_getid()
setl foldcolumn=3
new
let w2_id = win_getid()
tabnew | let w3_id = win_getid()
new | let w4_id = win_getid()
vert new | let w5_id = win_getid()
eval 'green'->setwinvar(0, 'signal')
tabfirst
let winlist = getwininfo()
call assert_equal(5, len(winlist))
call assert_equal(winwidth(1), winlist[0].width)
call assert_equal(1, winlist[0].wincol)
" tabline adds one row in terminal, not in GUI
let tablineheight = winlist[0].winrow == 2 ? 1 : 0
call assert_equal(tablineheight + 1, winlist[0].winrow)
call assert_equal(winbufnr(2), winlist[1].bufnr)
call assert_equal(winheight(2), winlist[1].height)
call assert_equal(1, winlist[1].wincol)
call assert_equal(3, winlist[1].textoff) " foldcolumn
call assert_equal(tablineheight + winheight(1) + 2, winlist[1].winrow)
call assert_equal(1, winlist[2].winnr)
call assert_equal(tablineheight + 1, winlist[2].winrow)
call assert_equal(1, winlist[2].wincol)
call assert_equal(winlist[2].width + 2, winlist[3].wincol)
call assert_equal(1, winlist[4].wincol)
call assert_equal(1, winlist[0].tabnr)
call assert_equal(1, winlist[1].tabnr)
call assert_equal(2, winlist[2].tabnr)
call assert_equal(2, winlist[3].tabnr)
call assert_equal(2, winlist[4].tabnr)
call assert_equal('green', winlist[2].variables.signal)
call assert_equal(w4_id, winlist[3].winid)
let winfo = w5_id->getwininfo()[0]
call assert_equal(2, winfo.tabnr)
call assert_equal([], getwininfo(3))
call settabvar(1, 'space', 'build')
let tablist = gettabinfo()
call assert_equal(2, len(tablist))
call assert_equal(3, len(tablist[1].windows))
call assert_equal(2, tablist[1].tabnr)
call assert_equal('build', tablist[0].variables.space)
call assert_equal(w2_id, tablist[0].windows[0])
call assert_equal([], 3->gettabinfo())
tabonly | only
lexpr ''
lopen
copen
let winlist = getwininfo()
call assert_false(winlist[0].quickfix)
call assert_false(winlist[0].loclist)
call assert_true(winlist[1].quickfix)
call assert_true(winlist[1].loclist)
call assert_true(winlist[2].quickfix)
call assert_false(winlist[2].loclist)
wincmd t | only
endfunction
function Test_get_buf_options()
let opts = bufnr()->getbufvar('&')
call assert_equal(v:t_dict, type(opts))
call assert_equal(8, opts.tabstop)
endfunc
function Test_get_win_options()
if has('folding')
set foldlevel=999
endif
set list
let opts = getwinvar(1, '&')
call assert_equal(v:t_dict, type(opts))
call assert_equal(0, opts.linebreak)
call assert_equal(1, opts.list)
if has('folding')
call assert_equal(999, opts.foldlevel)
endif
if has('signs')
call assert_equal('auto', opts.signcolumn)
endif
let opts = gettabwinvar(1, 1, '&')
call assert_equal(v:t_dict, type(opts))
call assert_equal(0, opts.linebreak)
call assert_equal(1, opts.list)
if has('signs')
call assert_equal('auto', opts.signcolumn)
endif
set list&
if has('folding')
set foldlevel=0
endif
endfunc
function Test_getbufinfo_lastused()
new Xfoo
let info = getbufinfo('Xfoo')[0]
call assert_equal(has_key(info, 'lastused'), 1)
call assert_equal(type(info.lastused), type(0))
endfunc
func Test_getbufinfo_lines()
new Xfoo
call setline(1, ['a', 'bc', 'd'])
let bn = bufnr('%')
hide
call assert_equal(3, getbufinfo(bn)[0]["linecount"])
edit Xfoo
bw!
endfunc
func Test_getwininfo_au()
enew
call setline(1, range(1, 16))
let g:info = #{}
augroup T1
au!
au WinEnter * let g:info = getwininfo(win_getid())[0]
augroup END
4split
" Check that calling getwininfo() from WinEnter returns fresh values for
" topline and botline.
call assert_equal(1, g:info.topline)
call assert_equal(4, g:info.botline)
close
unlet g:info
augroup! T1
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,256 +0,0 @@
" Test for :cd and chdir()
source shared.vim
source check.vim
func Test_cd_large_path()
" This used to crash with a heap write overflow.
call assert_fails('cd ' . repeat('x', 5000), 'E344:')
endfunc
func Test_cd_up_and_down()
let path = getcwd()
cd ..
call assert_notequal(path, getcwd())
exe 'cd ' .. fnameescape(path)
call assert_equal(path, getcwd())
endfunc
func Test_cd_no_arg()
if has('unix')
" Test that cd without argument goes to $HOME directory on Unix systems.
let path = getcwd()
cd
call assert_equal($HOME, getcwd())
call assert_notequal(path, getcwd())
exe 'cd ' .. fnameescape(path)
call assert_equal(path, getcwd())
else
" Test that cd without argument echoes cwd on non-Unix systems.
call assert_match(getcwd(), execute('cd'))
endif
endfunc
func Test_cd_minus()
" Test the :cd - goes back to the previous directory.
let path = getcwd()
cd ..
let path_dotdot = getcwd()
call assert_notequal(path, path_dotdot)
cd -
call assert_equal(path, getcwd())
cd -
call assert_equal(path_dotdot, getcwd())
cd -
call assert_equal(path, getcwd())
" Test for :cd - after a failed :cd
call assert_fails('cd /nonexistent', 'E344:')
call assert_equal(path, getcwd())
cd -
call assert_equal(path_dotdot, getcwd())
cd -
" Test for :cd - without a previous directory
let lines =<< trim [SCRIPT]
call assert_fails('cd -', 'E186:')
call assert_fails('call chdir("-")', 'E186:')
call writefile(v:errors, 'Xresult')
qall!
[SCRIPT]
call writefile(lines, 'Xscript')
if RunVim([], [], '--clean -S Xscript')
call assert_equal([], readfile('Xresult'))
endif
call delete('Xscript')
call delete('Xresult')
endfunc
" Test for chdir()
func Test_chdir_func()
let topdir = getcwd()
call mkdir('Xdir/y/z', 'p')
" Create a few tabpages and windows with different directories
new
cd Xdir
tabnew
tcd y
below new
below new
lcd z
tabfirst
call assert_match('^\[global\] .*/Xdir$', trim(execute('verbose pwd')))
call chdir('..')
call assert_equal('y', fnamemodify(getcwd(1, 2), ':t'))
call assert_equal('z', fnamemodify(3->getcwd(2), ':t'))
tabnext | wincmd t
call assert_match('^\[tabpage\] .*/y$', trim(execute('verbose pwd')))
eval '..'->chdir()
call assert_equal('Xdir', fnamemodify(getcwd(1, 2), ':t'))
call assert_equal('Xdir', fnamemodify(getcwd(2, 2), ':t'))
call assert_equal('z', fnamemodify(getcwd(3, 2), ':t'))
call assert_equal('testdir', fnamemodify(getcwd(1, 1), ':t'))
3wincmd w
call assert_match('^\[window\] .*/z$', trim(execute('verbose pwd')))
call chdir('..')
call assert_equal('Xdir', fnamemodify(getcwd(1, 2), ':t'))
call assert_equal('Xdir', fnamemodify(getcwd(2, 2), ':t'))
call assert_equal('y', fnamemodify(getcwd(3, 2), ':t'))
call assert_equal('testdir', fnamemodify(getcwd(1, 1), ':t'))
" Error case
call assert_fails("call chdir('dir-abcd')", 'E344:')
silent! let d = chdir("dir_abcd")
call assert_equal("", d)
" Should not crash
call chdir(d)
only | tabonly
call chdir(topdir)
call delete('Xdir', 'rf')
endfunc
" Test for changing to the previous directory '-'
func Test_prev_dir()
let topdir = getcwd()
call mkdir('Xdir/a/b/c', 'p')
" Create a few tabpages and windows with different directories
new | only
tabnew | new
tabnew
tabfirst
cd Xdir
tabnext | wincmd t
tcd a
wincmd w
lcd b
tabnext
tcd a/b/c
" Change to the previous directory twice in all the windows.
tabfirst
cd - | cd -
tabnext | wincmd t
tcd - | tcd -
wincmd w
lcd - | lcd -
tabnext
tcd - | tcd -
" Check the directory of all the windows
tabfirst
call assert_equal('Xdir', fnamemodify(getcwd(), ':t'))
tabnext | wincmd t
call assert_equal('a', fnamemodify(getcwd(), ':t'))
wincmd w
call assert_equal('b', fnamemodify(getcwd(), ':t'))
tabnext
call assert_equal('c', fnamemodify(getcwd(), ':t'))
" Change to the previous directory using chdir()
tabfirst
call chdir("-") | call chdir("-")
tabnext | wincmd t
call chdir("-") | call chdir("-")
wincmd w
call chdir("-") | call chdir("-")
tabnext
call chdir("-") | call chdir("-")
" Check the directory of all the windows
tabfirst
call assert_equal('Xdir', fnamemodify(getcwd(), ':t'))
tabnext | wincmd t
call assert_equal('a', fnamemodify(getcwd(), ':t'))
wincmd w
call assert_equal('b', fnamemodify(getcwd(), ':t'))
tabnext
call assert_equal('c', fnamemodify(getcwd(), ':t'))
only | tabonly
call chdir(topdir)
call delete('Xdir', 'rf')
endfunc
func Test_lcd_split()
let curdir = getcwd()
lcd ..
split
lcd -
call assert_equal(curdir, getcwd())
quit!
endfunc
func Test_cd_from_non_existing_dir()
CheckNotMSWindows
let saveddir = getcwd()
call mkdir('Xdeleted_dir')
cd Xdeleted_dir
call delete(saveddir .. '/Xdeleted_dir', 'd')
" Expect E187 as the current directory was deleted.
call assert_fails('pwd', 'E187:')
call assert_equal('', getcwd())
cd -
call assert_equal(saveddir, getcwd())
endfunc
func Test_cd_completion()
call mkdir('XComplDir1', 'p')
call mkdir('XComplDir2', 'p')
call writefile([], 'XComplFile')
for cmd in ['cd', 'chdir', 'lcd', 'lchdir', 'tcd', 'tchdir']
call feedkeys(':' .. cmd .. " XCompl\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"' .. cmd .. ' XComplDir1/ XComplDir2/', @:)
endfor
call delete('XComplDir1', 'd')
call delete('XComplDir2', 'd')
call delete('XComplFile')
endfunc
func Test_cd_unknown_dir()
call mkdir('Xa')
cd Xa
call writefile(['text'], 'Xb.txt')
edit Xa/Xb.txt
let first_buf = bufnr()
cd ..
edit
call assert_equal(first_buf, bufnr())
edit Xa/Xb.txt
call assert_notequal(first_buf, bufnr())
bwipe!
exe "bwipe! " .. first_buf
call delete('Xa', 'rf')
endfunc
func Test_getcwd_actual_dir()
CheckFunction test_autochdir
CheckOption autochdir
let startdir = getcwd()
call mkdir('Xactual')
call test_autochdir()
set autochdir
edit Xactual/file.txt
call assert_match('testdir.Xactual$', getcwd())
lcd ..
call assert_match('testdir$', getcwd())
edit
call assert_match('testdir.Xactual$', getcwd())
call assert_match('testdir$', getcwd(win_getid()))
set noautochdir
bwipe!
call chdir(startdir)
call delete('Xactual', 'rf')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,216 +0,0 @@
" Tests for the :cdo, :cfdo, :ldo and :lfdo commands
source check.vim
CheckFeature quickfix
" Create the files used by the tests
func SetUp()
call writefile(["Line1", "Line2", "Line3"], 'Xtestfile1')
call writefile(["Line1", "Line2", "Line3"], 'Xtestfile2')
call writefile(["Line1", "Line2", "Line3"], 'Xtestfile3')
endfunc
" Remove the files used by the tests
func TearDown()
call delete('Xtestfile1')
call delete('Xtestfile2')
call delete('Xtestfile3')
endfunc
" Returns the current line in '<filename> <linenum>L <column>C' format
func GetRuler()
return expand('%') . ' ' . line('.') . 'L' . ' ' . col('.') . 'C'
endfunc
" Tests for the :cdo and :ldo commands
func XdoTests(cchar)
enew
" Shortcuts for calling the cdo and ldo commands
let Xdo = a:cchar . 'do'
let Xgetexpr = a:cchar . 'getexpr'
let Xprev = a:cchar. 'prev'
let XdoCmd = Xdo . ' call add(l, GetRuler())'
" Try with an empty list
let l = []
exe XdoCmd
call assert_equal([], l)
" Populate the list and then try
exe Xgetexpr . " ['non-error 1', 'Xtestfile1:1:3:Line1', 'non-error 2', 'Xtestfile2:2:2:Line2', 'non-error 3', 'Xtestfile3:3:1:Line3']"
let l = []
exe XdoCmd
call assert_equal(['Xtestfile1 1L 3C', 'Xtestfile2 2L 2C', 'Xtestfile3 3L 1C'], l)
" Run command only on selected error lines
let l = []
enew
exe "2,3" . XdoCmd
call assert_equal(['Xtestfile2 2L 2C', 'Xtestfile3 3L 1C'], l)
" Boundary condition tests
let l = []
enew
exe "1,1" . XdoCmd
call assert_equal(['Xtestfile1 1L 3C'], l)
let l = []
enew
exe "3" . XdoCmd
call assert_equal(['Xtestfile3 3L 1C'], l)
" Range test commands
let l = []
enew
exe "%" . XdoCmd
call assert_equal(['Xtestfile1 1L 3C', 'Xtestfile2 2L 2C', 'Xtestfile3 3L 1C'], l)
let l = []
enew
exe "1,$" . XdoCmd
call assert_equal(['Xtestfile1 1L 3C', 'Xtestfile2 2L 2C', 'Xtestfile3 3L 1C'], l)
let l = []
enew
exe Xprev
exe "." . XdoCmd
call assert_equal(['Xtestfile2 2L 2C'], l)
let l = []
enew
exe "+" . XdoCmd
call assert_equal(['Xtestfile3 3L 1C'], l)
" Invalid error lines test
let l = []
enew
exe "silent! 27" . XdoCmd
exe "silent! 4,5" . XdoCmd
call assert_equal([], l)
" Run commands from an unsaved buffer
let v:errmsg=''
let l = []
enew
setlocal modified
exe "silent! 2,2" . XdoCmd
if v:errmsg !~# 'No write since last change'
call add(v:errors, 'Unsaved file change test failed')
endif
" If the executed command fails, then the operation should be aborted
enew!
let subst_count = 0
exe "silent!" . Xdo . " s/Line/xLine/ | let subst_count += 1"
if subst_count != 1 || getline('.') != 'xLine1'
call add(v:errors, 'Abort command on error test failed')
endif
let l = []
exe "2,2" . Xdo . "! call add(l, GetRuler())"
call assert_equal(['Xtestfile2 2L 2C'], l)
" List with no valid error entries
let l = []
edit! +2 Xtestfile1
exe Xgetexpr . " ['non-error 1', 'non-error 2', 'non-error 3']"
exe XdoCmd
call assert_equal([], l)
exe "silent! 2" . XdoCmd
call assert_equal([], l)
let v:errmsg=''
exe "%" . XdoCmd
exe "1,$" . XdoCmd
exe "." . XdoCmd
call assert_equal('', v:errmsg)
" List with only one valid entry
let l = []
exe Xgetexpr . " ['Xtestfile3:3:1:Line3']"
exe XdoCmd
call assert_equal(['Xtestfile3 3L 1C'], l)
endfunc
" Tests for the :cfdo and :lfdo commands
func XfdoTests(cchar)
enew
" Shortcuts for calling the cfdo and lfdo commands
let Xfdo = a:cchar . 'fdo'
let Xgetexpr = a:cchar . 'getexpr'
let XfdoCmd = Xfdo . ' call add(l, GetRuler())'
let Xpfile = a:cchar. 'pfile'
" Clear the quickfix/location list
exe Xgetexpr . " []"
" Try with an empty list
let l = []
exe XfdoCmd
call assert_equal([], l)
" Populate the list and then try
exe Xgetexpr . " ['non-error 1', 'Xtestfile1:1:3:Line1', 'Xtestfile1:2:1:Line2', 'non-error 2', 'Xtestfile2:2:2:Line2', 'non-error 3', 'Xtestfile3:2:3:Line2', 'Xtestfile3:3:1:Line3']"
let l = []
exe XfdoCmd
call assert_equal(['Xtestfile1 1L 3C', 'Xtestfile2 2L 2C', 'Xtestfile3 2L 3C'], l)
" Run command only on selected error lines
let l = []
exe "2,3" . XfdoCmd
call assert_equal(['Xtestfile2 2L 2C', 'Xtestfile3 2L 3C'], l)
" Boundary condition tests
let l = []
exe "3" . XfdoCmd
call assert_equal(['Xtestfile3 2L 3C'], l)
" Range test commands
let l = []
exe "%" . XfdoCmd
call assert_equal(['Xtestfile1 1L 3C', 'Xtestfile2 2L 2C', 'Xtestfile3 2L 3C'], l)
let l = []
exe "1,$" . XfdoCmd
call assert_equal(['Xtestfile1 1L 3C', 'Xtestfile2 2L 2C', 'Xtestfile3 2L 3C'], l)
let l = []
exe Xpfile
exe "." . XfdoCmd
call assert_equal(['Xtestfile2 2L 2C'], l)
" List with only one valid entry
let l = []
exe Xgetexpr . " ['Xtestfile2:2:5:Line2']"
exe XfdoCmd
call assert_equal(['Xtestfile2 2L 5C'], l)
endfunc
" Tests for cdo and cfdo
func Test_cdo()
call XdoTests('c')
call XfdoTests('c')
endfunc
" Tests for ldo and lfdo
func Test_ldo()
call XdoTests('l')
call XfdoTests('l')
endfunc
" Test for making 'shm' doesn't interfere with the output.
func Test_cdo_print()
enew | only!
cgetexpr ["Xtestfile1:1:Line1", "Xtestfile2:1:Line1", "Xtestfile3:1:Line1"]
cdo print
call assert_equal('Line1', Screenline(&lines))
call assert_equal('Line1', Screenline(&lines - 3))
call assert_equal('Line1', Screenline(&lines - 6))
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,95 +0,0 @@
" Tests for b:changedtick
func Test_changedtick_increments()
new
" New buffer has an empty line, tick starts at 2.
let expected = 2
call assert_equal(expected, b:changedtick)
call assert_equal(expected, b:['changedtick'])
call setline(1, 'hello')
let expected += 1
call assert_equal(expected, b:changedtick)
call assert_equal(expected, b:['changedtick'])
undo
" Somehow undo counts as two changes.
let expected += 2
call assert_equal(expected, b:changedtick)
call assert_equal(expected, b:['changedtick'])
bwipe!
endfunc
func Test_changedtick_dict_entry()
let d = b:
call assert_equal(b:changedtick, d['changedtick'])
endfunc
func Test_changedtick_bdel()
new
let bnr = bufnr('%')
let v = b:changedtick
bdel
" Delete counts as a change too.
call assert_equal(v + 1, getbufvar(bnr, 'changedtick'))
endfunc
func Test_changedtick_islocked()
call assert_equal(0, islocked('b:changedtick'))
let d = b:
call assert_equal(0, islocked('d.changedtick'))
endfunc
func Test_changedtick_fixed()
call assert_fails('let b:changedtick = 4', 'E46:')
call assert_fails('let b:["changedtick"] = 4', 'E46:')
call assert_fails('lockvar b:changedtick', 'E940:')
call assert_fails('lockvar b:["changedtick"]', 'E46:')
call assert_fails('unlockvar b:changedtick', 'E940:')
call assert_fails('unlockvar b:["changedtick"]', 'E46:')
call assert_fails('unlet b:changedtick', 'E795:')
call assert_fails('unlet b:["changedtick"]', 'E46:')
let d = b:
call assert_fails('lockvar d["changedtick"]', 'E46:')
call assert_fails('unlockvar d["changedtick"]', 'E46:')
call assert_fails('unlet d["changedtick"]', 'E46:')
endfunc
func Test_changedtick_not_incremented_with_write()
new
let fname = "XChangeTick"
exe 'w ' .. fname
" :write when the buffer is not changed does not increment changedtick
let expected = b:changedtick
w
call assert_equal(expected, b:changedtick)
" :write when the buffer IS changed DOES increment changedtick
let expected = b:changedtick + 1
setlocal modified
w
call assert_equal(expected, b:changedtick)
" Two ticks: change + write
let expected = b:changedtick + 2
call setline(1, 'hello')
w
call assert_equal(expected, b:changedtick)
" Two ticks: start insert + write
let expected = b:changedtick + 2
normal! o
w
call assert_equal(expected, b:changedtick)
" Three ticks: start insert + change + write
let expected = b:changedtick + 3
normal! ochanged
w
call assert_equal(expected, b:changedtick)
bwipe
call delete(fname)
endfunc

View File

@@ -1,107 +0,0 @@
" Tests for the changelist functionality
" When splitting a window the changelist position is wrong.
" Test the changelist position after splitting a window.
" Test for the bug fixed by 7.4.386
func Test_changelist()
let save_ul = &ul
enew!
call append('$', ['1', '2'])
exe "normal i\<C-G>u"
exe "normal Gkylpa\<C-G>u"
set ul=100
exe "normal Gylpa\<C-G>u"
set ul=100
normal gg
vsplit
normal g;
call assert_equal([3, 2], [line('.'), col('.')])
normal g;
call assert_equal([2, 2], [line('.'), col('.')])
call assert_fails('normal g;', 'E662:')
new
call assert_fails('normal g;', 'E664:')
%bwipe!
let &ul = save_ul
endfunc
" Moving a split should not change its changelist index.
func Test_changelist_index_move_split()
exe "norm! iabc\<C-G>u\ndef\<C-G>u\nghi"
vsplit
normal 99g;
call assert_equal(0, getchangelist('%')[1])
wincmd L
call assert_equal(0, getchangelist('%')[1])
endfunc
" Tests for the getchangelist() function
func Test_changelist_index()
edit Xfile1.txt
exe "normal iabc\<C-G>u\ndef\<C-G>u\nghi"
call assert_equal(3, getchangelist('%')[1])
" Move one step back in the changelist.
normal 2g;
hide edit Xfile2.txt
exe "normal iabcd\<C-G>u\ndefg\<C-G>u\nghij"
call assert_equal(3, getchangelist('%')[1])
" Move to the beginning of the changelist.
normal 99g;
" Check the changelist indices.
call assert_equal(0, getchangelist('%')[1])
call assert_equal(1, getchangelist('#')[1])
bwipe!
call delete('Xfile1.txt')
call delete('Xfile2.txt')
endfunc
func Test_getchangelist()
bwipe!
enew
call assert_equal([], 10->getchangelist())
call assert_equal([[], 0], getchangelist())
call writefile(['line1', 'line2', 'line3'], 'Xfile1.txt')
call writefile(['line1', 'line2', 'line3'], 'Xfile2.txt')
edit Xfile1.txt
let buf_1 = bufnr()
exe "normal 1Goline\<C-G>u1.1"
exe "normal 3Goline\<C-G>u2.1"
exe "normal 5Goline\<C-G>u3.1"
normal g;
call assert_equal([[
\ {'lnum' : 2, 'col' : 4, 'coladd' : 0},
\ {'lnum' : 4, 'col' : 4, 'coladd' : 0},
\ {'lnum' : 6, 'col' : 4, 'coladd' : 0}], 2],
\ getchangelist('%'))
hide edit Xfile2.txt
let buf_2 = bufnr()
exe "normal 1GOline\<C-G>u1.0"
exe "normal 2Goline\<C-G>u2.0"
call assert_equal([[
\ {'lnum' : 1, 'col' : 6, 'coladd' : 0},
\ {'lnum' : 3, 'col' : 6, 'coladd' : 0}], 2],
\ getchangelist('%'))
hide enew
call assert_equal([[
\ {'lnum' : 2, 'col' : 4, 'coladd' : 0},
\ {'lnum' : 4, 'col' : 4, 'coladd' : 0},
\ {'lnum' : 6, 'col' : 4, 'coladd' : 0}], 2],
\ getchangelist(buf_1))
call assert_equal([[
\ {'lnum' : 1, 'col' : 6, 'coladd' : 0},
\ {'lnum' : 3, 'col' : 6, 'coladd' : 0}], 2],
\ getchangelist(buf_2))
bwipe!
call delete('Xfile1.txt')
call delete('Xfile2.txt')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,99 +0,0 @@
" Test for character search commands - t, T, f, F, ; and ,
func Test_charsearch()
enew!
call append(0, ['Xabcdefghijkemnopqretuvwxyz',
\ 'Yabcdefghijkemnopqretuvwxyz',
\ 'Zabcdefghijkemnokqretkvwxyz'])
" check that "fe" and ";" work
1
normal! ylfep;;p,,p
call assert_equal('XabcdeXfghijkeXmnopqreXtuvwxyz', getline(1))
" check that save/restore works
2
normal! ylfep
let csave = getcharsearch()
normal! fip
call setcharsearch(csave)
normal! ;p;p
call assert_equal('YabcdeYfghiYjkeYmnopqreYtuvwxyz', getline(2))
" check that setcharsearch() changes the settings.
3
normal! ylfep
eval {'char': 'k'}->setcharsearch()
normal! ;p
call setcharsearch({'forward': 0})
normal! $;p
call setcharsearch({'until': 1})
set cpo-=;
normal! ;;p
call assert_equal('ZabcdeZfghijkZZemnokqretkZvwxyz', getline(3))
" check that repeating a search before and after a line fails
normal 3Gfv
call assert_beeps('normal ;')
call assert_beeps('normal ,')
" clear the character search
call setcharsearch({'char' : ''})
call assert_equal('', getcharsearch().char)
call assert_fails("call setcharsearch([])", 'E715:')
enew!
endfunc
" Test for character search in virtual edit mode with <Tab>
func Test_csearch_virtualedit()
new
set virtualedit=all
call setline(1, "a\tb")
normal! tb
call assert_equal([0, 1, 2, 6], getpos('.'))
set virtualedit&
bw!
endfunc
" Test for character search failure in latin1 encoding
func Test_charsearch_latin1()
new
let save_enc = &encoding
" set encoding=latin1
call setline(1, 'abcdefghijk')
call assert_beeps('normal fz')
call assert_beeps('normal tx')
call assert_beeps('normal $Fz')
call assert_beeps('normal $Tx')
let &encoding = save_enc
bw!
endfunc
" Test for using character search to find a multibyte character with composing
" characters.
func Test_charsearch_composing_char()
new
call setline(1, "one two thq\u0328\u0301r\u0328\u0301ree")
call feedkeys("fr\u0328\u0301", 'xt')
call assert_equal([0, 1, 16, 0, 12], getcurpos())
" use character search with a multi-byte character followed by a
" non-composing character
call setline(1, "abc deȉf ghi")
call feedkeys("ggcf\u0209\u0210", 'xt')
call assert_equal("\u0210f ghi", getline(1))
bw!
endfunc
" Test for character search with 'hkmap'
func Test_charsearch_hkmap()
throw "Skipped: Nvim does not support 'hkmap'"
new
set hkmap
call setline(1, "ùðáâ÷ëòéïçìêöî")
call feedkeys("fë", 'xt')
call assert_equal([0, 1, 11, 0, 6], getcurpos())
set hkmap&
bw!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,19 +0,0 @@
" Tests for related f{char} and t{char} using utf-8.
" Test for t,f,F,T movement commands
func Test_search_cmds()
new!
call setline(1, "・最初から最後まで最強のVimは最高")
1
normal! f最
call assert_equal([0, 1, 4, 0], getpos('.'))
normal! ;
call assert_equal([0, 1, 16, 0], getpos('.'))
normal! 2;
call assert_equal([0, 1, 43, 0], getpos('.'))
normal! ,
call assert_equal([0, 1, 28, 0], getpos('.'))
bw!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,121 +0,0 @@
" Tests for the :checkpath command
" Test for 'include' without \zs or \ze
func Test_checkpath1()
call mkdir("Xdir1/dir2", "p")
call writefile(['#include "bar.a"'], 'Xdir1/dir2/foo.a')
call writefile(['#include "baz.a"'], 'Xdir1/dir2/bar.a')
call writefile(['#include "foo.a"'], 'Xdir1/dir2/baz.a')
call writefile(['#include <foo.a>'], 'Xbase.a')
edit Xbase.a
set path=Xdir1/dir2
let res = split(execute("checkpath!"), "\n")
call assert_equal([
\ '--- Included files in path ---',
\ 'Xdir1/dir2/foo.a',
\ 'Xdir1/dir2/foo.a -->',
\ ' Xdir1/dir2/bar.a',
\ ' Xdir1/dir2/bar.a -->',
\ ' Xdir1/dir2/baz.a',
\ ' Xdir1/dir2/baz.a -->',
\ ' "foo.a" (Already listed)'], res)
enew
call delete("./Xbase.a")
call delete("Xdir1", "rf")
set path&
endfunc
func DotsToSlashes()
return substitute(v:fname, '\.', '/', 'g') . '.b'
endfunc
" Test for 'include' with \zs and \ze
func Test_checkpath2()
call mkdir("Xdir1/dir2", "p")
call writefile(['%inc /bar/'], 'Xdir1/dir2/foo.b')
call writefile(['%inc /baz/'], 'Xdir1/dir2/bar.b')
call writefile(['%inc /foo/'], 'Xdir1/dir2/baz.b')
call writefile(['%inc /foo/'], 'Xbase.b')
let &include='^\s*%inc\s*/\zs[^/]\+\ze'
let &includeexpr='DotsToSlashes()'
edit Xbase.b
set path=Xdir1/dir2
let res = split(execute("checkpath!"), "\n")
call assert_equal([
\ '--- Included files in path ---',
\ 'Xdir1/dir2/foo.b',
\ 'Xdir1/dir2/foo.b -->',
\ ' Xdir1/dir2/bar.b',
\ ' Xdir1/dir2/bar.b -->',
\ ' Xdir1/dir2/baz.b',
\ ' Xdir1/dir2/baz.b -->',
\ ' foo (Already listed)'], res)
enew
call delete("./Xbase.b")
call delete("Xdir1", "rf")
set path&
set include&
set includeexpr&
endfunc
func StripNewlineChar()
if v:fname =~ '\n$'
return v:fname[:-2]
endif
return v:fname
endfunc
" Test for 'include' with \zs and no \ze
func Test_checkpath3()
call mkdir("Xdir1/dir2", "p")
call writefile(['%inc bar.c'], 'Xdir1/dir2/foo.c')
call writefile(['%inc baz.c'], 'Xdir1/dir2/bar.c')
call writefile(['%inc foo.c'], 'Xdir1/dir2/baz.c')
call writefile(['%inc foo.c'], 'Xdir1/dir2/FALSE.c')
call writefile(['%inc FALSE.c foo.c'], 'Xbase.c')
let &include='^\s*%inc\s*\%([[:upper:]][^[:space:]]*\s\+\)\?\zs\S\+\ze'
let &includeexpr='StripNewlineChar()'
edit Xbase.c
set path=Xdir1/dir2
let res = split(execute("checkpath!"), "\n")
call assert_equal([
\ '--- Included files in path ---',
\ 'Xdir1/dir2/foo.c',
\ 'Xdir1/dir2/foo.c -->',
\ ' Xdir1/dir2/bar.c',
\ ' Xdir1/dir2/bar.c -->',
\ ' Xdir1/dir2/baz.c',
\ ' Xdir1/dir2/baz.c -->',
\ ' foo.c (Already listed)'], res)
enew
call delete("./Xbase.c")
call delete("Xdir1", "rf")
set path&
set include&
set includeexpr&
endfunc
" Test for invalid regex in 'include' and 'define' options
func Test_checkpath_errors()
let save_include = &include
set include=\\%(
call assert_fails('checkpath', 'E53:')
let &include = save_include
let save_define = &define
set define=\\%(
call assert_fails('dsearch abc', 'E53:')
let &define = save_define
call assert_fails('psearch \%(', 'E53:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

File diff suppressed because it is too large Load Diff

View File

@@ -1,97 +0,0 @@
scriptencoding utf-8
func Run_cjk_linebreak_after(rigorous)
set textwidth=12
for punct in [
\ '!', '%', ')', ',', ':', ';', '>', '?', ']', '}', '', '”', '†', '‡',
\ '…', '‰', '‱', '‼', '⁇', '⁈', '⁉', '℃', '℉', '、', '。', '〉', '》',
\ '」', '』', '】', '', '〗', '〙', '〛', '', '', '', '', '',
\ '', '', '', '']
call setline('.', '这是一个测试' .. punct.'试试 CJK 行禁则补丁。')
normal gqq
if a:rigorous
call assert_equal('这是一个测', getline(1))
else
call assert_equal('这是一个测试' .. punct, getline(1))
endif
%d_
endfor
endfunc
func Test_cjk_linebreak_after()
set formatoptions=croqn2mB1j
call Run_cjk_linebreak_after(0)
endfunc
func Test_cjk_linebreak_after_rigorous()
set formatoptions=croqn2mB1j]
call Run_cjk_linebreak_after(1)
endfunc
func Run_cjk_linebreak_before()
set textwidth=12
for punct in [
\ '(', '<', '[', '`', '{', '', '“', '〈', '《', '「', '『', '【', '',
\ '〖', '〘', '〚', '', '', '']
call setline('.', '这是个测试' .. punct.'试试 CJK 行禁则补丁。')
normal gqq
call assert_equal('这是个测试', getline(1))
%d_
endfor
endfunc
func Test_cjk_linebreak_before()
set formatoptions=croqn2mB1j
call Run_cjk_linebreak_before()
endfunc
func Test_cjk_linebreak_before_rigorous()
set formatoptions=croqn2mB1j]
call Run_cjk_linebreak_before()
endfunc
func Run_cjk_linebreak_nobetween(rigorous)
" …… must not start a line
call setline('.', '这是个测试……试试 CJK 行禁则补丁。')
set textwidth=12 ambiwidth=double
normal gqq
if a:rigorous
call assert_equal('这是个测', getline(1))
else
call assert_equal('这是个测试……', getline(1))
endif
%d_
call setline('.', '这是一个测试……试试 CJK 行禁则补丁。')
set textwidth=12 ambiwidth=double
normal gqq
call assert_equal('这是一个测', getline(1))
%d_
" but —— can
call setline('.', '这是个测试——试试 CJK 行禁则补丁。')
set textwidth=12 ambiwidth=double
normal gqq
call assert_equal('这是个测试', getline(1))
endfunc
func Test_cjk_linebreak_nobetween()
set formatoptions=croqn2mB1j
call Run_cjk_linebreak_nobetween(0)
endfunc
func Test_cjk_linebreak_nobetween_rigorous()
set formatoptions=croqn2mB1j]
call Run_cjk_linebreak_nobetween(1)
endfunc
func Test_cjk_linebreak_join_punct()
for punct in ['——', '〗', '', '。', '……']
call setline(1, '文本文本' .. punct)
call setline(2, 'English')
set formatoptions=croqn2mB1j
normal ggJ
call assert_equal('文本文本' .. punct.'English', getline(1))
%d_
endfor
endfunc

View File

@@ -1,195 +0,0 @@
" Tests for the +clientserver feature.
source check.vim
CheckFeature job
if !has('clientserver')
call assert_fails('call remote_startserver("local")', 'E942:')
endif
CheckFeature clientserver
source shared.vim
func Check_X11_Connection()
if has('x11')
CheckEnv DISPLAY
try
call remote_send('xxx', '')
catch
if v:exception =~ 'E240:'
throw 'Skipped: no connection to the X server'
endif
" ignore other errors
endtry
endif
endfunc
func Test_client_server()
let cmd = GetVimCommand()
if cmd == ''
return
endif
call Check_X11_Connection()
let name = 'XVIMTEST'
let cmd .= ' --servername ' . name
let job = job_start(cmd, {'stoponexit': 'kill', 'out_io': 'null'})
call WaitForAssert({-> assert_equal("run", job_status(job))})
" Takes a short while for the server to be active.
" When using valgrind it takes much longer.
call WaitForAssert({-> assert_match(name, serverlist())})
if !has('win32')
if RunVim([], [], '--serverlist >Xtest_serverlist')
let lines = readfile('Xtest_serverlist')
call assert_true(index(lines, 'XVIMTEST') >= 0)
endif
call delete('Xtest_serverlist')
endif
eval name->remote_foreground()
call remote_send(name, ":let testvar = 'yes'\<CR>")
call WaitFor('remote_expr("' . name . '", "exists(\"testvar\") ? testvar : \"\"", "", 1) == "yes"')
call assert_equal('yes', remote_expr(name, "testvar", "", 2))
call assert_fails("let x=remote_expr(name, '2+x')", 'E449:')
call assert_fails("let x=remote_expr('[], '2+2')", 'E116:')
if has('unix') && has('gui') && !has('gui_running')
" Running in a terminal and the GUI is available: Tell the server to open
" the GUI and check that the remote command still works.
" Need to wait for the GUI to start up, otherwise the send hangs in trying
" to send to the terminal window.
if has('gui_motif')
" For this GUI ignore the 'failed to create input context' error.
call remote_send(name, ":call test_ignore_error('E285') | gui -f\<CR>")
else
call remote_send(name, ":gui -f\<CR>")
endif
" Wait for the server to be up and answering requests.
" When using valgrind this can be very, very slow.
sleep 1
call WaitForAssert({-> assert_match('\d', name->remote_expr("v:version", "", 1))}, 10000)
call remote_send(name, ":let testvar = 'maybe'\<CR>")
call WaitForAssert({-> assert_equal('maybe', remote_expr(name, "testvar", "", 2))})
endif
call assert_fails('call remote_send("XXX", ":let testvar = ''yes''\<CR>")', 'E241')
call writefile(['one'], 'Xclientfile')
let cmd = GetVimProg() .. ' --servername ' .. name .. ' --remote Xclientfile'
call system(cmd)
call WaitForAssert({-> assert_equal('Xclientfile', remote_expr(name, "bufname()", "", 2))})
call WaitForAssert({-> assert_equal('one', remote_expr(name, "getline(1)", "", 2))})
call writefile(['one', 'two'], 'Xclientfile')
call system(cmd)
call WaitForAssert({-> assert_equal('two', remote_expr(name, "getline(2)", "", 2))})
call delete('Xclientfile')
" Expression evaluated locally.
if v:servername == ''
eval 'MYSELF'->remote_startserver()
" May get MYSELF1 when running the test again.
call assert_match('MYSELF', v:servername)
call assert_fails("call remote_startserver('MYSELF')", 'E941:')
endif
let g:testvar = 'myself'
call assert_equal('myself', remote_expr(v:servername, 'testvar'))
call remote_send(v:servername, ":let g:testvar2 = 75\<CR>")
call feedkeys('', 'x')
call assert_equal(75, g:testvar2)
call assert_fails('let v = remote_expr(v:servername, "/2")', ['E15:.*/2'])
call remote_send(name, ":call server2client(expand('<client>'), 'got it')\<CR>", 'g:myserverid')
call assert_equal('got it', g:myserverid->remote_read(2))
call remote_send(name, ":eval expand('<client>')->server2client('another')\<CR>", 'g:myserverid')
let peek_result = 'nothing'
let r = g:myserverid->remote_peek('peek_result')
" unpredictable whether the result is already available.
if r > 0
call assert_equal('another', peek_result)
elseif r == 0
call assert_equal('nothing', peek_result)
else
call assert_report('remote_peek() failed')
endif
let g:peek_result = 'empty'
call WaitFor('remote_peek(g:myserverid, "g:peek_result") > 0')
call assert_equal('another', g:peek_result)
call assert_equal('another', remote_read(g:myserverid, 2))
if !has('gui_running')
" In GUI vim, the following tests display a dialog box
let cmd = GetVimProg() .. ' --servername ' .. name
" Run a separate instance to send a command to the server
call remote_expr(name, 'execute("only")')
call system(cmd .. ' --remote-send ":new Xfile<CR>"')
call assert_equal('2', remote_expr(name, 'winnr("$")'))
call assert_equal('Xfile', remote_expr(name, 'winbufnr(1)->bufname()'))
call remote_expr(name, 'execute("only")')
" Invoke a remote-expr. On MS-Windows, the returned value has a carriage
" return.
let l = system(cmd .. ' --remote-expr "2 + 2"')
call assert_equal(['4'], split(l, "\n"))
" Edit multiple files using --remote
call system(cmd .. ' --remote Xfile1 Xfile2 Xfile3')
call assert_match(".*Xfile1\n.*Xfile2\n.*Xfile3\n", remote_expr(name, 'argv()'))
eval name->remote_send(":%bw!\<CR>")
" Edit files in separate tab pages
call system(cmd .. ' --remote-tab Xfile1 Xfile2 Xfile3')
call WaitForAssert({-> assert_equal('3', remote_expr(name, 'tabpagenr("$")'))})
call assert_match('.*\<Xfile2', remote_expr(name, 'bufname(tabpagebuflist(2)[0])'))
eval name->remote_send(":%bw!\<CR>")
" Edit a file using --remote-wait
eval name->remote_send(":source $VIMRUNTIME/plugin/rrhelper.vim\<CR>")
call system(cmd .. ' --remote-wait +enew Xfile1')
call assert_match('.*\<Xfile1', remote_expr(name, 'bufname("#")'))
eval name->remote_send(":%bw!\<CR>")
" Edit files using --remote-tab-wait
call system(cmd .. ' --remote-tabwait +tabonly\|enew Xfile1 Xfile2')
call assert_equal('1', remote_expr(name, 'tabpagenr("$")'))
eval name->remote_send(":%bw!\<CR>")
" Error cases
if v:lang == "C" || v:lang =~ '^[Ee]n'
let l = split(system(cmd .. ' --remote +pwd'), "\n")
call assert_equal("Argument missing after: \"+pwd\"", l[1])
endif
let l = system(cmd .. ' --remote-expr "abcd"')
call assert_match('^E449: ', l)
endif
eval name->remote_send(":%bw!\<CR>")
eval name->remote_send(":qa!\<CR>")
try
call WaitForAssert({-> assert_equal("dead", job_status(job))})
finally
if job_status(job) != 'dead'
call assert_report('Server did not exit')
call job_stop(job, 'kill')
endif
endtry
call assert_fails('call remote_startserver([])', 'E730:')
call assert_fails("let x = remote_peek([])", 'E730:')
call assert_fails("let x = remote_read('vim10')",
\ has('unix') ? ['E573:.*vim10'] : 'E277:')
call assert_fails("call server2client('abc', 'xyz')",
\ has('unix') ? ['E573:.*abc'] : 'E258:')
endfunc
" Uncomment this line to get a debugging log
" call ch_logfile('channellog', 'w')
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,174 +0,0 @@
" Tests for :[count]close! command
func Test_close_count()
enew! | only
let wids = [win_getid()]
for i in range(5)
new
call add(wids, win_getid())
endfor
4wincmd w
close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[5], wids[4], wids[3], wids[1], wids[0]], ids)
1close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[3], wids[1], wids[0]], ids)
$close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[3], wids[1]], ids)
1wincmd w
2close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[1]], ids)
1wincmd w
new
call add(wids, win_getid())
new
call add(wids, win_getid())
2wincmd w
-1close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[6], wids[4], wids[1]], ids)
2wincmd w
+1close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[6], wids[4]], ids)
only!
endfunc
" Tests for :[count]hide command
func Test_hide_count()
enew! | only
let wids = [win_getid()]
for i in range(5)
new
call add(wids, win_getid())
endfor
4wincmd w
.hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[5], wids[4], wids[3], wids[1], wids[0]], ids)
1hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[3], wids[1], wids[0]], ids)
$hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[3], wids[1]], ids)
1wincmd w
2hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[1]], ids)
1wincmd w
new
call add(wids, win_getid())
new
call add(wids, win_getid())
3wincmd w
-hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[7], wids[4], wids[1]], ids)
2wincmd w
+hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[7], wids[4]], ids)
only!
endfunc
" Tests for :[count]close! command with 'hidden'
func Test_hidden_close_count()
enew! | only
let wids = [win_getid()]
for i in range(5)
new
call add(wids, win_getid())
endfor
set hidden
$ hide
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[5], wids[4], wids[3], wids[2], wids[1]], ids)
$-1 close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[5], wids[4], wids[3], wids[1]], ids)
1wincmd w
.+close!
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[5], wids[3], wids[1]], ids)
set nohidden
only!
endfunc
" Tests for 'CTRL-W c' command to close windows.
func Test_winclose_command()
enew! | only
let wids = [win_getid()]
for i in range(5)
new
call add(wids, win_getid())
endfor
set hidden
4wincmd w
exe "normal \<C-W>c"
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[5], wids[4], wids[3], wids[1], wids[0]], ids)
exe "normal 1\<C-W>c"
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[3], wids[1], wids[0]], ids)
exe "normal 9\<C-W>c"
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[3], wids[1]], ids)
1wincmd w
exe "normal 2\<C-W>c"
let ids = []
windo call add(ids, win_getid())
call assert_equal([wids[4], wids[1]], ids)
set nohidden
only!
endfunc

File diff suppressed because it is too large Load Diff

View File

@@ -1,196 +0,0 @@
" Test for user command counts.
func Test_command_count_0()
let bufnr = bufnr('%')
set hidden
set noswapfile
split DoesNotExistEver
let lastbuf = bufnr('$')
call setline(1, 'asdf')
quit!
command! -range -addr=loaded_buffers RangeLoadedBuffers :let lines = [<line1>, <line2>]
command! -range=% -addr=loaded_buffers RangeLoadedBuffersAll :let lines = [<line1>, <line2>]
command! -range -addr=buffers RangeBuffers :let lines = [<line1>, <line2>]
command! -range=% -addr=buffers RangeBuffersAll :let lines = [<line1>, <line2>]
.,$RangeLoadedBuffers
call assert_equal([bufnr, bufnr], lines)
%RangeLoadedBuffers
call assert_equal([bufnr, bufnr], lines)
RangeLoadedBuffersAll
call assert_equal([bufnr, bufnr], lines)
.,$RangeBuffers
call assert_equal([bufnr, lastbuf], lines)
%RangeBuffers
call assert_equal([bufnr, lastbuf], lines)
RangeBuffersAll
call assert_equal([bufnr, lastbuf], lines)
delcommand RangeLoadedBuffers
delcommand RangeLoadedBuffersAll
delcommand RangeBuffers
delcommand RangeBuffersAll
set hidden&
set swapfile&
endfunc
func Test_command_count_1()
silent! %argd
arga a b c d e
argdo echo "loading buffers"
argu 3
command! -range -addr=arguments RangeArguments :let lines = [<line1>, <line2>]
command! -range=% -addr=arguments RangeArgumentsAll :let lines = [<line1>, <line2>]
.-,$-RangeArguments
call assert_equal([2, 4], lines)
%RangeArguments
call assert_equal([1, 5], lines)
RangeArgumentsAll
call assert_equal([1, 5], lines)
N
.RangeArguments
call assert_equal([2, 2], lines)
delcommand RangeArguments
delcommand RangeArgumentsAll
split|split|split|split
3wincmd w
command! -range -addr=windows RangeWindows :let lines = [<line1>, <line2>]
.,$RangeWindows
call assert_equal([3, 5], lines)
%RangeWindows
call assert_equal([1, 5], lines)
delcommand RangeWindows
command! -range=% -addr=windows RangeWindowsAll :let lines = [<line1>, <line2>]
RangeWindowsAll
call assert_equal([1, 5], lines)
delcommand RangeWindowsAll
only
blast|bd
tabe|tabe|tabe|tabe
normal 2gt
command! -range -addr=tabs RangeTabs :let lines = [<line1>, <line2>]
.,$RangeTabs
call assert_equal([2, 5], lines)
%RangeTabs
call assert_equal([1, 5], lines)
delcommand RangeTabs
command! -range=% -addr=tabs RangeTabsAll :let lines = [<line1>, <line2>]
RangeTabsAll
call assert_equal([1, 5], lines)
delcommand RangeTabsAll
1tabonly
s/\n/\r\r\r\r\r/
2ma<
$-ma>
command! -range=% RangeLines :let lines = [<line1>, <line2>]
'<,'>RangeLines
call assert_equal([2, 5], lines)
delcommand RangeLines
command! -range=% -buffer LocalRangeLines :let lines = [<line1>, <line2>]
'<,'>LocalRangeLines
call assert_equal([2, 5], lines)
delcommand LocalRangeLines
endfunc
func Test_command_count_2()
silent! %argd
arga a b c d
call assert_fails('5argu', 'E16:')
$argu
call assert_equal('d', expand('%:t'))
1argu
call assert_equal('a', expand('%:t'))
call assert_fails('300b', 'E16:')
split|split|split|split
0close
$wincmd w
$close
call assert_equal(3, winnr())
call assert_fails('$+close', 'E16:')
$tabe
call assert_equal(2, tabpagenr())
call assert_fails('$+tabe', 'E16:')
only!
e x
0tabm
normal 1gt
call assert_equal('x', expand('%:t'))
tabonly!
only!
endfunc
func Test_command_count_3()
let bufnr = bufnr('%')
se nohidden
e aaa
let buf_aaa = bufnr('%')
e bbb
let buf_bbb = bufnr('%')
e ccc
let buf_ccc = bufnr('%')
exe bufnr . 'buf'
call assert_equal([1, 1, 1], [buflisted(buf_aaa), buflisted(buf_bbb), buflisted(buf_ccc)])
exe buf_bbb . "," . buf_ccc . "bdelete"
call assert_equal([1, 0, 0], [buflisted(buf_aaa), buflisted(buf_bbb), buflisted(buf_ccc)])
exe buf_aaa . "bdelete"
call assert_equal([0, 0, 0], [buflisted(buf_aaa), buflisted(buf_bbb), buflisted(buf_ccc)])
endfunc
func Test_command_count_4()
%argd
let bufnr = bufnr('$')
next aa bb cc dd ee ff
call assert_equal(bufnr, bufnr('%'))
3argu
let args = []
.,$-argdo call add(args, expand('%'))
call assert_equal(['cc', 'dd', 'ee'], args)
" create windows to get 5
split|split|split|split
2wincmd w
let windows = []
.,$-windo call add(windows, winnr())
call assert_equal([2, 3, 4], windows)
only!
exe bufnr . 'buf'
let bufnr = bufnr('%')
let buffers = []
.,$-bufdo call add(buffers, bufnr('%'))
call assert_equal([bufnr, bufnr + 1, bufnr + 2, bufnr + 3, bufnr + 4], buffers)
exe (bufnr + 3) . 'bdel'
let buffers = []
exe (bufnr + 2) . ',' . (bufnr + 5) . "bufdo call add(buffers, bufnr('%'))"
call assert_equal([bufnr + 2, bufnr + 4, bufnr + 5], buffers)
" create tabpages to get 5
tabe|tabe|tabe|tabe
normal! 2gt
let tabpages = []
.,$-tabdo call add(tabpages, tabpagenr())
call assert_equal([2, 3, 4], tabpages)
tabonly!
bwipe!
endfunc

View File

@@ -1,277 +0,0 @@
" Tests for the various flags in the 'comments' option
" Test for the 'n' flag in 'comments'
func Test_comment_nested()
new
setlocal comments=n:> fo+=ro
exe "normal i> B\nD\<C-C>ggOA\<C-C>joC\<C-C>Go\<BS>>>> F\nH"
exe "normal 5GOE\<C-C>6GoG"
let expected =<< trim END
> A
> B
> C
> D
>>>> E
>>>> F
>>>> G
>>>> H
END
call assert_equal(expected, getline(1, '$'))
close!
endfunc
" Test for the 'b' flag in 'comments'
func Test_comment_blank()
new
setlocal comments=b:* fo+=ro
exe "normal i* E\nF\n\<BS>G\nH\<C-C>ggOC\<C-C>O\<BS>B\<C-C>OA\<C-C>2joD"
let expected =<< trim END
A
*B
* C
* D
* E
* F
*G
H
END
call assert_equal(expected, getline(1, '$'))
close!
endfunc
" Test for the 'f' flag in 'comments' (only the first line has a comment
" string)
func Test_comment_firstline()
new
setlocal comments=f:- fo+=ro
exe "normal i- B\nD\<C-C>ggoC\<C-C>ggOA\<C-C>"
call assert_equal(['A', '- B', ' C', ' D'], getline(1, '$'))
%d
setlocal comments=:-
exe "normal i- B\nD\<C-C>ggoC\<C-C>ggOA\<C-C>"
call assert_equal(['- A', '- B', '- C', '- D'], getline(1, '$'))
close!
endfunc
" Test for the 's', 'm' and 'e' flags in 'comments'
" Test for automatically adding comment leaders in insert mode
func Test_comment_threepiece()
new
setlocal expandtab
call setline(1, ["\t/*"])
setlocal formatoptions=croql
call cursor(1, 3)
call feedkeys("A\<cr>\<cr>/", 'tnix')
call assert_equal(["\t/*", " *", " */"], getline(1, '$'))
" If a comment ends in a single line, then don't add it in the next line
%d
call setline(1, '/* line1 */')
call feedkeys("A\<CR>next line", 'xt')
call assert_equal(['/* line1 */', 'next line'], getline(1, '$'))
%d
" Copy the trailing indentation from the leader comment to a new line
setlocal autoindent noexpandtab
call feedkeys("a\t/*\tone\ntwo\n/", 'xt')
call assert_equal(["\t/*\tone", "\t *\ttwo", "\t */"], getline(1, '$'))
close!
endfunc
" Test for the 'r' flag in 'comments' (right align comment)
func Test_comment_rightalign()
new
setlocal comments=sr:/***,m:**,ex-2:******/ fo+=ro
exe "normal i=\<C-C>o\t /***\nD\n/"
exe "normal 2GOA\<C-C>joB\<C-C>jOC\<C-C>joE\<C-C>GOF\<C-C>joG"
let expected =<< trim END
=
A
/***
** B
** C
** D
** E
** F
******/
G
END
call assert_equal(expected, getline(1, '$'))
close!
endfunc
" Test for the 'O' flag in 'comments'
func Test_comment_O()
new
setlocal comments=Ob:* fo+=ro
exe "normal i* B\nD\<C-C>kOA\<C-C>joC"
let expected =<< trim END
A
* B
* C
* D
END
call assert_equal(expected, getline(1, '$'))
close!
endfunc
" Test for using a multibyte character as a comment leader
func Test_comment_multibyte_leader()
new
let t =<< trim END
{
a
a
a
}
END
call setline(1, t)
call cursor(2, 1)
set tw=2 fo=cqm comments=n:
exe "normal gqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgq"
let t =<< trim END
a
a
a
END
exe "normal o\n" . join(t, "\n")
let expected =<< trim END
{
a
a
a
a
a
a
}
END
call assert_equal(expected, getline(1, '$'))
set tw& fo& comments&
close!
endfunc
" Test for a space character in 'comments' setting
func Test_comment_space()
new
setlocal comments=b:\ > fo+=ro
exe "normal i> B\nD\<C-C>ggOA\<C-C>joC"
exe "normal Go > F\nH\<C-C>kOE\<C-C>joG"
let expected =<< trim END
A
> B
C
D
> E
> F
> G
> H
END
call assert_equal(expected, getline(1, '$'))
close!
endfunc
" Test for formatting lines with and without comments
func Test_comment_format_lines()
new
call setline(1, ['one', '/* two */', 'three'])
normal gggqG
call assert_equal(['one', '/* two */', 'three'], getline(1, '$'))
close!
endfunc
" Test for using 'a' in 'formatoptions' with comments
func Test_comment_autoformat()
new
setlocal formatoptions+=a
call feedkeys("a- one\n- two\n", 'xt')
call assert_equal(['- one', '- two', ''], getline(1, '$'))
%d
call feedkeys("a\none\n", 'xt')
call assert_equal(['', 'one', ''], getline(1, '$'))
setlocal formatoptions+=aw
%d
call feedkeys("aone \ntwo\n", 'xt')
call assert_equal(['one two', ''], getline(1, '$'))
%d
call feedkeys("aone\ntwo\n", 'xt')
call assert_equal(['one', 'two', ''], getline(1, '$'))
close!
endfunc
" Test for joining lines with comments ('j' flag in 'formatoptions')
func Test_comment_join_lines_fo_j()
new
setlocal fo+=j comments=://
call setline(1, ['i++; // comment1', ' // comment2'])
normal J
call assert_equal('i++; // comment1 comment2', getline(1))
setlocal fo-=j
call setline(1, ['i++; // comment1', ' // comment2'])
normal J
call assert_equal('i++; // comment1 // comment2', getline(1))
" Test with nested comments
setlocal fo+=j comments=n:>,n:)
call setline(1, ['i++; > ) > ) comment1', ' > ) comment2'])
normal J
call assert_equal('i++; > ) > ) comment1 comment2', getline(1))
close!
endfunc
" Test for formatting lines where only the first line has a comment.
func Test_comment_format_firstline_comment()
new
setlocal formatoptions=tcq
call setline(1, ['- one two', 'three'])
normal gggqG
call assert_equal(['- one two three'], getline(1, '$'))
%d
call setline(1, ['- one', '- two'])
normal gggqG
call assert_equal(['- one', '- two'], getline(1, '$'))
close!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,9 +0,0 @@
function Test_Comparators()
try
let oldisident=&isident
set isident+=#
call assert_equal(1, 1 is#1)
finally
let &isident=oldisident
endtry
endfunction

View File

@@ -1,78 +0,0 @@
" Test the :compiler command
source check.vim
source shared.vim
func Test_compiler()
CheckExecutable perl
CheckFeature quickfix
" $LANG changes the output of Perl.
if $LANG != ''
unlet $LANG
endif
" %:S does not work properly with 'shellslash' set
let save_shellslash = &shellslash
set noshellslash
e Xfoo.pl
compiler perl
call assert_equal('perl', b:current_compiler)
call assert_fails('let g:current_compiler', 'E121:')
let verbose_efm = execute('verbose set efm')
call assert_match('Last set from .*[/\\]compiler[/\\]perl.vim ', verbose_efm)
call setline(1, ['#!/usr/bin/perl -w', 'use strict;', 'my $foo=1'])
w!
call feedkeys(":make\<CR>\<CR>", 'tx')
call assert_fails('clist', 'E42:')
call setline(1, ['#!/usr/bin/perl -w', 'use strict;', '$foo=1'])
w!
call feedkeys(":make\<CR>\<CR>", 'tx')
let a=execute('clist')
call assert_match('\n \d\+ Xfoo.pl:3: Global symbol "$foo" '
\ . 'requires explicit package name', a)
let &shellslash = save_shellslash
call delete('Xfoo.pl')
bw!
endfunc
func GetCompilerNames()
return glob('$VIMRUNTIME/compiler/*.vim', 0, 1)
\ ->map({i, v -> substitute(v, '.*[\\/]\([a-zA-Z0-9_\-]*\).vim', '\1', '')})
\ ->sort()
endfunc
func Test_compiler_without_arg()
let runtime = substitute($VIMRUNTIME, '\\', '/', 'g')
let a = split(execute('compiler'))
let exp = GetCompilerNames()
call assert_match(runtime .. '/compiler/' .. exp[0] .. '.vim$', a[0])
call assert_match(runtime .. '/compiler/' .. exp[1] .. '.vim$', a[1])
call assert_match(runtime .. '/compiler/' .. exp[-1] .. '.vim$', a[-1])
endfunc
func Test_compiler_completion()
let clist = GetCompilerNames()->join(' ')
call feedkeys(":compiler \<C-A>\<C-B>\"\<CR>", 'tx')
call assert_match('^"compiler ' .. clist .. '$', @:)
call feedkeys(":compiler p\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_match('"compiler pbx perl\( p[a-z]\+\)\+ pylint pyunit', @:)
call feedkeys(":compiler! p\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_match('"compiler! pbx perl\( p[a-z]\+\)\+ pylint pyunit', @:)
endfunc
func Test_compiler_error()
let g:current_compiler = 'abc'
call assert_fails('compiler doesnotexist', 'E666:')
call assert_equal('abc', g:current_compiler)
call assert_fails('compiler! doesnotexist', 'E666:')
unlet! g:current_compiler
endfunc

View File

@@ -1,284 +0,0 @@
" Tests for 'conceal'.
source check.vim
CheckFeature conceal
source screendump.vim
func Test_conceal_two_windows()
CheckScreendump
let code =<< trim [CODE]
let lines = ["one one one one one", "two |hidden| here", "three |hidden| three"]
call setline(1, lines)
syntax match test /|hidden|/ conceal
set conceallevel=2
set concealcursor=
exe "normal /here\r"
new
call setline(1, lines)
call setline(4, "Second window")
syntax match test /|hidden|/ conceal
set conceallevel=2
set concealcursor=nc
exe "normal /here\r"
[CODE]
call writefile(code, 'XTest_conceal')
" Check that cursor line is concealed
let buf = RunVimInTerminal('-S XTest_conceal', {})
call VerifyScreenDump(buf, 'Test_conceal_two_windows_01', {})
" Check that with concealed text vertical cursor movement is correct.
call term_sendkeys(buf, "k")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_02', {})
" Check that with cursor line is not concealed
call term_sendkeys(buf, "j")
call term_sendkeys(buf, ":set concealcursor=\r")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_03', {})
" Check that with cursor line is not concealed when moving cursor down
call term_sendkeys(buf, "j")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_04', {})
" Check that with cursor line is not concealed when switching windows
call term_sendkeys(buf, "\<C-W>\<C-W>")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_05', {})
" Check that with cursor line is only concealed in Normal mode
call term_sendkeys(buf, ":set concealcursor=n\r")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_06n', {})
call term_sendkeys(buf, "a")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_06i', {})
call term_sendkeys(buf, "\<Esc>/e")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_06c', {})
call term_sendkeys(buf, "\<Esc>v")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_06v', {})
call term_sendkeys(buf, "\<Esc>")
" Check that with cursor line is only concealed in Insert mode
call term_sendkeys(buf, ":set concealcursor=i\r")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_07n', {})
call term_sendkeys(buf, "a")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_07i', {})
call term_sendkeys(buf, "\<Esc>/e")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_07c', {})
call term_sendkeys(buf, "\<Esc>v")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_07v', {})
call term_sendkeys(buf, "\<Esc>")
" Check that with cursor line is only concealed in Command mode
call term_sendkeys(buf, ":set concealcursor=c\r")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_08n', {})
call term_sendkeys(buf, "a")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_08i', {})
call term_sendkeys(buf, "\<Esc>/e")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_08c', {})
call term_sendkeys(buf, "\<Esc>v")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_08v', {})
call term_sendkeys(buf, "\<Esc>")
" Check that with cursor line is only concealed in Visual mode
call term_sendkeys(buf, ":set concealcursor=v\r")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_09n', {})
call term_sendkeys(buf, "a")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_09i', {})
call term_sendkeys(buf, "\<Esc>/e")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_09c', {})
call term_sendkeys(buf, "\<Esc>v")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_09v', {})
call term_sendkeys(buf, "\<Esc>")
" Check moving the cursor while in insert mode.
call term_sendkeys(buf, ":set concealcursor=\r")
call term_sendkeys(buf, "a")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_10', {})
call term_sendkeys(buf, "\<Down>")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_11', {})
call term_sendkeys(buf, "\<Esc>")
" Check the "o" command
call VerifyScreenDump(buf, 'Test_conceal_two_windows_12', {})
call term_sendkeys(buf, "o")
call VerifyScreenDump(buf, 'Test_conceal_two_windows_13', {})
call term_sendkeys(buf, "\<Esc>")
" clean up
call StopVimInTerminal(buf)
call delete('XTest_conceal')
endfunc
func Test_conceal_with_cursorline()
CheckScreendump
" Opens a help window, where 'conceal' is set, switches to the other window
" where 'cursorline' needs to be updated when the cursor moves.
let code =<< trim [CODE]
set cursorline
normal othis is a test
new
call setline(1, ["one", "two", "three", "four", "five"])
set ft=help
normal M
[CODE]
call writefile(code, 'XTest_conceal_cul')
let buf = RunVimInTerminal('-S XTest_conceal_cul', {})
call VerifyScreenDump(buf, 'Test_conceal_cul_01', {})
call term_sendkeys(buf, ":wincmd w\r")
call VerifyScreenDump(buf, 'Test_conceal_cul_02', {})
call term_sendkeys(buf, "k")
call VerifyScreenDump(buf, 'Test_conceal_cul_03', {})
" clean up
call StopVimInTerminal(buf)
call delete('XTest_conceal_cul')
endfunc
func Test_conceal_resize_term()
CheckScreendump
let code =<< trim [CODE]
call setline(1, '`one` `two` `three` `four` `five`, the backticks should be concealed')
setl cocu=n cole=3
syn region CommentCodeSpan matchgroup=Comment start=/`/ end=/`/ concealends
normal fb
[CODE]
call writefile(code, 'XTest_conceal_resize')
let buf = RunVimInTerminal('-S XTest_conceal_resize', {'rows': 6})
call VerifyScreenDump(buf, 'Test_conceal_resize_01', {})
call win_execute(buf->win_findbuf()[0], 'wincmd +')
call TermWait(buf)
call VerifyScreenDump(buf, 'Test_conceal_resize_02', {})
" clean up
call StopVimInTerminal(buf)
call delete('XTest_conceal_resize')
endfunc
" Tests for correct display (cursor column position) with +conceal and
" tabulators. Need to run this test in a separate Vim instance. Otherwise the
" screen is not updated (lazy redraw) and the cursor position is wrong.
func Test_conceal_cursor_pos()
let code =<< trim [CODE]
:let l = ['start:', '.concealed. text', "|concealed|\ttext"]
:let l += ['', "\t.concealed.\ttext", "\t|concealed|\ttext", '']
:let l += [".a.\t.b.\t.c.\t.d.", "|a|\t|b|\t|c|\t|d|"]
:call append(0, l)
:call cursor(1, 1)
:" Conceal settings.
:set conceallevel=2
:set concealcursor=nc
:syntax match test /|/ conceal
:" Save current cursor position. Only works in <expr> mode, can't be used
:" with :normal because it moves the cursor to the command line. Thanks
:" to ZyX <zyx.vim@gmail.com> for the idea to use an <expr> mapping.
:let curpos = []
:nnoremap <expr> GG ":let curpos += ['".screenrow().":".screencol()."']\n"
:normal ztj
GGk
:" We should end up in the same column when running these commands on the
:" two lines.
:normal ft
GGk
:normal $
GGk
:normal 0j
GGk
:normal ft
GGk
:normal $
GGk
:normal 0j0j
GGk
:" Same for next test block.
:normal ft
GGk
:normal $
GGk
:normal 0j
GGk
:normal ft
GGk
:normal $
GGk
:normal 0j0j
GGk
:" And check W with multiple tabs and conceals in a line.
:normal W
GGk
:normal W
GGk
:normal W
GGk
:normal $
GGk
:normal 0j
GGk
:normal W
GGk
:normal W
GGk
:normal W
GGk
:normal $
GGk
:set lbr
:normal $
GGk
:set list listchars=tab:>-
:normal 0
GGk
:normal W
GGk
:normal W
GGk
:normal W
GGk
:normal $
GGk
:call writefile(curpos, 'Xconceal_curpos.out')
:q!
[CODE]
call writefile(code, 'XTest_conceal_curpos')
if RunVim([], [], '-s XTest_conceal_curpos')
call assert_equal([
\ '2:1', '2:17', '2:20', '3:1', '3:17', '3:20', '5:8', '5:25',
\ '5:28', '6:8', '6:25', '6:28', '8:1', '8:9', '8:17', '8:25',
\ '8:27', '9:1', '9:9', '9:17', '9:25', '9:26', '9:26', '9:1',
\ '9:9', '9:17', '9:25', '9:26'], readfile('Xconceal_curpos.out'))
endif
call delete('Xconceal_curpos.out')
call delete('XTest_conceal_curpos')
endfunc
func Test_conceal_eol()
new!
setlocal concealcursor=n conceallevel=1
call setline(1, ["x", ""])
call matchaddpos('Conceal', [[2, 1, 1]], 2, -1, {'conceal': 1})
redraw!
call assert_notequal(screenchar(1, 1), screenchar(2, 2))
call assert_equal(screenattr(1, 1), screenattr(1, 2))
call assert_equal(screenattr(1, 2), screenattr(2, 2))
call assert_equal(screenattr(2, 1), screenattr(2, 2))
set list
redraw!
call assert_equal(screenattr(1, 1), screenattr(2, 2))
call assert_notequal(screenattr(1, 1), screenattr(1, 2))
call assert_notequal(screenattr(1, 2), screenattr(2, 1))
set nolist
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,294 +0,0 @@
" Test for :const
func s:noop()
endfunc
func Test_define_var_with_lock()
const i = 1
const f = 1.1
const s = 'vim'
const F = funcref('s:noop')
const l = [1, 2, 3]
const d = {'foo': 10}
if has('channel')
const j = test_null_job()
const c = test_null_channel()
endif
const b = v:true
const n = v:null
call assert_true(exists('i'))
call assert_true(exists('f'))
call assert_true(exists('s'))
call assert_true(exists('F'))
call assert_true(exists('l'))
call assert_true(exists('d'))
if has('channel')
call assert_true(exists('j'))
call assert_true(exists('c'))
endif
call assert_true(exists('b'))
call assert_true(exists('n'))
call assert_fails('let i = 1', 'E741:')
call assert_fails('let f = 1.1', 'E741:')
call assert_fails('let s = "vim"', 'E741:')
call assert_fails('let F = funcref("s:noop")', 'E741:')
call assert_fails('let l = [1, 2, 3]', 'E741:')
call assert_fails('call filter(l, "v:val % 2 == 0")', 'E741:')
call assert_fails('let d = {"foo": 10}', 'E741:')
if has('channel')
call assert_fails('let j = test_null_job()', 'E741:')
call assert_fails('let c = test_null_channel()', 'E741:')
endif
call assert_fails('let b = v:true', 'E741:')
call assert_fails('let n = v:null', 'E741:')
" Unlet
unlet i
unlet f
unlet s
unlet F
unlet l
unlet d
if has('channel')
unlet j
unlet c
endif
unlet b
unlet n
endfunc
func Test_define_l_var_with_lock()
" With l: prefix
const l:i = 1
const l:f = 1.1
const l:s = 'vim'
const l:F = funcref('s:noop')
const l:l = [1, 2, 3]
const l:d = {'foo': 10}
if has('channel')
const l:j = test_null_job()
const l:c = test_null_channel()
endif
const l:b = v:true
const l:n = v:null
call assert_fails('let l:i = 1', 'E741:')
call assert_fails('let l:f = 1.1', 'E741:')
call assert_fails('let l:s = "vim"', 'E741:')
call assert_fails('let l:F = funcref("s:noop")', 'E741:')
call assert_fails('let l:l = [1, 2, 3]', 'E741:')
call assert_fails('let l:d = {"foo": 10}', 'E741:')
if has('channel')
call assert_fails('let l:j = test_null_job()', 'E741:')
call assert_fails('let l:c = test_null_channel()', 'E741:')
endif
call assert_fails('let l:b = v:true', 'E741:')
call assert_fails('let l:n = v:null', 'E741:')
" Unlet
unlet l:i
unlet l:f
unlet l:s
unlet l:F
unlet l:l
unlet l:d
if has('channel')
unlet l:j
unlet l:c
endif
unlet l:b
unlet l:n
endfunc
func Test_define_script_var_with_lock()
const s:x = 0
call assert_fails('let s:x = 1', 'E741:')
unlet s:x
endfunc
func Test_destructuring_with_lock()
const [a, b, c] = [1, 1.1, 'vim']
call assert_fails('let a = 1', 'E741:')
call assert_fails('let b = 1.1', 'E741:')
call assert_fails('let c = "vim"', 'E741:')
const [d; e] = [1, 1.1, 'vim']
call assert_fails('let d = 1', 'E741:')
call assert_fails('let e = [2.2, "a"]', 'E741:')
endfunc
func Test_cannot_modify_existing_variable()
let i = 1
let f = 1.1
let s = 'vim'
let F = funcref('s:noop')
let l = [1, 2, 3]
let d = {'foo': 10}
if has('channel')
let j = test_null_job()
let c = test_null_channel()
endif
let b = v:true
let n = v:null
call assert_fails('const i = 1', 'E995:')
call assert_fails('const f = 1.1', 'E995:')
call assert_fails('const s = "vim"', 'E995:')
call assert_fails('const F = funcref("s:noop")', 'E995:')
call assert_fails('const l = [1, 2, 3]', 'E995:')
call assert_fails('const d = {"foo": 10}', 'E995:')
if has('channel')
call assert_fails('const j = test_null_job()', 'E995:')
call assert_fails('const c = test_null_channel()', 'E995:')
endif
call assert_fails('const b = v:true', 'E995:')
call assert_fails('const n = v:null', 'E995:')
call assert_fails('const [i, f, s] = [1, 1.1, "vim"]', 'E995:')
const i2 = 1
const f2 = 1.1
const s2 = 'vim'
const F2 = funcref('s:noop')
const l2 = [1, 2, 3]
const d2 = {'foo': 10}
if has('channel')
const j2 = test_null_job()
const c2 = test_null_channel()
endif
const b2 = v:true
const n2 = v:null
call assert_fails('const i2 = 1', 'E995:')
call assert_fails('const f2 = 1.1', 'E995:')
call assert_fails('const s2 = "vim"', 'E995:')
call assert_fails('const F2 = funcref("s:noop")', 'E995:')
call assert_fails('const l2 = [1, 2, 3]', 'E995:')
call assert_fails('const d2 = {"foo": 10}', 'E995:')
if has('channel')
call assert_fails('const j2 = test_null_job()', 'E995:')
call assert_fails('const c2 = test_null_channel()', 'E995:')
endif
call assert_fails('const b2 = v:true', 'E995:')
call assert_fails('const n2 = v:null', 'E995:')
call assert_fails('const [i2, f2, s2] = [1, 1.1, "vim"]', 'E995:')
endfunc
func Test_const_with_condition()
const x = 0
if 0 | const x = 1 | endif
call assert_equal(0, x)
endfunc
func Test_lockvar()
let x = 'hello'
lockvar x
call assert_fails('let x = "there"', 'E741')
if 0 | unlockvar x | endif
call assert_fails('let x = "there"', 'E741')
unlockvar x
let x = 'there'
if 0 | lockvar x | endif
let x = 'again'
let val = [1, 2, 3]
lockvar 0 val
let val[0] = 9
call assert_equal([9, 2, 3], val)
call add(val, 4)
call assert_equal([9, 2, 3, 4], val)
call assert_fails('let val = [4, 5, 6]', 'E1122:')
endfunc
func Test_const_with_index_access()
let l = [1, 2, 3]
call assert_fails('const l[0] = 4', 'E996:')
call assert_fails('const l[0:1] = [1, 2]', 'E996:')
let d = {'aaa': 0}
call assert_fails("const d['aaa'] = 4", 'E996:')
call assert_fails("const d.aaa = 4", 'E996:')
endfunc
func Test_const_with_compound_assign()
let i = 0
call assert_fails('const i += 4', 'E995:')
call assert_fails('const i -= 4', 'E995:')
call assert_fails('const i *= 4', 'E995:')
call assert_fails('const i /= 4', 'E995:')
call assert_fails('const i %= 4', 'E995:')
let s = 'a'
call assert_fails('const s .= "b"', 'E995:')
let [a, b, c] = [1, 2, 3]
call assert_fails('const [a, b, c] += [4, 5, 6]', 'E995:')
let [d; e] = [1, 2, 3]
call assert_fails('const [d; e] += [4, 5, 6]', 'E995:')
endfunc
func Test_const_with_special_variables()
call assert_fails('const $FOO = "hello"', 'E996:')
call assert_fails('const @a = "hello"', 'E996:')
call assert_fails('const &filetype = "vim"', 'E996:')
call assert_fails('const &l:filetype = "vim"', 'E996:')
call assert_fails('const &g:encoding = "utf-8"', 'E996:')
call assert_fails('const [a, $CONST_FOO] = [369, "abc"]', 'E996:')
call assert_equal(369, a)
call assert_equal(v:null, getenv("CONST_FOO"))
call assert_fails('const [b; $CONST_FOO] = [246, 2, "abc"]', 'E996:')
call assert_equal(246, b)
call assert_equal(v:null, getenv("CONST_FOO"))
endfunc
func Test_const_with_eval_name()
let s = 'foo'
" eval name with :const should work
const abc_{s} = 1
const {s}{s} = 1
let s2 = 'abc_foo'
call assert_fails('const {s2} = "bar"', 'E995:')
endfunc
func Test_lock_depth_is_2()
" Modify list - error when changing item or adding/removing items
const l = [1, 2, [3, 4]]
call assert_fails('let l[0] = 42', 'E741:')
call assert_fails('let l[2][0] = 42', 'E741:')
call assert_fails('call add(l, 4)', 'E741:')
call assert_fails('unlet l[1]', 'E741:')
" Modify blob - error when changing
const b = 0z001122
call assert_fails('let b[0] = 42', 'E741:')
" Modify dict - error when changing item or adding/removing items
const d = {'foo': 10}
call assert_fails("let d['foo'] = 'hello'", 'E741:')
call assert_fails("let d.foo = 'hello'", 'E741:')
call assert_fails("let d['bar'] = 'hello'", 'E741:')
call assert_fails("unlet d['foo']", 'E741:')
" Modifying list or dict item contents is OK.
let lvar = ['a', 'b']
let bvar = 0z1122
const l2 = [0, lvar, bvar]
let l2[1][0] = 'c'
let l2[2][1] = 0x33
call assert_equal([0, ['c', 'b'], 0z1133], l2)
const d2 = #{a: 0, b: lvar, c: 4}
let d2.b[1] = 'd'
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,934 +0,0 @@
" Test for the various 'cpoptions' (cpo) flags
source check.vim
source shared.vim
source view_util.vim
" Test for the 'a' flag in 'cpo'. Reading a file should set the alternate
" file name.
func Test_cpo_a()
let save_cpo = &cpo
call writefile(['one'], 'XfileCpoA')
" Wipe out all the buffers, so that the alternate file is empty
edit Xfoo | %bw
set cpo-=a
new
read XfileCpoA
call assert_equal('', @#)
%d
set cpo+=a
read XfileCpoA
call assert_equal('XfileCpoA', @#)
close!
call delete('XfileCpoA')
let &cpo = save_cpo
endfunc
" Test for the 'A' flag in 'cpo'. Writing a file should set the alternate
" file name.
func Test_cpo_A()
let save_cpo = &cpo
" Wipe out all the buffers, so that the alternate file is empty
edit Xfoo | %bw
set cpo-=A
new Xfile1
write Xfile2
call assert_equal('', @#)
%bw
call delete('Xfile2')
new Xfile1
set cpo+=A
write Xfile2
call assert_equal('Xfile2', @#)
close!
call delete('Xfile2')
let &cpo = save_cpo
endfunc
" Test for the 'b' flag in 'cpo'. "\|" at the end of a map command is
" recognized as the end of the map.
func Test_cpo_b()
let save_cpo = &cpo
set cpo+=b
nnoremap <F5> :pwd\<CR>\|let i = 1
call assert_equal(':pwd\<CR>\', maparg('<F5>'))
nunmap <F5>
exe "nnoremap <F5> :pwd\<C-V>|let i = 1"
call assert_equal(':pwd|let i = 1', maparg('<F5>'))
nunmap <F5>
set cpo-=b
nnoremap <F5> :pwd\<CR>\|let i = 1
call assert_equal(':pwd\<CR>|let i = 1', maparg('<F5>'))
let &cpo = save_cpo
nunmap <F5>
endfunc
" Test for the 'B' flag in 'cpo'. A backslash in mappings, abbreviations, user
" commands and menu commands has no special meaning.
func Test_cpo_B()
let save_cpo = &cpo
new
imap <buffer> x<Bslash>k Test
set cpo-=B
iabbr <buffer> abc ab\<BS>d
exe "normal iabc "
call assert_equal('ab<BS>d ', getline(1))
call feedkeys(":imap <buffer> x\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"imap <buffer> x\\k', @:)
%d
set cpo+=B
iabbr <buffer> abc ab\<BS>d
exe "normal iabc "
call assert_equal('abd ', getline(1))
call feedkeys(":imap <buffer> x\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"imap <buffer> x\k', @:)
close!
let &cpo = save_cpo
endfunc
" Test for the 'c' flag in 'cpo'.
func Test_cpo_c()
let save_cpo = &cpo
set cpo+=c
new
call setline(1, ' abababababab')
exe "normal gg/abab\<CR>"
call assert_equal(3, searchcount().total)
set cpo-=c
exe "normal gg/abab\<CR>"
call assert_equal(5, searchcount().total)
close!
let &cpo = save_cpo
endfunc
" Test for the 'C' flag in 'cpo' (line continuation)
func Test_cpo_C()
let save_cpo = &cpo
call writefile(['let l = [', '\ 1,', '\ 2]'], 'XfileCpoC')
set cpo-=C
source XfileCpoC
call assert_equal([1, 2], g:l)
set cpo+=C
call assert_fails('source XfileCpoC', ['E697:', 'E10:'])
call delete('XfileCpoC')
let &cpo = save_cpo
endfunc
" Test for the 'd' flag in 'cpo' (tags relative to the current file)
func Test_cpo_d()
let save_cpo = &cpo
call mkdir('XdirCpoD')
call writefile(["one\tXfile1\t/^one$/"], 'tags')
call writefile(["two\tXfile2\t/^two$/"], 'XdirCpoD/tags')
set tags=./tags
set cpo-=d
edit XdirCpoD/Xfile
call assert_equal('two', taglist('.*')[0].name)
set cpo+=d
call assert_equal('one', taglist('.*')[0].name)
%bw!
call delete('tags')
call delete('XdirCpoD', 'rf')
set tags&
let &cpo = save_cpo
endfunc
" Test for the 'D' flag in 'cpo' (digraph after a r, f or t)
func Test_cpo_D()
CheckFeature digraphs
let save_cpo = &cpo
new
set cpo-=D
call setline(1, 'abcdefgh|')
exe "norm! 1gg0f\<c-k>!!"
call assert_equal(9, col('.'))
set cpo+=D
exe "norm! 1gg0f\<c-k>!!"
call assert_equal(1, col('.'))
set cpo-=D
close!
let &cpo = save_cpo
endfunc
" Test for the 'e' flag in 'cpo'
func Test_cpo_e()
let save_cpo = &cpo
let @a='let i = 45'
set cpo+=e
call feedkeys(":@a\<CR>", 'xt')
call assert_equal(45, i)
set cpo-=e
call feedkeys(":@a\<CR>6\<CR>", 'xt')
call assert_equal(456, i)
let &cpo = save_cpo
endfunc
" Test for the 'E' flag in 'cpo' with yank, change, delete, etc. operators
func Test_cpo_E()
new
call setline(1, '')
set cpo+=E
" yank an empty line
call assert_beeps('normal "ayl')
" change an empty line
call assert_beeps('normal lcTa')
call assert_beeps('normal 0c0')
" delete an empty line
call assert_beeps('normal D')
call assert_beeps('normal dl')
call assert_equal('', getline(1))
" change case of an empty line
call assert_beeps('normal gul')
call assert_beeps('normal gUl')
" replace a character
call assert_beeps('normal vrx')
" increment and decrement
call assert_beeps('exe "normal v\<C-A>"')
call assert_beeps('exe "normal v\<C-X>"')
set cpo-=E
close!
endfunc
" Test for the 'f' flag in 'cpo' (read in an empty buffer sets the file name)
func Test_cpo_f()
let save_cpo = &cpo
new
set cpo-=f
read test_cpoptions.vim
call assert_equal('', @%)
%d
set cpo+=f
read test_cpoptions.vim
call assert_equal('test_cpoptions.vim', @%)
bwipe!
let &cpo = save_cpo
endfunc
" Test for the 'F' flag in 'cpo' (write in an empty buffer sets the file name)
func Test_cpo_F()
let save_cpo = &cpo
new
set cpo-=F
write XfileCpoF
call assert_equal('', @%)
call delete('XfileCpoF')
set cpo+=F
write XfileCpoF
call assert_equal('XfileCpoF', @%)
close!
call delete('XfileCpoF')
let &cpo = save_cpo
endfunc
" Test for the 'g' flag in 'cpo' (jump to line 1 when re-editing a file)
func Test_cpo_g()
let save_cpo = &cpo
new test_cpoptions.vim
set cpo-=g
normal 20G
edit
call assert_equal(20, line('.'))
" Nvim: no "g" flag in 'cpoptions'.
" set cpo+=g
" edit
" call assert_equal(1, line('.'))
close!
let &cpo = save_cpo
endfunc
" Test for inserting text in a line with only spaces ('H' flag in 'cpoptions')
func Test_cpo_H()
let save_cpo = &cpo
new
set cpo-=H
call setline(1, ' ')
normal! Ia
call assert_equal(' a', getline(1))
" Nvim: no "H" flag in 'cpoptions'.
" set cpo+=H
" call setline(1, ' ')
" normal! Ia
" call assert_equal(' a ', getline(1))
close!
let &cpo = save_cpo
endfunc
" TODO: Add a test for the 'i' flag in 'cpo'
" Interrupting the reading of a file will leave it modified.
" Test for the 'I' flag in 'cpo' (deleting autoindent when using arrow keys)
func Test_cpo_I()
let save_cpo = &cpo
new
setlocal autoindent
set cpo+=I
exe "normal i one\<CR>\<Up>"
call assert_equal(' ', getline(2))
set cpo-=I
%d
exe "normal i one\<CR>\<Up>"
call assert_equal('', getline(2))
close!
let &cpo = save_cpo
endfunc
" Test for the 'j' flag in 'cpo' is in the test_join.vim file.
" Test for the 'J' flag in 'cpo' (two spaces after a sentence)
func Test_cpo_J()
let save_cpo = &cpo
new
set cpo-=J
call setline(1, 'one. two! three? four."'' five.)]')
normal 0
for colnr in [6, 12, 19, 28, 34]
normal )
call assert_equal(colnr, col('.'))
endfor
for colnr in [28, 19, 12, 6, 1]
normal (
call assert_equal(colnr, col('.'))
endfor
set cpo+=J
normal 0
for colnr in [12, 28, 34]
normal )
call assert_equal(colnr, col('.'))
endfor
for colnr in [28, 12, 1]
normal (
call assert_equal(colnr, col('.'))
endfor
close!
let &cpo = save_cpo
endfunc
" TODO: Add a test for the 'k' flag in 'cpo'.
" Disable the recognition of raw key codes in mappings, abbreviations, and the
" "to" part of menu commands.
" TODO: Add a test for the 'K' flag in 'cpo'.
" Don't wait for a key code to complete when it is halfway a mapping.
" Test for the 'l' flag in 'cpo' (backslash in a [] range)
func Test_cpo_l()
let save_cpo = &cpo
new
call setline(1, ['', "a\tc" .. '\t'])
set cpo-=l
exe 'normal gg/[\t]' .. "\<CR>"
call assert_equal([2, 8], [col('.'), virtcol('.')])
set cpo+=l
exe 'normal gg/[\t]' .. "\<CR>"
call assert_equal([4, 10], [col('.'), virtcol('.')])
close!
let &cpo = save_cpo
endfunc
" Test for inserting tab in virtual replace mode ('L' flag in 'cpoptions')
func Test_cpo_L()
let save_cpo = &cpo
new
set cpo-=L
call setline(1, 'abcdefghijklmnopqr')
exe "normal 0gR\<Tab>"
call assert_equal("\<Tab>ijklmnopqr", getline(1))
set cpo+=L
set list
call setline(1, 'abcdefghijklmnopqr')
exe "normal 0gR\<Tab>"
call assert_equal("\<Tab>cdefghijklmnopqr", getline(1))
set nolist
call setline(1, 'abcdefghijklmnopqr')
exe "normal 0gR\<Tab>"
call assert_equal("\<Tab>ijklmnopqr", getline(1))
close!
let &cpo = save_cpo
endfunc
" TODO: Add a test for the 'm' flag in 'cpo'.
" When included, a showmatch will always wait half a second. When not
" included, a showmatch will wait half a second or until a character is typed.
" Test for the 'M' flag in 'cpo' (% with escape parenthesis)
func Test_cpo_M()
let save_cpo = &cpo
new
call setline(1, ['( \( )', '\( ( \)'])
set cpo-=M
call cursor(1, 1)
normal %
call assert_equal(6, col('.'))
call cursor(1, 4)
call assert_beeps('normal %')
call cursor(2, 2)
normal %
call assert_equal(7, col('.'))
call cursor(2, 4)
call assert_beeps('normal %')
set cpo+=M
call cursor(1, 4)
normal %
call assert_equal(6, col('.'))
call cursor(1, 1)
call assert_beeps('normal %')
call cursor(2, 4)
normal %
call assert_equal(7, col('.'))
call cursor(2, 1)
call assert_beeps('normal %')
close!
let &cpo = save_cpo
endfunc
" Test for the 'n' flag in 'cpo' (using number column for wrapped lines)
func Test_cpo_n()
let save_cpo = &cpo
new
call setline(1, repeat('a', &columns))
setlocal number
set cpo-=n
redraw!
call assert_equal(' aaaa', Screenline(2))
set cpo+=n
redraw!
call assert_equal('aaaa', Screenline(2))
close!
let &cpo = save_cpo
endfunc
" Test for the 'o' flag in 'cpo' (line offset to search command)
func Test_cpo_o()
let save_cpo = &cpo
new
call setline(1, ['', 'one', 'two', 'three', 'one', 'two', 'three'])
set cpo-=o
exe "normal /one/+2\<CR>"
normal n
call assert_equal(7, line('.'))
set cpo+=o
exe "normal /one/+2\<CR>"
normal n
call assert_equal(5, line('.'))
close!
let &cpo = save_cpo
endfunc
" Test for the 'O' flag in 'cpo' (overwriting an existing file)
func Test_cpo_O()
let save_cpo = &cpo
new XfileCpoO
call setline(1, 'one')
call writefile(['two'], 'XfileCpoO')
set cpo-=O
call assert_fails('write', 'E13:')
set cpo+=O
write
call assert_equal(['one'], readfile('XfileCpoO'))
close!
call delete('XfileCpoO')
let &cpo = save_cpo
endfunc
" Test for the 'p' flag in 'cpo' is in the test_lispindent.vim file.
" Test for the 'P' flag in 'cpo' (appending to a file sets the current file
" name)
func Test_cpo_P()
let save_cpo = &cpo
call writefile([], 'XfileCpoP')
new
call setline(1, 'one')
set cpo+=F
set cpo-=P
write >> XfileCpoP
call assert_equal('', @%)
set cpo+=P
write >> XfileCpoP
call assert_equal('XfileCpoP', @%)
bwipe!
call delete('XfileCpoP')
let &cpo = save_cpo
endfunc
" Test for the 'q' flag in 'cpo' (joining multiple lines)
func Test_cpo_q()
let save_cpo = &cpo
new
call setline(1, ['one', 'two', 'three', 'four', 'five'])
set cpo-=q
normal gg4J
call assert_equal(14, col('.'))
%d
call setline(1, ['one', 'two', 'three', 'four', 'five'])
set cpo+=q
normal gg4J
call assert_equal(4, col('.'))
close!
let &cpo = save_cpo
endfunc
" Test for the 'r' flag in 'cpo' (redo command with a search motion)
func Test_cpo_r()
let save_cpo = &cpo
new
call setline(1, repeat(['one two three four'], 2))
set cpo-=r
exe "normal ggc/two\<CR>abc "
let @/ = 'three'
normal 2G.
call assert_equal('abc two three four', getline(2))
%d
call setline(1, repeat(['one two three four'], 2))
set cpo+=r
exe "normal ggc/two\<CR>abc "
let @/ = 'three'
normal 2G.
call assert_equal('abc three four', getline(2))
close!
let &cpo = save_cpo
endfunc
" Test for the 'R' flag in 'cpo' (clear marks after a filter command)
func Test_cpo_R()
CheckUnix
let save_cpo = &cpo
new
call setline(1, ['three', 'one', 'two'])
set cpo-=R
3mark r
%!sort
call assert_equal(3, line("'r"))
%d
call setline(1, ['three', 'one', 'two'])
set cpo+=R
3mark r
%!sort
call assert_equal(0, line("'r"))
close!
let &cpo = save_cpo
endfunc
" TODO: Add a test for the 's' flag in 'cpo'.
" Set buffer options when entering the buffer for the first time. If not
" present the options are set when the buffer is created.
" Test for the 'S' flag in 'cpo' (copying buffer options)
func Test_cpo_S()
let save_cpo = &cpo
new Xfile1
set noautoindent
new Xfile2
set cpo-=S
set autoindent
wincmd p
call assert_equal(0, &autoindent)
wincmd p
call assert_equal(1, &autoindent)
set cpo+=S
wincmd p
call assert_equal(1, &autoindent)
set noautoindent
wincmd p
call assert_equal(0, &autoindent)
wincmd t
close!
close!
let &cpo = save_cpo
endfunc
" Test for the 't' flag in 'cpo' is in the test_tagjump.vim file.
" Test for the 'u' flag in 'cpo' (Vi-compatible undo)
func Test_cpo_u()
let save_cpo = &cpo
new
set cpo-=u
exe "normal iabc\<C-G>udef\<C-G>ughi"
normal uu
call assert_equal('abc', getline(1))
%d
set cpo+=u
exe "normal iabc\<C-G>udef\<C-G>ughi"
normal uu
call assert_equal('abcdefghi', getline(1))
close!
let &cpo = save_cpo
endfunc
" TODO: Add a test for the 'v' flag in 'cpo'.
" Backspaced characters remain visible on the screen in Insert mode.
" Test for the 'w' flag in 'cpo' ('cw' on a blank character changes only one
" character)
func Test_cpo_w()
let save_cpo = &cpo
new
" Nvim: no "w" flag in 'cpoptions'.
" set cpo+=w
" call setline(1, 'here are some words')
" norm! 1gg0elcwZZZ
" call assert_equal('hereZZZ are some words', getline('.'))
" norm! 1gg2elcWYYY
" call assert_equal('hereZZZ areYYY some words', getline('.'))
set cpo-=w
call setline(1, 'here are some words')
norm! 1gg0elcwZZZ
call assert_equal('hereZZZare some words', getline('.'))
norm! 1gg2elcWYYY
call assert_equal('hereZZZare someYYYwords', getline('.'))
close!
let &cpo = save_cpo
endfunc
" Test for the 'W' flag in 'cpo' is in the test_writefile.vim file
" Test for the 'x' flag in 'cpo' (Esc on command-line executes command)
func Test_cpo_x()
let save_cpo = &cpo
set cpo-=x
let i = 1
call feedkeys(":let i=10\<Esc>", 'xt')
call assert_equal(1, i)
set cpo+=x
call feedkeys(":let i=10\<Esc>", 'xt')
call assert_equal(10, i)
let &cpo = save_cpo
endfunc
" Test for the 'X' flag in 'cpo' ('R' with a count)
func Test_cpo_X()
let save_cpo = &cpo
new
call setline(1, 'aaaaaa')
set cpo-=X
normal gg4Rx
call assert_equal('xxxxaa', getline(1))
normal ggRy
normal 4.
call assert_equal('yyyyaa', getline(1))
call setline(1, 'aaaaaa')
set cpo+=X
normal gg4Rx
call assert_equal('xxxxaaaaa', getline(1))
normal ggRy
normal 4.
call assert_equal('yyyyxxxaaaaa', getline(1))
close!
let &cpo = save_cpo
endfunc
" Test for the 'y' flag in 'cpo' (repeating a yank command)
func Test_cpo_y()
let save_cpo = &cpo
new
call setline(1, ['one', 'two'])
set cpo-=y
normal ggyy
normal 2G.
call assert_equal("one\n", @")
%d
call setline(1, ['one', 'two'])
set cpo+=y
normal ggyy
normal 2G.
call assert_equal("two\n", @")
close!
let &cpo = save_cpo
endfunc
" Test for the 'Z' flag in 'cpo' (write! resets 'readonly')
func Test_cpo_Z()
let save_cpo = &cpo
call writefile([], 'XfileCpoZ')
new XfileCpoZ
setlocal readonly
set cpo-=Z
write!
call assert_equal(0, &readonly)
set cpo+=Z
setlocal readonly
write!
call assert_equal(1, &readonly)
close!
call delete('XfileCpoZ')
let &cpo = save_cpo
endfunc
" Test for the '!' flag in 'cpo' is in the test_normal.vim file
" Test for displaying dollar when changing text ('$' flag in 'cpoptions')
func Test_cpo_dollar()
throw 'Skipped: use test/functional/legacy/cpoptions_spec.lua'
new
let g:Line = ''
func SaveFirstLine()
let g:Line = Screenline(1)
return ''
endfunc
inoremap <expr> <buffer> <F2> SaveFirstLine()
call test_override('redraw_flag', 1)
set cpo+=$
call setline(1, 'one two three')
redraw!
exe "normal c2w\<F2>vim"
call assert_equal('one tw$ three', g:Line)
call assert_equal('vim three', getline(1))
set cpo-=$
call test_override('ALL', 0)
delfunc SaveFirstLine
%bw!
endfunc
" Test for the '%' flag in 'cpo' (parenthesis matching inside strings)
func Test_cpo_percent()
let save_cpo = &cpo
new
call setline(1, ' if (strcmp("ab)cd(", s))')
set cpo-=%
normal 8|%
call assert_equal(28, col('.'))
normal 15|%
call assert_equal(27, col('.'))
normal 27|%
call assert_equal(15, col('.'))
call assert_beeps("normal 19|%")
call assert_beeps("normal 22|%")
set cpo+=%
normal 8|%
call assert_equal(28, col('.'))
normal 15|%
call assert_equal(19, col('.'))
normal 27|%
call assert_equal(22, col('.'))
normal 19|%
call assert_equal(15, col('.'))
normal 22|%
call assert_equal(27, col('.'))
close!
let &cpo = save_cpo
endfunc
" Test for cursor movement with '-' in 'cpoptions'
func Test_cpo_minus()
throw 'Skipped: Nvim does not support cpoptions flag "-"'
new
call setline(1, ['foo', 'bar', 'baz'])
let save_cpo = &cpo
set cpo+=-
call assert_beeps('normal 10j')
call assert_equal(1, line('.'))
normal G
call assert_beeps('normal 10k')
call assert_equal(3, line('.'))
call assert_fails(10, 'E16:')
close!
let &cpo = save_cpo
endfunc
" Test for the '+' flag in 'cpo' ('write file' command resets the 'modified'
" flag)
func Test_cpo_plus()
let save_cpo = &cpo
call writefile([], 'XfileCpoPlus')
new XfileCpoPlus
call setline(1, 'foo')
write X1
call assert_equal(1, &modified)
set cpo+=+
write X2
call assert_equal(0, &modified)
close!
call delete('XfileCpoPlus')
call delete('X1')
call delete('X2')
let &cpo = save_cpo
endfunc
" Test for the '*' flag in 'cpo' (':*' is same as ':@')
func Test_cpo_star()
let save_cpo = &cpo
let x = 0
new
set cpo-=*
let @a = 'let x += 1'
call assert_fails('*a', 'E20:')
" Nvim: no "*" flag in 'cpoptions'.
" set cpo+=*
" *a
" call assert_equal(1, x)
close!
let &cpo = save_cpo
endfunc
" Test for the '<' flag in 'cpo' is in the test_mapping.vim file
" Test for the '>' flag in 'cpo' (use a new line when appending to a register)
func Test_cpo_gt()
let save_cpo = &cpo
new
call setline(1, 'one two')
set cpo-=>
let @r = ''
normal gg"Rye
normal "Rye
call assert_equal("oneone", @r)
set cpo+=>
let @r = ''
normal gg"Rye
normal "Rye
call assert_equal("\none\none", @r)
close!
let &cpo = save_cpo
endfunc
" Test for the ';' flag in 'cpo'
" Test for t,f,F,T movement commands and 'cpo-;' setting
func Test_cpo_semicolon()
let save_cpo = &cpo
new
call append(0, ["aaa two three four", " zzz", "yyy ",
\ "bbb yee yoo four", "ccc two three four",
\ "ddd yee yoo four"])
set cpo-=;
1
normal! 0tt;D
2
normal! 0fz;D
3
normal! $Fy;D
4
normal! $Ty;D
set cpo+=;
5
normal! 0tt;;D
6
normal! $Ty;;D
call assert_equal('aaa two', getline(1))
call assert_equal(' z', getline(2))
call assert_equal('y', getline(3))
call assert_equal('bbb y', getline(4))
call assert_equal('ccc', getline(5))
call assert_equal('ddd yee y', getline(6))
close!
let &cpo = save_cpo
endfunc
" Test for the '#' flag in 'cpo' (count before 'D', 'o' and 'O' operators)
func Test_cpo_hash()
let save_cpo = &cpo
new
set cpo-=#
call setline(1, ['one', 'two', 'three'])
normal gg2D
call assert_equal(['three'], getline(1, '$'))
normal gg2ofour
call assert_equal(['three', 'four', 'four'], getline(1, '$'))
normal gg2Otwo
call assert_equal(['two', 'two', 'three', 'four', 'four'], getline(1, '$'))
%d
" Nvim: no "#" flag in 'cpoptions'.
" set cpo+=#
" call setline(1, ['one', 'two', 'three'])
" normal gg2D
" call assert_equal(['', 'two', 'three'], getline(1, '$'))
" normal gg2oone
" call assert_equal(['', 'one', 'two', 'three'], getline(1, '$'))
" normal gg2Ozero
" call assert_equal(['zero', '', 'one', 'two', 'three'], getline(1, '$'))
close!
let &cpo = save_cpo
endfunc
" Test for the '&' flag in 'cpo'. The swap file is kept when a buffer is still
" loaded and ':preserve' is used.
func Test_cpo_ampersand()
throw 'Skipped: Nvim does not support cpoptions flag "&"'
call writefile(['one'], 'XfileCpoAmp')
let after =<< trim [CODE]
set cpo+=&
preserve
qall
[CODE]
if RunVim([], after, 'XfileCpoAmp')
call assert_equal(1, filereadable('.XfileCpoAmp.swp'))
call delete('.XfileCpoAmp.swp')
endif
call delete('XfileCpoAmp')
endfunc
" Test for the '\' flag in 'cpo' (backslash in a [] range in a search pattern)
func Test_cpo_backslash()
let save_cpo = &cpo
new
call setline(1, ['', " \\-string"])
set cpo-=\
exe 'normal gg/[ \-]' .. "\<CR>n"
call assert_equal(3, col('.'))
" Nvim: no "\" flag in 'cpoptions'.
" set cpo+=\
" exe 'normal gg/[ \-]' .. "\<CR>n"
" call assert_equal(2, col('.'))
close!
let &cpo = save_cpo
endfunc
" Test for the '/' flag in 'cpo' is in the test_substitute.vim file
" Test for the '{' flag in 'cpo' (the "{" and "}" commands stop at a {
" character at the start of a line)
func Test_cpo_brace()
let save_cpo = &cpo
new
call setline(1, ['', '{', ' int i;', '}', ''])
set cpo-={
normal gg}
call assert_equal(5, line('.'))
normal G{
call assert_equal(1, line('.'))
" Nvim: no "{" flag in 'cpoptions'.
" set cpo+={
" normal gg}
" call assert_equal(2, line('.'))
" normal G{
" call assert_equal(2, line('.'))
close!
let &cpo = save_cpo
endfunc
" Test for the '.' flag in 'cpo' (:cd command fails if the current buffer is
" modified)
func Test_cpo_dot()
throw 'Skipped: Nvim does not support cpoptions flag "."'
let save_cpo = &cpo
new Xfoo
call setline(1, 'foo')
let save_dir = getcwd()
set cpo+=.
" :cd should fail when buffer is modified and 'cpo' contains dot.
call assert_fails('cd ..', 'E747:')
call assert_equal(save_dir, getcwd())
" :cd with exclamation mark should succeed.
cd! ..
call assert_notequal(save_dir, getcwd())
" :cd should succeed when buffer has been written.
w!
exe 'cd ' .. fnameescape(save_dir)
call assert_equal(save_dir, getcwd())
call delete('Xfoo')
set cpo&
close!
let &cpo = save_cpo
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,481 +0,0 @@
" Tests for cursor() and other functions that get/set the cursor position
source check.vim
func Test_wrong_arguments()
call assert_fails('call cursor(1. 3)', 'E474:')
call assert_fails('call cursor(v:_null_list)', 'E474:')
endfunc
func Test_move_cursor()
new
call setline(1, ['aaa', 'bbb', 'ccc', 'ddd'])
call cursor([1, 1, 0, 1])
call assert_equal([1, 1, 0, 1], getcurpos()[1:])
call cursor([4, 3, 0, 3])
call assert_equal([4, 3, 0, 3], getcurpos()[1:])
call cursor(2, 2)
call assert_equal([2, 2, 0, 2], getcurpos()[1:])
" line number zero keeps the line number
call cursor(0, 1)
call assert_equal([2, 1, 0, 1], getcurpos()[1:])
" col number zero keeps the column
call cursor(3, 0)
call assert_equal([3, 1, 0, 1], getcurpos()[1:])
" below last line goes to last line
eval [9, 1]->cursor()
call assert_equal([4, 1, 0, 1], getcurpos()[1:])
" pass string arguments
call cursor('3', '3')
call assert_equal([3, 3, 0, 3], getcurpos()[1:])
call setline(1, ["\<TAB>"])
call cursor(1, 1, 1)
call assert_equal([1, 1, 1], getcurpos()[1:3])
call assert_fails('call cursor(-1, -1)', 'E475:')
quit!
endfunc
" Very short version of what matchparen does.
function s:Highlight_Matching_Pair()
let save_cursor = getcurpos()
eval save_cursor->setpos('.')
endfunc
func Test_curswant_with_autocommand()
new
call setline(1, ['func()', '{', '}', '----'])
autocmd! CursorMovedI * call s:Highlight_Matching_Pair()
exe "normal! 3Ga\<Down>X\<Esc>"
call assert_equal('-X---', getline(4))
autocmd! CursorMovedI *
quit!
endfunc
" Tests for behavior of curswant with cursorcolumn/line
func Test_curswant_with_cursorcolumn()
new
call setline(1, ['01234567', ''])
exe "normal! ggf6j"
call assert_equal(6, winsaveview().curswant)
set cursorcolumn
call assert_equal(6, winsaveview().curswant)
quit!
endfunc
func Test_curswant_with_cursorline()
new
call setline(1, ['01234567', ''])
exe "normal! ggf6j"
call assert_equal(6, winsaveview().curswant)
set cursorline
call assert_equal(6, winsaveview().curswant)
quit!
endfunc
func Test_screenpos()
rightbelow new
rightbelow 20vsplit
call setline(1, ["\tsome text", "long wrapping line here", "next line"])
redraw
let winid = win_getid()
let [winrow, wincol] = win_screenpos(winid)
call assert_equal({'row': winrow,
\ 'col': wincol + 0,
\ 'curscol': wincol + 7,
\ 'endcol': wincol + 7}, winid->screenpos(1, 1))
call assert_equal({'row': winrow,
\ 'col': wincol + 13,
\ 'curscol': wincol + 13,
\ 'endcol': wincol + 13}, winid->screenpos(1, 7))
call assert_equal({'row': winrow + 2,
\ 'col': wincol + 1,
\ 'curscol': wincol + 1,
\ 'endcol': wincol + 1}, screenpos(winid, 2, 22))
setlocal number
call assert_equal({'row': winrow + 3,
\ 'col': wincol + 9,
\ 'curscol': wincol + 9,
\ 'endcol': wincol + 9}, screenpos(winid, 2, 22))
let wininfo = getwininfo(winid)[0]
call setline(3, ['x']->repeat(wininfo.height))
call setline(line('$') + 1, 'x'->repeat(wininfo.width * 3))
setlocal nonumber display=lastline so=0
exe "normal G\<C-Y>\<C-Y>"
redraw
call assert_equal({'row': winrow + wininfo.height - 1,
\ 'col': wincol + 7,
\ 'curscol': wincol + 7,
\ 'endcol': wincol + 7}, winid->screenpos(line('$'), 8))
call assert_equal({'row': 0, 'col': 0, 'curscol': 0, 'endcol': 0},
\ winid->screenpos(line('$'), 22))
close
call assert_equal({}, screenpos(999, 1, 1))
bwipe!
set display&
call assert_equal(#{col: 1, row: 1, endcol: 1, curscol: 1}, screenpos(win_getid(), 1, 1))
" nmenu WinBar.TEST :
setlocal winbar=TEST
call assert_equal(#{col: 1, row: 2, endcol: 1, curscol: 1}, screenpos(win_getid(), 1, 1))
" nunmenu WinBar.TEST
setlocal winbar&
endfunc
func Test_screenpos_fold()
CheckFeature folding
enew!
call setline(1, range(10))
3,5fold
redraw
call assert_equal(2, screenpos(1, 2, 1).row)
call assert_equal(#{col: 1, row: 3, endcol: 1, curscol: 1}, screenpos(1, 3, 1))
call assert_equal(#{col: 1, row: 3, endcol: 1, curscol: 1}, screenpos(1, 4, 1))
call assert_equal(#{col: 1, row: 3, endcol: 1, curscol: 1}, screenpos(1, 5, 1))
setlocal number
call assert_equal(#{col: 5, row: 3, endcol: 5, curscol: 5}, screenpos(1, 3, 1))
call assert_equal(#{col: 5, row: 3, endcol: 5, curscol: 5}, screenpos(1, 4, 1))
call assert_equal(#{col: 5, row: 3, endcol: 5, curscol: 5}, screenpos(1, 5, 1))
call assert_equal(4, screenpos(1, 6, 1).row)
bwipe!
endfunc
func Test_screenpos_diff()
CheckFeature diff
enew!
call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])
vnew
call setline(1, ['a', 'b', 'c', 'g', 'h', 'i'])
windo diffthis
wincmd w
call assert_equal(#{col: 3, row: 7, endcol: 3, curscol: 3}, screenpos(0, 4, 1))
windo diffoff
bwipe!
bwipe!
endfunc
func Test_screenpos_number()
rightbelow new
rightbelow 73vsplit
call setline (1, repeat('x', 66))
setlocal number
redraw
let winid = win_getid()
let [winrow, wincol] = win_screenpos(winid)
let pos = screenpos(winid, 1, 66)
call assert_equal(winrow, pos.row)
call assert_equal(wincol + 66 + 3, pos.col)
call assert_fails('echo screenpos(0, 2, 1)', 'E966:')
close
bwipe!
endfunc
" Save the visual start character position
func SaveVisualStartCharPos()
call add(g:VisualStartPos, getcharpos('v'))
return ''
endfunc
" Save the current cursor character position in insert mode
func SaveInsertCurrentCharPos()
call add(g:InsertCurrentPos, getcharpos('.'))
return ''
endfunc
" Test for the getcharpos() function
func Test_getcharpos()
call assert_fails('call getcharpos({})', 'E731:')
call assert_equal([0, 0, 0, 0], getcharpos(0))
new
call setline(1, ['', "01\tà4è678", 'Ⅵ', '012345678', ' │ x'])
" Test for '.' and '$'
normal 1G
call assert_equal([0, 1, 1, 0], getcharpos('.'))
call assert_equal([0, 5, 1, 0], getcharpos('$'))
normal 2G6l
call assert_equal([0, 2, 7, 0], getcharpos('.'))
normal 3G$
call assert_equal([0, 3, 1, 0], getcharpos('.'))
normal 4G$
call assert_equal([0, 4, 9, 0], getcharpos('.'))
" Test for a mark
normal 2G7lmmgg
call assert_equal([0, 2, 8, 0], getcharpos("'m"))
delmarks m
call assert_equal([0, 0, 0, 0], getcharpos("'m"))
" Check mark does not move
normal 5Gfxma
call assert_equal([0, 5, 5, 0], getcharpos("'a"))
call assert_equal([0, 5, 5, 0], getcharpos("'a"))
call assert_equal([0, 5, 5, 0], getcharpos("'a"))
" Test for the visual start column
vnoremap <expr> <F3> SaveVisualStartCharPos()
let g:VisualStartPos = []
exe "normal 2G6lv$\<F3>ohh\<F3>o\<F3>"
call assert_equal([[0, 2, 7, 0], [0, 2, 10, 0], [0, 2, 5, 0]], g:VisualStartPos)
call assert_equal([0, 2, 9, 0], getcharpos('v'))
let g:VisualStartPos = []
exe "normal 3Gv$\<F3>o\<F3>"
call assert_equal([[0, 3, 1, 0], [0, 3, 2, 0]], g:VisualStartPos)
let g:VisualStartPos = []
exe "normal 1Gv$\<F3>o\<F3>"
call assert_equal([[0, 1, 1, 0], [0, 1, 1, 0]], g:VisualStartPos)
vunmap <F3>
" Test for getting the position in insert mode with the cursor after the
" last character in a line
inoremap <expr> <F3> SaveInsertCurrentCharPos()
let g:InsertCurrentPos = []
exe "normal 1GA\<F3>"
exe "normal 2GA\<F3>"
exe "normal 3GA\<F3>"
exe "normal 4GA\<F3>"
exe "normal 2G6li\<F3>"
call assert_equal([[0, 1, 1, 0], [0, 2, 10, 0], [0, 3, 2, 0], [0, 4, 10, 0],
\ [0, 2, 7, 0]], g:InsertCurrentPos)
iunmap <F3>
%bw!
endfunc
" Test for the setcharpos() function
func Test_setcharpos()
call assert_equal(-1, setcharpos('.', v:_null_list))
new
call setline(1, ['', "01\tà4è678", 'Ⅵ', '012345678'])
call setcharpos('.', [0, 1, 1, 0])
call assert_equal([1, 1], [line('.'), col('.')])
call setcharpos('.', [0, 2, 7, 0])
call assert_equal([2, 9], [line('.'), col('.')])
call setcharpos('.', [0, 3, 4, 0])
call assert_equal([3, 1], [line('.'), col('.')])
call setcharpos('.', [0, 3, 1, 0])
call assert_equal([3, 1], [line('.'), col('.')])
call setcharpos('.', [0, 4, 0, 0])
call assert_equal([4, 1], [line('.'), col('.')])
call setcharpos('.', [0, 4, 20, 0])
call assert_equal([4, 9], [line('.'), col('.')])
" Test for mark
delmarks m
call setcharpos("'m", [0, 2, 9, 0])
normal `m
call assert_equal([2, 11], [line('.'), col('.')])
" unload the buffer and try to set the mark
let bnr = bufnr()
enew!
call assert_equal(-1, setcharpos("'m", [bnr, 2, 2, 0]))
%bw!
call assert_equal(-1, setcharpos('.', [10, 3, 1, 0]))
endfunc
func SaveVisualStartCharCol()
call add(g:VisualStartCol, charcol('v'))
return ''
endfunc
func SaveInsertCurrentCharCol()
call add(g:InsertCurrentCol, charcol('.'))
return ''
endfunc
" Test for the charcol() function
func Test_charcol()
call assert_fails('call charcol({})', 'E1222:')
call assert_fails('call charcol(".", [])', 'E1210:')
call assert_fails('call charcol(0)', 'E1222:')
new
call setline(1, ['', "01\tà4è678", 'Ⅵ', '012345678'])
" Test for '.' and '$'
normal 1G
call assert_equal(1, charcol('.'))
call assert_equal(1, charcol('$'))
normal 2G6l
call assert_equal(7, charcol('.'))
call assert_equal(10, charcol('$'))
normal 3G$
call assert_equal(1, charcol('.'))
call assert_equal(2, charcol('$'))
normal 4G$
call assert_equal(9, charcol('.'))
call assert_equal(10, charcol('$'))
" Test for [lnum, '$']
call assert_equal(1, charcol([1, '$']))
call assert_equal(10, charcol([2, '$']))
call assert_equal(2, charcol([3, '$']))
call assert_equal(0, charcol([5, '$']))
" Test for a mark
normal 2G7lmmgg
call assert_equal(8, charcol("'m"))
delmarks m
call assert_equal(0, charcol("'m"))
" Test for the visual start column
vnoremap <expr> <F3> SaveVisualStartCharCol()
let g:VisualStartCol = []
exe "normal 2G6lv$\<F3>ohh\<F3>o\<F3>"
call assert_equal([7, 10, 5], g:VisualStartCol)
call assert_equal(9, charcol('v'))
let g:VisualStartCol = []
exe "normal 3Gv$\<F3>o\<F3>"
call assert_equal([1, 2], g:VisualStartCol)
let g:VisualStartCol = []
exe "normal 1Gv$\<F3>o\<F3>"
call assert_equal([1, 1], g:VisualStartCol)
vunmap <F3>
" Test for getting the column number in insert mode with the cursor after
" the last character in a line
inoremap <expr> <F3> SaveInsertCurrentCharCol()
let g:InsertCurrentCol = []
exe "normal 1GA\<F3>"
exe "normal 2GA\<F3>"
exe "normal 3GA\<F3>"
exe "normal 4GA\<F3>"
exe "normal 2G6li\<F3>"
call assert_equal([1, 10, 2, 10, 7], g:InsertCurrentCol)
iunmap <F3>
" Test for getting the column number in another window.
let winid = win_getid()
new
call win_execute(winid, 'normal 1G')
call assert_equal(1, charcol('.', winid))
call assert_equal(1, charcol('$', winid))
call win_execute(winid, 'normal 2G6l')
call assert_equal(7, charcol('.', winid))
call assert_equal(10, charcol('$', winid))
" calling from another tab page also works
tabnew
call assert_equal(7, charcol('.', winid))
call assert_equal(10, charcol('$', winid))
tabclose
" unknown window ID
call assert_equal(0, charcol('.', 10001))
%bw!
endfunc
func SaveInsertCursorCharPos()
call add(g:InsertCursorPos, getcursorcharpos('.'))
return ''
endfunc
" Test for getcursorcharpos()
func Test_getcursorcharpos()
call assert_equal(getcursorcharpos(), getcursorcharpos(0))
call assert_equal([0, 0, 0, 0, 0], getcursorcharpos(-1))
call assert_equal([0, 0, 0, 0, 0], getcursorcharpos(1999))
new
call setline(1, ['', "01\tà4è678", 'Ⅵ', '012345678'])
normal 1G9l
call assert_equal([0, 1, 1, 0, 1], getcursorcharpos())
normal 2G9l
call assert_equal([0, 2, 9, 0, 14], getcursorcharpos())
normal 3G9l
call assert_equal([0, 3, 1, 0, 1], getcursorcharpos())
normal 4G9l
call assert_equal([0, 4, 9, 0, 9], getcursorcharpos())
" Test for getting the cursor position in insert mode with the cursor after
" the last character in a line
inoremap <expr> <F3> SaveInsertCursorCharPos()
let g:InsertCursorPos = []
exe "normal 1GA\<F3>"
exe "normal 2GA\<F3>"
exe "normal 3GA\<F3>"
exe "normal 4GA\<F3>"
exe "normal 2G6li\<F3>"
call assert_equal([[0, 1, 1, 0, 1], [0, 2, 10, 0, 15], [0, 3, 2, 0, 2],
\ [0, 4, 10, 0, 10], [0, 2, 7, 0, 12]], g:InsertCursorPos)
iunmap <F3>
let winid = win_getid()
normal 2G5l
wincmd w
call assert_equal([0, 2, 6, 0, 11], getcursorcharpos(winid))
%bw!
endfunc
" Test for setcursorcharpos()
func Test_setcursorcharpos()
call assert_fails('call setcursorcharpos(v:_null_list)', 'E474:')
call assert_fails('call setcursorcharpos([1])', 'E474:')
call assert_fails('call setcursorcharpos([1, 1, 1, 1, 1])', 'E474:')
new
call setline(1, ['', "01\tà4è678", 'Ⅵ', '012345678'])
normal G
call setcursorcharpos([1, 1])
call assert_equal([1, 1], [line('.'), col('.')])
call setcursorcharpos([2, 7, 0])
call assert_equal([2, 9], [line('.'), col('.')])
call setcursorcharpos([0, 7, 0])
call assert_equal([2, 9], [line('.'), col('.')])
call setcursorcharpos(0, 7, 0)
call assert_equal([2, 9], [line('.'), col('.')])
call setcursorcharpos(3, 4)
call assert_equal([3, 1], [line('.'), col('.')])
call setcursorcharpos([3, 1])
call assert_equal([3, 1], [line('.'), col('.')])
call setcursorcharpos([4, 0, 0, 0])
call assert_equal([4, 1], [line('.'), col('.')])
call setcursorcharpos([4, 20])
call assert_equal([4, 9], [line('.'), col('.')])
normal 1G
call setcursorcharpos([100, 100, 100, 100])
call assert_equal([4, 9], [line('.'), col('.')])
normal 1G
call setcursorcharpos('$', 1)
call assert_equal([4, 1], [line('.'), col('.')])
%bw!
endfunc
" Test for virtcol2col()
func Test_virtcol2col()
new
call setline(1, ["a\tb\tc"])
call assert_equal(1, virtcol2col(0, 1, 1))
call assert_equal(2, virtcol2col(0, 1, 2))
call assert_equal(2, virtcol2col(0, 1, 8))
call assert_equal(3, virtcol2col(0, 1, 9))
call assert_equal(4, virtcol2col(0, 1, 10))
call assert_equal(4, virtcol2col(0, 1, 16))
call assert_equal(5, virtcol2col(0, 1, 17))
call assert_equal(-1, virtcol2col(10, 1, 1))
call assert_equal(-1, virtcol2col(0, 10, 1))
call assert_equal(-1, virtcol2col(0, -1, 1))
call assert_equal(-1, virtcol2col(0, 1, -1))
call assert_equal(5, virtcol2col(0, 1, 20))
call assert_fails('echo virtcol2col("0", 1, 20)', 'E1210:')
call assert_fails('echo virtcol2col(0, "1", 20)', 'E1210:')
call assert_fails('echo virtcol2col(0, 1, "1")', 'E1210:')
bw!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,354 +0,0 @@
" Test for cursorline and cursorlineopt
source check.vim
source screendump.vim
func s:screen_attr(lnum) abort
return map(range(1, 8), 'screenattr(a:lnum, v:val)')
endfunc
func s:test_windows(h, w) abort
call NewWindow(a:h, a:w)
endfunc
func s:close_windows() abort
call CloseWindow()
endfunc
func s:new_hi() abort
redir => save_hi
silent! hi CursorLineNr
redir END
let save_hi = join(split(substitute(save_hi, '\s*xxx\s*', ' ', ''), "\n"), '')
exe 'hi' save_hi 'ctermbg=0 guibg=Black'
return save_hi
endfunc
func Test_cursorline_highlight1()
let save_hi = s:new_hi()
try
call s:test_windows(10, 20)
call setline(1, repeat(['aaaa'], 10))
redraw
let attr01 = s:screen_attr(1)
call assert_equal(repeat([attr01[0]], 8), attr01)
setl number numberwidth=4
redraw
let attr11 = s:screen_attr(1)
call assert_equal(repeat([attr11[0]], 4), attr11[0:3])
call assert_equal(repeat([attr11[4]], 4), attr11[4:7])
call assert_notequal(attr11[0], attr11[4])
setl cursorline
redraw
let attr21 = s:screen_attr(1)
let attr22 = s:screen_attr(2)
call assert_equal(repeat([attr21[0]], 4), attr21[0:3])
call assert_equal(repeat([attr21[4]], 4), attr21[4:7])
call assert_equal(attr11, attr22)
call assert_notequal(attr22, attr21)
setl nocursorline relativenumber
redraw
let attr31 = s:screen_attr(1)
call assert_equal(attr22[0:3], attr31[0:3])
call assert_equal(attr11[4:7], attr31[4:7])
call s:close_windows()
finally
exe 'hi' save_hi
endtry
endfunc
func Test_cursorline_highlight2()
CheckOption cursorlineopt
let save_hi = s:new_hi()
try
call s:test_windows(10, 20)
call setline(1, repeat(['aaaa'], 10))
redraw
let attr0 = s:screen_attr(1)
call assert_equal(repeat([attr0[0]], 8), attr0)
setl number
redraw
let attr1 = s:screen_attr(1)
call assert_notequal(attr0[0:3], attr1[0:3])
call assert_equal(attr0[0:3], attr1[4:7])
setl cursorline cursorlineopt=both
redraw
let attr2 = s:screen_attr(1)
call assert_notequal(attr1[0:3], attr2[0:3])
call assert_notequal(attr1[4:7], attr2[4:7])
setl cursorlineopt=line
redraw
let attr3 = s:screen_attr(1)
call assert_equal(attr1[0:3], attr3[0:3])
call assert_equal(attr2[4:7], attr3[4:7])
setl cursorlineopt=number
redraw
let attr4 = s:screen_attr(1)
call assert_equal(attr2[0:3], attr4[0:3])
call assert_equal(attr1[4:7], attr4[4:7])
setl nonumber
redraw
let attr5 = s:screen_attr(1)
call assert_equal(attr0, attr5)
call s:close_windows()
finally
exe 'hi' save_hi
endtry
endfunc
func Test_cursorline_screenline()
CheckScreendump
CheckOption cursorlineopt
let filename='Xcursorline'
let lines = []
let file_content =<< trim END
1 foooooooo ar einszwei drei vier fünf sechs sieben acht un zehn elf zwöfl dreizehn v ierzehn fünfzehn
2 foooooooo bar eins zwei drei vier fünf sechs sieben
3 foooooooo bar eins zwei drei vier fünf sechs sieben
4 foooooooo bar eins zwei drei vier fünf sechs sieben
END
let lines1 =<< trim END1
set nocp
set display=lastline
set cursorlineopt=screenline cursorline nu wrap sbr=>
hi CursorLineNr ctermfg=blue
25vsp
END1
let lines2 =<< trim END2
call cursor(1,1)
END2
call extend(lines, lines1)
call extend(lines, ["call append(0, ".. string(file_content).. ')'])
call extend(lines, lines2)
call writefile(lines, filename)
" basic test
let buf = RunVimInTerminal('-S '. filename, #{rows: 20})
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_1', {})
call term_sendkeys(buf, "fagj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_2', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_3', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_4', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_5', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_6', {})
" test with set list and cursorlineopt containing number
call term_sendkeys(buf, "gg0")
call term_sendkeys(buf, ":set list cursorlineopt+=number listchars=space:-\<cr>")
call VerifyScreenDump(buf, 'Test_'. filename. '_7', {})
call term_sendkeys(buf, "fagj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_8', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_9', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_10', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_11', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_12', {})
if exists("+foldcolumn") && exists("+signcolumn") && exists("+breakindent")
" test with set foldcolumn signcoloumn and breakindent
call term_sendkeys(buf, "gg0")
call term_sendkeys(buf, ":set breakindent foldcolumn=2 signcolumn=yes\<cr>")
call VerifyScreenDump(buf, 'Test_'. filename. '_13', {})
call term_sendkeys(buf, "fagj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_14', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_15', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_16', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_17', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_18', {})
call term_sendkeys(buf, ":set breakindent& foldcolumn& signcolumn&\<cr>")
endif
" showbreak should not be highlighted with CursorLine when 'number' is off
call term_sendkeys(buf, "gg0")
call term_sendkeys(buf, ":set list cursorlineopt=screenline listchars=space:-\<cr>")
call term_sendkeys(buf, ":set nonumber\<cr>")
call VerifyScreenDump(buf, 'Test_'. filename. '_19', {})
call term_sendkeys(buf, "fagj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_20', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_21', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_22', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_23', {})
call term_sendkeys(buf, "gj")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_'. filename. '_24', {})
call term_sendkeys(buf, ":set list& cursorlineopt& listchars&\<cr>")
call StopVimInTerminal(buf)
call delete(filename)
endfunc
func Test_cursorline_redraw()
CheckScreendump
CheckOption cursorlineopt
let textlines =<< END
When the option is a list of flags, {value} must be
exactly as they appear in the option. Remove flags
one by one to avoid problems.
Also see |:set-args| above.
The {option} arguments to ":set" may be repeated. For example: >
:set ai nosi sw=3 ts=3
If you make an error in one of the arguments, an error message will be given
and the following arguments will be ignored.
*:set-verbose*
When 'verbose' is non-zero, displaying an option value will also tell where it
was last set. Example: >
:verbose set shiftwidth cindent?
< shiftwidth=4 ~
Last set from modeline line 1 ~
cindent ~
Last set from /usr/local/share/vim/vim60/ftplugin/c.vim line 30 ~
This is only done when specific option values are requested, not for ":verbose
set all" or ":verbose set" without an argument.
When the option was set by hand there is no "Last set" message.
When the option was set while executing a function, user command or
END
call writefile(textlines, 'Xtextfile')
let script =<< trim END
set cursorline scrolloff=2
normal 12G
END
call writefile(script, 'Xscript')
let buf = RunVimInTerminal('-S Xscript Xtextfile', #{rows: 20, cols: 40})
call VerifyScreenDump(buf, 'Test_cursorline_redraw_1', {})
call term_sendkeys(buf, "zt")
call TermWait(buf)
call term_sendkeys(buf, "\<C-U>")
call VerifyScreenDump(buf, 'Test_cursorline_redraw_2', {})
call StopVimInTerminal(buf)
call delete('Xscript')
call delete('Xtextfile')
endfunc
func Test_cursorline_callback()
CheckScreendump
CheckFeature timers
let lines =<< trim END
call setline(1, ['aaaaa', 'bbbbb', 'ccccc', 'ddddd'])
set cursorline
call cursor(4, 1)
func Func(timer)
call cursor(2, 1)
endfunc
call timer_start(300, 'Func')
END
call writefile(lines, 'Xcul_timer')
let buf = RunVimInTerminal('-S Xcul_timer', #{rows: 8})
call TermWait(buf, 310)
call VerifyScreenDump(buf, 'Test_cursorline_callback_1', {})
call StopVimInTerminal(buf)
call delete('Xcul_timer')
endfunc
func Test_cursorline_screenline_update()
CheckScreendump
let lines =<< trim END
call setline(1, repeat('xyz ', 30))
set cursorline cursorlineopt=screenline
inoremap <F2> <Cmd>call cursor(1, 1)<CR>
END
call writefile(lines, 'Xcul_screenline')
let buf = RunVimInTerminal('-S Xcul_screenline', #{rows: 8})
call term_sendkeys(buf, "A")
call VerifyScreenDump(buf, 'Test_cursorline_screenline_1', {})
call term_sendkeys(buf, "\<F2>")
call VerifyScreenDump(buf, 'Test_cursorline_screenline_2', {})
call term_sendkeys(buf, "\<Esc>")
call StopVimInTerminal(buf)
call delete('Xcul_screenline')
endfunc
func Test_cursorline_cursorbind_horizontal_scroll()
CheckScreendump
let lines =<< trim END
call setline(1, 'aa bb cc dd ee ff gg hh ii jj kk ll mm' ..
\ ' nn oo pp qq rr ss tt uu vv ww xx yy zz')
set nowrap
" The following makes the cursor apparent on the screen dump
set sidescroll=1 cursorcolumn
" add empty lines, required for cursorcolumn
call append(1, ['','','',''])
20vsp
windo :set cursorbind
END
call writefile(lines, 'Xhor_scroll')
let buf = RunVimInTerminal('-S Xhor_scroll', #{rows: 8})
call term_sendkeys(buf, "20l")
call VerifyScreenDump(buf, 'Test_hor_scroll_1', {})
call term_sendkeys(buf, "10l")
call VerifyScreenDump(buf, 'Test_hor_scroll_2', {})
call term_sendkeys(buf, ":windo :set cursorline\<cr>")
call term_sendkeys(buf, "0")
call term_sendkeys(buf, "20l")
call VerifyScreenDump(buf, 'Test_hor_scroll_3', {})
call term_sendkeys(buf, "10l")
call VerifyScreenDump(buf, 'Test_hor_scroll_4', {})
call term_sendkeys(buf, ":windo :set nocursorline nocursorcolumn\<cr>")
call term_sendkeys(buf, "0")
call term_sendkeys(buf, "40l")
call VerifyScreenDump(buf, 'Test_hor_scroll_5', {})
call StopVimInTerminal(buf)
call delete('Xhor_scroll')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,23 +0,0 @@
" Tests for curswant not changing when setting an option
func Test_curswant()
new
call append(0, ['1234567890', '12345'])
normal! ggf8j
call assert_equal(7, winsaveview().curswant)
let &tabstop=&tabstop
call assert_equal(4, winsaveview().curswant)
normal! ggf8j
call assert_equal(7, winsaveview().curswant)
let &timeoutlen=&timeoutlen
call assert_equal(7, winsaveview().curswant)
normal! ggf8j
call assert_equal(7, winsaveview().curswant)
let &ttimeoutlen=&ttimeoutlen
call assert_equal(7, winsaveview().curswant)
enew!
endfunc

File diff suppressed because it is too large Load Diff

View File

@@ -1,110 +0,0 @@
" Test for delete().
source check.vim
func Test_file_delete()
split Xfile
call setline(1, ['a', 'b'])
wq
call assert_equal(['a', 'b'], readfile('Xfile'))
call assert_equal(0, delete('Xfile'))
call assert_fails('call readfile("Xfile")', 'E484:')
call assert_equal(-1, delete('Xfile'))
bwipe Xfile
endfunc
func Test_dir_delete()
call mkdir('Xdir1')
call assert_true(isdirectory('Xdir1'))
call assert_equal(0, delete('Xdir1', 'd'))
call assert_false(isdirectory('Xdir1'))
call assert_equal(-1, delete('Xdir1', 'd'))
endfunc
func Test_recursive_delete()
call mkdir('Xdir1')
call mkdir('Xdir1/subdir')
call mkdir('Xdir1/empty')
split Xdir1/Xfile
call setline(1, ['a', 'b'])
w
w Xdir1/subdir/Xfile
close
call assert_true(isdirectory('Xdir1'))
call assert_equal(['a', 'b'], readfile('Xdir1/Xfile'))
call assert_true(isdirectory('Xdir1/subdir'))
call assert_equal(['a', 'b'], readfile('Xdir1/subdir/Xfile'))
call assert_true('Xdir1/empty'->isdirectory())
call assert_equal(0, delete('Xdir1', 'rf'))
call assert_false(isdirectory('Xdir1'))
call assert_equal(-1, delete('Xdir1', 'd'))
bwipe Xdir1/Xfile
bwipe Xdir1/subdir/Xfile
endfunc
func Test_symlink_delete()
CheckUnix
split Xfile
call setline(1, ['a', 'b'])
wq
silent !ln -s Xfile Xlink
" Delete the link, not the file
call assert_equal(0, delete('Xlink'))
call assert_equal(-1, delete('Xlink'))
call assert_equal(0, delete('Xfile'))
bwipe Xfile
endfunc
func Test_symlink_dir_delete()
CheckUnix
call mkdir('Xdir1')
silent !ln -s Xdir1 Xlink
call assert_true(isdirectory('Xdir1'))
call assert_true(isdirectory('Xlink'))
" Delete the link, not the directory
call assert_equal(0, delete('Xlink'))
call assert_equal(-1, delete('Xlink'))
call assert_equal(0, delete('Xdir1', 'd'))
endfunc
func Test_symlink_recursive_delete()
CheckUnix
call mkdir('Xdir3')
call mkdir('Xdir3/subdir')
call mkdir('Xdir4')
split Xdir3/Xfile
call setline(1, ['a', 'b'])
w
w Xdir3/subdir/Xfile
w Xdir4/Xfile
close
silent !ln -s ../Xdir4 Xdir3/Xlink
call assert_true(isdirectory('Xdir3'))
call assert_equal(['a', 'b'], readfile('Xdir3/Xfile'))
call assert_true(isdirectory('Xdir3/subdir'))
call assert_equal(['a', 'b'], readfile('Xdir3/subdir/Xfile'))
call assert_true(isdirectory('Xdir4'))
call assert_true(isdirectory('Xdir3/Xlink'))
call assert_equal(['a', 'b'], readfile('Xdir4/Xfile'))
call assert_equal(0, delete('Xdir3', 'rf'))
call assert_false(isdirectory('Xdir3'))
call assert_equal(-1, delete('Xdir3', 'd'))
" symlink is deleted, not the directory it points to
call assert_true(isdirectory('Xdir4'))
call assert_equal(['a', 'b'], readfile('Xdir4/Xfile'))
call assert_equal(0, delete('Xdir4/Xfile'))
call assert_equal(0, delete('Xdir4', 'd'))
bwipe Xdir3/Xfile
bwipe Xdir3/subdir/Xfile
bwipe Xdir4/Xfile
endfunc
func Test_delete_errors()
call assert_fails('call delete('''')', 'E474:')
call assert_fails('call delete(''foo'', 0)', 'E15:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

File diff suppressed because it is too large Load Diff

View File

@@ -1,604 +0,0 @@
" Tests for digraphs
source check.vim
CheckFeature digraphs
source term_util.vim
func Put_Dig(chars)
exe "norm! o\<c-k>".a:chars
endfu
func Put_Dig_BS(char1, char2)
exe "norm! o".a:char1."\<bs>".a:char2
endfu
func Test_digraphs()
new
call Put_Dig("00")
call assert_equal("∞", getline('.'))
" not a digraph
call Put_Dig("el")
call assert_equal("l", getline('.'))
call Put_Dig("ht")
call assert_equal("þ", getline('.'))
" digraph "ab" is the same as "ba"
call Put_Dig("ab")
call Put_Dig("ba")
call assert_equal(["ば","ば"], getline(line('.')-1,line('.')))
" Euro sign
call Put_Dig("e=")
call Put_Dig("=e")
call Put_Dig("Eu")
call Put_Dig("uE")
call assert_equal(['е']+repeat(["€"],3), getline(line('.')-3,line('.')))
" Rouble sign
call Put_Dig("R=")
call Put_Dig("=R")
call Put_Dig("=P")
call Put_Dig("P=")
call assert_equal(['Р']+repeat(["₽"],2)+['П'], getline(line('.')-3,line('.')))
" Not a digraph
call Put_Dig("a\<bs>")
call Put_Dig("\<bs>a")
call assert_equal(["<BS>", "<BS>a"], getline(line('.')-1,line('.')))
" Grave
call Put_Dig("a!")
call Put_Dig("!e")
call Put_Dig("b!") " not defined
call assert_equal(["à", "è", "!"], getline(line('.')-2,line('.')))
" Acute accent
call Put_Dig("a'")
call Put_Dig("'e")
call Put_Dig("b'") " not defined
call assert_equal(["á", "é", "'"], getline(line('.')-2,line('.')))
" Cicumflex
call Put_Dig("a>")
call Put_Dig(">e")
call Put_Dig("b>") " not defined
call assert_equal(['â', 'ê', '>'], getline(line('.')-2,line('.')))
" Tilde
call Put_Dig("o~")
call Put_Dig("~u") " not defined
call Put_Dig("z~") " not defined
call assert_equal(['õ', 'u', '~'], getline(line('.')-2,line('.')))
" Tilde
call Put_Dig("o?")
call Put_Dig("?u")
call Put_Dig("z?") " not defined
call assert_equal(['õ', 'ũ', '?'], getline(line('.')-2,line('.')))
" Macron
call Put_Dig("o-")
call Put_Dig("-u")
call Put_Dig("z-") " not defined
call assert_equal(['ō', 'ū', '-'], getline(line('.')-2,line('.')))
" Breve
call Put_Dig("o(")
call Put_Dig("(u")
call Put_Dig("z(") " not defined
call assert_equal(['ŏ', 'ŭ', '('], getline(line('.')-2,line('.')))
" Dot above
call Put_Dig("b.")
call Put_Dig(".e")
call Put_Dig("a.") " not defined
call assert_equal(['ḃ', 'ė', '.'], getline(line('.')-2,line('.')))
" Diaeresis
call Put_Dig("a:")
call Put_Dig(":u")
call Put_Dig("b:") " not defined
call assert_equal(['ä', 'ü', ':'], getline(line('.')-2,line('.')))
" Cedilla
call Put_Dig("',")
call Put_Dig(",C")
call Put_Dig("b,") " not defined
call assert_equal(['¸', 'Ç', ','], getline(line('.')-2,line('.')))
" Underline
call Put_Dig("B_")
call Put_Dig("_t")
call Put_Dig("a_") " not defined
call assert_equal(['Ḇ', 'ṯ', '_'], getline(line('.')-2,line('.')))
" Stroke
call Put_Dig("j/")
call Put_Dig("/l")
call Put_Dig("b/") " not defined
call assert_equal(['/', 'ł', '/'], getline(line('.')-2,line('.')))
" Double acute
call Put_Dig('O"')
call Put_Dig('"y')
call Put_Dig('b"') " not defined
call assert_equal(['Ő', 'ÿ', '"'], getline(line('.')-2,line('.')))
" Ogonek
call Put_Dig('u;')
call Put_Dig(';E')
call Put_Dig('b;') " not defined
call assert_equal(['ų', 'Ę', ';'], getline(line('.')-2,line('.')))
" Caron
call Put_Dig('u<')
call Put_Dig('<E')
call Put_Dig('b<') " not defined
call assert_equal(['ǔ', 'Ě', '<'], getline(line('.')-2,line('.')))
" Ring above
call Put_Dig('u0')
call Put_Dig('0E') " not defined
call Put_Dig('b0') " not defined
call assert_equal(['ů', 'E', '0'], getline(line('.')-2,line('.')))
" Hook
call Put_Dig('u2')
call Put_Dig('2E')
call Put_Dig('b2') " not defined
call assert_equal(['ủ', 'Ẻ', '2'], getline(line('.')-2,line('.')))
" Horn
call Put_Dig('u9')
call Put_Dig('9E') " not defined
call Put_Dig('b9') " not defined
call assert_equal(['ư', 'E', '9'], getline(line('.')-2,line('.')))
" Cyrillic
call Put_Dig('u=')
call Put_Dig('=b')
call Put_Dig('=_')
call assert_equal(['у', 'б', '〓'], getline(line('.')-2,line('.')))
" Greek
call Put_Dig('u*')
call Put_Dig('*b')
call Put_Dig('*_')
call assert_equal(['υ', 'β', '々'], getline(line('.')-2,line('.')))
" Greek/Cyrillic special
call Put_Dig('u%')
call Put_Dig('%b') " not defined
call Put_Dig('%_') " not defined
call assert_equal(['ύ', 'b', '_'], getline(line('.')-2,line('.')))
" Arabic
call Put_Dig('u+')
call Put_Dig('+b')
call Put_Dig('+_') " japanese industrial symbol
call assert_equal(['+', 'ب', '〄'], getline(line('.')-2,line('.')))
" Hebrew
call Put_Dig('Q+')
call Put_Dig('+B')
call Put_Dig('+X')
call assert_equal(['ק', 'ב', 'ח'], getline(line('.')-2,line('.')))
" Latin
call Put_Dig('a3')
call Put_Dig('A3')
call Put_Dig('3X')
call assert_equal(['ǣ', 'Ǣ', 'X'], getline(line('.')-2,line('.')))
" Bopomofo
call Put_Dig('a4')
call Put_Dig('A4')
call Put_Dig('4X')
call assert_equal(['ㄚ', '4', 'X'], getline(line('.')-2,line('.')))
" Hiragana
call Put_Dig('a5')
call Put_Dig('A5')
call Put_Dig('5X')
call assert_equal(['あ', 'ぁ', 'X'], getline(line('.')-2,line('.')))
" Katakana
call Put_Dig('a6')
call Put_Dig('A6')
call Put_Dig('6X')
call assert_equal(['ァ', 'ア', 'X'], getline(line('.')-2,line('.')))
" Superscripts
call Put_Dig('1S')
call Put_Dig('2S')
call Put_Dig('3S')
call assert_equal(['¹', '²', '³'], getline(line('.')-2,line('.')))
" Subscripts
call Put_Dig('1s')
call Put_Dig('2s')
call Put_Dig('3s')
call assert_equal(['₁', '₂', '₃'], getline(line('.')-2,line('.')))
" Eszet (only lowercase)
call Put_Dig("ss")
call Put_Dig("SS") " start of string
call assert_equal(["ß", "˜"], getline(line('.')-1,line('.')))
" High bit set
call Put_Dig("a ")
call Put_Dig(" A")
call assert_equal(['á', 'Á'], getline(line('.')-1,line('.')))
" Escape is not part of a digraph
call Put_Dig("a\<esc>")
call Put_Dig("\<esc>A")
call assert_equal(['', 'A'], getline(line('.')-1,line('.')))
" define some custom digraphs
" old: 00 ∞
" old: el l
digraph 00 9216
digraph el 0252
call Put_Dig("00")
call Put_Dig("el")
" Reset digraphs
digraph 00 8734
digraph el 108
call Put_Dig("00")
call Put_Dig("el")
call assert_equal(['␀', 'ü', '∞', 'l'], getline(line('.')-3,line('.')))
call assert_fails('exe "digraph a\<Esc> 100"', 'E104:')
call assert_fails('exe "digraph \<Esc>a 100"', 'E104:')
call assert_fails('digraph xy z', 'E39:')
call assert_fails('digraph x', 'E1214:')
bw!
endfunc
func Test_digraphs_option()
" reset whichwrap option, so that testing <esc><bs>A works,
" without moving up a line
set digraph ww=
new
call Put_Dig_BS("0","0")
call assert_equal("∞", getline('.'))
" not a digraph
call Put_Dig_BS("e","l")
call assert_equal("l", getline('.'))
call Put_Dig_BS("h","t")
call assert_equal("þ", getline('.'))
" digraph "ab" is the same as "ba"
call Put_Dig_BS("a","b")
call Put_Dig_BS("b","a")
call assert_equal(["ば","ば"], getline(line('.')-1,line('.')))
" Euro sign
call Put_Dig_BS("e","=")
call Put_Dig_BS("=","e")
call Put_Dig_BS("E","u")
call Put_Dig_BS("u","E")
call assert_equal(['е']+repeat(["€"],3), getline(line('.')-3,line('.')))
" Rouble sign
call Put_Dig_BS("R","=")
call Put_Dig_BS("=","R")
call Put_Dig_BS("=","P")
call Put_Dig_BS("P","=")
call assert_equal(['Р']+repeat(["₽"],2)+['П'], getline(line('.')-3,line('.')))
" Not a digraph: this is different from <c-k>!
call Put_Dig_BS("a","\<bs>")
call Put_Dig_BS("\<bs>","a")
call assert_equal(['','a'], getline(line('.')-1,line('.')))
" Grave
call Put_Dig_BS("a","!")
call Put_Dig_BS("!","e")
call Put_Dig_BS("b","!") " not defined
call assert_equal(["à", "è", "!"], getline(line('.')-2,line('.')))
" Acute accent
call Put_Dig_BS("a","'")
call Put_Dig_BS("'","e")
call Put_Dig_BS("b","'") " not defined
call assert_equal(["á", "é", "'"], getline(line('.')-2,line('.')))
" Cicumflex
call Put_Dig_BS("a",">")
call Put_Dig_BS(">","e")
call Put_Dig_BS("b",">") " not defined
call assert_equal(['â', 'ê', '>'], getline(line('.')-2,line('.')))
" Tilde
call Put_Dig_BS("o","~")
call Put_Dig_BS("~","u") " not defined
call Put_Dig_BS("z","~") " not defined
call assert_equal(['õ', 'u', '~'], getline(line('.')-2,line('.')))
" Tilde
call Put_Dig_BS("o","?")
call Put_Dig_BS("?","u")
call Put_Dig_BS("z","?") " not defined
call assert_equal(['õ', 'ũ', '?'], getline(line('.')-2,line('.')))
" Macron
call Put_Dig_BS("o","-")
call Put_Dig_BS("-","u")
call Put_Dig_BS("z","-") " not defined
call assert_equal(['ō', 'ū', '-'], getline(line('.')-2,line('.')))
" Breve
call Put_Dig_BS("o","(")
call Put_Dig_BS("(","u")
call Put_Dig_BS("z","(") " not defined
call assert_equal(['ŏ', 'ŭ', '('], getline(line('.')-2,line('.')))
" Dot above
call Put_Dig_BS("b",".")
call Put_Dig_BS(".","e")
call Put_Dig_BS("a",".") " not defined
call assert_equal(['ḃ', 'ė', '.'], getline(line('.')-2,line('.')))
" Diaeresis
call Put_Dig_BS("a",":")
call Put_Dig_BS(":","u")
call Put_Dig_BS("b",":") " not defined
call assert_equal(['ä', 'ü', ':'], getline(line('.')-2,line('.')))
" Cedilla
call Put_Dig_BS("'",",")
call Put_Dig_BS(",","C")
call Put_Dig_BS("b",",") " not defined
call assert_equal(['¸', 'Ç', ','], getline(line('.')-2,line('.')))
" Underline
call Put_Dig_BS("B","_")
call Put_Dig_BS("_","t")
call Put_Dig_BS("a","_") " not defined
call assert_equal(['Ḇ', 'ṯ', '_'], getline(line('.')-2,line('.')))
" Stroke
call Put_Dig_BS("j","/")
call Put_Dig_BS("/","l")
call Put_Dig_BS("b","/") " not defined
call assert_equal(['/', 'ł', '/'], getline(line('.')-2,line('.')))
" Double acute
call Put_Dig_BS('O','"')
call Put_Dig_BS('"','y')
call Put_Dig_BS('b','"') " not defined
call assert_equal(['Ő', 'ÿ', '"'], getline(line('.')-2,line('.')))
" Ogonek
call Put_Dig_BS('u',';')
call Put_Dig_BS(';','E')
call Put_Dig_BS('b',';') " not defined
call assert_equal(['ų', 'Ę', ';'], getline(line('.')-2,line('.')))
" Caron
call Put_Dig_BS('u','<')
call Put_Dig_BS('<','E')
call Put_Dig_BS('b','<') " not defined
call assert_equal(['ǔ', 'Ě', '<'], getline(line('.')-2,line('.')))
" Ring above
call Put_Dig_BS('u','0')
call Put_Dig_BS('0','E') " not defined
call Put_Dig_BS('b','0') " not defined
call assert_equal(['ů', 'E', '0'], getline(line('.')-2,line('.')))
" Hook
call Put_Dig_BS('u','2')
call Put_Dig_BS('2','E')
call Put_Dig_BS('b','2') " not defined
call assert_equal(['ủ', 'Ẻ', '2'], getline(line('.')-2,line('.')))
" Horn
call Put_Dig_BS('u','9')
call Put_Dig_BS('9','E') " not defined
call Put_Dig_BS('b','9') " not defined
call assert_equal(['ư', 'E', '9'], getline(line('.')-2,line('.')))
" Cyrillic
call Put_Dig_BS('u','=')
call Put_Dig_BS('=','b')
call Put_Dig_BS('=','_')
call assert_equal(['у', 'б', '〓'], getline(line('.')-2,line('.')))
" Greek
call Put_Dig_BS('u','*')
call Put_Dig_BS('*','b')
call Put_Dig_BS('*','_')
call assert_equal(['υ', 'β', '々'], getline(line('.')-2,line('.')))
" Greek/Cyrillic special
call Put_Dig_BS('u','%')
call Put_Dig_BS('%','b') " not defined
call Put_Dig_BS('%','_') " not defined
call assert_equal(['ύ', 'b', '_'], getline(line('.')-2,line('.')))
" Arabic
call Put_Dig_BS('u','+')
call Put_Dig_BS('+','b')
call Put_Dig_BS('+','_') " japanese industrial symbol
call assert_equal(['+', 'ب', '〄'], getline(line('.')-2,line('.')))
" Hebrew
call Put_Dig_BS('Q','+')
call Put_Dig_BS('+','B')
call Put_Dig_BS('+','X')
call assert_equal(['ק', 'ב', 'ח'], getline(line('.')-2,line('.')))
" Latin
call Put_Dig_BS('a','3')
call Put_Dig_BS('A','3')
call Put_Dig_BS('3','X')
call assert_equal(['ǣ', 'Ǣ', 'X'], getline(line('.')-2,line('.')))
" Bopomofo
call Put_Dig_BS('a','4')
call Put_Dig_BS('A','4')
call Put_Dig_BS('4','X')
call assert_equal(['ㄚ', '4', 'X'], getline(line('.')-2,line('.')))
" Hiragana
call Put_Dig_BS('a','5')
call Put_Dig_BS('A','5')
call Put_Dig_BS('5','X')
call assert_equal(['あ', 'ぁ', 'X'], getline(line('.')-2,line('.')))
" Katakana
call Put_Dig_BS('a','6')
call Put_Dig_BS('A','6')
call Put_Dig_BS('6','X')
call assert_equal(['ァ', 'ア', 'X'], getline(line('.')-2,line('.')))
" Superscripts
call Put_Dig_BS('1','S')
call Put_Dig_BS('2','S')
call Put_Dig_BS('3','S')
call assert_equal(['¹', '²', '³'], getline(line('.')-2,line('.')))
" Subscripts
call Put_Dig_BS('1','s')
call Put_Dig_BS('2','s')
call Put_Dig_BS('3','s')
call assert_equal(['₁', '₂', '₃'], getline(line('.')-2,line('.')))
" Eszet (only lowercase)
call Put_Dig_BS("s","s")
call Put_Dig_BS("S","S") " start of string
call assert_equal(["ß", "˜"], getline(line('.')-1,line('.')))
" High bit set (different from <c-k>)
call Put_Dig_BS("a"," ")
call Put_Dig_BS(" ","A")
call assert_equal([' ', 'A'], getline(line('.')-1,line('.')))
" Escape is not part of a digraph (different from <c-k>)
call Put_Dig_BS("a","\<esc>")
call Put_Dig_BS("\<esc>","A")
call assert_equal(['', ''], getline(line('.')-1,line('.')))
" define some custom digraphs
" old: 00 ∞
" old: el l
digraph 00 9216
digraph el 0252
call Put_Dig_BS("0","0")
call Put_Dig_BS("e","l")
" Reset digraphs
digraph 00 8734
digraph el 108
call Put_Dig_BS("0","0")
call Put_Dig_BS("e","l")
call assert_equal(['␀', 'ü', '∞', 'l'], getline(line('.')-3,line('.')))
set nodigraph ww&vim
bw!
endfunc
func Test_digraphs_output()
new
let out = execute(':digraph')
call assert_equal('Eu € 8364', matchstr(out, '\C\<Eu\D*8364\>'))
call assert_equal('=e € 8364', matchstr(out, '\C=e\D*8364\>'))
call assert_equal('=R ₽ 8381', matchstr(out, '\C=R\D*8381\>'))
call assert_equal('=P ₽ 8381', matchstr(out, '\C=P\D*8381\>'))
call assert_equal('o: ö 246', matchstr(out, '\C\<o:\D*246\>'))
call assert_equal('v4 ㄪ 12586', matchstr(out, '\C\<v4\D*12586\>'))
call assert_equal("'0 ˚ 730", matchstr(out, '\C''0\D*730\>'))
call assert_equal('Z% Ж 1046', matchstr(out, '\C\<Z%\D*1046\>'))
call assert_equal('u- ū 363', matchstr(out, '\C\<u-\D*363\>'))
call assert_equal('SH ^A 1', matchstr(out, '\C\<SH\D*1\>'))
call assert_notmatch('Latin supplement', out)
let out_bang_without_custom = execute(':digraph!')
digraph lt 60
let out_bang_with_custom = execute(':digraph!')
call assert_notmatch('lt', out_bang_without_custom)
call assert_match("^\n"
\ .. "NU ^@ 10 .*\n"
\ .. "Latin supplement\n"
\ .. "!I ¡ 161 .*\n"
\ .. ".*\n"
\ .. 'Custom\n.*\<lt < 60\>', out_bang_with_custom)
bw!
endfunc
func Test_loadkeymap()
if !has('keymap')
return
endif
new
set keymap=czech
set iminsert=0
call feedkeys("o|\<c-^>|01234567890|\<esc>", 'tx')
call assert_equal("|'é+ěščřžýáíé'", getline('.'))
" reset keymap and encoding option
set keymap=
bw!
endfunc
func Test_digraph_cmndline()
" Create digraph on commandline
call feedkeys(":\"\<c-k>Eu\<cr>", 'xt')
call assert_equal('"€', @:)
" Canceling a CTRL-K on the cmdline
call feedkeys(":\"a\<c-k>\<esc>b\<cr>", 'xt')
call assert_equal('"ab', @:)
endfunc
func Test_show_digraph()
new
call Put_Dig("e=")
call assert_equal("\n<е> 1077, Hex 0435, Oct 2065, Digr e=", execute('ascii'))
bwipe!
endfunc
func Test_show_digraph_cp1251()
throw 'skipped: Nvim supports ''utf8'' encoding only'
new
set encoding=cp1251
call Put_Dig("='")
call assert_equal("\n<\xfa> <|z> <M-z> 250, Hex fa, Oct 372, Digr ='", execute('ascii'))
set encoding=utf-8
bwipe!
endfunc
" Test for error in a keymap file
func Test_loadkeymap_error()
if !has('keymap')
return
endif
call assert_fails('loadkeymap', 'E105:')
call writefile(['loadkeymap', 'a'], 'Xkeymap')
call assert_fails('source Xkeymap', 'E791:')
call delete('Xkeymap')
endfunc
" Test for the characters displayed on the screen when entering a digraph
func Test_entering_digraph()
CheckRunVimInTerminal
let buf = RunVimInTerminal('', {'rows': 6})
call term_sendkeys(buf, "i\<C-K>")
call term_wait(buf)
call assert_equal('?', term_getline(buf, 1))
call term_sendkeys(buf, "1")
call term_wait(buf)
call assert_equal('1', term_getline(buf, 1))
call term_sendkeys(buf, "2")
call term_wait(buf)
call assert_equal('½', term_getline(buf, 1))
call StopVimInTerminal(buf)
endfunc
func Test_digraph_set_function()
new
call digraph_set('aa', 'あ')
call Put_Dig('aa')
call assert_equal('あ', getline('$'))
call digraph_set(' i', 'い')
call Put_Dig(' i')
call assert_equal('い', getline('$'))
call digraph_set(' ', 'う')
call Put_Dig(' ')
call assert_equal('う', getline('$'))
eval 'aa'->digraph_set('え')
call Put_Dig('aa')
call assert_equal('え', getline('$'))
call assert_fails('call digraph_set("aaa", "あ")', 'E1214: Digraph must be just two characters: aaa')
call assert_fails('call digraph_set("b", "あ")', 'E1214: Digraph must be just two characters: b')
call assert_fails('call digraph_set("あ", "あ")', 'E1214: Digraph must be just two characters: あ')
call assert_fails('call digraph_set("aa", "ああ")', 'E1215: Digraph must be one character: ああ')
call assert_fails('call digraph_set("aa", "か" .. nr2char(0x3099))', 'E1215: Digraph must be one character: か' .. nr2char(0x3099))
bwipe!
endfunc
func Test_digraph_get_function()
" Built-in digraphs
call assert_equal('∞', digraph_get('00'))
" User-defined digraphs
call digraph_set('aa', 'あ')
call digraph_set(' i', 'い')
call digraph_set(' ', 'う')
call assert_equal('あ', digraph_get('aa'))
call assert_equal('あ', 'aa'->digraph_get())
call assert_equal('い', digraph_get(' i'))
call assert_equal('う', digraph_get(' '))
call assert_fails('call digraph_get("aaa")', 'E1214: Digraph must be just two characters: aaa')
call assert_fails('call digraph_get("b")', 'E1214: Digraph must be just two characters: b')
endfunc
func Test_digraph_get_function_encode()
throw 'Skipped: Nvim does not support setting encoding=japan'
CheckFeature iconv
let testcases = {
\'00': '∞',
\'aa': 'あ',
\}
for [key, ch] in items(testcases)
call digraph_set(key, ch)
set encoding=japan
call assert_equal(iconv(ch, 'utf-8', 'japan'), digraph_get(key))
set encoding=utf-8
endfor
endfunc
func Test_digraph_setlist_function()
call digraph_setlist([['aa', 'き'], ['bb', 'く']])
call assert_equal('き', digraph_get('aa'))
call assert_equal('く', digraph_get('bb'))
call assert_fails('call digraph_setlist([[]])', 'E1216:')
call assert_fails('call digraph_setlist([["aa", "b", "cc"]])', '1216:')
call assert_fails('call digraph_setlist([["あ", "あ"]])', 'E1214: Digraph must be just two characters: あ')
endfunc
func Test_digraph_getlist_function()
" Make sure user-defined digraphs are defined
call digraph_setlist([['aa', 'き'], ['bb', 'く']])
for pair in digraph_getlist(1)
call assert_equal(digraph_get(pair[0]), pair[1])
endfor
" We don't know how many digraphs are registered before, so check the number
" of digraphs returned.
call assert_equal(digraph_getlist()->len(), digraph_getlist(0)->len())
call assert_notequal((digraph_getlist()->len()), digraph_getlist(1)->len())
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,482 +0,0 @@
" Test for displaying stuff
" Nvim: `:set term` is not supported.
" if !has('gui_running') && has('unix')
" set term=ansi
" endif
source view_util.vim
source check.vim
source screendump.vim
func Test_display_foldcolumn()
CheckFeature folding
new
vnew
vert resize 25
call assert_equal(25, winwidth(winnr()))
set isprint=@
1put='e more noise blah blah‚ more stuff here'
let expect = [
\ "e more noise blah blah<82",
\ "> more stuff here "
\ ]
call cursor(2, 1)
norm! zt
let lines = ScreenLines([1,2], winwidth(0))
call assert_equal(expect, lines)
set fdc=2
let lines = ScreenLines([1,2], winwidth(0))
let expect = [
\ " e more noise blah blah<",
\ " 82> more stuff here "
\ ]
call assert_equal(expect, lines)
quit!
quit!
endfunc
func Test_display_foldtext_mbyte()
CheckFeature folding
call NewWindow(10, 40)
call append(0, range(1,20))
exe "set foldmethod=manual foldtext=foldtext() fillchars=fold:\u2500,vert:\u2502 fdc=2"
call cursor(2, 1)
norm! zf13G
let lines=ScreenLines([1,3], winwidth(0)+1)
let expect=[
\ " 1 \u2502",
\ "+ +-- 12 lines: 2". repeat("\u2500", 23). "\u2502",
\ " 14 \u2502",
\ ]
call assert_equal(expect, lines)
set fillchars=fold:-,vert:\|
let lines=ScreenLines([1,3], winwidth(0)+1)
let expect=[
\ " 1 |",
\ "+ +-- 12 lines: 2". repeat("-", 23). "|",
\ " 14 |",
\ ]
call assert_equal(expect, lines)
set foldtext& fillchars& foldmethod& fdc&
bw!
endfunc
" check that win_ins_lines() and win_del_lines() work when t_cs is empty.
func Test_scroll_without_region()
CheckScreendump
let lines =<< trim END
call setline(1, range(1, 20))
set t_cs=
set laststatus=2
END
call writefile(lines, 'Xtestscroll')
let buf = RunVimInTerminal('-S Xtestscroll', #{rows: 10})
call VerifyScreenDump(buf, 'Test_scroll_no_region_1', {})
call term_sendkeys(buf, ":3delete\<cr>")
call VerifyScreenDump(buf, 'Test_scroll_no_region_2', {})
call term_sendkeys(buf, ":4put\<cr>")
call VerifyScreenDump(buf, 'Test_scroll_no_region_3', {})
call term_sendkeys(buf, ":undo\<cr>")
call term_sendkeys(buf, ":undo\<cr>")
call term_sendkeys(buf, ":set laststatus=0\<cr>")
call VerifyScreenDump(buf, 'Test_scroll_no_region_4', {})
call term_sendkeys(buf, ":3delete\<cr>")
call VerifyScreenDump(buf, 'Test_scroll_no_region_5', {})
call term_sendkeys(buf, ":4put\<cr>")
call VerifyScreenDump(buf, 'Test_scroll_no_region_6', {})
" clean up
call StopVimInTerminal(buf)
call delete('Xtestscroll')
endfunc
func Test_display_listchars_precedes()
set fillchars+=vert:\|
call NewWindow(10, 10)
" Need a physical line that wraps over the complete
" window size
call append(0, repeat('aaa aaa aa ', 10))
call append(1, repeat(['bbb bbb bbb bbb'], 2))
" remove blank trailing line
$d
set list nowrap
call cursor(1, 1)
" move to end of line and scroll 2 characters back
norm! $2zh
let lines=ScreenLines([1,4], winwidth(0)+1)
let expect = [
\ " aaa aa $ |",
\ "$ |",
\ "$ |",
\ "~ |",
\ ]
call assert_equal(expect, lines)
set list listchars+=precedes:< nowrap
call cursor(1, 1)
" move to end of line and scroll 2 characters back
norm! $2zh
let lines = ScreenLines([1,4], winwidth(0)+1)
let expect = [
\ "<aaa aa $ |",
\ "< |",
\ "< |",
\ "~ |",
\ ]
call assert_equal(expect, lines)
set wrap
call cursor(1, 1)
" the complete line should be displayed in the window
norm! $
let lines = ScreenLines([1,10], winwidth(0)+1)
let expect = [
\ "<aaa aaa a|",
\ "a aaa aaa |",
\ "aa aaa aaa|",
\ " aa aaa aa|",
\ "a aa aaa a|",
\ "aa aa aaa |",
\ "aaa aa aaa|",
\ " aaa aa aa|",
\ "a aaa aa a|",
\ "aa aaa aa |",
\ ]
call assert_equal(expect, lines)
set list& listchars& wrap&
bw!
endfunc
" Check that win_lines() works correctly with the number_only parameter=TRUE
" should break early to optimize cost of drawing, but needs to make sure
" that the number column is correctly highlighted.
func Test_scroll_CursorLineNr_update()
CheckScreendump
let lines =<< trim END
hi CursorLineNr ctermfg=73 ctermbg=236
set nu rnu cursorline cursorlineopt=number
exe ":norm! o\<esc>110ia\<esc>"
END
let filename = 'Xdrawscreen'
call writefile(lines, filename)
let buf = RunVimInTerminal('-S '.filename, #{rows: 5, cols: 50})
call term_sendkeys(buf, "k")
call term_wait(buf)
call VerifyScreenDump(buf, 'Test_winline_rnu', {})
" clean up
call StopVimInTerminal(buf)
call delete(filename)
endfunc
" check a long file name does not result in the hit-enter prompt
func Test_edit_long_file_name()
CheckScreendump
let longName = 'x'->repeat(min([&columns, 255]))
call writefile([], longName)
let buf = RunVimInTerminal('-N -u NONE ' .. longName, #{rows: 8})
call VerifyScreenDump(buf, 'Test_long_file_name_1', {})
" clean up
call StopVimInTerminal(buf)
call delete(longName)
endfunc
func Test_unprintable_fileformats()
CheckScreendump
call writefile(["unix\r", "two"], 'Xunix.txt')
call writefile(["mac\r", "two"], 'Xmac.txt')
let lines =<< trim END
edit Xunix.txt
split Xmac.txt
edit ++ff=mac
END
let filename = 'Xunprintable'
call writefile(lines, filename)
let buf = RunVimInTerminal('-S '.filename, #{rows: 9, cols: 50})
call VerifyScreenDump(buf, 'Test_display_unprintable_01', {})
call term_sendkeys(buf, "\<C-W>\<C-W>\<C-L>")
call VerifyScreenDump(buf, 'Test_display_unprintable_02', {})
" clean up
call StopVimInTerminal(buf)
call delete('Xunix.txt')
call delete('Xmac.txt')
call delete(filename)
endfunc
" Test for scrolling that modifies buffer during visual block
func Test_visual_block_scroll()
CheckScreendump
let lines =<< trim END
source $VIMRUNTIME/plugin/matchparen.vim
set scrolloff=1
call setline(1, ['a', 'b', 'c', 'd', 'e', '', '{', '}', '{', 'f', 'g', '}'])
call cursor(5, 1)
END
let filename = 'Xvisualblockmodifiedscroll'
call writefile(lines, filename, 'D')
let buf = RunVimInTerminal('-S '.filename, #{rows: 7})
call term_sendkeys(buf, "V\<C-D>\<C-D>")
call VerifyScreenDump(buf, 'Test_display_visual_block_scroll', {})
call StopVimInTerminal(buf)
endfunc
" Test for clearing paren highlight when switching buffers
func Test_matchparen_clear_highlight()
CheckScreendump
let lines =<< trim END
source $VIMRUNTIME/plugin/matchparen.vim
set hidden
call setline(1, ['()'])
normal 0
func OtherBuffer()
enew
exe "normal iaa\<Esc>0"
endfunc
END
call writefile(lines, 'XMatchparenClear', 'D')
let buf = RunVimInTerminal('-S XMatchparenClear', #{rows: 5})
call VerifyScreenDump(buf, 'Test_matchparen_clear_highlight_1', {})
call term_sendkeys(buf, ":call OtherBuffer()\<CR>:\<Esc>")
call VerifyScreenDump(buf, 'Test_matchparen_clear_highlight_2', {})
call term_sendkeys(buf, "\<C-^>:\<Esc>")
call VerifyScreenDump(buf, 'Test_matchparen_clear_highlight_1', {})
call term_sendkeys(buf, "\<C-^>:\<Esc>")
call VerifyScreenDump(buf, 'Test_matchparen_clear_highlight_2', {})
call StopVimInTerminal(buf)
endfunc
func Test_display_scroll_at_topline()
CheckScreendump
let buf = RunVimInTerminal('', #{cols: 20})
call term_sendkeys(buf, ":call setline(1, repeat('a', 21))\<CR>")
call term_wait(buf)
call term_sendkeys(buf, "O\<Esc>")
call VerifyScreenDump(buf, 'Test_display_scroll_at_topline', #{rows: 4})
call StopVimInTerminal(buf)
endfunc
func Test_display_scroll_update_visual()
CheckScreendump
let lines =<< trim END
set scrolloff=0
call setline(1, repeat(['foo'], 10))
call sign_define('foo', { 'text': '>' })
call sign_place(1, 'bar', 'foo', bufnr(), { 'lnum': 2 })
call sign_place(2, 'bar', 'foo', bufnr(), { 'lnum': 1 })
autocmd CursorMoved * if getcurpos()[1] == 2 | call sign_unplace('bar', { 'id': 1 }) | endif
END
call writefile(lines, 'XupdateVisual.vim')
let buf = RunVimInTerminal('-S XupdateVisual.vim', #{rows: 8, cols: 60})
call term_sendkeys(buf, "VG7kk")
call VerifyScreenDump(buf, 'Test_display_scroll_update_visual', {})
call StopVimInTerminal(buf)
call delete('XupdateVisual.vim')
endfunc
" Test for 'eob' (EndOfBuffer) item in 'fillchars'
func Test_eob_fillchars()
" default value (skipped)
" call assert_match('eob:\~', &fillchars)
" invalid values
call assert_fails(':set fillchars=eob:', 'E474:')
call assert_fails(':set fillchars=eob:xy', 'E474:')
call assert_fails(':set fillchars=eob:\255', 'E474:')
call assert_fails(':set fillchars=eob:<ff>', 'E474:')
call assert_fails(":set fillchars=eob:\x01", 'E474:')
call assert_fails(':set fillchars=eob:\\x01', 'E474:')
" default is ~
new
redraw
call assert_equal('~', Screenline(2))
set fillchars=eob:+
redraw
call assert_equal('+', Screenline(2))
set fillchars=eob:\
redraw
call assert_equal(' ', nr2char(screenchar(2, 1)))
set fillchars&
close
endfunc
" Test for 'foldopen', 'foldclose' and 'foldsep' in 'fillchars'
func Test_fold_fillchars()
new
set fdc=2 foldenable foldmethod=manual
call setline(1, ['one', 'two', 'three', 'four', 'five'])
2,4fold
" First check for the default setting for a closed fold
let lines = ScreenLines([1, 3], 8)
let expected = [
\ ' one ',
\ '+ +-- 3',
\ ' five '
\ ]
call assert_equal(expected, lines)
normal 2Gzo
" check the characters for an open fold
let lines = ScreenLines([1, 5], 8)
let expected = [
\ ' one ',
\ '- two ',
\ '| three ',
\ '| four ',
\ ' five '
\ ]
call assert_equal(expected, lines)
" change the setting
set fillchars=vert:\|,fold:-,eob:~,foldopen:[,foldclose:],foldsep:-
" check the characters for an open fold
let lines = ScreenLines([1, 5], 8)
let expected = [
\ ' one ',
\ '[ two ',
\ '- three ',
\ '- four ',
\ ' five '
\ ]
call assert_equal(expected, lines)
" check the characters for a closed fold
normal 2Gzc
let lines = ScreenLines([1, 3], 8)
let expected = [
\ ' one ',
\ '] +-- 3',
\ ' five '
\ ]
call assert_equal(expected, lines)
%bw!
set fillchars& fdc& foldmethod& foldenable&
endfunc
func Test_local_fillchars()
CheckScreendump
let lines =<< trim END
call setline(1, ['window 1']->repeat(3))
setlocal fillchars=stl:1,stlnc:a,vert:=,eob:x
vnew
call setline(1, ['window 2']->repeat(3))
setlocal fillchars=stl:2,stlnc:b,vert:+,eob:y
new
wincmd J
call setline(1, ['window 3']->repeat(3))
setlocal fillchars=stl:3,stlnc:c,vert:<,eob:z
vnew
call setline(1, ['window 4']->repeat(3))
setlocal fillchars=stl:4,stlnc:d,vert:>,eob:o
END
call writefile(lines, 'Xdisplayfillchars')
let buf = RunVimInTerminal('-S Xdisplayfillchars', #{rows: 12})
call VerifyScreenDump(buf, 'Test_display_fillchars_1', {})
call term_sendkeys(buf, ":wincmd k\r")
call VerifyScreenDump(buf, 'Test_display_fillchars_2', {})
call StopVimInTerminal(buf)
call delete('Xdisplayfillchars')
endfunc
func Test_display_linebreak_breakat()
new
vert resize 25
let _breakat = &breakat
setl signcolumn=yes linebreak breakat=) showbreak=+\
call setline(1, repeat('x', winwidth(0) - 2) .. ')abc')
let lines = ScreenLines([1, 2], 25)
let expected = [
\ ' xxxxxxxxxxxxxxxxxxxxxxx',
\ ' + )abc '
\ ]
call assert_equal(expected, lines)
%bw!
let &breakat=_breakat
endfunc
func Run_Test_display_lastline(euro)
let lines =<< trim END
call setline(1, ['aaa', 'b'->repeat(200)])
set display=truncate
vsplit
100wincmd <
END
if a:euro != ''
let lines[2] = 'set fillchars=vert:\|,lastline:€'
endif
call writefile(lines, 'XdispLastline', 'D')
let buf = RunVimInTerminal('-S XdispLastline', #{rows: 10})
call VerifyScreenDump(buf, $'Test_display_lastline_{a:euro}1', {})
call term_sendkeys(buf, ":set display=lastline\<CR>")
call VerifyScreenDump(buf, $'Test_display_lastline_{a:euro}2', {})
call term_sendkeys(buf, ":100wincmd >\<CR>")
call VerifyScreenDump(buf, $'Test_display_lastline_{a:euro}3', {})
call term_sendkeys(buf, ":set display=truncate\<CR>")
call VerifyScreenDump(buf, $'Test_display_lastline_{a:euro}4', {})
call term_sendkeys(buf, ":close\<CR>")
call term_sendkeys(buf, ":3split\<CR>")
call VerifyScreenDump(buf, $'Test_display_lastline_{a:euro}5', {})
call term_sendkeys(buf, ":close\<CR>")
call term_sendkeys(buf, ":2vsplit\<CR>")
call VerifyScreenDump(buf, $'Test_display_lastline_{a:euro}6', {})
call StopVimInTerminal(buf)
endfunc
func Test_display_lastline()
CheckScreendump
call Run_Test_display_lastline('')
call Run_Test_display_lastline('euro_')
call assert_fails(':set fillchars=lastline:', 'E474:')
call assert_fails(':set fillchars=lastline:', 'E474:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

File diff suppressed because it is too large Load Diff

View File

@@ -1,89 +0,0 @@
" Test for environment variables.
scriptencoding utf-8
source check.vim
func Test_environ()
unlet! $TESTENV
call assert_equal(0, has_key(environ(), 'TESTENV'))
let $TESTENV = 'foo'
call assert_equal(1, has_key(environ(), 'TESTENV'))
let $TESTENV = 'こんにちわ'
call assert_equal('こんにちわ', environ()['TESTENV'])
endfunc
func Test_getenv()
unlet! $TESTENV
call assert_equal(v:null, 'TESTENV'->getenv())
let $TESTENV = 'foo'
call assert_equal('foo', getenv('TESTENV'))
endfunc
func Test_setenv()
unlet! $TESTENV
eval 'foo'->setenv('TEST ENV')
call assert_equal('foo', getenv('TEST ENV'))
call setenv('TEST ENV', v:null)
call assert_equal(v:null, getenv('TEST ENV'))
endfunc
func Test_special_env()
" The value for $HOME is cached internally by Vim, ensure the value is up to
" date.
let orig_ENV = $HOME
let $HOME = 'foo'
call assert_equal('foo', expand('~'))
" old $HOME value is kept until a new one is set
unlet $HOME
call assert_equal('foo', expand('~'))
call setenv('HOME', 'bar')
call assert_equal('bar', expand('~'))
" old $HOME value is kept until a new one is set
call setenv('HOME', v:null)
call assert_equal('bar', expand('~'))
let $HOME = orig_ENV
endfunc
func Test_external_env()
call setenv('FOO', 'HelloWorld')
if has('win32')
let result = system('echo %FOO%')
else
let result = system('echo $FOO')
endif
let result = substitute(result, '[ \r\n]', '', 'g')
call assert_equal('HelloWorld', result)
call setenv('FOO', v:null)
if has('win32')
let result = system('set | findstr "^FOO="')
else
let result = system('env | grep ^FOO=')
endif
call assert_equal('', result)
endfunc
func Test_mac_locale()
CheckFeature osxdarwin
" If $LANG is not set then the system locale will be used.
" Run Vim after unsetting all the locale environmental vars, and capture the
" output of :lang.
let lang_results = system("unset LANG; unset LC_MESSAGES; unset LC_CTYPE; " ..
\ shellescape(v:progpath) ..
\ " --clean -esX -c 'redir @a' -c 'lang' -c 'put a' -c 'print' -c 'qa!' ")
" Check that:
" 1. The locale is the form of <locale>.UTF-8.
" 2. Check that fourth item (LC_NUMERIC) is properly set to "C".
" Example match: "en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8"
call assert_match('"\([a-zA-Z_]\+\.UTF-8/\)\{3}C\(/[a-zA-Z_]\+\.UTF-8\)\{2}"',
\ lang_results,
\ "Default locale should have UTF-8 encoding set, and LC_NUMERIC set to 'C'")
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,19 +0,0 @@
func Test_erasebackword()
enew
exe "normal o wwwこんにちわ世界ワールドvim \<C-W>"
call assert_equal(' wwwこんにちわ世界ワールド', getline('.'))
exe "normal o wwwこんにちわ世界ワールドvim \<C-W>\<C-W>"
call assert_equal(' wwwこんにちわ世界', getline('.'))
exe "normal o wwwこんにちわ世界ワールドvim \<C-W>\<C-W>\<C-W>"
call assert_equal(' wwwこんにちわ', getline('.'))
exe "normal o wwwこんにちわ世界ワールドvim \<C-W>\<C-W>\<C-W>\<C-W>"
call assert_equal(' www', getline('.'))
exe "normal o wwwこんにちわ世界ワールドvim \<C-W>\<C-W>\<C-W>\<C-W>\<C-W>"
call assert_equal(' ', getline('.'))
exe "normal o wwwこんにちわ世界ワールドvim \<C-W>\<C-W>\<C-W>\<C-W>\<C-W>\<C-W>"
call assert_equal('', getline('.'))
enew!
endfunc

View File

@@ -1,34 +0,0 @@
" Test whether glob()/globpath() return correct results with certain escaped
" characters.
func SetUp()
" consistent sorting of file names
set nofileignorecase
endfunction
function Test_glob()
if !has('unix')
" This test fails on Windows because of the special characters in the
" filenames. Disable the test on non-Unix systems for now.
return
endif
" Execute these commands in the sandbox, so that using the shell fails.
" Setting 'shell' to an invalid name causes a memory leak.
sandbox call assert_equal("", glob('Xxx\{'))
sandbox call assert_equal("", 'Xxx\$'->glob())
w! Xxx\{
" } to fix highlighting
w! Xxx\$
sandbox call assert_equal("Xxx{", glob('Xxx\{'))
sandbox call assert_equal("Xxx$", glob('Xxx\$'))
call delete('Xxx{')
call delete('Xxx$')
endfunction
function Test_globpath()
sandbox call assert_equal(expand("sautest/autoload/globone.vim\nsautest/autoload/globtwo.vim"),
\ globpath('sautest/autoload', 'glob*.vim'))
sandbox call assert_equal([expand('sautest/autoload/globone.vim'), expand('sautest/autoload/globtwo.vim')],
\ 'glob*.vim'->globpath('sautest/autoload', 0, 1))
endfunction

View File

@@ -1,392 +0,0 @@
" Tests for various eval things.
source view_util.vim
source shared.vim
function s:foo() abort
try
return [] == 0
catch
return 1
endtry
endfunction
func Test_catch_return_with_error()
call assert_equal(1, s:foo())
endfunc
func Test_nocatch_restore_silent_emsg()
silent! try
throw 1
catch
endtry
echoerr 'wrong again'
call assert_equal('wrong again', ScreenLine(&lines))
endfunc
func Test_mkdir_p()
call mkdir('Xmkdir/nested', 'p')
call assert_true(isdirectory('Xmkdir/nested'))
try
" Trying to make existing directories doesn't error
call mkdir('Xmkdir', 'p')
call mkdir('Xmkdir/nested', 'p')
catch /E739:/
call assert_report('mkdir(..., "p") failed for an existing directory')
endtry
" 'p' doesn't suppress real errors
call writefile([], 'Xfile')
call assert_fails('call mkdir("Xfile", "p")', 'E739')
call delete('Xfile')
call delete('Xmkdir', 'rf')
endfunc
func Test_line_continuation()
let array = [5,
"\ ignore this
\ 6,
"\ more to ignore
"\ more moreto ignore
\ ]
"\ and some more
call assert_equal([5, 6], array)
endfunc
func Test_E963()
" These commands used to cause an internal error prior to vim 8.1.0563
let v_e = v:errors
let v_o = v:oldfiles
call assert_fails("let v:errors=''", 'E963:')
call assert_equal(v_e, v:errors)
call assert_fails("let v:oldfiles=''", 'E963:')
call assert_equal(v_o, v:oldfiles)
endfunc
func Test_for_invalid()
call assert_fails("for x in 99", 'E1098:')
call assert_fails("for x in function('winnr')", 'E1098:')
call assert_fails("for x in {'a': 9}", 'E1098:')
if 0
/1/5/2/s/\n
endif
redraw
endfunc
func Test_for_over_null_string()
let save_enc = &enc
" set enc=iso8859
let cnt = 0
for c in v:_null_string
let cnt += 1
endfor
call assert_equal(0, cnt)
let &enc = save_enc
endfunc
func Test_for_invalid_line_count()
let lines =<< trim END
111111111111111111111111 for line in ['one']
endfor
END
call writefile(lines, 'XinvalidFor')
" only test that this doesn't crash
call RunVim([], [], '-u NONE -e -s -S XinvalidFor -c qa')
call delete('XinvalidFor')
endfunc
func Test_readfile_binary()
new
call setline(1, ['one', 'two', 'three'])
setlocal ff=dos
silent write XReadfile_bin
let lines = 'XReadfile_bin'->readfile()
call assert_equal(['one', 'two', 'three'], lines)
let lines = readfile('XReadfile_bin', '', 2)
call assert_equal(['one', 'two'], lines)
let lines = readfile('XReadfile_bin', 'b')
call assert_equal(["one\r", "two\r", "three\r", ""], lines)
let lines = readfile('XReadfile_bin', 'b', 2)
call assert_equal(["one\r", "two\r"], lines)
bwipe!
call delete('XReadfile_bin')
endfunc
func Test_readfile_binary_empty()
call writefile([], 'Xempty-file')
" This used to compare uninitialized memory in Vim <= 8.2.4065
call assert_equal([''], readfile('Xempty-file', 'b'))
call delete('Xempty-file')
endfunc
func Test_readfile_bom()
call writefile(["\ufeffFOO", "FOO\ufeffBAR"], 'XReadfile_bom')
call assert_equal(['FOO', 'FOOBAR'], readfile('XReadfile_bom'))
call delete('XReadfile_bom')
endfunc
func Test_readfile_max()
call writefile(range(1, 4), 'XReadfile_max')
call assert_equal(['1', '2'], readfile('XReadfile_max', '', 2))
call assert_equal(['3', '4'], readfile('XReadfile_max', '', -2))
call delete('XReadfile_max')
endfunc
func Test_let_errmsg()
call assert_fails('let v:errmsg = []', 'E730:')
let v:errmsg = ''
call assert_fails('let v:errmsg = []', 'E730:')
let v:errmsg = ''
endfunc
func Test_string_concatenation()
call assert_equal('ab', 'a'.'b')
call assert_equal('ab', 'a' .'b')
call assert_equal('ab', 'a'. 'b')
call assert_equal('ab', 'a' . 'b')
call assert_equal('ab', 'a'..'b')
call assert_equal('ab', 'a' ..'b')
call assert_equal('ab', 'a'.. 'b')
call assert_equal('ab', 'a' .. 'b')
let a = 'a'
let b = 'b'
let a .= b
call assert_equal('ab', a)
let a = 'a'
let a.=b
call assert_equal('ab', a)
let a = 'a'
let a ..= b
call assert_equal('ab', a)
let a = 'a'
let a..=b
call assert_equal('ab', a)
endfunc
" Test fix for issue #4507
func Test_skip_after_throw()
try
throw 'something'
let x = wincol() || &ts
catch /something/
endtry
endfunc
" scriptversion 1
func Test_string_concat_scriptversion1()
call assert_true(has('vimscript-1'))
let a = 'a'
let b = 'b'
echo a . b
let a .= b
let vers = 1.2.3
call assert_equal('123', vers)
if has('float')
call assert_fails('let f = .5', 'E15:')
endif
endfunc
" scriptversion 1
func Test_vvar_scriptversion1()
call assert_equal(15, 017)
call assert_equal(15, 0o17)
call assert_equal(15, 0O17)
call assert_equal(18, 018)
call assert_equal(511, 0o777)
endfunc
func Test_number_max_min_size()
" This will fail on systems without 64 bit number support or when not
" configured correctly.
call assert_equal(64, v:numbersize)
call assert_true(v:numbermin < -9999999)
call assert_true(v:numbermax > 9999999)
endfunc
func Assert_reg(name, type, value, valuestr, expr, exprstr)
call assert_equal(a:type, getregtype(a:name))
call assert_equal(a:value, getreg(a:name))
call assert_equal(a:valuestr, string(getreg(a:name, 0, 1)))
call assert_equal(a:expr, getreg(a:name, 1))
call assert_equal(a:exprstr, string(getreg(a:name, 1, 1)))
endfunc
func Test_let_register()
let @" = 'abc'
call Assert_reg('"', 'v', "abc", "['abc']", "abc", "['abc']")
let @" = "abc\n"
call Assert_reg('"', 'V', "abc\n", "['abc']", "abc\n", "['abc']")
let @" = "abc\<C-m>"
call Assert_reg('"', 'V', "abc\r\n", "['abc\r']", "abc\r\n", "['abc\r']")
let @= = '"abc"'
call Assert_reg('=', 'v', "abc", "['abc']", '"abc"', "['\"abc\"']")
endfunc
func Assert_regput(name, result)
new
execute "silent normal! o==\n==\e\"" . a:name . "P"
call assert_equal(a:result, getline(2, line('$')))
bwipe!
endfunc
func Test_setreg_basic()
call setreg('a', 'abcA', 'c')
call Assert_reg('a', 'v', "abcA", "['abcA']", "abcA", "['abcA']")
call Assert_regput('a', ['==', '=abcA='])
call setreg('A', 'abcAc', 'c')
call Assert_reg('A', 'v', "abcAabcAc", "['abcAabcAc']", "abcAabcAc", "['abcAabcAc']")
call Assert_regput('a', ['==', '=abcAabcAc='])
call setreg('A', 'abcAl', 'l')
call Assert_reg('A', 'V', "abcAabcAcabcAl\n", "['abcAabcAcabcAl']", "abcAabcAcabcAl\n", "['abcAabcAcabcAl']")
call Assert_regput('a', ['==', 'abcAabcAcabcAl', '=='])
call setreg('A', 'abcAc2','c')
call Assert_reg('A', 'v', "abcAabcAcabcAl\nabcAc2", "['abcAabcAcabcAl', 'abcAc2']", "abcAabcAcabcAl\nabcAc2", "['abcAabcAcabcAl', 'abcAc2']")
call Assert_regput('a', ['==', '=abcAabcAcabcAl', 'abcAc2='])
call setreg('b', 'abcB', 'v')
call Assert_reg('b', 'v', "abcB", "['abcB']", "abcB", "['abcB']")
call Assert_regput('b', ['==', '=abcB='])
call setreg('b', 'abcBc', 'ca')
call Assert_reg('b', 'v', "abcBabcBc", "['abcBabcBc']", "abcBabcBc", "['abcBabcBc']")
call Assert_regput('b', ['==', '=abcBabcBc='])
call setreg('b', 'abcBb', 'ba')
call Assert_reg('b', "\<C-V>5", "abcBabcBcabcBb", "['abcBabcBcabcBb']", "abcBabcBcabcBb", "['abcBabcBcabcBb']")
call Assert_regput('b', ['==', '=abcBabcBcabcBb='])
call setreg('b', 'abcBc2','ca')
call Assert_reg('b', "v", "abcBabcBcabcBb\nabcBc2", "['abcBabcBcabcBb', 'abcBc2']", "abcBabcBcabcBb\nabcBc2", "['abcBabcBcabcBb', 'abcBc2']")
call Assert_regput('b', ['==', '=abcBabcBcabcBb', 'abcBc2='])
call setreg('b', 'abcBb2','b50a')
call Assert_reg('b', "\<C-V>50", "abcBabcBcabcBb\nabcBc2abcBb2", "['abcBabcBcabcBb', 'abcBc2abcBb2']", "abcBabcBcabcBb\nabcBc2abcBb2", "['abcBabcBcabcBb', 'abcBc2abcBb2']")
call Assert_regput('b', ['==', '=abcBabcBcabcBb =', ' abcBc2abcBb2'])
call setreg('c', 'abcC', 'l')
call Assert_reg('c', 'V', "abcC\n", "['abcC']", "abcC\n", "['abcC']")
call Assert_regput('c', ['==', 'abcC', '=='])
call setreg('C', 'abcCl', 'l')
call Assert_reg('C', 'V', "abcC\nabcCl\n", "['abcC', 'abcCl']", "abcC\nabcCl\n", "['abcC', 'abcCl']")
call Assert_regput('c', ['==', 'abcC', 'abcCl', '=='])
call setreg('C', 'abcCc', 'c')
call Assert_reg('C', 'v', "abcC\nabcCl\nabcCc", "['abcC', 'abcCl', 'abcCc']", "abcC\nabcCl\nabcCc", "['abcC', 'abcCl', 'abcCc']")
call Assert_regput('c', ['==', '=abcC', 'abcCl', 'abcCc='])
call setreg('d', 'abcD', 'V')
call Assert_reg('d', 'V', "abcD\n", "['abcD']", "abcD\n", "['abcD']")
call Assert_regput('d', ['==', 'abcD', '=='])
call setreg('D', 'abcDb', 'b')
call Assert_reg('d', "\<C-V>5", "abcD\nabcDb", "['abcD', 'abcDb']", "abcD\nabcDb", "['abcD', 'abcDb']")
call Assert_regput('d', ['==', '=abcD =', ' abcDb'])
call setreg('e', 'abcE', 'b')
call Assert_reg('e', "\<C-V>4", "abcE", "['abcE']", "abcE", "['abcE']")
call Assert_regput('e', ['==', '=abcE='])
call setreg('E', 'abcEb', 'b')
call Assert_reg('E', "\<C-V>5", "abcE\nabcEb", "['abcE', 'abcEb']", "abcE\nabcEb", "['abcE', 'abcEb']")
call Assert_regput('e', ['==', '=abcE =', ' abcEb'])
call setreg('E', 'abcEl', 'l')
call Assert_reg('E', "V", "abcE\nabcEb\nabcEl\n", "['abcE', 'abcEb', 'abcEl']", "abcE\nabcEb\nabcEl\n", "['abcE', 'abcEb', 'abcEl']")
call Assert_regput('e', ['==', 'abcE', 'abcEb', 'abcEl', '=='])
call setreg('f', 'abcF', "\<C-v>")
call Assert_reg('f', "\<C-V>4", "abcF", "['abcF']", "abcF", "['abcF']")
call Assert_regput('f', ['==', '=abcF='])
call setreg('F', 'abcFc', 'c')
call Assert_reg('F', "v", "abcF\nabcFc", "['abcF', 'abcFc']", "abcF\nabcFc", "['abcF', 'abcFc']")
call Assert_regput('f', ['==', '=abcF', 'abcFc='])
call setreg('g', 'abcG', 'b10')
call Assert_reg('g', "\<C-V>10", "abcG", "['abcG']", "abcG", "['abcG']")
call Assert_regput('g', ['==', '=abcG ='])
call setreg('h', 'abcH', "\<C-v>10")
call Assert_reg('h', "\<C-V>10", "abcH", "['abcH']", "abcH", "['abcH']")
call Assert_regput('h', ['==', '=abcH ='])
call setreg('I', 'abcI')
call Assert_reg('I', "v", "abcI", "['abcI']", "abcI", "['abcI']")
call Assert_regput('I', ['==', '=abcI='])
" Error cases
call assert_fails('call setreg()', 'E119:')
call assert_fails('call setreg(1)', 'E119:')
call assert_fails('call setreg(1, 2, 3, 4)', 'E118:')
call assert_fails('call setreg([], 2)', 'E730:')
call assert_fails('call setreg(1, 2, [])', 'E730:')
call assert_fails('call setreg("/", ["1", "2"])', 'E883:')
call assert_fails('call setreg("=", ["1", "2"])', 'E883:')
call assert_fails('call setreg(1, ["", "", [], ""])', 'E730:')
endfunc
func Test_curly_assignment()
let s:svar = 'svar'
let g:gvar = 'gvar'
let lname = 'gvar'
let gname = 'gvar'
let {'s:'.lname} = {'g:'.gname}
call assert_equal('gvar', s:gvar)
let s:gvar = ''
let { 's:'.lname } = { 'g:'.gname }
call assert_equal('gvar', s:gvar)
let s:gvar = ''
let { 's:' . lname } = { 'g:' . gname }
call assert_equal('gvar', s:gvar)
let s:gvar = ''
let { 's:' .. lname } = { 'g:' .. gname }
call assert_equal('gvar', s:gvar)
unlet s:svar
unlet s:gvar
unlet g:gvar
endfunc
func Test_deep_recursion()
" this was running out of stack
call assert_fails("exe 'if ' .. repeat('(', 1002)", 'E1169: Expression too recursive: ((')
endfunc
" K_SPECIAL in the modified character used be escaped, which causes
" double-escaping with feedkeys() or as the return value of an <expr> mapping,
" and doesn't match what getchar() returns,
func Test_modified_char_no_escape_special()
nnoremap <M-> <Cmd>let g:got_m_ellipsis += 1<CR>
call feedkeys("\<M-…>", 't')
call assert_equal("\<M-…>", getchar())
let g:got_m_ellipsis = 0
call feedkeys("\<M-…>", 'xt')
call assert_equal(1, g:got_m_ellipsis)
func Func()
return "\<M-…>"
endfunc
nmap <expr> <F2> Func()
call feedkeys("\<F2>", 'xt')
call assert_equal(2, g:got_m_ellipsis)
delfunc Func
nunmap <F2>
unlet g:got_m_ellipsis
nunmap <M->
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,32 +0,0 @@
" Test Ex := command.
func Test_ex_equal()
new
call setline(1, ["foo\tbar", "bar\tfoo"])
let a = execute('=')
call assert_equal("\n2", a)
let a = execute('=#')
call assert_equal("\n2\n 1 foo bar", a)
let a = execute('=l')
call assert_equal("\n2\nfoo^Ibar$", a)
let a = execute('=p')
call assert_equal("\n2\nfoo bar", a)
let a = execute('=l#')
call assert_equal("\n2\n 1 foo^Ibar$", a)
let a = execute('=p#')
call assert_equal("\n2\n 1 foo bar", a)
let a = execute('.=')
call assert_equal("\n1", a)
call assert_fails('3=', 'E16:')
call assert_fails('=x', 'E488:')
bwipe!
endfunc

View File

@@ -1,243 +0,0 @@
" Test editing line in Ex mode (see :help Q and :help gQ).
source check.vim
source shared.vim
" Helper function to test editing line in Q Ex mode
func Ex_Q(cmd)
" Is there a simpler way to test editing Ex line?
call feedkeys("Q"
\ .. "let s:test_ex =<< END\<CR>"
\ .. a:cmd .. "\<CR>"
\ .. "END\<CR>"
\ .. "visual\<CR>", 'tx')
return s:test_ex[0]
endfunc
" Helper function to test editing line in gQ Ex mode
func Ex_gQ(cmd)
call feedkeys("gQ" .. a:cmd .. "\<C-b>\"\<CR>", 'tx')
let ret = @:[1:] " Remove leading quote.
call feedkeys("visual\<CR>", 'tx')
return ret
endfunc
" Helper function to test editing line with both Q and gQ Ex mode.
func Ex(cmd)
return [Ex_Q(a:cmd), Ex_gQ(a:cmd)]
endfunc
" Test editing line in Ex mode (both Q and gQ)
func Test_ex_mode()
throw 'Skipped: Nvim only supports Vim Ex mode'
let encoding_save = &encoding
set sw=2
for e in ['utf8', 'latin1']
exe 'set encoding=' . e
call assert_equal(['bar', 'bar'], Ex("foo bar\<C-u>bar"), e)
call assert_equal(["1\<C-u>2", "1\<C-u>2"], Ex("1\<C-v>\<C-u>2"), e)
call assert_equal(["1\<C-b>2\<C-e>3", '213'], Ex("1\<C-b>2\<C-e>3"), e)
call assert_equal(['0123', '2013'], Ex("01\<Home>2\<End>3"), e)
call assert_equal(['0123', '0213'], Ex("01\<Left>2\<Right>3"), e)
call assert_equal(['01234', '0342'], Ex("012\<Left>\<Left>\<Insert>3\<Insert>4"), e)
call assert_equal(["foo bar\<C-w>", 'foo '], Ex("foo bar\<C-w>"), e)
call assert_equal(['foo', 'foo'], Ex("fooba\<Del>\<Del>"), e)
call assert_equal(["foo\tbar", 'foobar'], Ex("foo\<Tab>bar"), e)
call assert_equal(["abbrev\t", 'abbreviate'], Ex("abbrev\<Tab>"), e)
call assert_equal([' 1', "1\<C-t>\<C-t>"], Ex("1\<C-t>\<C-t>"), e)
call assert_equal([' 1', "1\<C-t>\<C-t>"], Ex("1\<C-t>\<C-t>\<C-d>"), e)
call assert_equal([' foo', ' foo'], Ex(" foo\<C-d>"), e)
call assert_equal(['foo', ' foo0'], Ex(" foo0\<C-d>"), e)
call assert_equal(['foo', ' foo^'], Ex(" foo^\<C-d>"), e)
call assert_equal(['foo', 'foo'],
\ Ex("\<BS>\<C-H>\<Del>\<kDel>foo"), e)
" default wildchar <Tab> interferes with this test
set wildchar=<c-e>
call assert_equal(["a\tb", "a\tb"], Ex("a\t\t\<C-H>b"), e)
call assert_equal(["\t mn", "\tm\<C-T>n"], Ex("\tm\<C-T>n"), e)
set wildchar&
endfor
set sw&
let &encoding = encoding_save
endfunc
" Test substitute confirmation prompt :%s/pat/str/c in Ex mode
func Test_Ex_substitute()
CheckRunVimInTerminal
let buf = RunVimInTerminal('', {'rows': 6})
call term_sendkeys(buf, ":call setline(1, ['foo foo', 'foo foo', 'foo foo'])\<CR>")
call term_sendkeys(buf, ":set number\<CR>")
call term_sendkeys(buf, "gQ")
call WaitForAssert({-> assert_match(':', term_getline(buf, 6))}, 1000)
call term_sendkeys(buf, "%s/foo/bar/gc\<CR>")
call WaitForAssert({-> assert_match(' 1 foo foo', term_getline(buf, 5))},
\ 1000)
call WaitForAssert({-> assert_match(' ^^^', term_getline(buf, 6))}, 1000)
call term_sendkeys(buf, "N\<CR>")
call term_wait(buf)
call WaitForAssert({-> assert_match(' ^^^', term_getline(buf, 6))}, 1000)
call term_sendkeys(buf, "n\<CR>")
call WaitForAssert({-> assert_match(' ^^^', term_getline(buf, 6))},
\ 1000)
call term_sendkeys(buf, "y\<CR>")
call term_sendkeys(buf, "q\<CR>")
call WaitForAssert({-> assert_match(':', term_getline(buf, 6))}, 1000)
" Pressing enter in ex mode should print the current line
call term_sendkeys(buf, "\<CR>")
call WaitForAssert({-> assert_match(' 3 foo foo',
\ term_getline(buf, 5))}, 1000)
call term_sendkeys(buf, ":vi\<CR>")
call WaitForAssert({-> assert_match('foo bar', term_getline(buf, 1))}, 1000)
call StopVimInTerminal(buf)
endfunc
" Test for displaying lines from an empty buffer in Ex mode
func Test_Ex_emptybuf()
new
call assert_fails('call feedkeys("Q\<CR>", "xt")', 'E749:')
call setline(1, "abc")
call assert_fails('call feedkeys("Q\<CR>", "xt")', 'E501:')
call assert_fails('call feedkeys("Q%d\<CR>", "xt")', 'E749:')
close!
endfunc
" Test for the :open command
func Test_open_command()
throw 'Skipped: Nvim does not have :open'
new
call setline(1, ['foo foo', 'foo bar', 'foo baz'])
call feedkeys("Qopen\<CR>j", 'xt')
call assert_equal('foo bar', getline('.'))
call feedkeys("Qopen /bar/\<CR>", 'xt')
call assert_equal(5, col('.'))
call assert_fails('call feedkeys("Qopen /baz/\<CR>", "xt")', 'E479:')
close!
endfunc
" Test for :g/pat/visual to run vi commands in Ex mode
" This used to hang Vim before 8.2.0274.
func Test_Ex_global()
new
call setline(1, ['', 'foo', 'bar', 'foo', 'bar', 'foo'])
call feedkeys("Q\<bs>g/bar/visual\<CR>$rxQ$ryQvisual\<CR>j", "xt")
call assert_equal('bax', getline(3))
call assert_equal('bay', getline(5))
bwipe!
endfunc
" Test for pressing Ctrl-C in :append inside a loop in Ex mode
" This used to hang Vim
func Test_Ex_append_in_loop()
CheckRunVimInTerminal
let buf = RunVimInTerminal('', {'rows': 6})
call term_sendkeys(buf, "gQ")
call term_sendkeys(buf, "for i in range(1)\<CR>")
call term_sendkeys(buf, "append\<CR>")
call WaitForAssert({-> assert_match(': append', term_getline(buf, 5))}, 1000)
call term_sendkeys(buf, "\<C-C>")
" Wait for input to be flushed
call term_wait(buf)
call term_sendkeys(buf, "foo\<CR>")
call WaitForAssert({-> assert_match('foo', term_getline(buf, 5))}, 1000)
call term_sendkeys(buf, ".\<CR>")
call WaitForAssert({-> assert_match('.', term_getline(buf, 5))}, 1000)
call term_sendkeys(buf, "endfor\<CR>")
call term_sendkeys(buf, "vi\<CR>")
call WaitForAssert({-> assert_match('foo', term_getline(buf, 1))}, 1000)
call StopVimInTerminal(buf)
endfunc
" In Ex-mode, a backslash escapes a newline
func Test_Ex_escape_enter()
call feedkeys("gQlet l = \"a\\\<kEnter>b\"\<cr>vi\<cr>", 'xt')
call assert_equal("a\rb", l)
endfunc
" Test for :append! command in Ex mode
func Test_Ex_append()
throw 'Skipped: Nvim only supports Vim Ex mode'
new
call setline(1, "\t abc")
call feedkeys("Qappend!\npqr\nxyz\n.\nvisual\n", 'xt')
call assert_equal(["\t abc", "\t pqr", "\t xyz"], getline(1, '$'))
close!
endfunc
" In Ex-mode, backslashes at the end of a command should be halved.
func Test_Ex_echo_backslash()
throw 'Skipped: Nvim only supports Vim Ex mode'
" This test works only when the language is English
CheckEnglish
let bsl = '\\\\'
let bsl2 = '\\\'
call assert_fails('call feedkeys("Qecho " .. bsl .. "\nvisual\n", "xt")',
\ "E15: Invalid expression: \\\\")
call assert_fails('call feedkeys("Qecho " .. bsl2 .. "\nm\nvisual\n", "xt")',
\ "E15: Invalid expression: \\\nm")
endfunc
func Test_ex_mode_errors()
" Not allowed to enter ex mode when text is locked
au InsertCharPre <buffer> normal! gQ<CR>
let caught_e565 = 0
try
call feedkeys("ix\<esc>", 'xt')
catch /^Vim\%((\a\+)\)\=:E565/ " catch E565
let caught_e565 = 1
endtry
call assert_equal(1, caught_e565)
au! InsertCharPre
new
au CmdLineEnter * call ExEnterFunc()
func ExEnterFunc()
endfunc
call feedkeys("gQvi\r", 'xt')
au! CmdLineEnter
delfunc ExEnterFunc
quit
endfunc
func Test_ex_mode_count_overflow()
" The multiplication causes an integer overflow
CheckNotAsan
" this used to cause a crash
let lines =<< trim END
call feedkeys("\<Esc>gQ\<CR>")
v9|9silent! vi|333333233333y32333333%O
call writefile(['done'], 'Xdidexmode')
qall!
END
call writefile(lines, 'Xexmodescript')
call assert_equal(1, RunVim([], [], '-e -s -S Xexmodescript -c qa'))
call assert_equal(['done'], readfile('Xdidexmode'))
call delete('Xdidexmode')
call delete('Xexmodescript')
endfunc
func Test_ex_mode_large_indent()
new
set ts=500 ai
call setline(1, "\t")
exe "normal gQi\<CR>."
set ts=8 noai
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,19 +0,0 @@
" Tests for :undo
func Test_ex_undo()
new ex-undo
setlocal ul=10
exe "normal ione\n\<Esc>"
setlocal ul=10
exe "normal itwo\n\<Esc>"
setlocal ul=10
exe "normal ithree\n\<Esc>"
call assert_equal(4, line('$'))
undo
call assert_equal(3, line('$'))
undo 1
call assert_equal(2, line('$'))
undo 0
call assert_equal(1, line('$'))
quit!
endfunc

View File

@@ -1,108 +0,0 @@
" Test :z
func Test_z()
call setline(1, range(1, 100))
let a = execute('20z3')
call assert_equal("\n20\n21\n22", a)
call assert_equal(22, line('.'))
" 'window' should be set to the {count} value.
call assert_equal(3, &window)
" If there is only one window, then twice the amount of 'scroll' is used.
set scroll=2
let a = execute('20z')
call assert_equal("\n20\n21\n22\n23", a)
call assert_equal(23, line('.'))
let a = execute('20z+3')
" FIXME: I would expect the same result as '20z3' since 'help z'
" says: Specifying no mark at all is the same as "+".
" However it " gives "\n21\n22\n23" instead. Bug in Vim or in ":help :z"?
"call assert_equal("\n20\n21\n22", a)
"call assert_equal(22, line('.'))
let a = execute('20z-3')
call assert_equal("\n18\n19\n20", a)
call assert_equal(20, line('.'))
let a = execute('20z=3')
call assert_match("^\n18\n19\n-\\+\n20\n-\\+\n21\n22$", a)
call assert_equal(20, line('.'))
let a = execute('20z^3')
call assert_equal("\n14\n15\n16\n17", a)
call assert_equal(17, line('.'))
let a = execute('20z.3')
call assert_equal("\n19\n20\n21", a)
call assert_equal(21, line('.'))
let a = execute('20z#3')
call assert_equal("\n 20 20\n 21 21\n 22 22", a)
call assert_equal(22, line('.'))
let a = execute('20z#-3')
call assert_equal("\n 18 18\n 19 19\n 20 20", a)
call assert_equal(20, line('.'))
let a = execute('20z#=3')
call assert_match("^\n 18 18\n 19 19\n-\\+\n 20 20\n-\\+\n 21 21\n 22 22$", a)
call assert_equal(20, line('.'))
" Test with {count} bigger than the number of lines in buffer.
let a = execute('20z1000')
call assert_match("^\n20\n21\n.*\n99\n100$", a)
call assert_equal(100, line('.'))
let a = execute('20z-1000')
call assert_equal(20, line('.'))
let a = execute('20z=1000')
call assert_match("^\n1\n.*\n-\\+\n20\n-\\\+\n.*\n100$", a)
call assert_equal(20, line('.'))
" Tests with multiple windows.
5split
call setline(1, range(1, 100))
" Without a count, the number line is window height - 3.
let a = execute('20z')
call assert_equal("\n20\n21", a)
call assert_equal(21, line('.'))
" If window height - 3 is less than 1, it should be clamped to 1.
resize 2
let a = execute('20z')
call assert_equal("\n20", a)
call assert_equal(20, line('.'))
call assert_fails('20z=a', 'E144:')
set window& scroll&
bw!
endfunc
" :z! is the same as :z but count uses the Vim window height when not specified.
func Test_z_bang()
4split
call setline(1, range(1, 20))
let a = execute('10z!')
call assert_equal("\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20", a)
let a = execute('10z!#')
call assert_equal("\n 10 10\n 11 11\n 12 12\n 13 13\n 14 14\n 15 15\n 16 16\n 17 17\n 18 18\n 19 19\n 20 20", a)
let a = execute('10z!3')
call assert_equal("\n10\n11\n12", a)
%bwipe!
endfunc
func Test_z_bug()
" This used to access invalid memory as a result of an integer overflow
" and freeze vim.
normal ox
normal Heat
z777777776666666
')
endfunc

View File

@@ -1,750 +0,0 @@
" Tests for various Ex commands.
source check.vim
source shared.vim
source term_util.vim
func Test_ex_delete()
new
call setline(1, ['a', 'b', 'c'])
2
" :dl is :delete with the "l" flag, not :dlist
.dl
call assert_equal(['a', 'c'], getline(1, 2))
endfunc
func Test_range_error()
call assert_fails(':.echo 1', 'E481:')
call assert_fails(':$echo 1', 'E481:')
call assert_fails(':1,2echo 1', 'E481:')
call assert_fails(':+1echo 1', 'E481:')
call assert_fails(':/1/echo 1', 'E481:')
call assert_fails(':\/echo 1', 'E481:')
normal vv
call assert_fails(":'<,'>echo 1", 'E481:')
call assert_fails(":\\xcenter", 'E10:')
endfunc
func Test_buffers_lastused()
edit bufc " oldest
sleep 1200m
edit bufa " middle
sleep 1200m
edit bufb " newest
enew
let ls = split(execute('buffers t', 'silent!'), '\n')
let bufs = []
for line in ls
let bufs += [split(line, '"\s*')[1:2]]
endfor
let names = []
for buf in bufs
if buf[0] !=# '[No Name]'
let names += [buf[0]]
endif
endfor
call assert_equal(['bufb', 'bufa', 'bufc'], names)
call assert_match('[0-2] seconds\= ago', bufs[1][1])
bwipeout bufa
bwipeout bufb
bwipeout bufc
endfunc
" Test for the :copy command
func Test_copy()
new
call setline(1, ['L1', 'L2', 'L3', 'L4'])
" copy lines in a range to inside the range
1,3copy 2
call assert_equal(['L1', 'L2', 'L1', 'L2', 'L3', 'L3', 'L4'], getline(1, 7))
" Specifying a count before using : to run an ex-command
exe "normal! gg4:yank\<CR>"
call assert_equal("L1\nL2\nL1\nL2\n", @")
close!
endfunc
" Test for the :file command
func Test_file_cmd()
call assert_fails('3file', 'E474:')
call assert_fails('0,0file', 'E474:')
call assert_fails('0file abc', 'E474:')
if !has('win32')
" Change the name of the buffer to the same name
new Xfile1
file Xfile1
call assert_equal('Xfile1', @%)
call assert_equal('Xfile1', @#)
bw!
endif
endfunc
" Test for the :drop command
func Test_drop_cmd()
call writefile(['L1', 'L2'], 'Xfile')
enew | only
drop Xfile
call assert_equal('L2', getline(2))
" Test for switching to an existing window
below new
drop Xfile
call assert_equal(1, winnr())
" Test for splitting the current window
enew | only
set modified
drop Xfile
call assert_equal(2, winnr('$'))
" Check for setting the argument list
call assert_equal(['Xfile'], argv())
enew | only!
call delete('Xfile')
endfunc
" Test for the :append command
func Test_append_cmd()
new
call setline(1, [' L1'])
call feedkeys(":append\<CR> L2\<CR> L3\<CR>.\<CR>", 'xt')
call assert_equal([' L1', ' L2', ' L3'], getline(1, '$'))
%delete _
" append after a specific line
call setline(1, [' L1', ' L2', ' L3'])
call feedkeys(":2append\<CR> L4\<CR> L5\<CR>.\<CR>", 'xt')
call assert_equal([' L1', ' L2', ' L4', ' L5', ' L3'], getline(1, '$'))
%delete _
" append with toggling 'autoindent'
call setline(1, [' L1'])
call feedkeys(":append!\<CR> L2\<CR> L3\<CR>.\<CR>", 'xt')
call assert_equal([' L1', ' L2', ' L3'], getline(1, '$'))
call assert_false(&autoindent)
%delete _
" append with 'autoindent' set and toggling 'autoindent'
set autoindent
call setline(1, [' L1'])
call feedkeys(":append!\<CR> L2\<CR> L3\<CR>.\<CR>", 'xt')
call assert_equal([' L1', ' L2', ' L3'], getline(1, '$'))
call assert_true(&autoindent)
set autoindent&
close!
endfunc
func Test_append_cmd_empty_buf()
CheckRunVimInTerminal
let lines =<< trim END
func Timer(timer)
append
aaaaa
bbbbb
.
endfunc
call timer_start(10, 'Timer')
END
call writefile(lines, 'Xtest_append_cmd_empty_buf')
let buf = RunVimInTerminal('-S Xtest_append_cmd_empty_buf', {'rows': 6})
call WaitForAssert({-> assert_equal('bbbbb', term_getline(buf, 2))})
call WaitForAssert({-> assert_equal('aaaaa', term_getline(buf, 1))})
" clean up
call StopVimInTerminal(buf)
call delete('Xtest_append_cmd_empty_buf')
endfunc
" Test for the :insert command
func Test_insert_cmd()
new
call setline(1, [' L1'])
call feedkeys(":insert\<CR> L2\<CR> L3\<CR>.\<CR>", 'xt')
call assert_equal([' L2', ' L3', ' L1'], getline(1, '$'))
%delete _
" insert before a specific line
call setline(1, [' L1', ' L2', ' L3'])
call feedkeys(":2insert\<CR> L4\<CR> L5\<CR>.\<CR>", 'xt')
call assert_equal([' L1', ' L4', ' L5', ' L2', ' L3'], getline(1, '$'))
%delete _
" insert with toggling 'autoindent'
call setline(1, [' L1'])
call feedkeys(":insert!\<CR> L2\<CR> L3\<CR>.\<CR>", 'xt')
call assert_equal([' L2', ' L3', ' L1'], getline(1, '$'))
call assert_false(&autoindent)
%delete _
" insert with 'autoindent' set and toggling 'autoindent'
set autoindent
call setline(1, [' L1'])
call feedkeys(":insert!\<CR> L2\<CR> L3\<CR>.\<CR>", 'xt')
call assert_equal([' L2', ' L3', ' L1'], getline(1, '$'))
call assert_true(&autoindent)
set autoindent&
close!
endfunc
func Test_insert_cmd_empty_buf()
CheckRunVimInTerminal
let lines =<< trim END
func Timer(timer)
insert
aaaaa
bbbbb
.
endfunc
call timer_start(10, 'Timer')
END
call writefile(lines, 'Xtest_insert_cmd_empty_buf')
let buf = RunVimInTerminal('-S Xtest_insert_cmd_empty_buf', {'rows': 6})
call WaitForAssert({-> assert_equal('bbbbb', term_getline(buf, 2))})
call WaitForAssert({-> assert_equal('aaaaa', term_getline(buf, 1))})
" clean up
call StopVimInTerminal(buf)
call delete('Xtest_insert_cmd_empty_buf')
endfunc
" Test for the :change command
func Test_change_cmd()
new
call setline(1, [' L1', 'L2', 'L3'])
call feedkeys(":change\<CR> L4\<CR> L5\<CR>.\<CR>", 'xt')
call assert_equal([' L4', ' L5', 'L2', 'L3'], getline(1, '$'))
%delete _
" change a specific line
call setline(1, [' L1', ' L2', ' L3'])
call feedkeys(":2change\<CR> L4\<CR> L5\<CR>.\<CR>", 'xt')
call assert_equal([' L1', ' L4', ' L5', ' L3'], getline(1, '$'))
%delete _
" change with toggling 'autoindent'
call setline(1, [' L1', 'L2', 'L3'])
call feedkeys(":change!\<CR> L4\<CR> L5\<CR>.\<CR>", 'xt')
call assert_equal([' L4', ' L5', 'L2', 'L3'], getline(1, '$'))
call assert_false(&autoindent)
%delete _
" change with 'autoindent' set and toggling 'autoindent'
set autoindent
call setline(1, [' L1', 'L2', 'L3'])
call feedkeys(":change!\<CR> L4\<CR> L5\<CR>.\<CR>", 'xt')
call assert_equal([' L4', ' L5', 'L2', 'L3'], getline(1, '$'))
call assert_true(&autoindent)
set autoindent&
close!
endfunc
" Test for the :language command
func Test_language_cmd()
CheckNotMSWindows " FIXME: why does this fail on Windows CI?
CheckFeature multi_lang
call assert_fails('language ctype non_existing_lang', 'E197:')
call assert_fails('language time non_existing_lang', 'E197:')
endfunc
" Test for the :confirm command dialog
func Test_confirm_cmd()
CheckNotGui
CheckRunVimInTerminal
call writefile(['foo1'], 'Xfoo')
call writefile(['bar1'], 'Xbar')
" Test for saving all the modified buffers
let lines =<< trim END
set nomore
new Xfoo
call setline(1, 'foo2')
new Xbar
call setline(1, 'bar2')
wincmd b
END
call writefile(lines, 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
call term_sendkeys(buf, ":confirm qall\n")
call WaitForAssert({-> assert_match('\[Y\]es, (N)o, Save (A)ll, (D)iscard All, (C)ancel: ', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, "A")
call StopVimInTerminal(buf)
call assert_equal(['foo2'], readfile('Xfoo'))
call assert_equal(['bar2'], readfile('Xbar'))
" Test for discarding all the changes to modified buffers
let lines =<< trim END
set nomore
new Xfoo
call setline(1, 'foo3')
new Xbar
call setline(1, 'bar3')
wincmd b
END
call writefile(lines, 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
call term_sendkeys(buf, ":confirm qall\n")
call WaitForAssert({-> assert_match('\[Y\]es, (N)o, Save (A)ll, (D)iscard All, (C)ancel: ', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, "D")
call StopVimInTerminal(buf)
call assert_equal(['foo2'], readfile('Xfoo'))
call assert_equal(['bar2'], readfile('Xbar'))
" Test for saving and discarding changes to some buffers
let lines =<< trim END
set nomore
new Xfoo
call setline(1, 'foo4')
new Xbar
call setline(1, 'bar4')
wincmd b
END
call writefile(lines, 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
call term_sendkeys(buf, ":confirm qall\n")
call WaitForAssert({-> assert_match('\[Y\]es, (N)o, Save (A)ll, (D)iscard All, (C)ancel: ', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, "N")
call WaitForAssert({-> assert_match('\[Y\]es, (N)o, (C)ancel: ', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, "Y")
call StopVimInTerminal(buf)
call assert_equal(['foo4'], readfile('Xfoo'))
call assert_equal(['bar2'], readfile('Xbar'))
call delete('Xscript')
call delete('Xfoo')
call delete('Xbar')
endfunc
func Test_confirm_cmd_cancel()
CheckNotGui
CheckRunVimInTerminal
" Test for closing a window with a modified buffer
let lines =<< trim END
set nomore
new
call setline(1, 'abc')
END
call writefile(lines, 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
call term_sendkeys(buf, ":confirm close\n")
call WaitForAssert({-> assert_match('^\[Y\]es, (N)o, (C)ancel: *$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, "C")
call WaitForAssert({-> assert_equal('', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, ":confirm close\n")
call WaitForAssert({-> assert_match('^\[Y\]es, (N)o, (C)ancel: *$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, "N")
call WaitForAssert({-> assert_match('^ *0,0-1 All$',
\ term_getline(buf, 20))}, 1000)
call StopVimInTerminal(buf)
call delete('Xscript')
endfunc
" The ":confirm" prompt was sometimes used with the terminal in cooked mode.
" This test verifies that a "\<CR>" character is NOT required to respond to a
" prompt from the ":conf q" and ":conf wq" commands.
func Test_confirm_q_wq()
CheckNotGui
CheckRunVimInTerminal
call writefile(['foo'], 'Xfoo')
let lines =<< trim END
set hidden nomore
call setline(1, 'abc')
edit Xfoo
END
call writefile(lines, 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
call term_sendkeys(buf, ":confirm q\n")
call WaitForAssert({-> assert_match('^\[Y\]es, (N)o, (C)ancel: *$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'C')
call WaitForAssert({-> assert_notmatch('^\[Y\]es, (N)o, (C)ancel: C*$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, ":edit Xfoo\n")
call term_sendkeys(buf, ":confirm wq\n")
call WaitForAssert({-> assert_match('^\[Y\]es, (N)o, (C)ancel: *$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'C')
call WaitForAssert({-> assert_notmatch('^\[Y\]es, (N)o, (C)ancel: C*$',
\ term_getline(buf, 20))}, 1000)
call StopVimInTerminal(buf)
call delete('Xscript')
call delete('Xfoo')
endfunc
func Test_confirm_write_ro()
CheckNotGui
CheckRunVimInTerminal
call writefile(['foo'], 'Xconfirm_write_ro')
let lines =<< trim END
set nobackup ff=unix cmdheight=2
edit Xconfirm_write_ro
norm Abar
END
call writefile(lines, 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
" Try to write with 'ro' option.
call term_sendkeys(buf, ":set ro | confirm w\n")
call WaitForAssert({-> assert_match("^'readonly' option is set for \"Xconfirm_write_ro\"\. *$",
\ term_getline(buf, 18))}, 1000)
call WaitForAssert({-> assert_match('^Do you wish to write anyway? *$',
\ term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('^(Y)es, \[N\]o: *$', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'N')
call WaitForAssert({-> assert_match('^ *$', term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('.* All$', term_getline(buf, 20))}, 1000)
call assert_equal(['foo'], readfile('Xconfirm_write_ro'))
call term_sendkeys(buf, ":confirm w\n")
call WaitForAssert({-> assert_match("^'readonly' option is set for \"Xconfirm_write_ro\"\. *$",
\ term_getline(buf, 18))}, 1000)
call WaitForAssert({-> assert_match('^Do you wish to write anyway? *$',
\ term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('^(Y)es, \[N\]o: *$', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'Y')
call WaitForAssert({-> assert_match('^"Xconfirm_write_ro" 1L, 7B written$',
\ term_getline(buf, 19))}, 1000)
call assert_equal(['foobar'], readfile('Xconfirm_write_ro'))
" Try to write with read-only file permissions.
call setfperm('Xconfirm_write_ro', 'r--r--r--')
call term_sendkeys(buf, ":set noro | undo | confirm w\n")
call WaitForAssert({-> assert_match("^File permissions of \"Xconfirm_write_ro\" are read-only\. *$",
\ term_getline(buf, 17))}, 1000)
call WaitForAssert({-> assert_match('^It may still be possible to write it\. *$',
\ term_getline(buf, 18))}, 1000)
call WaitForAssert({-> assert_match('^Do you wish to try? *$', term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('^(Y)es, \[N\]o: *$', term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'Y')
call WaitForAssert({-> assert_match('^"Xconfirm_write_ro" 1L, 4B written$',
\ term_getline(buf, 19))}, 1000)
call assert_equal(['foo'], readfile('Xconfirm_write_ro'))
call StopVimInTerminal(buf)
call delete('Xscript')
call delete('Xconfirm_write_ro')
endfunc
func Test_confirm_write_partial_file()
CheckNotGui
CheckRunVimInTerminal
call writefile(['a', 'b', 'c', 'd'], 'Xwrite_partial')
call writefile(['set nobackup ff=unix cmdheight=2',
\ 'edit Xwrite_partial'], 'Xscript')
let buf = RunVimInTerminal('-S Xscript', {'rows': 20})
call term_sendkeys(buf, ":confirm 2,3w\n")
call WaitForAssert({-> assert_match('^Write partial file? *$',
\ term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('^(Y)es, \[N\]o: *$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'N')
call WaitForAssert({-> assert_match('.* All$', term_getline(buf, 20))}, 1000)
call assert_equal(['a', 'b', 'c', 'd'], readfile('Xwrite_partial'))
call delete('Xwrite_partial')
call term_sendkeys(buf, ":confirm 2,3w\n")
call WaitForAssert({-> assert_match('^Write partial file? *$',
\ term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('^(Y)es, \[N\]o: *$',
\ term_getline(buf, 20))}, 1000)
call term_sendkeys(buf, 'Y')
call WaitForAssert({-> assert_match('^"Xwrite_partial" \[New\] 2L, 4B written *$',
\ term_getline(buf, 19))}, 1000)
call WaitForAssert({-> assert_match('^Press ENTER or type command to continue *$',
\ term_getline(buf, 20))}, 1000)
call assert_equal(['b', 'c'], readfile('Xwrite_partial'))
call StopVimInTerminal(buf)
call delete('Xwrite_partial')
call delete('Xscript')
endfunc
" Test for the :print command
func Test_print_cmd()
call assert_fails('print', 'E749:')
endfunc
" Test for the :winsize command
func Test_winsize_cmd()
call assert_fails('winsize 1', 'E465:')
call assert_fails('winsize 1 x', 'E465:')
call assert_fails('win_getid(1)', 'E475: Invalid argument: _getid(1)')
" Actually changing the window size would be flaky.
endfunc
" Test for the :redir command
" NOTE: if you run tests as root this will fail. Don't run tests as root!
func Test_redir_cmd()
call assert_fails('redir @@', 'E475:')
call assert_fails('redir abc', 'E475:')
call assert_fails('redir => 1abc', 'E474:')
call assert_fails('redir => a b', 'E488:')
call assert_fails('redir => abc[1]', 'E121:')
let b = 0zFF
call assert_fails('redir =>> b', 'E734:')
unlet b
if has('unix')
" Redirecting to a directory name
call mkdir('Xdir')
call assert_fails('redir > Xdir', 'E17:')
call delete('Xdir', 'd')
endif
" Test for redirecting to a register
redir @q> | echon 'clean ' | redir END
redir @q>> | echon 'water' | redir END
call assert_equal('clean water', @q)
" Test for redirecting to a variable
redir => color | echon 'blue ' | redir END
redir =>> color | echon 'sky' | redir END
call assert_equal('blue sky', color)
endfunc
func Test_redir_cmd_readonly()
CheckNotRoot
" Redirecting to a read-only file
call writefile([], 'Xfile')
call setfperm('Xfile', 'r--r--r--')
call assert_fails('redir! > Xfile', 'E190:')
call delete('Xfile')
endfunc
" Test for the :filetype command
func Test_filetype_cmd()
call assert_fails('filetype abc', 'E475:')
endfunc
" Test for the :mode command
func Test_mode_cmd()
call assert_fails('mode abc', 'E359:')
endfunc
" Test for the :sleep command
func Test_sleep_cmd()
call assert_fails('sleep x', 'E475:')
endfunc
" Test for the :read command
func Test_read_cmd()
call writefile(['one'], 'Xfile')
new
call assert_fails('read', 'E32:')
edit Xfile
read
call assert_equal(['one', 'one'], getline(1, '$'))
close!
new
read Xfile
call assert_equal(['', 'one'], getline(1, '$'))
call deletebufline('', 1, '$')
call feedkeys("Qr Xfile\<CR>visual\<CR>", 'xt')
call assert_equal(['one'], getline(1, '$'))
close!
call delete('Xfile')
endfunc
" Test for running Ex commands when text is locked.
" <C-\>e in the command line is used to lock the text
func Test_run_excmd_with_text_locked()
" :quit
let cmd = ":\<C-\>eexecute('quit')\<CR>\<C-C>"
call assert_fails("call feedkeys(cmd, 'xt')", 'E565:')
" :qall
let cmd = ":\<C-\>eexecute('qall')\<CR>\<C-C>"
call assert_fails("call feedkeys(cmd, 'xt')", 'E565:')
" :exit
let cmd = ":\<C-\>eexecute('exit')\<CR>\<C-C>"
call assert_fails("call feedkeys(cmd, 'xt')", 'E565:')
" :close - should be ignored
new
let cmd = ":\<C-\>eexecute('close')\<CR>\<C-C>"
call assert_equal(2, winnr('$'))
close
call assert_fails("call feedkeys(\":\<C-R>=execute('bnext')\<CR>\", 'xt')", 'E565:')
" :tabfirst
tabnew
call assert_fails("call feedkeys(\":\<C-R>=execute('tabfirst')\<CR>\", 'xt')", 'E565:')
tabclose
endfunc
" Test for the :verbose command
func Test_verbose_cmd()
set verbose=3
call assert_match(' verbose=1\n\s*Last set from ', execute('verbose set vbs'), "\n")
call assert_equal([' verbose=0'], split(execute('0verbose set vbs'), "\n"))
set verbose=0
call assert_match(' verbose=4\n\s*Last set from .*\n verbose=0',
\ execute("4verbose set verbose | set verbose"))
endfunc
" Test for the :delete command and the related abbreviated commands
func Test_excmd_delete()
new
call setline(1, ['foo', "\tbar"])
call assert_equal(['^Ibar$'], split(execute('dl'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal(['^Ibar$'], split(execute('dell'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal(['^Ibar$'], split(execute('delel'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal(['^Ibar$'], split(execute('deletl'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal(['^Ibar$'], split(execute('deletel'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal([' bar'], split(execute('dp'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal([' bar'], split(execute('dep'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal([' bar'], split(execute('delp'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal([' bar'], split(execute('delep'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal([' bar'], split(execute('deletp'), "\n"))
call setline(1, ['foo', "\tbar"])
call assert_equal([' bar'], split(execute('deletep'), "\n"))
close!
endfunc
" Test for commands that are blocked in a sandbox
func Sandbox_tests()
call assert_fails("call histadd(':', 'ls')", 'E48:')
call assert_fails("call mkdir('Xdir')", 'E48:')
call assert_fails("call rename('a', 'b')", 'E48:')
call assert_fails("call setbufvar(1, 'myvar', 1)", 'E48:')
call assert_fails("call settabvar(1, 'myvar', 1)", 'E48:')
call assert_fails("call settabwinvar(1, 1, 'myvar', 1)", 'E48:')
call assert_fails("call setwinvar(1, 'myvar', 1)", 'E48:')
call assert_fails("call timer_start(100, '')", 'E48:')
if has('channel')
call assert_fails("call prompt_setcallback(1, '')", 'E48:')
call assert_fails("call prompt_setinterrupt(1, '')", 'E48:')
call assert_fails("call prompt_setprompt(1, '')", 'E48:')
endif
call assert_fails("let $TESTVAR=1", 'E48:')
call assert_fails("call feedkeys('ivim')", 'E48:')
call assert_fails("source! Xfile", 'E48:')
call assert_fails("call delete('Xfile')", 'E48:')
call assert_fails("call writefile([], 'Xfile')", 'E48:')
call assert_fails('!ls', 'E48:')
" call assert_fails('shell', 'E48:')
call assert_fails('stop', 'E48:')
call assert_fails('exe "normal \<C-Z>"', 'E48:')
" set insertmode
" call assert_fails('call feedkeys("\<C-Z>", "xt")', 'E48:')
" set insertmode&
call assert_fails('suspend', 'E48:')
call assert_fails('call system("ls")', 'E48:')
call assert_fails('call systemlist("ls")', 'E48:')
if has('clientserver')
call assert_fails('let s=remote_expr("gvim", "2+2")', 'E48:')
if !has('win32')
" remote_foreground() doesn't thrown an error message on MS-Windows
call assert_fails('call remote_foreground("gvim")', 'E48:')
endif
call assert_fails('let s=remote_peek("gvim")', 'E48:')
call assert_fails('let s=remote_read("gvim")', 'E48:')
call assert_fails('let s=remote_send("gvim", "abc")', 'E48:')
call assert_fails('let s=server2client("gvim", "abc")', 'E48:')
endif
if has('terminal')
call assert_fails('terminal', 'E48:')
call assert_fails('call term_start("vim")', 'E48:')
call assert_fails('call term_dumpwrite(1, "Xfile")', 'E48:')
endif
if has('channel')
call assert_fails("call ch_logfile('chlog')", 'E48:')
call assert_fails("call ch_open('localhost:8765')", 'E48:')
endif
if has('job')
call assert_fails("call job_start('vim')", 'E48:')
endif
if has('unix') && has('libcall')
call assert_fails("echo libcall('libc.so', 'getenv', 'HOME')", 'E48:')
endif
if has('unix')
call assert_fails('cd `pwd`', 'E48:')
endif
" some options cannot be changed in a sandbox
call assert_fails('set exrc', 'E48:')
call assert_fails('set cdpath', 'E48:')
if has('xim') && has('gui_gtk')
call assert_fails('set imstyle', 'E48:')
endif
endfunc
func Test_sandbox()
sandbox call Sandbox_tests()
endfunc
func Test_command_not_implemented_E319()
if !has('mzscheme')
call assert_fails('mzscheme', 'E319:')
endif
endfunc
func Test_not_break_expression_register()
call setreg('=', '1+1')
if 0
put =1
endif
call assert_equal('1+1', getreg('=', 1))
endfunc
func Test_address_line_overflow()
throw 'Skipped: v:sizeoflong is N/A' " use legacy/excmd_spec.lua instead
if v:sizeoflong < 8
throw 'Skipped: only works with 64 bit long ints'
endif
new
call setline(1, 'text')
call assert_fails('|.44444444444444444444444', 'E1247:')
call assert_fails('|.9223372036854775806', 'E1247:')
bwipe!
endfunc
" This was leaving the cursor in line zero
func Test_using_zero_in_range()
new
norm o00
silent! 0;s/\%')
bwipe!
endfunc
" Test :write after changing name with :file and loading it with :edit
func Test_write_after_rename()
call writefile(['text'], 'Xfile')
enew
file Xfile
call assert_fails('write', 'E13: File exists (add ! to override)')
" works OK after ":edit"
edit
write
call delete('Xfile')
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,43 +0,0 @@
" Test for :execute, :while, :for and :if
func Test_exec_while_if()
new
let i = 0
while i < 12
let i = i + 1
execute "normal o" . i . "\033"
if i % 2
normal Ax
if i == 9
break
endif
if i == 5
continue
else
let j = 9
while j > 0
execute "normal" j . "a" . j . "\x1b"
let j = j - 1
endwhile
endif
endif
if i == 9
execute "normal Az\033"
endif
endwhile
unlet i j
call assert_equal(["",
\ "1x999999999888888887777777666666555554444333221",
\ "2",
\ "3x999999999888888887777777666666555554444333221",
\ "4",
\ "5x",
\ "6",
\ "7x999999999888888887777777666666555554444333221",
\ "8",
\ "9x"], getline(1, 10))
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,176 +0,0 @@
" test execute()
source view_util.vim
func NestedEval()
let nested = execute('echo "nested\nlines"')
echo 'got: "' . nested . '"'
endfunc
func NestedRedir()
redir => var
echo 'broken'
redir END
endfunc
func Test_execute_string()
call assert_equal("\nnocompatible", execute('set compatible?'))
call assert_equal("\nsomething\nnice", execute('echo "something\nnice"'))
call assert_equal("noendofline", execute('echon "noendofline"'))
call assert_equal("", execute(123))
call assert_equal("\ngot: \"\nnested\nlines\"", execute('call NestedEval()'))
redir => redired
echo 'this'
let evaled = execute('echo "that"')
echo 'theend'
redir END
" Nvim supports execute('... :redir ...'), so this test is intentionally
" disabled.
" call assert_equal("\nthis\ntheend", redired)
call assert_equal("\nthat", evaled)
call assert_fails('call execute("doesnotexist")', 'E492:')
call assert_fails('call execute(3.4)', 'E806:')
" Nvim supports execute('... :redir ...'), so this test is intentionally
" disabled.
" call assert_fails('call execute("call NestedRedir()")', 'E930:')
call assert_equal("\nsomething", execute('echo "something"', ''))
call assert_equal("\nsomething", execute('echo "something"', 'silent'))
call assert_equal("\nsomething", execute('echo "something"', 'silent!'))
call assert_equal("", execute('burp', 'silent!'))
call assert_fails('call execute("echo \"x\"", 3.4)', 'E806:')
call assert_equal("", execute(""))
endfunc
func Test_execute_list()
call assert_equal("\nsomething\nnice", execute(['echo "something"', 'echo "nice"']))
let l = ['for n in range(0, 3)',
\ 'echo n',
\ 'endfor']
call assert_equal("\n0\n1\n2\n3", execute(l))
call assert_equal("", execute([]))
call assert_equal("", execute(v:_null_list))
endfunc
func Test_execute_does_not_change_col()
echo ''
echon 'abcd'
let x = execute('silent echo 234343')
echon 'xyz'
let text = ''
for col in range(1, 7)
let text .= nr2char(screenchar(&lines, col))
endfor
call assert_equal('abcdxyz', text)
endfunc
func Test_execute_not_silent()
echo ''
echon 'abcd'
let x = execute('echon 234', '')
echo 'xyz'
let text1 = ''
for col in range(1, 8)
let text1 .= nr2char(screenchar(&lines - 1, col))
endfor
call assert_equal('abcd234 ', text1)
let text2 = ''
for col in range(1, 4)
let text2 .= nr2char(screenchar(&lines, col))
endfor
call assert_equal('xyz ', text2)
endfunc
func Test_win_execute()
let thiswin = win_getid()
new
let otherwin = win_getid()
call setline(1, 'the new window')
call win_gotoid(thiswin)
let line = win_execute(otherwin, 'echo getline(1)')
call assert_match('the new window', line)
let line = win_execute(134343, 'echo getline(1)')
call assert_equal('', line)
if has('textprop')
let popupwin = popup_create('the popup win', {'line': 2, 'col': 3})
redraw
let line = 'echo getline(1)'->win_execute(popupwin)
call assert_match('the popup win', line)
call popup_close(popupwin)
endif
call win_gotoid(otherwin)
bwipe!
" check :lcd in another window does not change directory
let curid = win_getid()
let curdir = getcwd()
split Xother
lcd ..
" Use :pwd to get the actual current directory
let otherdir = execute('pwd')
call win_execute(curid, 'lcd testdir')
call assert_equal(otherdir, execute('pwd'))
bwipe!
execute 'cd ' .. curdir
endfunc
func Test_win_execute_update_ruler()
enew
call setline(1, range(500))
20
split
let winid = win_getid()
set ruler
wincmd w
let height = winheight(winid)
redraw
call assert_match('20,1', Screenline(height + 1))
let line = win_execute(winid, 'call cursor(100, 1)')
redraw
call assert_match('100,1', Screenline(height + 1))
bwipe!
endfunc
func Test_win_execute_other_tab()
let thiswin = win_getid()
tabnew
call win_execute(thiswin, 'let xyz = 1')
call assert_equal(1, xyz)
tabclose
unlet xyz
endfunc
func Test_win_execute_visual_redraw()
call setline(1, ['a', 'b', 'c'])
new
wincmd p
" start Visual in current window, redraw in other window with fewer lines
call feedkeys("G\<C-V>", 'txn')
call win_execute(winnr('#')->win_getid(), 'redraw')
call feedkeys("\<Esc>", 'txn')
bwipe!
bwipe!
enew
new
call setline(1, ['a', 'b', 'c'])
let winid = win_getid()
wincmd p
" start Visual in current window, extend it in other window with more lines
call feedkeys("\<C-V>", 'txn')
call win_execute(winid, 'call feedkeys("G\<C-V>", ''txn'')')
redraw
bwipe!
bwipe!
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,331 +0,0 @@
" Tests for the exists() function
func Test_exists()
augroup myagroup
autocmd! BufEnter *.my echo "myfile edited"
autocmd! FuncUndefined UndefFun exec "fu UndefFun()\nendfu"
augroup END
set rtp+=./sautest
" valid autocmd group
call assert_equal(1, exists('#myagroup'))
" valid autocmd group with garbage
call assert_equal(0, exists('#myagroup+b'))
" Valid autocmd group and event
call assert_equal(1, exists('#myagroup#BufEnter'))
" Valid autocmd group, event and pattern
call assert_equal(1, exists('#myagroup#BufEnter#*.my'))
" Valid autocmd event
call assert_equal(1, exists('#BufEnter'))
" Valid autocmd event and pattern
call assert_equal(1, exists('#BufEnter#*.my'))
" Non-existing autocmd group or event
call assert_equal(0, exists('#xyzagroup'))
" Non-existing autocmd group and valid autocmd event
call assert_equal(0, exists('#xyzagroup#BufEnter'))
" Valid autocmd group and event with no matching pattern
call assert_equal(0, exists('#myagroup#CmdwinEnter'))
" Valid autocmd group and non-existing autocmd event
call assert_equal(0, exists('#myagroup#xyzacmd'))
" Valid autocmd group and event and non-matching pattern
call assert_equal(0, exists('#myagroup#BufEnter#xyzpat'))
" Valid autocmd event and non-matching pattern
call assert_equal(0, exists('#BufEnter#xyzpat'))
" Empty autocmd group, event and pattern
call assert_equal(0, exists('###'))
" Empty autocmd group and event or empty event and pattern
call assert_equal(0, exists('##'))
" Valid autocmd event
call assert_equal(1, exists('##FileReadCmd'))
" Non-existing autocmd event
call assert_equal(0, exists('##MySpecialCmd'))
" Existing and working option (long form)
call assert_equal(1, exists('&textwidth'))
" Existing and working option (short form)
call assert_equal(1, exists('&tw'))
" Existing and working option with garbage
call assert_equal(0, exists('&tw-'))
" Global option
call assert_equal(1, exists('&g:errorformat'))
" Local option
call assert_equal(1, exists('&l:errorformat'))
" Negative form of existing and working option (long form)
call assert_equal(0, exists('&nojoinspaces'))
" Negative form of existing and working option (short form)
call assert_equal(0, exists('&nojs'))
" Non-existing option
call assert_equal(0, exists('&myxyzoption'))
" Existing and working option (long form)
call assert_equal(1, exists('+incsearch'))
" Existing and working option with garbage
call assert_equal(0, exists('+incsearch!1'))
" Existing and working option (short form)
call assert_equal(1, exists('+is'))
" Existing option that is hidden.
call assert_equal(0, exists('+autoprint'))
" Existing environment variable
let $EDITOR_NAME = 'Vim Editor'
call assert_equal(1, exists('$EDITOR_NAME'))
if has('unix')
" ${name} environment variables are supported only on Unix-like systems
call assert_equal(1, exists('${VIM}'))
endif
" Non-existing environment variable
call assert_equal(0, exists('$NON_ENV_VAR'))
" Valid internal function
call assert_equal(1, exists('*bufnr'))
" Valid internal function with ()
call assert_equal(1, exists('*bufnr()'))
" Non-existing internal function
call assert_equal(0, exists('*myxyzfunc'))
" Valid internal function with garbage
call assert_equal(0, exists('*bufnr&6'))
" Valid user defined function
call assert_equal(1, exists('*Test_exists'))
" Non-existing user defined function
call assert_equal(0, exists('*MyxyzFunc'))
" Function that may be created by FuncUndefined event
call assert_equal(0, exists('*UndefFun'))
" Function that may be created by script autoloading
call assert_equal(0, exists('*footest#F'))
" Valid internal command (full match)
call assert_equal(2, exists(':edit'))
" Valid internal command (full match) with garbage
call assert_equal(0, exists(':edit/a'))
" Valid internal command (partial match)
call assert_equal(1, exists(':q'))
" Valid internal command with a digit
call assert_equal(2, exists(':2match'))
" Non-existing internal command
call assert_equal(0, exists(':invalidcmd'))
" Internal command with a count
call assert_equal(0, exists(':3buffer'))
" User defined command (full match)
command! MyCmd :echo 'My command'
call assert_equal(2, exists(':MyCmd'))
" User defined command (partial match)
command! MyOtherCmd :echo 'Another command'
call assert_equal(3, exists(':My'))
" Command modifier
call assert_equal(2, exists(':rightbelow'))
" Non-existing user defined command (full match)
delcommand MyCmd
call assert_equal(0, exists(':MyCmd'))
" Non-existing user defined command (partial match)
delcommand MyOtherCmd
call assert_equal(0, exists(':My'))
" Valid local variable
let local_var = 1
call assert_equal(1, exists('local_var'))
" Valid local variable with garbage
call assert_equal(0, exists('local_var%n'))
" Non-existing local variable
unlet local_var
call assert_equal(0, exists('local_var'))
" Non-existing autoload variable that may be autoloaded
call assert_equal(0, exists('footest#x'))
" Valid local list
let local_list = ["blue", "orange"]
call assert_equal(1, exists('local_list'))
" Valid local list item
call assert_equal(1, exists('local_list[1]'))
" Valid local list item with garbage
call assert_equal(0, exists('local_list[1]+5'))
" Invalid local list item
call assert_equal(0, exists('local_list[2]'))
" Non-existing local list
unlet local_list
call assert_equal(0, exists('local_list'))
" Valid local dictionary
let local_dict = {"xcord":100, "ycord":2}
call assert_equal(1, exists('local_dict'))
" Non-existing local dictionary
unlet local_dict
call assert_equal(0, exists('local_dict'))
" Existing local curly-brace variable
let str = "local"
let curly_{str}_var = 1
call assert_equal(1, exists('curly_{str}_var'))
" Non-existing local curly-brace variable
unlet curly_{str}_var
call assert_equal(0, exists('curly_{str}_var'))
" Existing global variable
let g:global_var = 1
call assert_equal(1, exists('g:global_var'))
" Existing global variable with garbage
call assert_equal(0, exists('g:global_var-n'))
" Non-existing global variable
unlet g:global_var
call assert_equal(0, exists('g:global_var'))
" Existing global list
let g:global_list = ["blue", "orange"]
call assert_equal(1, exists('g:global_list'))
" Non-existing global list
unlet g:global_list
call assert_equal(0, exists('g:global_list'))
" Existing global dictionary
let g:global_dict = {"xcord":100, "ycord":2}
call assert_equal(1, exists('g:global_dict'))
" Non-existing global dictionary
unlet g:global_dict
call assert_equal(0, exists('g:global_dict'))
" Existing global curly-brace variable
let str = "global"
let g:curly_{str}_var = 1
call assert_equal(1, exists('g:curly_{str}_var'))
" Non-existing global curly-brace variable
unlet g:curly_{str}_var
call assert_equal(0, exists('g:curly_{str}_var'))
" Existing window variable
let w:window_var = 1
call assert_equal(1, exists('w:window_var'))
" Non-existing window variable
unlet w:window_var
call assert_equal(0, exists('w:window_var'))
" Existing window list
let w:window_list = ["blue", "orange"]
call assert_equal(1, exists('w:window_list'))
" Non-existing window list
unlet w:window_list
call assert_equal(0, exists('w:window_list'))
" Existing window dictionary
let w:window_dict = {"xcord":100, "ycord":2}
call assert_equal(1, exists('w:window_dict'))
" Non-existing window dictionary
unlet w:window_dict
call assert_equal(0, exists('w:window_dict'))
" Existing window curly-brace variable
let str = "window"
let w:curly_{str}_var = 1
call assert_equal(1, exists('w:curly_{str}_var'))
" Non-existing window curly-brace variable
unlet w:curly_{str}_var
call assert_equal(0, exists('w:curly_{str}_var'))
" Existing tab variable
let t:tab_var = 1
call assert_equal(1, exists('t:tab_var'))
" Non-existing tab variable
unlet t:tab_var
call assert_equal(0, exists('t:tab_var'))
" Existing tab list
let t:tab_list = ["blue", "orange"]
call assert_equal(1, exists('t:tab_list'))
" Non-existing tab list
unlet t:tab_list
call assert_equal(0, exists('t:tab_list'))
" Existing tab dictionary
let t:tab_dict = {"xcord":100, "ycord":2}
call assert_equal(1, exists('t:tab_dict'))
" Non-existing tab dictionary
unlet t:tab_dict
call assert_equal(0, exists('t:tab_dict'))
" Existing tab curly-brace variable
let str = "tab"
let t:curly_{str}_var = 1
call assert_equal(1, exists('t:curly_{str}_var'))
" Non-existing tab curly-brace variable
unlet t:curly_{str}_var
call assert_equal(0, exists('t:curly_{str}_var'))
" Existing buffer variable
let b:buffer_var = 1
call assert_equal(1, exists('b:buffer_var'))
" Non-existing buffer variable
unlet b:buffer_var
call assert_equal(0, exists('b:buffer_var'))
" Existing buffer list
let b:buffer_list = ["blue", "orange"]
call assert_equal(1, exists('b:buffer_list'))
" Non-existing buffer list
unlet b:buffer_list
call assert_equal(0, exists('b:buffer_list'))
" Existing buffer dictionary
let b:buffer_dict = {"xcord":100, "ycord":2}
call assert_equal(1, exists('b:buffer_dict'))
" Non-existing buffer dictionary
unlet b:buffer_dict
call assert_equal(0, exists('b:buffer_dict'))
" Existing buffer curly-brace variable
let str = "buffer"
let b:curly_{str}_var = 1
call assert_equal(1, exists('b:curly_{str}_var'))
" Non-existing buffer curly-brace variable
unlet b:curly_{str}_var
call assert_equal(0, exists('b:curly_{str}_var'))
" Existing Vim internal variable
call assert_equal(1, exists('v:version'))
" Non-existing Vim internal variable
call assert_equal(0, exists('v:non_exists_var'))
" Existing script-local variable
let s:script_var = 1
call assert_equal(1, exists('s:script_var'))
" Non-existing script-local variable
unlet s:script_var
call assert_equal(0, exists('s:script_var'))
" Existing script-local list
let s:script_list = ["blue", "orange"]
call assert_equal(1, exists('s:script_list'))
" Non-existing script-local list
unlet s:script_list
call assert_equal(0, exists('s:script_list'))
" Existing script-local dictionary
let s:script_dict = {"xcord":100, "ycord":2}
call assert_equal(1, exists('s:script_dict'))
" Non-existing script-local dictionary
unlet s:script_dict
call assert_equal(0, exists('s:script_dict'))
" Existing script curly-brace variable
let str = "script"
let s:curly_{str}_var = 1
call assert_equal(1, exists('s:curly_{str}_var'))
" Non-existing script-local curly-brace variable
unlet s:curly_{str}_var
call assert_equal(0, exists('s:curly_{str}_var'))
" Existing script-local function
function! s:my_script_func()
endfunction
echo '*s:my_script_func: 1'
call assert_equal(1, exists('*s:my_script_func'))
" Non-existing script-local function
delfunction s:my_script_func
call assert_equal(0, exists('*s:my_script_func'))
unlet str
call assert_equal(1, g:footest#x)
call assert_equal(0, footest#F())
call assert_equal(0, UndefFun())
endfunc
" exists() test for Function arguments
func FuncArg_Tests(func_arg, ...)
call assert_equal(1, exists('a:func_arg'))
call assert_equal(0, exists('a:non_exists_arg'))
call assert_equal(1, exists('a:1'))
call assert_equal(0, exists('a:2'))
endfunc
func Test_exists_funcarg()
call FuncArg_Tests("arg1", "arg2")
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,26 +0,0 @@
" Test that groups and patterns are tested correctly when calling exists() for
" autocommands.
function Test_AutoCommands()
let results=[]
augroup auexists
augroup END
call assert_true(exists("##BufEnter"))
call assert_false(exists("#BufEnter"))
au BufEnter * let g:entered=1
call assert_true(exists("#BufEnter"))
call assert_false(exists("#auexists#BufEnter"))
augroup auexists
au BufEnter * let g:entered=1
augroup END
call assert_true(exists("#auexists#BufEnter"))
call assert_false(exists("#BufEnter#*.test"))
au BufEnter *.test let g:entered=1
call assert_true(exists("#BufEnter#*.test"))
edit testfile.test
call assert_false(exists("#BufEnter#<buffer>"))
au BufEnter <buffer> let g:entered=1
call assert_true(exists("#BufEnter#<buffer>"))
edit testfile2.test
call assert_false(exists("#BufEnter#<buffer>"))
endfunction

View File

@@ -1,135 +0,0 @@
" Tests for exiting Vim.
source shared.vim
source check.vim
func Test_exiting()
let after =<< trim [CODE]
au QuitPre * call writefile(["QuitPre"], "Xtestout")
au ExitPre * call writefile(["ExitPre"], "Xtestout", "a")
quit
[CODE]
if RunVim([], after, '')
call assert_equal(['QuitPre', 'ExitPre'], readfile('Xtestout'))
endif
call delete('Xtestout')
let after =<< trim [CODE]
au QuitPre * call writefile(["QuitPre"], "Xtestout")
au ExitPre * call writefile(["ExitPre"], "Xtestout", "a")
help
wincmd w
quit
[CODE]
if RunVim([], after, '')
call assert_equal(['QuitPre', 'ExitPre'], readfile('Xtestout'))
endif
call delete('Xtestout')
let after =<< trim [CODE]
au QuitPre * call writefile(["QuitPre"], "Xtestout")
au ExitPre * call writefile(["ExitPre"], "Xtestout", "a")
split
new
qall
[CODE]
if RunVim([], after, '')
call assert_equal(['QuitPre', 'ExitPre'], readfile('Xtestout'))
endif
call delete('Xtestout')
" ExitPre autocommand splits the window, so that it's no longer the last one.
let after =<< trim [CODE]
au QuitPre * call writefile(["QuitPre"], "Xtestout", "a")
au ExitPre * call writefile(["ExitPre"], "Xtestout", "a")
augroup nasty
au ExitPre * split
augroup END
quit
augroup nasty
au! ExitPre
augroup END
quit
[CODE]
if RunVim([], after, '')
call assert_equal(['QuitPre', 'ExitPre', 'QuitPre', 'ExitPre'],
\ readfile('Xtestout'))
endif
call delete('Xtestout')
" ExitPre autocommand splits and closes the window, so that there is still
" one window but it's a different one.
let after =<< trim [CODE]
au QuitPre * call writefile(["QuitPre"], "Xtestout", "a")
au ExitPre * call writefile(["ExitPre"], "Xtestout", "a")
augroup nasty
au ExitPre * split | only
augroup END
quit
augroup nasty
au! ExitPre
augroup END
quit
[CODE]
if RunVim([], after, '')
call assert_equal(['QuitPre', 'ExitPre', 'QuitPre', 'ExitPre'],
\ readfile('Xtestout'))
endif
call delete('Xtestout')
endfunc
" Test for getting the Vim exit code from v:exiting
func Test_exit_code()
call assert_equal(v:null, v:exiting)
let before =<< trim [CODE]
au QuitPre * call writefile(['qp = ' .. v:exiting], 'Xtestout', 'a')
au ExitPre * call writefile(['ep = ' .. v:exiting], 'Xtestout', 'a')
au VimLeavePre * call writefile(['lp = ' .. v:exiting], 'Xtestout', 'a')
au VimLeave * call writefile(['l = ' .. v:exiting], 'Xtestout', 'a')
[CODE]
if RunVim(before, ['quit'], '')
call assert_equal(['qp = v:null', 'ep = v:null', 'lp = 0', 'l = 0'], readfile('Xtestout'))
endif
call delete('Xtestout')
if RunVim(before, ['cquit'], '')
call assert_equal(['lp = 1', 'l = 1'], readfile('Xtestout'))
endif
call delete('Xtestout')
if RunVim(before, ['cquit 4'], '')
call assert_equal(['lp = 4', 'l = 4'], readfile('Xtestout'))
endif
call delete('Xtestout')
endfunc
func Test_exit_error_reading_input()
throw 'Skipped: Nvim does not exit after stdin is read'
CheckNotGui
CheckNotMSWindows
" The early exit causes memory not to be freed somehow
CheckNotAsan
CheckNotValgrind
call writefile([":au VimLeave * call writefile(['l = ' .. v:exiting], 'Xtestout')", ":tabnew", "q:"], 'Xscript', 'b')
" Nvim requires "-s -" to read stdin as Normal mode input
" if RunVim([], [], '<Xscript')
if RunVim([], [], '-s - <Xscript')
call assert_equal(1, v:shell_error)
call assert_equal(['l = 1'], readfile('Xtestout'))
endif
call delete('Xscript')
call delete('Xtestout')
endfun
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,229 +0,0 @@
" Test for expanding file names
source shared.vim
source check.vim
func Test_with_directories()
call mkdir('Xdir1')
call mkdir('Xdir2')
call mkdir('Xdir3')
cd Xdir3
call mkdir('Xdir4')
cd ..
split Xdir1/file
call setline(1, ['a', 'b'])
w
w Xdir3/Xdir4/file
close
next Xdir?/*/file
call assert_equal('Xdir3/Xdir4/file', expand('%'))
if has('unix')
next! Xdir?/*/nofile
call assert_equal('Xdir?/*/nofile', expand('%'))
endif
" Edit another file, on MS-Windows the swap file would be in use and can't
" be deleted.
edit foo
call assert_equal(0, delete('Xdir1', 'rf'))
call assert_equal(0, delete('Xdir2', 'rf'))
call assert_equal(0, delete('Xdir3', 'rf'))
endfunc
func Test_with_tilde()
let dir = getcwd()
call mkdir('Xdir ~ dir')
call assert_true(isdirectory('Xdir ~ dir'))
cd Xdir\ ~\ dir
call assert_true(getcwd() =~ 'Xdir \~ dir')
call chdir(dir)
call delete('Xdir ~ dir', 'd')
call assert_false(isdirectory('Xdir ~ dir'))
endfunc
func Test_expand_tilde_filename()
split ~
call assert_equal('~', expand('%'))
call assert_notequal(expand('%:p'), expand('~/'))
call assert_match('\~', expand('%:p'))
bwipe!
endfunc
func Test_expandcmd()
let $FOO = 'Test'
call assert_equal('e x/Test/y', expandcmd('e x/$FOO/y'))
unlet $FOO
new
edit Xfile1
call assert_equal('e Xfile1', expandcmd('e %'))
edit Xfile2
edit Xfile1
call assert_equal('e Xfile2', 'e #'->expandcmd())
edit Xfile2
edit Xfile3
edit Xfile4
let bnum = bufnr('Xfile2')
call assert_equal('e Xfile2', expandcmd('e #' . bnum))
call setline('.', 'Vim!@#')
call assert_equal('e Vim', expandcmd('e <cword>'))
call assert_equal('e Vim!@#', expandcmd('e <cWORD>'))
enew!
edit Xfile.java
call assert_equal('e Xfile.py', expandcmd('e %:r.py'))
call assert_equal('make abc.java', expandcmd('make abc.%:e'))
call assert_equal('make Xabc.java', expandcmd('make %:s?file?abc?'))
edit a1a2a3.rb
call assert_equal('make b1b2b3.rb a1a2a3 Xfile.o', expandcmd('make %:gs?a?b? %< #<.o'))
call assert_equal('make <afile>', expandcmd("make <afile>"))
call assert_equal('make <amatch>', expandcmd("make <amatch>"))
call assert_equal('make <abuf>', expandcmd("make <abuf>"))
enew
call assert_equal('make %', expandcmd("make %"))
let $FOO="blue\tsky"
call setline(1, "$FOO")
call assert_equal("grep pat blue\tsky", expandcmd('grep pat <cfile>'))
" Test for expression expansion `=
let $FOO= "blue"
call assert_equal("blue sky", expandcmd("`=$FOO .. ' sky'`"))
let x = expandcmd("`=axbycz`")
call assert_equal('`=axbycz`', x)
call assert_fails('let x = expandcmd("`=axbycz`", #{errmsg: 1})', 'E121:')
let x = expandcmd("`=axbycz`", #{abc: []})
call assert_equal('`=axbycz`', x)
" Test for env variable with spaces
let $FOO= "foo bar baz"
call assert_equal("e foo bar baz", expandcmd("e $FOO"))
if has('unix') && executable('bash')
" test for using the shell to expand a command argument.
" only bash supports the {..} syntax
set shell=bash
let x = expandcmd('{1..4}')
call assert_equal('{1..4}', x)
call assert_fails("let x = expandcmd('{1..4}', #{errmsg: v:true})", 'E77:')
let x = expandcmd('{1..4}', #{error: v:true})
call assert_equal('{1..4}', x)
set shell&
endif
unlet $FOO
close!
endfunc
" Test for expanding <sfile>, <slnum> and <sflnum> outside of sourcing a script
func Test_source_sfile()
let lines =<< trim [SCRIPT]
:call assert_equal('<sfile>', expandcmd("<sfile>"))
:call assert_equal('<slnum>', expandcmd("<slnum>"))
:call assert_equal('<sflnum>', expandcmd("<sflnum>"))
:call assert_equal('edit <cfile>', expandcmd("edit <cfile>"))
:call assert_equal('edit #', expandcmd("edit #"))
:call assert_equal('edit #<2', expandcmd("edit #<2"))
:call assert_equal('edit <cword>', expandcmd("edit <cword>"))
:call assert_equal('edit <cexpr>', expandcmd("edit <cexpr>"))
:call assert_fails('autocmd User MyCmd echo "<sfile>"', 'E498:')
:
:call assert_equal('', expand('<script>'))
:verbose echo expand('<script>')
:call add(v:errors, v:errmsg)
:verbose echo expand('<sfile>')
:call add(v:errors, v:errmsg)
:call writefile(v:errors, 'Xresult')
:qall!
[SCRIPT]
call writefile(lines, 'Xscript')
if RunVim([], [], '--clean -s Xscript')
call assert_equal([
\ 'E1274: No script file name to substitute for "<script>"',
\ 'E498: no :source file name to substitute for "<sfile>"'],
\ readfile('Xresult'))
endif
call delete('Xscript')
call delete('Xresult')
endfunc
" Test for expanding filenames multiple times in a command line
func Test_expand_filename_multicmd()
edit foo
call setline(1, 'foo!')
new
call setline(1, 'foo!')
new <cword> | new <cWORD>
call assert_equal(4, winnr('$'))
call assert_equal('foo!', bufname(winbufnr(1)))
call assert_equal('foo', bufname(winbufnr(2)))
call assert_fails('e %:s/.*//', 'E500:')
%bwipe!
endfunc
func Test_expandcmd_shell_nonomatch()
CheckNotMSWindows
call assert_equal('$*', expandcmd('$*'))
endfunc
func Test_expand_script_source()
let lines0 =<< trim [SCRIPT]
call extend(g:script_level, [expand('<script>:t')])
so Xscript1
func F0()
call extend(g:func_level, [expand('<script>:t')])
endfunc
au User * call extend(g:au_level, [expand('<script>:t')])
[SCRIPT]
let lines1 =<< trim [SCRIPT]
call extend(g:script_level, [expand('<script>:t')])
so Xscript2
func F1()
call extend(g:func_level, [expand('<script>:t')])
endfunc
au User * call extend(g:au_level, [expand('<script>:t')])
[SCRIPT]
let lines2 =<< trim [SCRIPT]
call extend(g:script_level, [expand('<script>:t')])
func F2()
call extend(g:func_level, [expand('<script>:t')])
endfunc
au User * call extend(g:au_level, [expand('<script>:t')])
[SCRIPT]
call writefile(lines0, 'Xscript0')
call writefile(lines1, 'Xscript1')
call writefile(lines2, 'Xscript2')
" Check the expansion of <script> at different levels.
let g:script_level = []
let g:func_level = []
let g:au_level = []
so Xscript0
call F0()
call F1()
call F2()
doautocmd User
call assert_equal(['Xscript0', 'Xscript1', 'Xscript2'], g:script_level)
call assert_equal(['Xscript0', 'Xscript1', 'Xscript2'], g:func_level)
call assert_equal(['Xscript2', 'Xscript1', 'Xscript0'], g:au_level)
unlet g:script_level g:func_level
delfunc F0
delfunc F1
delfunc F2
call delete('Xscript0')
call delete('Xscript1')
call delete('Xscript2')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,146 +0,0 @@
" Tests for expand()
source shared.vim
let s:sfile = expand('<sfile>')
let s:slnum = str2nr(expand('<slnum>'))
let s:sflnum = str2nr(expand('<sflnum>'))
func s:expand_sfile()
return expand('<sfile>')
endfunc
func s:expand_slnum()
return str2nr(expand('<slnum>'))
endfunc
func s:expand_sflnum()
return str2nr(expand('<sflnum>'))
endfunc
" This test depends on the location in the test file, put it first.
func Test_expand_sflnum()
call assert_equal(7, s:sflnum)
call assert_equal(24, str2nr(expand('<sflnum>')))
" Line-continuation
call assert_equal(
\ 27,
\ str2nr(expand('<sflnum>')))
" Call in script-local function
call assert_equal(18, s:expand_sflnum())
" Call in command
command Flnum echo expand('<sflnum>')
call assert_equal(36, str2nr(trim(execute('Flnum'))))
delcommand Flnum
endfunc
func Test_expand_sfile_and_stack()
call assert_match('test_expand_func\.vim$', s:sfile)
let expected = 'script .*testdir/runtest.vim\[\d\+\]\.\.function RunTheTest\[\d\+\]\.\.Test_expand_sfile_and_stack'
call assert_match(expected .. '$', expand('<sfile>'))
call assert_match(expected .. '\[4\]$' , expand('<stack>'))
" Call in script-local function
call assert_match('script .*testdir/runtest.vim\[\d\+\]\.\.function RunTheTest\[\d\+\]\.\.Test_expand_sfile_and_stack\[7\]\.\.<SNR>\d\+_expand_sfile$', s:expand_sfile())
" Call in command
command Sfile echo expand('<sfile>')
call assert_match('script .*testdir/runtest.vim\[\d\+\]\.\.function RunTheTest\[\d\+\]\.\.Test_expand_sfile_and_stack$', trim(execute('Sfile')))
delcommand Sfile
" Use <stack> from sourced script.
let lines =<< trim END
" comment here
let g:stack_value = expand('<stack>')
END
call writefile(lines, 'Xstack')
source Xstack
call assert_match('\<Xstack\[2\]$', g:stack_value)
unlet g:stack_value
call delete('Xstack')
if exists('+shellslash')
call mkdir('Xshellslash')
let lines =<< trim END
let g:stack1 = expand('<stack>')
set noshellslash
let g:stack2 = expand('<stack>')
set shellslash
let g:stack3 = expand('<stack>')
END
call writefile(lines, 'Xshellslash/Xstack')
" Test that changing 'shellslash' always affects the result of expand()
" when sourcing a script multiple times.
for i in range(2)
source Xshellslash/Xstack
call assert_match('\<Xshellslash/Xstack\[1\]$', g:stack1)
call assert_match('\<Xshellslash\\Xstack\[3\]$', g:stack2)
call assert_match('\<Xshellslash/Xstack\[5\]$', g:stack3)
unlet g:stack1
unlet g:stack2
unlet g:stack3
endfor
call delete('Xshellslash', 'rf')
endif
endfunc
func Test_expand_slnum()
call assert_equal(6, s:slnum)
call assert_equal(2, str2nr(expand('<slnum>')))
" Line-continuation
call assert_equal(
\ 5,
\ str2nr(expand('<slnum>')))
" Call in script-local function
call assert_equal(1, s:expand_slnum())
" Call in command
command Slnum echo expand('<slnum>')
call assert_equal(14, str2nr(trim(execute('Slnum'))))
delcommand Slnum
endfunc
func Test_expand()
new
call assert_equal("", expand('%:S'))
call assert_equal('3', '<slnum>'->expand())
call assert_equal(['4'], expand('<slnum>', v:false, v:true))
" Don't add any line above this, otherwise <slnum> will change.
call assert_equal("", expand('%'))
set verbose=1
call assert_equal("", expand('%'))
set verbose=0
call assert_equal("", expand('%:p'))
quit
endfunc
func s:sid_test()
return 'works'
endfunc
func Test_expand_SID()
let sid = expand('<SID>')
execute 'let g:sid_result = ' .. sid .. 'sid_test()'
call assert_equal('works', g:sid_result)
endfunc
" Test for 'wildignore' with expand()
func Test_expand_wildignore()
set wildignore=*.vim
call assert_equal('', expand('test_expand_func.vim'))
call assert_equal('', expand('test_expand_func.vim', 0))
call assert_equal([], expand('test_expand_func.vim', 0, 1))
call assert_equal('test_expand_func.vim', expand('test_expand_func.vim', 1))
call assert_equal(['test_expand_func.vim'],
\ expand('test_expand_func.vim', 1, 1))
call assert_fails("call expand('*', [])", 'E745:')
set wildignore&
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,676 +0,0 @@
" Tests for expressions.
source check.vim
func Test_equal()
let base = {}
func base.method()
return 1
endfunc
func base.other() dict
return 1
endfunc
let instance = copy(base)
call assert_true(base.method == instance.method)
call assert_true([base.method] == [instance.method])
call assert_true(base.other == instance.other)
call assert_true([base.other] == [instance.other])
call assert_false(base.method == base.other)
call assert_false([base.method] == [base.other])
call assert_false(base.method == instance.other)
call assert_false([base.method] == [instance.other])
call assert_fails('echo base.method > instance.method')
endfunc
func Test_version()
call assert_true(has('patch-7.4.001'))
call assert_true(has('patch-7.4.01'))
call assert_true(has('patch-7.4.1'))
call assert_true(has('patch-6.9.999'))
call assert_true(has('patch-7.1.999'))
call assert_true(has('patch-7.4.123'))
call assert_false(has('patch-7'))
call assert_false(has('patch-7.4'))
call assert_false(has('patch-7.4.'))
call assert_false(has('patch-9.1.0'))
call assert_false(has('patch-9.9.1'))
endfunc
func Test_dict()
let d = {'': 'empty', 'a': 'a', 0: 'zero'}
call assert_equal('empty', d[''])
call assert_equal('a', d['a'])
call assert_equal('zero', d[0])
call assert_true(has_key(d, ''))
call assert_true(has_key(d, 'a'))
call assert_fails("let i = has_key([], 'a')", 'E715:')
let d[''] = 'none'
let d['a'] = 'aaa'
call assert_equal('none', d[''])
call assert_equal('aaa', d['a'])
let d[ 'b' ] = 'bbb'
call assert_equal('bbb', d[ 'b' ])
endfunc
func Test_strgetchar()
call assert_equal(char2nr('a'), strgetchar('axb', 0))
call assert_equal(char2nr('x'), 'axb'->strgetchar(1))
call assert_equal(char2nr('b'), strgetchar('axb', 2))
call assert_equal(-1, strgetchar('axb', -1))
call assert_equal(-1, strgetchar('axb', 3))
call assert_equal(-1, strgetchar('', 0))
call assert_fails("let c=strgetchar([], 1)", 'E730:')
call assert_fails("let c=strgetchar('axb', [])", 'E745:')
endfunc
func Test_strcharpart()
call assert_equal('a', strcharpart('axb', 0, 1))
call assert_equal('x', 'axb'->strcharpart(1, 1))
call assert_equal('b', strcharpart('axb', 2, 1))
call assert_equal('xb', strcharpart('axb', 1))
call assert_equal('', strcharpart('axb', 1, 0))
call assert_equal('', strcharpart('axb', 1, -1))
call assert_equal('', strcharpart('axb', -1, 1))
call assert_equal('', strcharpart('axb', -2, 2))
call assert_equal('a', strcharpart('axb', -1, 2))
call assert_equal('edit', "editor"[-10:3])
endfunc
func Test_getreg_empty_list()
call assert_equal('', getreg('x'))
call assert_equal([], getreg('x', 1, 1))
let x = getreg('x', 1, 1)
let y = x
call add(x, 'foo')
call assert_equal(['foo'], y)
call assert_fails('call getreg([])', 'E730:')
endfunc
func Test_loop_over_null_list()
let null_list = v:_null_list
for i in null_list
call assert_report('should not get here')
endfor
endfunc
func Test_set_reg_null_list()
call setreg('x', v:_null_list)
endfunc
func Test_special_char()
" The failure is only visible using valgrind.
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()
call assert_equal("123456789012345", printf('%d', 123456789012345))
endfunc
function Test_printf_spec_s()
" number
call assert_equal("1234567890", printf('%s', 1234567890))
" string
call assert_equal("abcdefgi", printf('%s', "abcdefgi"))
" float
call assert_equal("1.23", printf('%s', 1.23))
" list
let value = [1, 'two', ['three', 4]]
call assert_equal(string(value), printf('%s', value))
" dict
let value = {'key1' : 'value1', 'key2' : ['list', 'value'], 'key3' : {'dict' : 'value'}}
call assert_equal(string(value), printf('%s', value))
" funcref
call assert_equal('printf', printf('%s', 'printf'->function()))
" partial
call assert_equal(string(function('printf', ['%s'])), printf('%s', function('printf', ['%s'])))
endfunc
function Test_printf_spec_b()
call assert_equal("0", printf('%b', 0))
call assert_equal("00001100", printf('%08b', 12))
call assert_equal("11111111", printf('%08b', 0xff))
call assert_equal(" 1111011", printf('%10b', 123))
call assert_equal("0001111011", printf('%010b', 123))
call assert_equal(" 0b1111011", printf('%#10b', 123))
call assert_equal("0B01111011", printf('%#010B', 123))
call assert_equal("1001001100101100000001011010010", printf('%b', 1234567890))
call assert_equal("11100000100100010000110000011011101111101111001", printf('%b', 123456789012345))
call assert_equal("1111111111111111111111111111111111111111111111111111111111111111", printf('%b', -1))
endfunc
function Test_printf_misc()
call assert_equal('123', printf('123'))
call assert_fails("call printf('123', 3)", "E767:")
call assert_equal('123', printf('%d', 123))
call assert_equal('123', printf('%i', 123))
call assert_equal('123', printf('%D', 123))
call assert_equal('123', printf('%U', 123))
call assert_equal('173', printf('%o', 123))
call assert_equal('173', printf('%O', 123))
call assert_equal('7b', printf('%x', 123))
call assert_equal('7B', printf('%X', 123))
call assert_equal('123', printf('%hd', 123))
call assert_equal('-123', printf('%hd', -123))
call assert_equal('-1', printf('%hd', 0xFFFF))
call assert_equal('-1', printf('%hd', 0x1FFFFF))
call assert_equal('123', printf('%hu', 123))
call assert_equal('65413', printf('%hu', -123))
call assert_equal('65535', printf('%hu', 0xFFFF))
call assert_equal('65535', printf('%hu', 0x1FFFFF))
call assert_equal('123', printf('%ld', 123))
call assert_equal('-123', printf('%ld', -123))
call assert_equal('65535', printf('%ld', 0xFFFF))
call assert_equal('131071', printf('%ld', 0x1FFFF))
call assert_equal('{', printf('%c', 123))
call assert_equal('abc', printf('%s', 'abc'))
call assert_equal('abc', printf('%S', 'abc'))
call assert_equal('+123', printf('%+d', 123))
call assert_equal('-123', printf('%+d', -123))
call assert_equal('+123', printf('%+ d', 123))
call assert_equal(' 123', printf('% d', 123))
call assert_equal(' 123', printf('% d', 123))
call assert_equal('-123', printf('% d', -123))
call assert_equal('123', printf('%2d', 123))
call assert_equal(' 123', printf('%6d', 123))
call assert_equal('000123', printf('%06d', 123))
call assert_equal('+00123', printf('%+06d', 123))
call assert_equal(' 00123', printf('% 06d', 123))
call assert_equal(' +123', printf('%+6d', 123))
call assert_equal(' 123', printf('% 6d', 123))
call assert_equal(' -123', printf('% 6d', -123))
" Test left adjusted.
call assert_equal('123 ', printf('%-6d', 123))
call assert_equal('+123 ', printf('%-+6d', 123))
call assert_equal(' 123 ', printf('%- 6d', 123))
call assert_equal('-123 ', printf('%- 6d', -123))
call assert_equal(' 00123', printf('%7.5d', 123))
call assert_equal(' -00123', printf('%7.5d', -123))
call assert_equal(' +00123', printf('%+7.5d', 123))
" Precision field should not be used when combined with %0
call assert_equal(' 00123', printf('%07.5d', 123))
call assert_equal(' -00123', printf('%07.5d', -123))
call assert_equal(' 123', printf('%*d', 5, 123))
call assert_equal('123 ', printf('%*d', -5, 123))
call assert_equal('00123', printf('%.*d', 5, 123))
call assert_equal(' 123', printf('% *d', 5, 123))
call assert_equal(' +123', printf('%+ *d', 5, 123))
call assert_equal('foobar', printf('%.*s', 9, 'foobar'))
call assert_equal('foo', printf('%.*s', 3, 'foobar'))
call assert_equal('', printf('%.*s', 0, 'foobar'))
call assert_equal('foobar', printf('%.*s', -1, 'foobar'))
" Simple quote (thousand grouping char) is ignored.
call assert_equal('+00123456', printf("%+'09d", 123456))
" Unrecognized format specifier kept as-is.
call assert_equal('_123', printf("%_%d", 123))
" Test alternate forms.
call assert_equal('0x7b', printf('%#x', 123))
call assert_equal('0X7B', printf('%#X', 123))
call assert_equal('0173', printf('%#o', 123))
call assert_equal('0173', printf('%#O', 123))
call assert_equal('abc', printf('%#s', 'abc'))
call assert_equal('abc', printf('%#S', 'abc'))
call assert_equal(' 0173', printf('%#6o', 123))
call assert_equal(' 00173', printf('%#6.5o', 123))
call assert_equal(' 0173', printf('%#6.2o', 123))
call assert_equal(' 0173', printf('%#6.2o', 123))
call assert_equal('0173', printf('%#2.2o', 123))
call assert_equal(' 00123', printf('%6.5d', 123))
call assert_equal(' 0007b', printf('%6.5x', 123))
call assert_equal('123', printf('%.2d', 123))
call assert_equal('0123', printf('%.4d', 123))
call assert_equal('0000000123', printf('%.10d', 123))
call assert_equal('123', printf('%.0d', 123))
call assert_equal('abc', printf('%2s', 'abc'))
call assert_equal('abc', printf('%2S', 'abc'))
call assert_equal('abc', printf('%.4s', 'abc'))
call assert_equal('abc', printf('%.4S', 'abc'))
call assert_equal('ab', printf('%.2s', 'abc'))
call assert_equal('ab', printf('%.2S', 'abc'))
call assert_equal('', printf('%.0s', 'abc'))
call assert_equal('', printf('%.s', 'abc'))
call assert_equal(' abc', printf('%4s', 'abc'))
call assert_equal(' abc', printf('%4S', 'abc'))
call assert_equal('0abc', printf('%04s', 'abc'))
call assert_equal('0abc', printf('%04S', 'abc'))
call assert_equal('abc ', printf('%-4s', 'abc'))
call assert_equal('abc ', printf('%-4S', 'abc'))
call assert_equal('🐍', printf('%.2S', '🐍🐍'))
call assert_equal('', printf('%.1S', '🐍🐍'))
call assert_equal('[ あいう]', printf('[%10.6S]', 'あいうえお'))
call assert_equal('[ あいうえ]', printf('[%10.8S]', 'あいうえお'))
call assert_equal('[あいうえお]', printf('[%10.10S]', 'あいうえお'))
call assert_equal('[あいうえお]', printf('[%10.12S]', 'あいうえお'))
call assert_equal('あいう', printf('%S', 'あいう'))
call assert_equal('あいう', printf('%#S', 'あいう'))
call assert_equal('あb', printf('%2S', 'あb'))
call assert_equal('あb', printf('%.4S', 'あb'))
call assert_equal('あ', printf('%.2S', 'あb'))
call assert_equal(' あb', printf('%4S', 'あb'))
call assert_equal('0あb', printf('%04S', 'あb'))
call assert_equal('あb ', printf('%-4S', 'あb'))
call assert_equal('あ ', printf('%-4.2S', 'あb'))
call assert_equal('aい', printf('%2S', 'aい'))
call assert_equal('aい', printf('%.4S', 'aい'))
call assert_equal('a', printf('%.2S', 'aい'))
call assert_equal(' aい', printf('%4S', 'aい'))
call assert_equal('0aい', printf('%04S', 'aい'))
call assert_equal('aい ', printf('%-4S', 'aい'))
call assert_equal('a ', printf('%-4.2S', 'aい'))
call assert_equal('[あいう]', printf('[%05S]', 'あいう'))
call assert_equal('[あいう]', printf('[%06S]', 'あいう'))
call assert_equal('[0あいう]', printf('[%07S]', 'あいう'))
call assert_equal('[あiう]', printf('[%05S]', 'あiう'))
call assert_equal('[0あiう]', printf('[%06S]', 'あiう'))
call assert_equal('[00あiう]', printf('[%07S]', 'あiう'))
call assert_equal('[0あい]', printf('[%05.4S]', 'あいう'))
call assert_equal('[00あい]', printf('[%06.4S]', 'あいう'))
call assert_equal('[000あい]', printf('[%07.4S]', 'あいう'))
call assert_equal('[00あi]', printf('[%05.4S]', 'あiう'))
call assert_equal('[000あi]', printf('[%06.4S]', 'あiう'))
call assert_equal('[0000あi]', printf('[%07.4S]', 'あiう'))
call assert_equal('[0あい]', printf('[%05.5S]', 'あいう'))
call assert_equal('[00あい]', printf('[%06.5S]', 'あいう'))
call assert_equal('[000あい]', printf('[%07.5S]', 'あいう'))
call assert_equal('[あiう]', printf('[%05.5S]', 'あiう'))
call assert_equal('[0あiう]', printf('[%06.5S]', 'あiう'))
call assert_equal('[00あiう]', printf('[%07.5S]', 'あiう'))
call assert_equal('[0000000000]', printf('[%010.0S]', 'あいう'))
call assert_equal('[0000000000]', printf('[%010.1S]', 'あいう'))
call assert_equal('[00000000あ]', printf('[%010.2S]', 'あいう'))
call assert_equal('[00000000あ]', printf('[%010.3S]', 'あいう'))
call assert_equal('[000000あい]', printf('[%010.4S]', 'あいう'))
call assert_equal('[000000あい]', printf('[%010.5S]', 'あいう'))
call assert_equal('[0000あいう]', printf('[%010.6S]', 'あいう'))
call assert_equal('[0000あいう]', printf('[%010.7S]', 'あいう'))
call assert_equal('[0000000000]', printf('[%010.1S]', 'あiう'))
call assert_equal('[00000000あ]', printf('[%010.2S]', 'あiう'))
call assert_equal('[0000000あi]', printf('[%010.3S]', 'あiう'))
call assert_equal('[0000000あi]', printf('[%010.4S]', 'あiう'))
call assert_equal('[00000あiう]', printf('[%010.5S]', 'あiう'))
call assert_equal('[00000あiう]', printf('[%010.6S]', 'あiう'))
call assert_equal('[00000あiう]', printf('[%010.7S]', 'あiう'))
call assert_equal('1%', printf('%d%%', 1))
endfunc
function Test_printf_float()
call assert_equal('1.000000', printf('%f', 1))
call assert_equal('1.230000', printf('%f', 1.23))
call assert_equal('1.230000', printf('%F', 1.23))
call assert_equal('9999999.9', printf('%g', 9999999.9))
call assert_equal('9999999.9', printf('%G', 9999999.9))
call assert_equal('1.00000001e7', printf('%.8g', 10000000.1))
call assert_equal('1.00000001E7', printf('%.8G', 10000000.1))
call assert_equal('1.230000e+00', printf('%e', 1.23))
call assert_equal('1.230000E+00', printf('%E', 1.23))
call assert_equal('1.200000e-02', printf('%e', 0.012))
call assert_equal('-1.200000e-02', printf('%e', -0.012))
call assert_equal('0.33', printf('%.2f', 1.0/3.0))
call assert_equal(' 0.33', printf('%6.2f', 1.0/3.0))
call assert_equal(' -0.33', printf('%6.2f', -1.0/3.0))
call assert_equal('000.33', printf('%06.2f', 1.0/3.0))
call assert_equal('-00.33', printf('%06.2f', -1.0/3.0))
call assert_equal('-00.33', printf('%+06.2f', -1.0/3.0))
call assert_equal('+00.33', printf('%+06.2f', 1.0/3.0))
call assert_equal(' 00.33', printf('% 06.2f', 1.0/3.0))
call assert_equal('000.33', printf('%06.2g', 1.0/3.0))
call assert_equal('-00.33', printf('%06.2g', -1.0/3.0))
call assert_equal('0.33', printf('%3.2f', 1.0/3.0))
call assert_equal('003.33e-01', printf('%010.2e', 1.0/3.0))
call assert_equal(' 03.33e-01', printf('% 010.2e', 1.0/3.0))
call assert_equal('+03.33e-01', printf('%+010.2e', 1.0/3.0))
call assert_equal('-03.33e-01', printf('%010.2e', -1.0/3.0))
" When precision is 0, the dot should be omitted.
call assert_equal(' 2', printf('%3.f', 7.0/3.0))
call assert_equal(' 2', printf('%3.g', 7.0/3.0))
call assert_equal(' 2e+00', printf('%7.e', 7.0/3.0))
" Float zero can be signed.
call assert_equal('+0.000000', printf('%+f', 0.0))
call assert_equal('0.000000', printf('%f', 1.0/(1.0/0.0)))
call assert_equal('-0.000000', printf('%f', 1.0/(-1.0/0.0)))
call assert_equal('0.0', printf('%s', 1.0/(1.0/0.0)))
call assert_equal('-0.0', printf('%s', 1.0/(-1.0/0.0)))
call assert_equal('0.0', printf('%S', 1.0/(1.0/0.0)))
call assert_equal('-0.0', printf('%S', 1.0/(-1.0/0.0)))
" Float infinity can be signed.
call assert_equal('inf', printf('%f', 1.0/0.0))
call assert_equal('-inf', printf('%f', -1.0/0.0))
call assert_equal('inf', printf('%g', 1.0/0.0))
call assert_equal('-inf', printf('%g', -1.0/0.0))
call assert_equal('inf', printf('%e', 1.0/0.0))
call assert_equal('-inf', printf('%e', -1.0/0.0))
call assert_equal('INF', printf('%F', 1.0/0.0))
call assert_equal('-INF', printf('%F', -1.0/0.0))
call assert_equal('INF', printf('%E', 1.0/0.0))
call assert_equal('-INF', printf('%E', -1.0/0.0))
call assert_equal('INF', printf('%E', 1.0/0.0))
call assert_equal('-INF', printf('%G', -1.0/0.0))
call assert_equal('+inf', printf('%+f', 1.0/0.0))
call assert_equal('-inf', printf('%+f', -1.0/0.0))
call assert_equal(' inf', printf('% f', 1.0/0.0))
call assert_equal(' inf', printf('%6f', 1.0/0.0))
call assert_equal(' -inf', printf('%6f', -1.0/0.0))
call assert_equal(' inf', printf('%6g', 1.0/0.0))
call assert_equal(' -inf', printf('%6g', -1.0/0.0))
call assert_equal(' +inf', printf('%+6f', 1.0/0.0))
call assert_equal(' inf', printf('% 6f', 1.0/0.0))
call assert_equal(' +inf', printf('%+06f', 1.0/0.0))
call assert_equal('inf ', printf('%-6f', 1.0/0.0))
call assert_equal('-inf ', printf('%-6f', -1.0/0.0))
call assert_equal('+inf ', printf('%-+6f', 1.0/0.0))
call assert_equal(' inf ', printf('%- 6f', 1.0/0.0))
call assert_equal('-INF ', printf('%-6F', -1.0/0.0))
call assert_equal('+INF ', printf('%-+6F', 1.0/0.0))
call assert_equal(' INF ', printf('%- 6F', 1.0/0.0))
call assert_equal('INF ', printf('%-6G', 1.0/0.0))
call assert_equal('-INF ', printf('%-6G', -1.0/0.0))
call assert_equal('INF ', printf('%-6E', 1.0/0.0))
call assert_equal('-INF ', printf('%-6E', -1.0/0.0))
call assert_equal("str2float('inf')", printf('%s', 1.0/0.0))
call assert_equal("-str2float('inf')", printf('%s', -1.0/0.0))
" Test special case where max precision is truncated at 340.
call assert_equal('1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%.330f', 1.0))
call assert_equal('1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%.340f', 1.0))
call assert_equal('1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%.350f', 1.0))
" Float nan (not a number) has no sign.
call assert_equal('nan', printf('%f', sqrt(-1.0)))
call assert_equal('nan', printf('%f', 0.0/0.0))
call assert_equal('nan', printf('%f', -0.0/0.0))
call assert_equal('nan', printf('%g', 0.0/0.0))
call assert_equal('nan', printf('%e', 0.0/0.0))
call assert_equal('NAN', printf('%F', 0.0/0.0))
call assert_equal('NAN', printf('%G', 0.0/0.0))
call assert_equal('NAN', printf('%E', 0.0/0.0))
call assert_equal('NAN', printf('%F', -0.0/0.0))
call assert_equal('NAN', printf('%G', -0.0/0.0))
call assert_equal('NAN', printf('%E', -0.0/0.0))
call assert_equal(' nan', printf('%6f', 0.0/0.0))
call assert_equal(' nan', printf('%06f', 0.0/0.0))
call assert_equal('nan ', printf('%-6f', 0.0/0.0))
call assert_equal('nan ', printf('%- 6f', 0.0/0.0))
call assert_equal("str2float('nan')", printf('%s', 0.0/0.0))
call assert_equal("str2float('nan')", printf('%s', -0.0/0.0))
call assert_equal("str2float('nan')", printf('%S', 0.0/0.0))
call assert_equal("str2float('nan')", printf('%S', -0.0/0.0))
call assert_fails('echo printf("%f", "a")', 'E807:')
endfunc
function Test_printf_errors()
call assert_fails('echo printf("%d", {})', 'E728:')
call assert_fails('echo printf("%d", [])', 'E745:')
call assert_fails('echo printf("%d", 1, 2)', 'E767:')
call assert_fails('echo printf("%*d", 1)', 'E766:')
call assert_fails('echo printf("%s")', 'E766:')
if has('float')
call assert_fails('echo printf("%d", 1.2)', 'E805:')
call assert_fails('echo printf("%f")')
endif
endfunc
function Test_max_min_errors()
call assert_fails('call max(v:true)', 'E712:')
call assert_fails('call max(v:true)', 'max()')
call assert_fails('call min(v:true)', 'E712:')
call assert_fails('call min(v:true)', 'min()')
endfunc
func Test_function_with_funcref()
let s:f = function('type')
let s:fref = function(s:f)
call assert_equal(v:t_string, s:fref('x'))
call assert_fails("call function('s:f')", 'E700:')
call assert_fails("call function('foo()')", 'E475:')
call assert_fails("call function('foo()')", 'foo()')
call assert_fails("function('')", 'E129:')
let Len = {s -> strlen(s)}
call assert_equal(6, Len('foobar'))
let name = string(Len)
" can evaluate "function('<lambda>99')"
call execute('let Ref = ' .. name)
call assert_equal(4, Ref('text'))
endfunc
func Test_funcref()
func! One()
return 1
endfunc
let OneByName = function('One')
let OneByRef = funcref('One')
func! One()
return 2
endfunc
call assert_equal(2, OneByName())
call assert_equal(1, OneByRef())
let OneByRef = 'One'->funcref()
call assert_equal(2, OneByRef())
call assert_fails('echo funcref("{")', 'E475:')
let OneByRef = funcref("One", repeat(["foo"], 20))
call assert_fails('let OneByRef = funcref("One", repeat(["foo"], 21))', 'E118:')
call assert_fails('echo function("min") =~ function("min")', 'E694:')
endfunc
" Test for calling function() and funcref() outside of a Vim script context.
func Test_function_outside_script()
let cleanup =<< trim END
call writefile([execute('messages')], 'Xtest.out')
qall
END
call writefile(cleanup, 'Xverify.vim')
call RunVim([], [], "-c \"echo function('s:abc')\" -S Xverify.vim")
call assert_match('E81: Using <SID> not in a', readfile('Xtest.out')[0])
call RunVim([], [], "-c \"echo funcref('s:abc')\" -S Xverify.vim")
call assert_match('E81: Using <SID> not in a', readfile('Xtest.out')[0])
call delete('Xtest.out')
call delete('Xverify.vim')
endfunc
func Test_setmatches()
hi def link 1 Comment
hi def link 2 PreProc
let set = [{"group": 1, "pattern": 2, "id": 3, "priority": 4}]
let exp = [{"group": '1', "pattern": '2', "id": 3, "priority": 4}]
if has('conceal')
let set[0]['conceal'] = 5
let exp[0]['conceal'] = '5'
endif
eval set->setmatches()
call assert_equal(exp, getmatches())
call assert_fails('let m = setmatches([], [])', 'E745:')
endfunc
func Test_empty_concatenate()
call assert_equal('b', 'a'[4:0] . 'b')
call assert_equal('b', 'b' . 'a'[4:0])
endfunc
func Test_broken_number()
let X = 'bad'
call assert_fails('echo 1X', 'E15:')
call assert_fails('echo 0b1X', 'E15:')
call assert_fails('echo 0b12', 'E15:')
call assert_fails('echo 0x1X', 'E15:')
call assert_fails('echo 011X', 'E15:')
call assert_equal(2, str2nr('2a'))
call assert_fails('inoremap <Char-0b1z> b', 'E474:')
endfunc
func Test_eval_after_if()
let s:val = ''
func SetVal(x)
let s:val ..= a:x
endfunc
if 0 | eval SetVal('a') | endif | call SetVal('b')
call assert_equal('b', s:val)
endfunc
func Test_divide_by_zero()
" only tests that this doesn't crash, the result is not important
echo 0 / 0
echo 0 / 0 / -1
endfunc
" Test for command-line completion of expressions
func Test_expr_completion()
CheckFeature cmdline_compl
for cmd in [
\ 'let a = ',
\ 'const a = ',
\ 'if',
\ 'elseif',
\ 'while',
\ 'for',
\ 'echo',
\ 'echon',
\ 'execute',
\ 'echomsg',
\ 'echoerr',
\ 'call',
\ 'return',
\ 'cexpr',
\ 'caddexpr',
\ 'cgetexpr',
\ 'lexpr',
\ 'laddexpr',
\ 'lgetexpr']
call feedkeys(":" . cmd . " getl\<Tab>\<Home>\"\<CR>", 'xt')
call assert_equal('"' . cmd . ' getline(', getreg(':'))
endfor
" completion for the expression register
call feedkeys(":\"\<C-R>=float2\t\"\<C-B>\"\<CR>", 'xt')
call assert_equal('"float2nr("', @=)
" completion for window local variables
let w:wvar1 = 10
let w:wvar2 = 10
call feedkeys(":echo w:wvar\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"echo w:wvar1 w:wvar2', @:)
unlet w:wvar1 w:wvar2
" completion for tab local variables
let t:tvar1 = 10
let t:tvar2 = 10
call feedkeys(":echo t:tvar\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"echo t:tvar1 t:tvar2', @:)
unlet t:tvar1 t:tvar2
" completion for variables
let g:tvar1 = 1
let g:tvar2 = 2
call feedkeys(":let g:tv\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"let g:tvar1 g:tvar2', @:)
" completion for variables after a ||
call feedkeys(":echo 1 || g:tv\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"echo 1 || g:tvar1 g:tvar2', @:)
" completion for options
call feedkeys(":echo &compat\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"echo &compatible', @:)
call feedkeys(":echo 1 && &compat\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"echo 1 && &compatible', @:)
call feedkeys(":echo &g:equala\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal('"echo &g:equalalways', @:)
" completion for string
call feedkeys(":echo \"Hello\\ World\"\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal("\"echo \"Hello\\ World\"\<C-A>", @:)
call feedkeys(":echo 'Hello World'\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal("\"echo 'Hello World'\<C-A>", @:)
" completion for command after a |
call feedkeys(":echo 'Hello' | cwin\<C-A>\<C-B>\"\<CR>", 'xt')
call assert_equal("\"echo 'Hello' | cwindow", @:)
" completion for environment variable
let $X_VIM_TEST_COMPLETE_ENV = 'foo'
call feedkeys(":let $X_VIM_TEST_COMPLETE_E\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_match('"let $X_VIM_TEST_COMPLETE_ENV', @:)
unlet $X_VIM_TEST_COMPLETE_ENV
endfunc
" Test for errors in expression evaluation
func Test_expr_eval_error()
call assert_fails("let i = 'abc' . []", 'E730:')
call assert_fails("let l = [] + 10", 'E745:')
call assert_fails("let v = 10 + []", 'E745:')
call assert_fails("let v = 10 / []", 'E745:')
call assert_fails("let v = -{}", 'E728:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,34 +0,0 @@
" Tests for expressions using utf-8.
func Test_strgetchar()
call assert_equal(char2nr('á'), strgetchar('áxb', 0))
call assert_equal(char2nr('x'), strgetchar('áxb', 1))
call assert_equal(char2nr('a'), strgetchar('àxb', 0))
call assert_equal(char2nr('̀'), strgetchar('àxb', 1))
call assert_equal(char2nr('x'), strgetchar('àxb', 2))
call assert_equal(char2nr('あ'), strgetchar('あaい', 0))
call assert_equal(char2nr('a'), strgetchar('あaい', 1))
call assert_equal(char2nr('い'), strgetchar('あaい', 2))
endfunc
func Test_strcharpart()
call assert_equal('áxb', strcharpart('áxb', 0))
call assert_equal('á', strcharpart('áxb', 0, 1))
call assert_equal('x', strcharpart('áxb', 1, 1))
call assert_equal('いうeお', strcharpart('あいうeお', 1))
call assert_equal('い', strcharpart('あいうeお', 1, 1))
call assert_equal('いう', strcharpart('あいうeお', 1, 2))
call assert_equal('いうe', strcharpart('あいうeお', 1, 3))
call assert_equal('いうeお', strcharpart('あいうeお', 1, 4))
call assert_equal('eお', strcharpart('あいうeお', 3))
call assert_equal('e', strcharpart('あいうeお', 3, 1))
call assert_equal('あ', strcharpart('あいうeお', -3, 4))
call assert_equal('a', strcharpart('àxb', 0, 1))
call assert_equal('̀', strcharpart('àxb', 1, 1))
call assert_equal('x', strcharpart('àxb', 2, 1))
endfunc

View File

@@ -1,30 +0,0 @@
" Test getting and setting file permissions.
func Test_file_perm()
call assert_equal('', getfperm('Xtest'))
call assert_equal(0, 'Xtest'->setfperm('r--------'))
call writefile(['one'], 'Xtest')
call assert_true(len('Xtest'->getfperm()) == 9)
call assert_equal(1, setfperm('Xtest', 'rwx------'))
if has('win32')
call assert_equal('rw-rw-rw-', getfperm('Xtest'))
else
call assert_equal('rwx------', getfperm('Xtest'))
endif
call assert_equal(1, setfperm('Xtest', 'r--r--r--'))
call assert_equal('r--r--r--', getfperm('Xtest'))
call assert_fails("setfperm('Xtest', '---')")
call assert_equal(1, setfperm('Xtest', 'rwx------'))
call delete('Xtest')
call assert_fails("call setfperm(['Xfile'], 'rw-rw-rw-')", 'E730:')
call assert_fails("call setfperm('Xfile', [])", 'E730:')
call assert_fails("call setfperm('Xfile', 'rwxrwxrwxrw')", 'E475:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,58 +0,0 @@
" Inserts 2 million lines with consecutive integers starting from 1
" (essentially, the output of GNU's seq 1 2000000), writes them to Xtest
" and writes its cksum to test.out.
"
" We need 2 million lines to trigger a call to mf_hash_grow(). If it would mess
" up the lines the checksum would differ.
"
" cksum is part of POSIX and so should be available on most Unixes.
" If it isn't available then the test will be skipped.
func Test_File_Size()
if !executable('cksum')
return
endif
new
set fileformat=unix undolevels=-1
for i in range(1, 2000000, 100)
call append(i, range(i, i + 99))
endfor
1delete
w! Xtest
let res = systemlist('cksum Xtest')[0]
let res = substitute(res, "\r", "", "")
call assert_equal('3678979763 14888896 Xtest', res)
enew!
call delete('Xtest')
set fileformat& undolevels&
endfunc
" Test for writing and reading a file of over 100 Kbyte
func Test_File_Read_Write()
enew!
" Create a file with the following contents
" 1 line: "This is the start"
" 3001 lines: "This is the leader"
" 1 line: "This is the middle"
" 3001 lines: "This is the trailer"
" 1 line: "This is the end"
call append(0, "This is the start")
call append(1, repeat(["This is the leader"], 3001))
call append(3002, "This is the middle")
call append(3003, repeat(["This is the trailer"], 3001))
call append(6004, "This is the end")
write! Xtest
enew!
edit! Xtest
call assert_equal("This is the start", getline(1))
call assert_equal("This is the middle", getline(3003))
call assert_equal("This is the end", getline(6005))
enew!
call delete("Xtest")
endfunc

View File

@@ -1,274 +0,0 @@
" Tests for when a file was changed outside of Vim.
source check.vim
func Test_FileChangedShell_reload()
CheckUnix
augroup testreload
au FileChangedShell Xchanged_r let g:reason = v:fcs_reason | let v:fcs_choice = 'reload'
augroup END
new Xchanged_r
call setline(1, 'reload this')
write
" Need to wait until the timestamp would change by at least a second.
sleep 2
silent !echo 'extra line' >>Xchanged_r
checktime
call assert_equal('changed', g:reason)
call assert_equal(2, line('$'))
call assert_equal('extra line', getline(2))
" Only triggers once
let g:reason = ''
checktime
call assert_equal('', g:reason)
" When deleted buffer is not reloaded
silent !rm Xchanged_r
let g:reason = ''
checktime
call assert_equal('deleted', g:reason)
call assert_equal(2, line('$'))
call assert_equal('extra line', getline(2))
" When recreated buffer is reloaded
call setline(1, 'buffer is changed')
silent !echo 'new line' >>Xchanged_r
let g:reason = ''
checktime
call assert_equal('conflict', g:reason)
call assert_equal(1, line('$'))
call assert_equal('new line', getline(1))
" Only mode changed
silent !chmod +x Xchanged_r
let g:reason = ''
checktime
call assert_equal('mode', g:reason)
call assert_equal(1, line('$'))
call assert_equal('new line', getline(1))
" Only time changed
sleep 2
silent !touch Xchanged_r
let g:reason = ''
checktime
call assert_equal('time', g:reason)
call assert_equal(1, line('$'))
call assert_equal('new line', getline(1))
if has('persistent_undo')
" With an undo file the reload can be undone and a change before the
" reload.
set undofile
call setline(2, 'before write')
write
call setline(2, 'after write')
sleep 2
silent !echo 'different line' >>Xchanged_r
let g:reason = ''
checktime
call assert_equal('conflict', g:reason)
call assert_equal(3, line('$'))
call assert_equal('before write', getline(2))
call assert_equal('different line', getline(3))
" undo the reload
undo
call assert_equal(2, line('$'))
call assert_equal('after write', getline(2))
" undo the change before reload
undo
call assert_equal(2, line('$'))
call assert_equal('before write', getline(2))
set noundofile
endif
au! testreload
bwipe!
call delete(undofile('Xchanged_r'))
call delete('Xchanged_r')
endfunc
func Test_FileChangedShell_edit()
CheckUnix
new Xchanged_r
call setline(1, 'reload this')
set fileformat=unix
write
" File format changed, reload (content only, no 'ff' etc)
augroup testreload
au!
au FileChangedShell Xchanged_r let g:reason = v:fcs_reason | let v:fcs_choice = 'reload'
augroup END
call assert_equal(&fileformat, 'unix')
sleep 10m " make the test less flaky in Nvim
call writefile(["line1\r", "line2\r"], 'Xchanged_r')
let g:reason = ''
checktime
call assert_equal('changed', g:reason)
call assert_equal(&fileformat, 'unix')
call assert_equal("line1\r", getline(1))
call assert_equal("line2\r", getline(2))
%s/\r
write
" File format changed, reload with 'ff', etc
augroup testreload
au!
au FileChangedShell Xchanged_r let g:reason = v:fcs_reason | let v:fcs_choice = 'edit'
augroup END
call assert_equal(&fileformat, 'unix')
sleep 10m " make the test less flaky in Nvim
call writefile(["line1\r", "line2\r"], 'Xchanged_r')
let g:reason = ''
checktime
call assert_equal('changed', g:reason)
call assert_equal(&fileformat, 'dos')
call assert_equal('line1', getline(1))
call assert_equal('line2', getline(2))
set fileformat=unix
write
au! testreload
bwipe!
call delete(undofile('Xchanged_r'))
call delete('Xchanged_r')
endfunc
func Test_FileChangedShell_edit_dialog()
" requires a UI to be active
throw 'Skipped: use test/functional/legacy/filechanged_spec.lua'
CheckNotGui
CheckUnix " Using low level feedkeys() does not work on MS-Windows.
new Xchanged_r
call setline(1, 'reload this')
set fileformat=unix
write
" File format changed, reload (content only) via prompt
augroup testreload
au!
au FileChangedShell Xchanged_r let g:reason = v:fcs_reason | let v:fcs_choice = 'ask'
augroup END
call assert_equal(&fileformat, 'unix')
call writefile(["line1\r", "line2\r"], 'Xchanged_r')
let g:reason = ''
call feedkeys('L', 'L') " load file content only
checktime
call assert_equal('changed', g:reason)
call assert_equal(&fileformat, 'unix')
call assert_equal("line1\r", getline(1))
call assert_equal("line2\r", getline(2))
%s/\r
write
" File format changed, reload (file and options) via prompt
augroup testreload
au!
au FileChangedShell Xchanged_r let g:reason = v:fcs_reason | let v:fcs_choice = 'ask'
augroup END
call assert_equal(&fileformat, 'unix')
call writefile(["line1\r", "line2\r"], 'Xchanged_r')
let g:reason = ''
call feedkeys('a', 'L') " load file content and options
checktime
call assert_equal('changed', g:reason)
call assert_equal(&fileformat, 'dos')
call assert_equal("line1", getline(1))
call assert_equal("line2", getline(2))
set fileformat=unix
write
au! testreload
bwipe!
call delete(undofile('Xchanged_r'))
call delete('Xchanged_r')
endfunc
func Test_file_changed_dialog()
" requires a UI to be active
throw 'Skipped: use test/functional/legacy/filechanged_spec.lua'
CheckUnix
CheckNotGui
au! FileChangedShell
new Xchanged_d
call setline(1, 'reload this')
write
" Need to wait until the timestamp would change by at least a second.
sleep 2
silent !echo 'extra line' >>Xchanged_d
call feedkeys('L', 'L')
checktime
call assert_match('W11:', v:warningmsg)
call assert_equal(2, line('$'))
call assert_equal('reload this', getline(1))
call assert_equal('extra line', getline(2))
" delete buffer, only shows an error, no prompt
silent !rm Xchanged_d
checktime
call assert_match('E211:', v:warningmsg)
call assert_equal(2, line('$'))
call assert_equal('extra line', getline(2))
let v:warningmsg = 'empty'
" change buffer, recreate the file and reload
call setline(1, 'buffer is changed')
silent !echo 'new line' >Xchanged_d
call feedkeys('L', 'L')
checktime
call assert_match('W12:', v:warningmsg)
call assert_equal(1, line('$'))
call assert_equal('new line', getline(1))
" Only mode changed, reload
silent !chmod +x Xchanged_d
call feedkeys('L', 'L')
checktime
call assert_match('W16:', v:warningmsg)
call assert_equal(1, line('$'))
call assert_equal('new line', getline(1))
" Only time changed, no prompt
sleep 2
silent !touch Xchanged_d
let v:warningmsg = ''
checktime Xchanged_d
call assert_equal('', v:warningmsg)
call assert_equal(1, line('$'))
call assert_equal('new line', getline(1))
" File created after starting to edit it
call delete('Xchanged_d')
new Xchanged_d
call writefile(['one'], 'Xchanged_d')
call feedkeys('L', 'L')
checktime Xchanged_d
call assert_equal(['one'], getline(1, '$'))
close!
bwipe!
call delete('Xchanged_d')
endfunc
" Test for editing a new buffer from a FileChangedShell autocmd
func Test_FileChangedShell_newbuf()
call writefile(['one', 'two'], 'Xfile')
new Xfile
augroup testnewbuf
autocmd FileChangedShell * enew
augroup END
sleep 10m " make the test less flaky in Nvim
call writefile(['red'], 'Xfile')
call assert_fails('checktime', 'E811:')
au! testnewbuf
call delete('Xfile')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

View File

@@ -1,309 +0,0 @@
" Test behavior of fileformat after bwipeout of last buffer
func Test_fileformat_after_bw()
bwipeout
set fileformat&
if &fileformat == 'dos'
let test_fileformats = 'unix'
elseif &fileformat == 'unix'
let test_fileformats = 'mac'
else " must be mac
let test_fileformats = 'dos'
endif
exec 'set fileformats='.test_fileformats
bwipeout!
call assert_equal(test_fileformats, &fileformat)
set fileformats&
endfunc
func Test_fileformat_autocommand()
let filecnt = ["", "foobar\<CR>", "eins\<CR>", "\<CR>", "zwei\<CR>", "drei", "vier", "fünf", ""]
let ffs = &ffs
call writefile(filecnt, 'Xfile', 'b')
au BufReadPre Xfile set ffs=dos ff=dos
new Xfile
call assert_equal('dos', &l:ff)
call assert_equal('dos', &ffs)
" cleanup
call delete('Xfile')
let &ffs = ffs
au! BufReadPre Xfile
bw!
endfunc
func Test_fileformat_nomodifiable()
new
setlocal nomodifiable
call assert_fails('set fileformat=latin1', 'E21:')
bw
endfunc
" Convert the contents of a file into a literal string
func s:file2str(fname)
let b = readfile(a:fname, 'B')
let s = ''
for c in b
let s .= nr2char(c)
endfor
return s
endfunc
" Concatenate the contents of files 'f1' and 'f2' and create 'destfile'
func s:concat_files(f1, f2, destfile)
let b1 = readfile(a:f1, 'B')
let b2 = readfile(a:f2, 'B')
let b3 = b1 + b2
call writefile(b3, a:destfile)
endfun
" Test for a lot of variations of the 'fileformats' option
func Test_fileformats()
" create three test files, one in each format
call writefile(['unix', 'unix'], 'XXUnix')
call writefile(["dos\r", "dos\r"], 'XXDos')
call writefile(["mac\rmac\r"], 'XXMac', 'b')
" create a file with no End Of Line
call writefile(["noeol"], 'XXEol', 'b')
" create mixed format files
call s:concat_files('XXUnix', 'XXDos', 'XXUxDs')
call s:concat_files('XXUnix', 'XXMac', 'XXUxMac')
call s:concat_files('XXDos', 'XXMac', 'XXDosMac')
call s:concat_files('XXMac', 'XXEol', 'XXMacEol')
call s:concat_files('XXUxDs', 'XXMac', 'XXUxDsMc')
new
" Test 1: try reading and writing with 'fileformats' empty
set fileformats=
" try with 'fileformat' set to 'unix'
set fileformat=unix
e! XXUnix
w! Xtest
call assert_equal("unix\nunix\n", s:file2str('Xtest'))
e! XXDos
w! Xtest
call assert_equal("dos\r\ndos\r\n", s:file2str('Xtest'))
e! XXMac
w! Xtest
call assert_equal("mac\rmac\r\n", s:file2str('Xtest'))
bwipe XXUnix XXDos XXMac
" try with 'fileformat' set to 'dos'
set fileformat=dos
e! XXUnix
w! Xtest
call assert_equal("unix\r\nunix\r\n", s:file2str('Xtest'))
e! XXDos
w! Xtest
call assert_equal("dos\r\ndos\r\n", s:file2str('Xtest'))
e! XXMac
w! Xtest
call assert_equal("mac\rmac\r\r\n", s:file2str('Xtest'))
bwipe XXUnix XXDos XXMac
" try with 'fileformat' set to 'mac'
set fileformat=mac
e! XXUnix
w! Xtest
call assert_equal("unix\nunix\n\r", s:file2str('Xtest'))
e! XXDos
w! Xtest
call assert_equal("dos\r\ndos\r\n\r", s:file2str('Xtest'))
e! XXMac
w! Xtest
call assert_equal("mac\rmac\r", s:file2str('Xtest'))
bwipe XXUnix XXDos XXMac
" Test 2: try reading and writing with 'fileformats' set to one format
" try with 'fileformats' set to 'unix'
set fileformats=unix
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
" try with 'fileformats' set to 'dos'
set fileformats=dos
e! XXUxDsMc
w! Xtest
call assert_equal("unix\r\nunix\r\ndos\r\ndos\r\nmac\rmac\r\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
" try with 'fileformats' set to 'mac'
set fileformats=mac
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
" Test 3: try reading and writing with 'fileformats' set to two formats
" try with 'fileformats' set to 'unix,dos'
set fileformats=unix,dos
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
e! XXUxMac
w! Xtest
call assert_equal("unix\nunix\nmac\rmac\r\n", s:file2str('Xtest'))
bwipe XXUxMac
e! XXDosMac
w! Xtest
call assert_equal("dos\r\ndos\r\nmac\rmac\r\r\n", s:file2str('Xtest'))
bwipe XXDosMac
" try with 'fileformats' set to 'unix,mac'
set fileformats=unix,mac
e! XXUxDs
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\n", s:file2str('Xtest'))
bwipe XXUxDs
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
e! XXDosMac
w! Xtest
call assert_equal("dos\r\ndos\r\nmac\rmac\r", s:file2str('Xtest'))
bwipe XXDosMac
e! XXEol
exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
w! Xtest
call assert_equal("unix,mac:unix\nnoeol\n", s:file2str('Xtest'))
bwipe! XXEol
" try with 'fileformats' set to 'dos,mac'
set fileformats=dos,mac
e! XXUxDs
w! Xtest
call assert_equal("unix\r\nunix\r\ndos\r\ndos\r\n", s:file2str('Xtest'))
bwipe XXUxDs
e! XXUxMac
exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
w! Xtest
call assert_equal("dos,mac:dos\r\nunix\r\nunix\r\nmac\rmac\r\r\n",
\ s:file2str('Xtest'))
bwipe! XXUxMac
e! XXUxDsMc
w! Xtest
call assert_equal("unix\r\nunix\r\ndos\r\ndos\r\nmac\rmac\r\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
e! XXMacEol
exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
w! Xtest
call assert_equal("dos,mac:mac\rmac\rmac\rnoeol\r", s:file2str('Xtest'))
bwipe! XXMacEol
" Test 4: try reading and writing with 'fileformats' set to three formats
set fileformats=unix,dos,mac
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
e! XXEol
exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
w! Xtest
call assert_equal("unix,dos,mac:unix\nnoeol\n", s:file2str('Xtest'))
bwipe! XXEol
set fileformats=mac,dos,unix
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
e! XXEol
exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
w! Xtest
call assert_equal("mac,dos,unix:mac\rnoeol\r", s:file2str('Xtest'))
bwipe! XXEol
" Test 5: try with 'binary' set
set fileformats=mac,unix,dos
set binary
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
set fileformats=mac
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
set fileformats=dos
e! XXUxDsMc
w! Xtest
call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
\ s:file2str('Xtest'))
bwipe XXUxDsMc
e! XXUnix
w! Xtest
call assert_equal("unix\nunix\n", s:file2str('Xtest'))
bwipe! XXUnix
set nobinary ff& ffs&
" cleanup
only
%bwipe!
call delete('XXUnix')
call delete('XXDos')
call delete('XXMac')
call delete('XXEol')
call delete('XXUxDs')
call delete('XXUxMac')
call delete('XXDosMac')
call delete('XXMacEol')
call delete('XXUxDsMc')
call delete('Xtest')
endfunc
" Test for changing the fileformat using ++read
func Test_fileformat_plusplus_read()
new
call setline(1, ['one', 'two', 'three'])
w ++ff=dos Xfile1
enew!
set ff=unix
" A :read doesn't change the fileformat, but does apply to the read lines.
r ++fileformat=unix Xfile1
call assert_equal('unix', &fileformat)
call assert_equal("three\r", getline('$'))
3r ++edit Xfile1
call assert_equal('dos', &fileformat)
close!
call delete('Xfile1')
set fileformat&
call assert_fails('e ++fileformat Xfile1', 'E474:')
call assert_fails('e ++ff=abc Xfile1', 'E474:')
call assert_fails('e ++abc1 Xfile1', 'E474:')
endfunc
" vim: shiftwidth=2 sts=2 expandtab

Some files were not shown because too many files have changed in this diff Show More